role_maker.py 13.1 KB
Newer Older
D
dongdaxiang 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#   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.

T
tangwei12 已提交
15
from __future__ import print_function
16

T
tangwei12 已提交
17
__all__ = [
18
    'Role', 'RoleMakerBase', 'MPISymetricRoleMaker', 'UserDefinedRoleMaker',
19
    'UserDefinedCollectiveRoleMaker', 'PaddleCloudRoleMaker'
T
tangwei12 已提交
20 21
]

22 23
import os

24

T
tangwei12 已提交
25 26
class Role:
    WORKER = 1
27 28
    SERVER = 2

D
dongdaxiang 已提交
29 30

class RoleMakerBase(object):
31 32 33 34 35 36 37
    """
    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 已提交
38
    def __init__(self):
T
tangwei12 已提交
39 40
        self._worker_endpoints = []
        self._server_endpoints = []
D
dongdaxiang 已提交
41
        self._role_is_generated = False
T
tangwei12 已提交
42 43
        self._role = None
        self._current_id = -1
D
dongdaxiang 已提交
44

T
tangwei12 已提交
45
    def is_worker(self):
46 47 48
        """
        return is_worker() of current process
        """
D
dongdaxiang 已提交
49 50
        raise NotImplementedError("Please implement this method in child class")

T
tangwei12 已提交
51
    def is_server(self):
52 53 54
        """
        return is_server() of current process
        """
D
dongdaxiang 已提交
55 56
        raise NotImplementedError("Please implement this method in child class")

T
tangwei12 已提交
57
    def is_first_worker(self):
58
        """
T
tangwei12 已提交
59 60 61 62
        Check whether the node is the first instance of worker.
        Returns:
            bool: True if this is the first node of worker,
                  False if not.
63
        """
T
tangwei12 已提交
64
        raise NotImplementedError("Please implement this method in child class")
D
dongdaxiang 已提交
65

66 67 68 69 70 71 72 73 74
    def worker_num(self):
        """
        Get current total worker number.

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

T
tangwei12 已提交
75
    def worker_index(self):
76
        """
T
tangwei12 已提交
77 78 79 80
        Get current worker id.

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

T
tangwei12 已提交
84
    def server_index(self):
85
        """
T
tangwei12 已提交
86 87 88 89
        Get current server id.

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

T
tangwei12 已提交
93
    def get_trainer_endpoints(self):
94
        """
T
tangwei12 已提交
95
        return trainer endpoints
96
        """
T
tangwei12 已提交
97 98 99 100 101 102 103
        return self._worker_endpoints

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


class MPIRoleMaker(RoleMakerBase):
107 108 109 110 111
    """
    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 已提交
112
    def __init__(self):
X
xujiaqi01 已提交
113
        super(MPIRoleMaker, self).__init__()
D
dongdaxiang 已提交
114 115
        from mpi4py import MPI
        self.MPI = MPI
T
tangwei12 已提交
116 117
        self._comm = MPI.COMM_WORLD
        self._node_type_comm = None
D
dongdaxiang 已提交
118
        self._ips = None
T
tangwei12 已提交
119
        self._ip = None
D
dongdaxiang 已提交
120

121
    def _get_rank(self):
122 123 124
        """
        return rank
        """
D
dongdaxiang 已提交
125 126
        self._rank = self._comm.Get_rank()
        return self._rank
D
dongdaxiang 已提交
127

128
    def _get_size(self):
129 130 131
        """
        return size
        """
D
dongdaxiang 已提交
132 133
        self._size = self._comm.Get_size()
        return self._size
D
dongdaxiang 已提交
134

135
    def _all_gather(self, obj):
136 137 138
        """
        all_gather(obj) will call MPI's allgather function
        """
X
xjqbest 已提交
139
        self._barrier_all()
D
dongdaxiang 已提交
140
        return self._comm.allgather(obj)
D
dongdaxiang 已提交
141

X
xjqbest 已提交
142 143 144 145
    def _worker_gather(self, obj):
        """
        worker_gather(obj) will call MPI's allgather function
        """
T
tangwei12 已提交
146
        if self.is_worker():
D
dongdaxiang 已提交
147 148
            self._node_type_comm.barrier()
            return self._node_type_comm.allgather(obj)
X
xjqbest 已提交
149 150
        return None

151
    def _barrier_all(self):
152 153 154
        """
        barrier_all() will call MPI's barrier_all function
        """
D
dongdaxiang 已提交
155
        self._comm.barrier()
D
dongdaxiang 已提交
156

T
tangwei12 已提交
157 158 159 160 161 162
    def _finalize(self):
        """
        finalize the current MPI instance.
        """
        pass

163
    def _get_ips(self):
164 165 166
        """
        collect current distributed job's ip list
        """
T
tangwei12 已提交
167 168
        if not self._ips:
            self._ips = self._comm.allgather(self.get_local_ip())
D
dongdaxiang 已提交
169
        return self._ips
D
dongdaxiang 已提交
170

T
tangwei12 已提交
171
    def get_local_ip(self):
172
        """
T
tangwei12 已提交
173
        return get local ip
174
        """
T
tangwei12 已提交
175 176 177 178 179 180 181 182 183
        import socket
        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 已提交
184 185 186


class MPISymetricRoleMaker(MPIRoleMaker):
187 188 189 190 191 192
    """
    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 已提交
193 194
    def __init__(self):
        super(MPISymetricRoleMaker, self).__init__()
D
dongdaxiang 已提交
195 196
        self._node_type = None
        self._proc_per_node = 2
D
dongdaxiang 已提交
197

198
    def _check_role_generation(self):
D
dongdaxiang 已提交
199
        if not self._role_is_generated:
T
tangwei12 已提交
200
            raise NameError("generate_role() should be called first")
201 202
        return True

T
tangwei12 已提交
203
    def is_first_worker(self):
204 205 206 207
        """
        return whether current process is the first worker assigned by role maker
        """
        if self._check_role_generation():
T
tangwei12 已提交
208
            return self.is_worker() and 0 == self.worker_index()
209
        return False
D
dongdaxiang 已提交
210

211 212 213
    def worker_num(self):
        return self._worker_num()

T
tangwei12 已提交
214
    def is_worker(self):
215 216 217 218
        """
        return whether current process is worker assigned by role maker
        """
        if self._check_role_generation():
D
dongdaxiang 已提交
219
            return self._node_type == 1
220
        return False
D
dongdaxiang 已提交
221

T
tangwei12 已提交
222
    def is_server(self):
223 224 225 226
        """
        return whether current process is server assigned by role maker
        """
        if self._check_role_generation():
D
dongdaxiang 已提交
227
            return self._node_type == 0
228
        return False
D
dongdaxiang 已提交
229

230
    def _worker_num(self):
231 232 233 234
        """
        return the current number of worker
        """
        if self._check_role_generation():
T
tangwei12 已提交
235
            if self.is_worker():
X
xjqbest 已提交
236
                return self._get_size() / 2
237
        return 0
D
dongdaxiang 已提交
238

239
    def _server_num(self):
240 241 242 243
        """
        return the current number of server
        """
        if self._check_role_generation():
T
tangwei12 已提交
244
            if self.is_server():
X
xjqbest 已提交
245
                return self._get_size() / 2
246
        return 0
D
dongdaxiang 已提交
247

T
tangwei12 已提交
248
    def worker_index(self):
249 250 251 252
        """
        return the index of worker
        """
        if self._check_role_generation():
D
dongdaxiang 已提交
253
            return self._rank / self._proc_per_node
254
        return 0
D
dongdaxiang 已提交
255

T
tangwei12 已提交
256
    def server_index(self):
257 258 259 260
        """
        return the index of server
        """
        if self._check_role_generation():
D
dongdaxiang 已提交
261
            return self._rank / self._proc_per_node
262
        return 0
D
dongdaxiang 已提交
263

264
    def _barrier_worker(self):
265 266 267 268
        """
        barrier all workers in current distributed job
        """
        if self._check_role_generation():
T
tangwei12 已提交
269
            if self.is_worker():
D
dongdaxiang 已提交
270
                self._node_type_comm.barrier()
D
dongdaxiang 已提交
271

272
    def _barrier_server(self):
273 274 275 276
        """
        barrier all servers in current distributed job
        """
        if self._check_role_generation():
T
tangwei12 已提交
277
            if self.is_server():
D
dongdaxiang 已提交
278
                self._node_type_comm.barrier()
D
dongdaxiang 已提交
279

T
tangwei12 已提交
280
    def generate_role(self):
281 282 283
        """
        generate currently process's role
        """
D
dongdaxiang 已提交
284
        if not self._role_is_generated:
285
            # TODO(guru4elephant): only allow to be called once
286 287
            self._worker_endpoints = self._get_ips()[1::2]
            self._server_endpoints = self._get_ips()[::2]
288

D
dongdaxiang 已提交
289 290
            if 0 == self._get_rank() % self._proc_per_node % 2:
                self._node_type = 0
291
            else:
D
dongdaxiang 已提交
292 293 294
                self._node_type = 1
            self._node_type_comm = self._comm.Split(self._node_type)
            self._role_is_generated = True
295 296


297 298 299
class PaddleCloudRoleMaker(RoleMakerBase):
    def __init__(self):
        super(PaddleCloudRoleMaker, self).__init__()
300
        self._role_is_generated = False
301 302 303 304 305 306

    def generate_role(self):
        if not self._role_is_generated:
            self.port = os.getenv("PADDLE_PORT", "6174")
            self.pserver_ips = os.getenv("PADDLE_PSERVERS", "")
            eplist = []
307 308 309 310 311 312 313 314
            for ip in self.pserver_ips.split(","):
                eplist.append(':'.join([ip, self.port]))
            self.endpoints = ",".join(eplist)
            self._trainers = int(os.getenv("PADDLE_TRAINERS_NUM", "1"))
            self.current_endpoint = os.getenv("POD_IP",
                                              "localhost") + ":" + self.port
            self.role = os.getenv("TRAINING_ROLE", "TRAINER")
            self.trainer_id = int(os.getenv("PADDLE_TRAINER_ID", "0"))
315
            self.eplist = eplist
316
            print("PaddleCloudRoleMaker() endpoints: %s" % self.endpoints)
317
            self.endpoints = self.endpoints.split(",")
318
            self._server_endpoints = self.endpoints
319
            if self.role.upper() == "PSERVER":
320 321
                self._current_id = self.endpoints.index(self.current_endpoint)
                self._role = Role.SERVER
322
            else:
323 324
                self._current_id = self.trainer_id
                self._role = Role.WORKER
325 326
            self._role_is_generated = True

327 328 329
    def is_worker(self):
        if not self._role_is_generated:
            self.generate_role()
330 331 332
        return self._role == Role.WORKER

    def is_server(self):
333 334
        if not self._role_is_generated:
            self.generate_role()
335 336 337
        return self._role == Role.SERVER

    def is_first_worker(self):
338 339
        if not self._role_is_generated:
            self.generate_role()
340 341 342
        return self._role == Role.WORKER and self._current_id == 0

    def worker_index(self):
343 344
        if not self._role_is_generated:
            self.generate_role()
345 346 347
        return self._current_id

    def server_index(self):
348 349
        if not self._role_is_generated:
            self.generate_role()
350 351 352
        return self._current_id

    def worker_num(self):
353 354 355
        if not self._role_is_generated:
            self.generate_role()
        return self._trainers
356 357


358 359 360
class UserDefinedRoleMaker(RoleMakerBase):
    def __init__(self,
                 current_id=0,
T
tangwei12 已提交
361 362 363
                 role=Role.WORKER,
                 worker_num=0,
                 server_endpoints=None):
364 365 366 367 368 369 370
        """
        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.
        """
        super(UserDefinedRoleMaker, self).__init__()

371 372 373 374 375 376 377
        if not isinstance(current_id, int):
            raise TypeError("current_id must be as int")
        else:
            if current_id < 0:
                raise ValueError("current_id must be gather or equal 0")
            self._current_id = current_id

T
tangwei12 已提交
378
        if role != Role.WORKER and role != Role.SERVER:
379 380 381 382 383 384 385 386 387 388 389 390 391 392 393
            raise TypeError("role must be as Role")
        else:
            self._role = role

        if not isinstance(worker_num, int):
            raise TypeError("worker_num must be as int")
        else:
            if worker_num < 0:
                raise ValueError("worker_num must be gather or equal 0")
            self._worker_num = worker_num

        if not isinstance(server_endpoints, list):
            raise TypeError("server_endpoints must be as string list")
        else:
            self._server_endpoints = server_endpoints
T
tangwei12 已提交
394

395 396 397
    def generate_role(self):
        self._role_is_generated = True

T
tangwei12 已提交
398 399 400 401 402
    def is_worker(self):
        return self._role == Role.WORKER

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

T
tangwei12 已提交
404 405
    def is_first_worker(self):
        return self._role == Role.WORKER and self._current_id == 0
406

T
tangwei12 已提交
407 408
    def worker_index(self):
        return self._current_id
409

T
tangwei12 已提交
410 411
    def server_index(self):
        return self._current_id
412 413 414

    def worker_num(self):
        return self._worker_num
415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437


class UserDefinedCollectiveRoleMaker(RoleMakerBase):
    def __init__(self, current_id=0, worker_endpoints=None):
        """
        UserDefinedCollectiveRoleMaker is designed for worker assignment
        under manual for collective mode.
        """
        super(UserDefinedCollectiveRoleMaker, self).__init__()

        if not isinstance(current_id, int):
            raise TypeError("current_id must be as int")
        else:
            if current_id < 0:
                raise ValueError("current_id must be greater or equal 0")
            self._current_id = current_id

        if not isinstance(worker_endpoints, list):
            raise TypeError("worker_endpoints must be as string list")
        else:
            self._worker_endpoints = worker_endpoints
        self._worker_num = len(self._worker_endpoints)

438 439 440
    def generate_role(self):
        self._role_is_generated = True

441 442 443 444 445 446 447 448 449 450 451
    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