role_maker.py 44.9 KB
Newer Older
D
dongdaxiang 已提交
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.
I
iLeGend 已提交
14
"""Definition of Role Makers."""
D
dongdaxiang 已提交
15

X
xujiaqi01 已提交
16
import os
17
import time
meteor135's avatar
meteor135 已提交
18 19 20
from multiprocessing import Manager, Process

import paddle.fluid as fluid
21

T
tangwei12 已提交
22
__all__ = [
23 24 25 26 27 28 29
    'Role',
    'RoleMakerBase',
    'MPISymetricRoleMaker',
    'UserDefinedRoleMaker',
    'UserDefinedCollectiveRoleMaker',
    'PaddleCloudRoleMaker',
    'GeneralRoleMaker',
T
tangwei12 已提交
30 31
]

32

T
tangwei12 已提交
33 34
class Role:
    WORKER = 1
35
    SERVER = 2
T
Thunderbrook 已提交
36
    XPU = 3
37

D
dongdaxiang 已提交
38

39
class MockBarrier:
X
xujiaqi01 已提交
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
    """
    MockBarrier is a empty impletation for barrier
    mock as a real barrier for never-barrier in a specific scenario
    """

    def barrier(self):
        """
        dummy barrier, do nothing
        """
        pass

    def barrier_all(self):
        """
        dummy all barrier, do nothing
        """
        pass

    def all_reduce(self, obj):
        """
        dummy all reduce, do nothing
        Args:
            obj(any): obj to do all reduce
        """
        return obj

    def all_gather(self, obj):
        """
        dummy all gather, do nothing
        Args:
            obj(any): obj to do all gather
        """
        return [obj]


74
class RoleMakerBase:
75 76 77 78 79 80 81
    """
    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.
    """

D
dongdaxiang 已提交
82
    def __init__(self):
T
tangwei12 已提交
83 84
        self._worker_endpoints = []
        self._server_endpoints = []
D
dongdaxiang 已提交
85
        self._role_is_generated = False
T
tangwei12 已提交
86 87
        self._role = None
        self._current_id = -1
D
dongdaxiang 已提交
88

T
tangwei12 已提交
89
    def is_worker(self):
90 91 92
        """
        return is_worker() of current process
        """
D
dongdaxiang 已提交
93 94
        raise NotImplementedError("Please implement this method in child class")

T
tangwei12 已提交
95
    def is_server(self):
96 97 98
        """
        return is_server() of current process
        """
D
dongdaxiang 已提交
99 100
        raise NotImplementedError("Please implement this method in child class")

T
tangwei12 已提交
101
    def is_first_worker(self):
102
        """
T
tangwei12 已提交
103 104 105 106
        Check whether the node is the first instance of worker.
        Returns:
            bool: True if this is the first node of worker,
                  False if not.
107
        """
T
tangwei12 已提交
108
        raise NotImplementedError("Please implement this method in child class")
D
dongdaxiang 已提交
109

110 111 112 113 114 115 116 117 118
    def worker_num(self):
        """
        Get current total worker number.

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

119 120 121
    def role_id(self):
        return self.worker_index() if self.is_worker() else self.server_index()

T
tangwei12 已提交
122
    def worker_index(self):
123
        """
T
tangwei12 已提交
124 125 126 127
        Get current worker id.

        Returns:
            int: node id
128
        """
T
tangwei12 已提交
129
        raise NotImplementedError("Please implement this method in child class")
D
dongdaxiang 已提交
130

T
tangwei12 已提交
131
    def server_index(self):
132
        """
T
tangwei12 已提交
133 134 135 136
        Get current server id.

        Returns:
            int: node id
137
        """
T
tangwei12 已提交
138
        raise NotImplementedError("Please implement this method in child class")
D
dongdaxiang 已提交
139

T
tangwei12 已提交
140
    def get_trainer_endpoints(self):
141
        """
T
tangwei12 已提交
142
        return trainer endpoints
143
        """
T
tangwei12 已提交
144 145 146 147 148 149 150
        return self._worker_endpoints

    def get_pserver_endpoints(self):
        """
        return pserver endpoints
        """
        return self._server_endpoints
D
dongdaxiang 已提交
151

T
tangwei12 已提交
152 153
    def to_string(self):
        return "role: {}, current_id: {}, worker_endpoints: {}, server_endpoints: {}".format(
154 155 156 157 158
            self._role,
            self._current_id,
            self._worker_endpoints,
            self._server_endpoints,
        )
T
tangwei12 已提交
159

X
xujiaqi01 已提交
160 161 162 163 164 165 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 191 192 193 194 195 196
    def all_gather(self, input):
        """
        all gather between trainers and pservers

        Args:
            input(int|float): input value

        Returns:
            return a list of values
        """
        print("warning: RoleMakerBase does not have all gather.")
        return None

    def all_reduce_worker(self, input, output, mode="sum"):
        """
        all reduce between trainers if current role is TRAINER,
        only support array of one dim.

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

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

    def barrier_all(self):
        """
        barrier between trainers if current role is PSERVER
        """
        print("warning: RoleMakerBase does not have barrier all.")

D
dongdaxiang 已提交
197 198

class MPIRoleMaker(RoleMakerBase):
199 200 201 202 203
    """
    MPIRoleMaker is a MPI-API based role maker which is a counter-part of K8SRoleMaker
    mpi4py will be used if a developer inherits MPIRoleMaker
    """

D
dongdaxiang 已提交
204
    def __init__(self):
X
xujiaqi01 已提交
205
        """Init."""
206
        super().__init__()
D
dongdaxiang 已提交
207
        from mpi4py import MPI
208

D
dongdaxiang 已提交
209
        self.MPI = MPI
T
tangwei12 已提交
210 211
        self._comm = MPI.COMM_WORLD
        self._node_type_comm = None
D
dongdaxiang 已提交
212
        self._ips = None
T
tangwei12 已提交
213
        self._ip = None
D
dongdaxiang 已提交
214

215
    def _get_rank(self):
X
xujiaqi01 已提交
216
        """Return rank."""
D
dongdaxiang 已提交
217 218
        self._rank = self._comm.Get_rank()
        return self._rank
D
dongdaxiang 已提交
219

220
    def _get_size(self):
X
xujiaqi01 已提交
221
        """Return size."""
D
dongdaxiang 已提交
222 223
        self._size = self._comm.Get_size()
        return self._size
D
dongdaxiang 已提交
224

225
    def _all_gather(self, obj):
226 227 228
        """
        all_gather(obj) will call MPI's allgather function
        """
X
xjqbest 已提交
229
        self._barrier_all()
D
dongdaxiang 已提交
230
        return self._comm.allgather(obj)
D
dongdaxiang 已提交
231

X
xjqbest 已提交
232 233 234 235
    def _worker_gather(self, obj):
        """
        worker_gather(obj) will call MPI's allgather function
        """
T
tangwei12 已提交
236
        if self.is_worker():
D
dongdaxiang 已提交
237 238
            self._node_type_comm.barrier()
            return self._node_type_comm.allgather(obj)
X
xjqbest 已提交
239 240
        return None

241
    def _barrier_all(self):
242 243 244
        """
        barrier_all() will call MPI's barrier_all function
        """
D
dongdaxiang 已提交
245
        self._comm.barrier()
D
dongdaxiang 已提交
246

T
tangwei12 已提交
247 248 249 250
    def _finalize(self):
        """
        finalize the current MPI instance.
        """
251
        self.MPI.Finalize()
T
tangwei12 已提交
252

253
    def _get_ips(self):
254 255 256
        """
        collect current distributed job's ip list
        """
T
tangwei12 已提交
257 258
        if not self._ips:
            self._ips = self._comm.allgather(self.get_local_ip())
D
dongdaxiang 已提交
259
        return self._ips
D
dongdaxiang 已提交
260

T
tangwei12 已提交
261
    def get_local_ip(self):
X
xujiaqi01 已提交
262
        """Return get local ip."""
T
tangwei12 已提交
263
        import socket
264

T
tangwei12 已提交
265 266 267 268 269 270 271 272
        self._ip = socket.gethostbyname(socket.gethostname())
        return self._ip

    def generate_role(self):
        """
        generate_role() should be called to identify current process's role
        """
        raise NotImplementedError("Please implement this method in child class")
D
dongdaxiang 已提交
273 274 275


class MPISymetricRoleMaker(MPIRoleMaker):
276 277 278 279 280 281
    """
    MPISymetricRoleMaker is designed for worker and server assignment
    under MPI. Typically, a worker and a server node will be appointed
    on each physical node. This role maker can be only used under MPI.
    """

D
dongdaxiang 已提交
282
    def __init__(self):
X
xujiaqi01 已提交
283
        """Init."""
284
        super().__init__()
D
dongdaxiang 已提交
285 286
        self._node_type = None
        self._proc_per_node = 2
G
guru4elephant 已提交
287
        self._pserver_rand_port = 0
D
dongdaxiang 已提交
288

289
    def _check_role_generation(self):
X
xujiaqi01 已提交
290
        """Check whether role has been generated."""
D
dongdaxiang 已提交
291
        if not self._role_is_generated:
T
tangwei12 已提交
292
            raise NameError("generate_role() should be called first")
293 294
        return True

X
xujiaqi01 已提交
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 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
    def all_gather(self, input):
        """
        all gather between trainers and pservers

        Args:
            input(int|float): input value

        Returns:
            return a list of values
        """
        if not self._role_is_generated:
            self.generate_role()
        return self._all_gather(input)

    def all_reduce_worker(self, input, output, mode="sum"):
        """
        all reduce between trainers if current role is TRAINER,
        only support array of one dim.

        Args:
            input(list/numpy.array): array of one dim
            output(list/numpy.array): array of one dim
            mode(str): "sum" or "min" or "max"
        """
        if not self._role_is_generated:
            self.generate_role()
        if not self.is_worker():
            print("warning: current role is not worker in all_reduce_worker")
            return
        self._all_reduce(input, output, mode)

    def barrier_worker(self):
        """
        barrier between trainers if current role is TRAINER
        """
        if not self._role_is_generated:
            self.generate_role()
        if self.is_worker():
            self._node_type_comm.barrier()
        else:
            print("warning: current role is not worker in barrier_worker")

    def barrier_all(self):
        """
        barrier between trainers if current role is PSERVER
        """
        if not self._role_is_generated:
            self.generate_role()
        self._comm.barrier()

T
tangwei12 已提交
345
    def is_first_worker(self):
346 347 348 349
        """
        return whether current process is the first worker assigned by role maker
        """
        if self._check_role_generation():
T
tangwei12 已提交
350
            return self.is_worker() and 0 == self.worker_index()
351
        return False
D
dongdaxiang 已提交
352

G
guru4elephant 已提交
353
    def get_pserver_endpoints(self):
X
xujiaqi01 已提交
354 355 356 357 358
        """
        get pserver endpoints
        Returns:
            endpoints(list): pserver endpoints
        """
G
guru4elephant 已提交
359 360
        if self._pserver_rand_port <= 0:
            import random
361

G
guru4elephant 已提交
362 363 364 365 366 367 368 369 370 371 372
            random.seed(self._server_num())
            # port will be randomly generated from 60001 to 63999
            # random seed is server num so that all nodes will get
            # the same port
            self._pserver_rand_port = random.randint(60001, 64000)
        endpoints = [
            x + ":" + str(self._pserver_rand_port)
            for x in self._server_endpoints
        ]
        return endpoints

373 374 375
    def worker_num(self):
        return self._worker_num()

T
tangwei12 已提交
376
    def is_worker(self):
377 378 379 380
        """
        return whether current process is worker assigned by role maker
        """
        if self._check_role_generation():
D
dongdaxiang 已提交
381
            return self._node_type == 1
382
        return False
D
dongdaxiang 已提交
383

T
tangwei12 已提交
384
    def is_server(self):
385 386 387 388
        """
        return whether current process is server assigned by role maker
        """
        if self._check_role_generation():
D
dongdaxiang 已提交
389
            return self._node_type == 0
390
        return False
D
dongdaxiang 已提交
391

392
    def _worker_num(self):
393 394 395 396
        """
        return the current number of worker
        """
        if self._check_role_generation():
397
            return int(self._get_size() / self._proc_per_node)
398
        return 0
D
dongdaxiang 已提交
399

400
    def _server_num(self):
401 402 403 404
        """
        return the current number of server
        """
        if self._check_role_generation():
405
            return int(self._get_size() / self._proc_per_node)
G
guru4elephant 已提交
406 407
        else:
            self.generate_role()
408
            return int(self._get_size() / self._proc_per_node)
D
dongdaxiang 已提交
409

T
tangwei12 已提交
410
    def worker_index(self):
411 412 413 414
        """
        return the index of worker
        """
        if self._check_role_generation():
415
            return int(self._rank / self._proc_per_node)
G
guru4elephant 已提交
416 417
        else:
            self.generate_role()
418
            return int(self._get_size() / 2)
D
dongdaxiang 已提交
419

T
tangwei12 已提交
420
    def server_index(self):
421 422 423 424
        """
        return the index of server
        """
        if self._check_role_generation():
425
            return int(self._rank / self._proc_per_node)
G
guru4elephant 已提交
426 427
        else:
            self.generate_role()
428
            return int(self._get_size() / self._proc_per_node)
D
dongdaxiang 已提交
429

X
xujiaqi01 已提交
430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451
    def _all_reduce(self, input, output, mode="sum"):
        """
        all reduce between trainers if current role is TRAINER,
        only support array of one dim.

        Args:
            input(list/numpy.array): array of one dim
            output(list/numpy.array): array of one dim
            mode(str): "sum" or "min" or "max"
        """
        if not self._role_is_generated:
            self.generate_role()
        if mode == "sum":
            mode = self.MPI.SUM
        elif mode == "max":
            mode = self.MPI.MAX
        elif mode == "min":
            mode = self.MPI.MIN
        else:
            raise ValueError("unknown mode: %s" % mode)
        self._node_type_comm.Allreduce(input, output, op=mode)

452
    def _barrier_worker(self):
453 454 455 456
        """
        barrier all workers in current distributed job
        """
        if self._check_role_generation():
T
tangwei12 已提交
457
            if self.is_worker():
D
dongdaxiang 已提交
458
                self._node_type_comm.barrier()
G
guru4elephant 已提交
459 460
        else:
            raise Exception("You should check role generation first")
D
dongdaxiang 已提交
461

462
    def _barrier_server(self):
463 464 465 466
        """
        barrier all servers in current distributed job
        """
        if self._check_role_generation():
T
tangwei12 已提交
467
            if self.is_server():
D
dongdaxiang 已提交
468
                self._node_type_comm.barrier()
G
guru4elephant 已提交
469 470
        else:
            raise Exception("You should check role generation first")
D
dongdaxiang 已提交
471

T
tangwei12 已提交
472
    def generate_role(self):
473 474 475
        """
        generate currently process's role
        """
D
dongdaxiang 已提交
476
        if not self._role_is_generated:
477
            # TODO(guru4elephant): only allow to be called once
478 479
            self._worker_endpoints = self._get_ips()[1::2]
            self._server_endpoints = self._get_ips()[::2]
480

D
dongdaxiang 已提交
481 482
            if 0 == self._get_rank() % self._proc_per_node % 2:
                self._node_type = 0
483
            else:
D
dongdaxiang 已提交
484 485 486
                self._node_type = 1
            self._node_type_comm = self._comm.Split(self._node_type)
            self._role_is_generated = True
G
guru4elephant 已提交
487 488
        else:
            raise Exception("You should check role generation first")
489 490


491
class PaddleCloudRoleMaker(RoleMakerBase):
X
xujiaqi01 已提交
492 493 494 495 496
    """
    role maker for paddle cloud,
    base class is RoleMakerBase
    """

497
    def __init__(self, is_collective=False):
498
        super().__init__()
499
        self._role_is_generated = False
500
        self._is_collective = is_collective
501 502

    def generate_role(self):
X
xujiaqi01 已提交
503
        """Generate role."""
504
        if not self._role_is_generated:
505
            if not self._is_collective:
T
tangwei12 已提交
506
                try:
C
Chengmo 已提交
507 508 509
                    # Environment variable PADDLE_PSERVERS_IP_PORT_LIST must be set
                    # format: string(ip:port), eg. 127.0.0.1:6001
                    eplist = os.environ["PADDLE_PSERVERS_IP_PORT_LIST"].split(
510 511
                        ","
                    )
T
tangwei12 已提交
512 513 514 515 516 517 518 519 520
                    # note that, we usually assign the same port to different ips
                    # if we run parameter server training in local mode
                    # port should be different in environment variables

                    trainers_num = int(os.environ["PADDLE_TRAINERS_NUM"])
                    training_role = os.environ["TRAINING_ROLE"]

                    if training_role not in ["TRAINER", "PSERVER"]:
                        raise ValueError(
521 522
                            "TRAINING_ROLE must be PSERVER or TRAINER"
                        )
T
tangwei12 已提交
523 524 525 526 527 528 529

                    if training_role == "TRAINER":
                        role = Role.WORKER
                        current_id = int(os.environ["PADDLE_TRAINER_ID"])
                    elif training_role == "PSERVER":
                        role = Role.SERVER
                        cur_ip = os.environ["POD_IP"]
C
Chengmo 已提交
530 531 532
                        curr_port = os.environ["PADDLE_PORT"]
                        curr_endpoint = ":".join([cur_ip, curr_port])
                        current_id = eplist.index(curr_endpoint)
T
tangwei12 已提交
533 534
                    else:
                        raise ValueError(
535 536
                            "TRAINING_ROLE must be PSERVER or TRAINER"
                        )
T
tangwei12 已提交
537 538 539 540 541 542 543 544 545
                except ValueError as ve:
                    raise ValueError(
                        "something wrong with PaddleCloud, please check environment"
                    )

                self._trainers_num = trainers_num
                self._server_endpoints = eplist
                self._role = role
                self._current_id = current_id
546
            else:
547
                self._current_id = int(os.getenv("PADDLE_TRAINER_ID", "0"))
548 549 550 551
                self._training_role = os.getenv(
                    "PADDLE_TRAINING_ROLE", "TRAINER"
                )
                assert self._training_role == "TRAINER"
552 553
                self._worker_endpoints = os.getenv("PADDLE_TRAINER_ENDPOINTS")
                self._current_endpoint = os.getenv("PADDLE_CURRENT_ENDPOINT")
554 555 556
                assert (
                    self._worker_endpoints is not None
                ), "can't find PADDLE_TRAINER_ENDPOINTS"
557 558 559
                self._worker_endpoints = self._worker_endpoints.split(",")
                self._trainers_num = len(self._worker_endpoints)

560 561
            self._role_is_generated = True

562 563 564 565 566
    def get_pserver_endpoints(self):
        if not self._role_is_generated:
            self.generate_role()
        return self._server_endpoints

567 568 569
    def is_worker(self):
        if not self._role_is_generated:
            self.generate_role()
570 571 572
        return self._role == Role.WORKER

    def is_server(self):
573 574
        if not self._role_is_generated:
            self.generate_role()
575 576 577
        return self._role == Role.SERVER

    def is_first_worker(self):
578 579
        if not self._role_is_generated:
            self.generate_role()
580 581 582
        return self._role == Role.WORKER and self._current_id == 0

    def worker_index(self):
583 584
        if not self._role_is_generated:
            self.generate_role()
585 586 587
        return self._current_id

    def server_index(self):
588 589
        if not self._role_is_generated:
            self.generate_role()
590 591 592
        return self._current_id

    def worker_num(self):
593 594
        if not self._role_is_generated:
            self.generate_role()
595
        return self._trainers_num
596 597


X
xujiaqi01 已提交
598 599 600
class GeneralRoleMaker(RoleMakerBase):
    """
    This role maker is for general use, you can set os.environ to customize:
T
tianshuo78520a 已提交
601 602
        PADDLE_PSERVERS_IP_PORT_LIST : all pservers' ip:port, separated by ','
        PADDLE_TRAINER_ENDPOINTS     : all trainers' ip:port, separated by ','
X
xujiaqi01 已提交
603 604 605 606 607 608 609 610
        TRAINING_ROLE                : TRAINER or PSERVER
        PADDLE_TRAINER_ID            : current trainer id (only for trainer),
                                       it is index in PADDLE_TRAINER_ENDPOINTS
        PADDLE_PSERVER_ID            : current pserver id (only for pserver)
                                       it is index in PADDLE_PSERVERS_IP_PORT_LIST
    """

    def __init__(self, **kwargs):
611
        super().__init__()
X
xujiaqi01 已提交
612 613 614
        self._role_is_generated = False
        self._hdfs_name = kwargs.get("hdfs_name", "")
        self._hdfs_ugi = kwargs.get("hdfs_ugi", "")
615 616 617
        self._hdfs_path = kwargs.get("path", "").rstrip("/")
        self._init_timeout_seconds = kwargs.get("init_timeout_seconds", 3600)
        self._run_timeout_seconds = kwargs.get("run_timeout_seconds", 9999999)
618
        self._use_metric = kwargs.get("use_metric", False)
619
        ip_port = kwargs.get("http_ip_port", "")
620
        self._use_ps_gpu = kwargs.get("use_ps_gpu", False)
621 622 623 624 625 626 627 628 629 630 631
        self._http_ip_port = []
        self._http_server = None
        # if ip_port is not empty, it will use http instead of hdfs
        if ip_port != "":
            self._http_ip_port = ip_port.split(":")
            # it's for communication between processes
            self._manager = Manager()
            # global dict to store status
            self._http_server_d = self._manager.dict()
            # set running status of http server
            self._http_server_d["running"] = False
X
xujiaqi01 已提交
632
        self._iface = self.__get_default_iface()
633
        self._iface = "" if self._iface == "lo" else self._iface
X
xujiaqi01 已提交
634 635 636 637 638 639 640 641 642 643 644 645 646 647
        # this environment variable can be empty
        self._prefix = os.getenv("SYS_JOB_ID", "")

    def generate_role(self):
        """
        generate role for general role maker
        """
        if not self._role_is_generated:
            eplist = os.environ["PADDLE_PSERVERS_IP_PORT_LIST"].split(",")
            training_role = os.environ["TRAINING_ROLE"]
            worker_endpoints = os.environ["PADDLE_TRAINER_ENDPOINTS"].split(",")
            trainers_num = len(worker_endpoints)
            if training_role not in ["TRAINER", "PSERVER"]:
                raise ValueError("TRAINING_ROLE must be PSERVER or TRAINER")
X
xujiaqi01 已提交
648 649
            self._is_barrier_all = 1
            if "PADDLE_IS_BARRIER_ALL_ROLE" in os.environ:
650
                self._is_barrier_all = int(
651 652
                    os.environ["PADDLE_IS_BARRIER_ALL_ROLE"]
                )
X
xujiaqi01 已提交
653 654 655
            if training_role == "TRAINER":
                role = Role.WORKER
                current_id = int(os.environ["PADDLE_TRAINER_ID"])
656 657 658 659
                if current_id == 0 and len(self._http_ip_port) != 0:
                    size_d = {
                        "trainer": len(worker_endpoints),
                        "pserver": len(eplist),
660
                        "all": len(worker_endpoints) + len(eplist),
661 662
                    }
                    # child process for http server
663 664 665 666
                    self._http_server = Process(
                        target=self.__start_kv_server,
                        args=(self._http_server_d, size_d),
                    )
667 668 669 670 671
                    self._http_server.daemon = True
                    # set running status to True
                    self._http_server_d["running"] = True
                    # start child process
                    self._http_server.start()
X
xujiaqi01 已提交
672 673
                self._node_type = 1
                self._cur_endpoint = worker_endpoints[current_id]
X
xujiaqi01 已提交
674 675 676 677 678 679
                if self._is_barrier_all:
                    gloo = fluid.core.Gloo()
                    gloo.set_rank(current_id)
                    gloo.set_size(len(worker_endpoints))
                    gloo.set_prefix(self._prefix)
                    gloo.set_iface(self._iface)
680 681 682
                    gloo.set_timeout_seconds(
                        self._init_timeout_seconds, self._run_timeout_seconds
                    )
X
xujiaqi01 已提交
683
                    if len(self._http_ip_port) != 0:
684 685 686 687 688
                        gloo.set_http_store(
                            self._http_ip_port[0],
                            int(self._http_ip_port[1]),
                            "trainer",
                        )
X
xujiaqi01 已提交
689
                    else:
690 691 692 693 694
                        gloo.set_hdfs_store(
                            self._hdfs_path + "/trainer",
                            self._hdfs_name,
                            self._hdfs_ugi,
                        )
X
xujiaqi01 已提交
695 696
                    gloo.init()
                    self._node_type_comm = gloo
697
                    if self._use_ps_gpu or self._use_metric:
698 699 700 701 702 703 704
                        Gloo_strategy = fluid.core.GlooParallelStrategy()
                        Gloo_strategy.rank = current_id
                        Gloo_strategy.rank_num = len(worker_endpoints)
                        Gloo_strategy.ip_address = self._http_ip_port[0]
                        Gloo_strategy.ip_port = int(self._http_ip_port[1])
                        Default_init_timeout_seconds = 3600
                        Default_run_timeout_seconds = 9999999
705 706 707
                        Gloo_strategy.init_seconds = (
                            Default_init_timeout_seconds
                        )
708 709 710
                        Gloo_strategy.run_seconds = Default_run_timeout_seconds
                        Gloo = fluid.core.GlooParallelContext(Gloo_strategy)
                        Gloo.init()
711
                else:
X
xujiaqi01 已提交
712
                    self._all_comm = MockBarrier()
X
xujiaqi01 已提交
713 714 715 716 717 718 719 720 721 722 723 724 725
            elif training_role == "PSERVER":
                role = Role.SERVER
                if os.environ.get("PADDLE_PSERVER_ID") is not None:
                    current_id = int(os.environ["PADDLE_PSERVER_ID"])
                    cur_endpoint = eplist[current_id]
                else:
                    # this is for compatible with paddlecloud
                    cur_ip = os.environ["POD_IP"]
                    cur_port = os.environ["PADDLE_PORT"]
                    cur_endpoint = ":".join([cur_ip, cur_port])
                    current_id = eplist.index(cur_endpoint)
                self._node_type = 0
                self._cur_endpoint = cur_endpoint
726
                gloo = fluid.core.Gloo()
727 728 729 730
                gloo.set_rank(current_id)
                gloo.set_size(len(eplist))
                gloo.set_prefix(self._prefix)
                gloo.set_iface(self._iface)
731 732 733
                gloo.set_timeout_seconds(
                    self._init_timeout_seconds, self._run_timeout_seconds
                )
734
                if len(self._http_ip_port) != 0:
735 736 737 738 739
                    gloo.set_http_store(
                        self._http_ip_port[0],
                        int(self._http_ip_port[1]),
                        "pserver",
                    )
740
                else:
741 742 743 744 745
                    gloo.set_hdfs_store(
                        self._hdfs_path + "/pserver",
                        self._hdfs_name,
                        self._hdfs_ugi,
                    )
746
                gloo.init()
X
xujiaqi01 已提交
747 748
                self._node_type_comm = gloo

749
            gloo = fluid.core.Gloo()
X
xujiaqi01 已提交
750
            all_list = worker_endpoints + eplist
751 752 753 754
            gloo.set_rank(all_list.index(self._cur_endpoint))
            gloo.set_size(len(all_list))
            gloo.set_prefix(self._prefix)
            gloo.set_iface(self._iface)
755 756 757
            gloo.set_timeout_seconds(
                self._init_timeout_seconds, self._run_timeout_seconds
            )
758
            if len(self._http_ip_port) != 0:
759 760 761
                gloo.set_http_store(
                    self._http_ip_port[0], int(self._http_ip_port[1]), "all"
                )
762
            else:
763 764 765
                gloo.set_hdfs_store(
                    self._hdfs_path + "/all", self._hdfs_name, self._hdfs_ugi
                )
766
            gloo.init()
X
xujiaqi01 已提交
767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004
            self._all_comm = gloo
            self._trainers_num = trainers_num
            self._server_endpoints = eplist
            self._role = role
            self._current_id = current_id
            self._rank = all_list.index(self._cur_endpoint)
            self._size = len(all_list)
            self._worker_endpoints = worker_endpoints
            self._role_is_generated = True

    def all_gather(self, input):
        """
        all gather between trainers and pservers

        Args:
            input(int|float): input value

        Returns:
            return a list of values
        """
        return self._all_gather(input)

    def all_reduce_worker(self, input, output, mode="sum"):
        """
        all reduce between trainers if current role is TRAINER,
        only support array of one dim.

        Args:
            input(list/numpy.array): array of one dim
            output(list/numpy.array): array of one dim
            mode(str): "sum" or "min" or "max"
        """
        if not self.is_worker():
            return
        self._all_reduce(input, output, mode)

    def barrier_worker(self):
        """
        barrier between trainers if current role is TRAINER
        """
        self._barrier_worker()

    def barrier_all(self):
        """
        barrier between trainers if current role is PSERVER
        """
        self._barrier_all()

    def get_local_endpoint(self):
        """
        get local endpoint of current process
        """
        if not self._role_is_generated:
            self.generate_role()
        return self._cur_endpoint

    def get_trainer_endpoints(self):
        """
        get endpoint of all trainers
        """
        if not self._role_is_generated:
            self.generate_role()
        return self._worker_endpoints

    def get_pserver_endpoints(self):
        """
        get endpoint of all pservers
        """
        if not self._role_is_generated:
            self.generate_role()
        return self._server_endpoints

    def is_worker(self):
        """
        whether current process is worker
        """
        if not self._role_is_generated:
            self.generate_role()
        return self._role == Role.WORKER

    def is_server(self):
        """
        whether current process is server
        """
        if not self._role_is_generated:
            self.generate_role()
        return self._role == Role.SERVER

    def is_first_worker(self):
        """
        whether current process is worker of rank 0
        """
        if not self._role_is_generated:
            self.generate_role()
        return self._role == Role.WORKER and self._current_id == 0

    def worker_index(self):
        """
        get index of current worker
        """
        if not self._role_is_generated:
            self.generate_role()
        return self._current_id

    def server_index(self):
        """
        get index of current server
        """
        if not self._role_is_generated:
            self.generate_role()
        return self._current_id

    def worker_num(self):
        """
        retrun the current number of worker
        """
        if not self._role_is_generated:
            self.generate_role()
        return self._worker_num()

    def server_num(self):
        """
        return the current number of server
        """
        if not self._role_is_generated:
            self.generate_role()
        return self._server_num()

    def _barrier_worker(self):
        """
        barrier all workers in current distributed job
        """
        if not self._role_is_generated:
            self.generate_role()
        if self.is_worker():
            self._node_type_comm.barrier()

    def _barrier_all(self):
        """
        barrier all workers and servers in current distributed job
        """
        if not self._role_is_generated:
            self.generate_role()
        self._all_comm.barrier()

    def _barrier_server(self):
        """
        barrier all servers in current distributed job
        """
        if not self._role_is_generated:
            self.generate_role()
        if self.is_server():
            self._node_type_comm.barrier()

    def _worker_num(self):
        """
        return the current number of worker
        """
        if not self._role_is_generated:
            self.generate_role()
        return self._trainers_num

    def _server_num(self):
        """
        return the current number of server
        """
        if not self._role_is_generated:
            self.generate_role()
        return len(self._server_endpoints)

    def _finalize(self):
        """Default do nothing."""
        pass

    def _all_reduce(self, input, output, mode="sum"):
        """
        all reduce between all workers

        Args:
            input(list|numpy.array): array of one dim
            output(list|numpy.array): array of one dim
            mode(str): "sum" or "min" or "max"
        """
        if not self._role_is_generated:
            self.generate_role()
        input_list = [i for i in input]
        ans = self._node_type_comm.all_reduce(input_list, mode)
        for i in range(len(ans)):
            output[i] = ans[i]

    def _all_gather(self, obj):
        """
        gather between all workers and pservers
        """
        if not self._role_is_generated:
            self.generate_role()
        self._barrier_all()
        return self._all_comm.all_gather(obj)

    def _worker_gather(self, obj):
        """
        gather between all workers
        """
        if not self._role_is_generated:
            self.generate_role()
        if not self.is_worker():
            return None
        self._barrier_worker()
        return self._node_type_comm.all_gather(obj)

    def _get_rank(self):
        """
        get current rank in all workers and pservers
        """
        if not self._role_is_generated:
            self.generate_role()
        return self._rank

    def _get_size(self):
        """
        get total num of all workers and pservers
        """
        if not self._role_is_generated:
            self.generate_role()
        return self._size

    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 已提交
1005 1006 1007 1008 1009 1010 1011 1012 1013
        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")
1014
            elif gateway_idx is not None and iface_idx is not None:
1
123malin 已提交
1015 1016 1017
                gateway = None
                if len(item) > gateway_idx:
                    gateway = item[gateway_idx]
1018 1019 1020 1021 1022 1023
                if (
                    gateway
                    and gateway != '*'
                    and gateway != "0.0.0.0"
                    and len(item) > iface_idx
                ):
1
123malin 已提交
1024
                    return item[iface_idx]
X
xujiaqi01 已提交
1025 1026 1027 1028 1029 1030
        return "lo"

    def __get_default_iface_from_interfaces(self):
        """
        get default physical interface
        """
1031 1032 1033
        res = (
            os.popen("ip -f inet addr | awk NR%3==1").read().strip().split("\n")
        )
1
123malin 已提交
1034 1035 1036
        for item in res:
            if "BROADCAST" in item:
                return item.split(":")[1].strip()
X
xujiaqi01 已提交
1037 1038
        return "lo"

1039
    def __start_kv_server(self, http_server_d, size_d):
meteor135's avatar
meteor135 已提交
1040
        from paddle.distributed.launch.utils.kv_server import KVServer
1041

1042 1043 1044
        http_server = KVServer(int(self._http_ip_port[1]), size_d)
        http_server.start()
        wait_seconds = 5
1045
        while http_server_d.get("running", False):
1046 1047 1048
            time.sleep(wait_seconds)
        http_server.stop()

X
xujiaqi01 已提交
1049

T
Thunderbrook 已提交
1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074
class HeterRoleMaker(GeneralRoleMaker):
    """
    This role maker is for general use, you can set os.environ to customize:
        PADDLE_PSERVERS_IP_PORT_LIST : all pservers' ip:port, separated by ','
        PADDLE_TRAINER_ENDPOINTS     : all trainers' ip:port, separated by ','
        TRAINING_ROLE                : TRAINER or PSERVER
        PADDLE_TRAINER_ID            : current trainer id (only for trainer),
                                       it is index in PADDLE_TRAINER_ENDPOINTS
        PADDLE_PSERVER_ID            : current pserver id (only for pserver)
                                       it is index in PADDLE_PSERVERS_IP_PORT_LIST
    """

    def generate_role(self):
        """
        generate role for general role maker
        """
        if not self._role_is_generated:
            eplist = os.environ["PADDLE_PSERVERS_IP_PORT_LIST"].split(",")
            training_role = os.environ["TRAINING_ROLE"]
            worker_endpoints = os.environ["PADDLE_TRAINER_ENDPOINTS"].split(",")
            trainers_num = len(worker_endpoints)
            xpu_endpoints = os.environ["PADDLE_XPU_ENDPOINTS"].split(",")
            xpu_num = len(xpu_endpoints)
            if training_role not in ["TRAINER", "PSERVER", "XPU"]:
                raise ValueError(
1075 1076
                    "TRAINING_ROLE must be PSERVER or TRAINER or XPU"
                )
T
Thunderbrook 已提交
1077 1078 1079 1080 1081 1082
            if training_role == "TRAINER":
                role = Role.WORKER
                current_id = int(os.environ["PADDLE_TRAINER_ID"])
                self._node_type = 1
                self._cur_endpoint = worker_endpoints[current_id]
                gloo = fluid.core.Gloo()
T
Thunderbrook 已提交
1083 1084 1085 1086 1087

                gloo.set_rank(current_id)
                gloo.set_size(len(worker_endpoints))
                gloo.set_prefix(self._prefix)
                gloo.set_iface(self._iface)
1088 1089 1090
                gloo.set_timeout_seconds(
                    self._init_timeout_seconds, self._run_timeout_seconds
                )
T
Thunderbrook 已提交
1091
                gloo.set_hdfs_store(
1092 1093 1094 1095
                    self._hdfs_path.rstrip("/") + "/trainer",
                    self._hdfs_name,
                    self._hdfs_ugi,
                )
T
Thunderbrook 已提交
1096
                gloo.init()
T
Thunderbrook 已提交
1097 1098 1099 1100 1101 1102 1103
                self._node_type_comm = gloo
            elif training_role == "XPU":
                role = Role.XPU
                current_id = int(os.environ["PADDLE_XPU_ID"])
                self._node_type = 2
                self._cur_endpoint = xpu_endpoints[current_id]
                gloo = fluid.core.Gloo()
T
Thunderbrook 已提交
1104 1105 1106 1107 1108

                gloo.set_rank(current_id)
                gloo.set_size(len(xpu_endpoints))
                gloo.set_prefix(self._prefix)
                gloo.set_iface(self._iface)
1109 1110 1111
                gloo.set_timeout_seconds(
                    self._init_timeout_seconds, self._run_timeout_seconds
                )
T
Thunderbrook 已提交
1112
                gloo.set_hdfs_store(
1113 1114 1115 1116
                    self._hdfs_path.rstrip("/") + "/xpu",
                    self._hdfs_name,
                    self._hdfs_ugi,
                )
T
Thunderbrook 已提交
1117
                gloo.init()
T
Thunderbrook 已提交
1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132
                self._node_type_comm = gloo
            elif training_role == "PSERVER":
                role = Role.SERVER
                if os.environ.get("PADDLE_PSERVER_ID") is not None:
                    current_id = int(os.environ["PADDLE_PSERVER_ID"])
                    cur_endpoint = eplist[current_id]
                else:
                    # this is for compatible with paddlecloud
                    cur_ip = os.environ["POD_IP"]
                    cur_port = os.environ["PADDLE_PORT"]
                    cur_endpoint = ":".join([cur_ip, cur_port])
                    current_id = eplist.index(cur_endpoint)
                self._node_type = 0
                self._cur_endpoint = cur_endpoint
                gloo = fluid.core.Gloo()
T
Thunderbrook 已提交
1133 1134 1135 1136
                gloo.set_rank(current_id)
                gloo.set_size(len(eplist))
                gloo.set_prefix(self._prefix)
                gloo.set_iface(self._iface)
1137 1138 1139
                gloo.set_timeout_seconds(
                    self._init_timeout_seconds, self._run_timeout_seconds
                )
T
Thunderbrook 已提交
1140
                gloo.set_hdfs_store(
1141 1142 1143 1144
                    self._hdfs_path.rstrip("/") + "/pserver",
                    self._hdfs_name,
                    self._hdfs_ugi,
                )
T
Thunderbrook 已提交
1145
                gloo.init()
T
Thunderbrook 已提交
1146 1147 1148 1149 1150
                self._node_type_comm = gloo

            if training_role == "TRAINER" or training_role == "XPU":
                gloo = fluid.core.Gloo()
                heter_list = worker_endpoints + xpu_endpoints
T
Thunderbrook 已提交
1151 1152 1153 1154 1155

                gloo.set_rank(heter_list.index(self._cur_endpoint))
                gloo.set_size(len(heter_list))
                gloo.set_prefix(self._prefix)
                gloo.set_iface(self._iface)
1156 1157 1158
                gloo.set_timeout_seconds(
                    self._init_timeout_seconds, self._run_timeout_seconds
                )
T
Thunderbrook 已提交
1159
                gloo.set_hdfs_store(
1160 1161 1162 1163
                    self._hdfs_path.rstrip("/") + "/heter",
                    self._hdfs_name,
                    self._hdfs_ugi,
                )
T
Thunderbrook 已提交
1164
                gloo.init()
T
Thunderbrook 已提交
1165 1166 1167 1168
                self._heter_comm = gloo

            gloo = fluid.core.Gloo()
            all_list = worker_endpoints + eplist + xpu_endpoints
T
Thunderbrook 已提交
1169 1170 1171 1172 1173

            gloo.set_rank(all_list.index(self._cur_endpoint))
            gloo.set_size(len(all_list))
            gloo.set_prefix(self._prefix)
            gloo.set_iface(self._iface)
1174 1175 1176
            gloo.set_timeout_seconds(
                self._init_timeout_seconds, self._run_timeout_seconds
            )
T
Thunderbrook 已提交
1177
            gloo.set_hdfs_store(
1178 1179 1180 1181
                self._hdfs_path.rstrip("/") + "/all",
                self._hdfs_name,
                self._hdfs_ugi,
            )
T
Thunderbrook 已提交
1182
            gloo.init()
T
Thunderbrook 已提交
1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229

            self._all_comm = gloo
            self._trainers_num = trainers_num
            self._server_endpoints = eplist
            self._role = role
            self._current_id = current_id
            self._rank = all_list.index(self._cur_endpoint)
            self._size = len(all_list)
            self._worker_endpoints = worker_endpoints
            self._xpu_endpoints = xpu_endpoints
            self._role_is_generated = True

    def is_xpu(self):
        """
        whether current process is server
        """
        if not self._role_is_generated:
            self.generate_role()
        return self._role == Role.XPU

    def is_first_xpu(self):
        """
        whether current process is worker of rank 0
        """
        if not self._role_is_generated:
            self.generate_role()
        return self._role == Role.XPU and self._current_id == 0

    def _barrier_xpu(self):
        """
        barrier all workers in current distributed job
        """
        if not self._role_is_generated:
            self.generate_role()
        if self.is_xpu():
            self._node_type_comm.barrier()

    def _barrier_heter(self):
        """
        barrier all workers in current distributed job
        """
        if not self._role_is_generated:
            self.generate_role()
        if self.is_xpu() or self.is_worker:
            self._heter_comm.barrier()

    def xpu_num(self):
1230
        """ """
T
Thunderbrook 已提交
1231 1232 1233 1234 1235
        if not self._role_is_generated:
            self.generate_role()
        return len(self._xpu_endpoints)


1236
class UserDefinedRoleMaker(RoleMakerBase):
X
xujiaqi01 已提交
1237 1238 1239 1240 1241 1242
    """
    UserDefinedRoleMaker is designed for worker and server assignment
    under manual. Typically, a worker and a server node will be appointed
    on each physical node, It can be assign by user.
    """

1243 1244 1245 1246 1247 1248 1249
    def __init__(
        self,
        current_id=0,
        role=Role.WORKER,
        worker_num=0,
        server_endpoints=None,
    ):
1250
        super().__init__()
1251

1252 1253 1254 1255
        if not isinstance(server_endpoints, list):
            raise TypeError("server_endpoints must be as string list")
        elif len(server_endpoints) <= 0:
            raise ValueError(
1256 1257
                "the length of server_endpoints list must be greater than 0"
            )
1258 1259
        elif len(server_endpoints) != len(set(server_endpoints)):
            raise ValueError("server_endpoints can't have duplicate elements")
1260
        else:
1261 1262 1263 1264 1265 1266
            for server_endpoint in server_endpoints:
                if not isinstance(server_endpoint, str):
                    raise TypeError(
                        "every element in server_endpoints list must be as string"
                    )
            self._server_endpoints = server_endpoints
1267

T
tangwei12 已提交
1268
        if role != Role.WORKER and role != Role.SERVER:
1269 1270 1271 1272
            raise TypeError("role must be as Role")
        else:
            self._role = role

1273 1274 1275 1276 1277
        if not isinstance(current_id, int):
            raise TypeError("current_id must be as int")
        else:
            if current_id < 0:
                raise ValueError(
1278 1279
                    "current_id must be greater than or equal to 0"
                )
1280
            elif self._role == Role.SERVER and current_id >= len(
1281 1282
                server_endpoints
            ):
1283 1284 1285 1286 1287
                raise ValueError(
                    "if role is Role.SERVER, current_id must be less than or equal to len(server_endpoints) - 1"
                )
            self._current_id = current_id

1288 1289 1290
        if not isinstance(worker_num, int):
            raise TypeError("worker_num must be as int")
        else:
1291 1292
            if worker_num <= 0:
                raise ValueError("worker_num must be greater than 0")
1293 1294
            self._worker_num = worker_num

1295 1296 1297
    def generate_role(self):
        self._role_is_generated = True

T
tangwei12 已提交
1298 1299 1300 1301 1302
    def is_worker(self):
        return self._role == Role.WORKER

    def is_server(self):
        return self._role == Role.SERVER
1303

T
tangwei12 已提交
1304 1305
    def is_first_worker(self):
        return self._role == Role.WORKER and self._current_id == 0
1306

T
tangwei12 已提交
1307 1308
    def worker_index(self):
        return self._current_id
1309

T
tangwei12 已提交
1310 1311
    def server_index(self):
        return self._current_id
1312 1313 1314

    def worker_num(self):
        return self._worker_num
1315 1316 1317


class UserDefinedCollectiveRoleMaker(RoleMakerBase):
X
xujiaqi01 已提交
1318 1319 1320 1321 1322
    """
    UserDefinedCollectiveRoleMaker is designed for worker assignment
    under manual for collective mode.
    """

1323
    def __init__(self, current_id=0, worker_endpoints=None):
1324
        super().__init__()
1325

1326 1327 1328 1329
        if not isinstance(worker_endpoints, list):
            raise TypeError("worker_endpoints must be as string list")
        elif len(worker_endpoints) <= 0:
            raise ValueError(
1330 1331
                "the length of worker_endpoints list must be greater than 0"
            )
1332 1333 1334 1335 1336 1337 1338 1339 1340 1341
        elif len(worker_endpoints) != len(set(worker_endpoints)):
            raise ValueError("worker_endpoints can't have duplicate elements")
        else:
            for worker_endpoint in worker_endpoints:
                if not isinstance(worker_endpoint, str):
                    raise TypeError(
                        "every element in worker_endpoints list must be as string"
                    )
            self._worker_endpoints = worker_endpoints

1342 1343 1344 1345
        if not isinstance(current_id, int):
            raise TypeError("current_id must be as int")
        else:
            if current_id < 0:
1346
                raise ValueError(
1347 1348
                    "current_id must be greater than or equal to 0"
                )
1349 1350 1351 1352
            elif current_id >= len(worker_endpoints):
                raise ValueError(
                    "current_id must be less than or equal to len(worker_endpoints) - 1"
                )
1353 1354 1355 1356
            self._current_id = current_id

        self._worker_num = len(self._worker_endpoints)

1357 1358 1359
    def generate_role(self):
        self._role_is_generated = True

1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370
    def is_worker(self):
        return True

    def is_first_worker(self):
        return self._current_id == 0

    def worker_index(self):
        return self._current_id

    def worker_num(self):
        return self._worker_num