manager.py 21.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
# Copyright (c) 2021 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.

15
import copy
16
import os
K
kuizhiqing 已提交
17
import random
18 19 20
import signal
import socket
import subprocess
21
import threading
22
import time
23
import traceback
24

25
from paddle.distributed.fleet import cloud_utils, launch_utils
R
Roc 已提交
26 27 28
from paddle.distributed.utils.log_utils import get_logger

logger = get_logger("INFO", "ELASTIC")
29 30

ELASTIC_EXIT_CODE = 101
31
ELASTIC_AUTO_PARALLEL_EXIT_CODE = 102
32

33 34 35 36 37 38 39 40 41 42 43 44
# wait for timeout, unit: seconds
ELASTIC_TIMEOUT = 2 * 60

# keepalived ttl, unit: seconds
ELASTIC_TTL = 60


# 1: Fault tolerance, 2: Elastic
class ElasticLevel:
    FAULT_TOLERANCE = 1
    ELASTIC = 2

45 46 47 48 49 50 51 52 53

class ElasticStatus:
    COMPLETED = "completed"
    ERROR = "error"
    HOLD = "hold"
    RESTART = "restart"
    EXIT = "exit"


54
class LauncherInterface:
55 56 57 58 59
    def __init__(self, args):
        self.args = args
        self.procs = []

    def _terminate_procs(self):
K
kuizhiqing 已提交
60
        # try to terminate process by group, this happend in multiprocess senario in user process
K
kuizhiqing 已提交
61 62 63 64 65 66
        if os.name != 'nt':
            for p in self.procs:
                if p.proc.poll() is None:
                    os.killpg(os.getpgid(p.proc.pid), signal.SIGTERM)
                    if p.log_fn:
                        p.log_fn.close()
67
                    logger.info(f"terminate process group gid:{p.proc.pid}")
K
kuizhiqing 已提交
68

K
kuizhiqing 已提交
69
            time.sleep(1)
70 71 72 73 74
        for p in self.procs:
            if p.proc.poll() is None:
                p.proc.terminate()
                if p.log_fn:
                    p.log_fn.close()
75
                logger.info(f"terminate process id:{p.proc.pid}")
76 77 78 79 80 81 82 83 84

        for step in range(0, 50):
            alive = False
            for p in self.procs:
                if p.proc.poll() is None:  # not termniate
                    os.kill(p.proc.pid, signal.SIGKILL)
                    alive = True

            if not alive:
K
kuizhiqing 已提交
85
                logger.info("terminated all the procs")
86 87 88 89 90 91 92 93 94 95 96 97 98
                return True

            time.sleep(1)
        return False

    def _check_procs(self):
        alive = False
        result = None
        for p in self.procs:
            ret = p.proc.poll()
            if ret is None:
                alive = True
            elif ret != 0:
99 100 101
                if ret == ELASTIC_AUTO_PARALLEL_EXIT_CODE:
                    logger.info("return form elastic auto parallel re-launch")
                    return ret
K
kuizhiqing 已提交
102 103
                logger.error("ABORT!!! ABORT!!! ABORT!!!")
                logger.error(
104 105 106 107
                    "ERROR rank {} error with exit code {}, check log for detail.".format(
                        p.rank, ret
                    )
                )
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
                result = ret
        if not alive and result is None:
            return 0
        else:
            return result

    def launch(self):
        raise NotImplementedError

    def stop(self):
        raise NotImplementedError

    def watch(self):
        raise NotImplementedError


124
class ElasticManager:
125
    def __init__(self, args, etcd_client):
126 127 128 129

        self.args = args
        server = args.elastic_server or os.getenv('PADDLE_ELASTIC_SERVER')
        name = args.job_id or os.getenv('PADDLE_ELASTIC_JOB_ID')
130
        self.min_np, self.max_np = self._parse_np(args.np)
131 132 133 134
        host = args.host or os.getenv('POD_IP')
        scale = args.scale or int(os.getenv('PADDLE_ELASTIC_SCALE', 0))
        force = args.force or os.getenv('PADDLE_ELASTIC_FORCE')

135
        self.host = host if host else self._get_host()
136

137 138 139 140
        (
            self.device_mode,
            self.devices_per_proc,
        ) = launch_utils.get_device_proc_info(args)
141 142

        self.elastic_timeout = int(
143 144
            os.getenv('PADDLE_ELASTIC_TIMEOUT', ELASTIC_TIMEOUT)
        )
145 146
        elastic_ttl = int(os.getenv('PADDLE_ELASTIC_TTL', ELASTIC_TTL))

147 148 149 150 151 152 153 154 155 156 157 158 159 160
        self.start_port = None
        if cloud_utils.use_paddlecloud():
            self.trainers = os.getenv('PADDLE_TRAINERS', '')
            self.np = len(self.trainers.split(","))
            self.start_port = int(os.getenv("PADDLE_PORT", "6170"))
            self.dist_endpoints = os.getenv('DISTRIBUTED_TRAINER_ENDPOINTS', '')
            trainer_endpoints = os.getenv('PADDLE_TRAINER_ENDPOINTS', '')
            self.trainer_endpoints_list = trainer_endpoints.split(",")
        else:
            self.trainers = args.ips or os.getenv('PADDLE_TRAINERS', '')
            node_ips = self.trainers.split(",")
            self.np = len(node_ips)
            self.start_port = int(os.getenv("FLAGS_START_PORT", "6170"))
            self.dist_endpoints = self._host_to_endpoints(
161 162
                node_ips, self.devices_per_proc, self.start_port
            )
163 164 165 166 167 168
            self.trainer_endpoints_list = [
                "%s:%d" % (ip, self.start_port) for ip in node_ips
            ]

        self.curr_host = "%s:%d" % (self.host, self.start_port)
        logger.info(f'start job with np={self.np}')
169
        logger.info(
170
            f"trainers={self.trainers}, trainer_endpoints_list={self.trainer_endpoints_list}"
171 172 173 174
        )

        # auto correct the value of elastic_level
        # 1: Fault tolerant, 2: Elastic
175
        self.elastic_level = int(
176 177 178 179 180 181
            os.getenv(
                'PADDLE_ELASTIC_FAULT_TOLERANC_LEVEL',
                ElasticLevel.FAULT_TOLERANCE,
            )
        )
        if self.min_np == self.max_np or (self.min_np > 0 and self.max_np == 0):
182
            self.elastic_level = ElasticLevel.FAULT_TOLERANCE
183
            logger.info('start job with ElasticLevel.FAULT_TOLERANCE')
184 185
        if self.min_np > 0 and self.max_np > self.min_np:
            self.elastic_level = ElasticLevel.ELASTIC
186
            logger.info('start job with ElasticLevel.ELASTIC')
187

K
kuizhiqing 已提交
188
        # compatible with kuberntes service discovery
189 190 191 192 193
        if (
            not server
            and os.getenv('PADDLE_ELASTIC_ETCD_SERVICE_HOST')
            and os.getenv('PADDLE_ELASTIC_ETCD_SERVICE_PORT')
        ):
K
kuizhiqing 已提交
194 195
            server = '{}:{}'.format(
                os.getenv('PADDLE_ELASTIC_ETCD_SERVICE_HOST'),
196 197
                os.getenv('PADDLE_ELASTIC_ETCD_SERVICE_PORT'),
            )
K
kuizhiqing 已提交
198

199
        logger.debug(f'init with server {server} host {host}')
200 201 202 203 204

        self.hosts = []
        self.stopped = False

        self.sigint = 0
K
kuizhiqing 已提交
205
        self.need_sync = False
206

207 208 209
        self.elastic_startup_time = None

        if not server or ':' not in server or not name or not self.np:
210
            logger.info(
211 212 213 214
                'Elastic is not enabled with server {} name {} and np {}'.format(
                    server, name, self.np
                )
            )
215 216 217 218 219
            self.enable = False
            return
        else:
            self.enable = True

220
        self.etcd = etcd_client
221 222 223

        # etcd data
        self.prefix = "/paddle/" + name
K
kuizhiqing 已提交
224
        self.node_prefix = self.prefix + '/nodes'
225 226
        self.np_path = self.prefix + '/np'
        self.endpoints_path = self.prefix + '/endpoints'
K
kuizhiqing 已提交
227 228

        node_tag = ''.join(
229 230 231 232 233
            random.choice('abcdefghijklmnopqrstuvwxyz') for _ in range(6)
        )
        self.host_path = '{}/{}{}'.format(
            self.node_prefix, node_tag, time.time()
        )
234 235 236 237 238 239
        '''
        0 group mode, be aware of healthy status of other workers
        1 decouple mode, check own status only
        '''
        self.etcd.put(self.prefix, b'0')

240
        # register callback
241
        def host_call_back(event):
242
            self.hosts = [
243
                i[0].decode() for i in self.etcd.get_prefix(self.node_prefix)
244
            ]
245
            self.hosts = list(set(self.hosts)) if self.hosts else self.hosts
246
            logger.info(
247 248
                f"host_call_back curr_host={self.curr_host}, hosts:{self.hosts}"
            )
249 250 251
            self.need_sync = True
            self.elastic_startup_time = None

252
        host_watch = self.etcd.add_watch_prefix_callback(
253 254
            self.node_prefix, host_call_back
        )
255 256 257 258 259 260 261 262 263
        host_lease = self.etcd.lease(elastic_ttl)

        # register etcd lease heartbeat
        def lease_heartbeat():
            while True:
                try:
                    host_lease.refresh()

                    hosts = [
264
                        i[0].decode()
265 266
                        for i in self.etcd.get_prefix(self.node_prefix)
                    ]
267
                    hosts = list(set(hosts)) if hosts else hosts
268
                    logger.info(
269
                        f"[lease_heartbeat] curr_host={self.curr_host}, hosts={hosts}"
270
                    )
271
                    if self.curr_host not in hosts:
272
                        logger.info(
273 274 275 276 277 278 279
                            f"[lease_heartbeat] register host={self.curr_host}"
                        )
                        self.etcd.put(
                            self.host_path,
                            self.curr_host.encode('latin-1'),
                            lease=host_lease,
                        )
280
                except Exception as e:
281 282
                    logger.error(
                        "[lease_heartbeat] internal error:{} {}".format(
283 284 285
                            e, traceback.format_exc()
                        )
                    )
286 287 288
                    break
                time.sleep(elastic_ttl / 3)

289 290 291
        keepalived_thread = threading.Thread(
            name='lease_heartbeat', target=lease_heartbeat, daemon=True
        )
292 293
        keepalived_thread.start()

294 295 296
        self.etcd.put(
            self.host_path, self.curr_host.encode('latin-1'), lease=host_lease
        )
297 298

        # endpoints handle DISTRIBUTED_TRAINER_ENDPOINTS and PADDLE_TRAINERS
299 300
        self.etcd.put(
            self.endpoints_path,
301
            f'{self.dist_endpoints}|{self.trainers}'.encode('latin-1'),
302
        )
303 304

        def endpoints_call_back(event):
305
            if not self.dist_endpoints:
306
                return
307 308
            value = self.etcd.get(self.endpoints_path)[0]
            edps = value.decode() if value is not None else ''
309
            self.dist_endpoints, self.trainers = edps.split('|')
310 311 312 313 314
            logger.info(
                "set DISTRIBUTED_TRAINER_ENDPOINTS {} ".format(
                    self.dist_endpoints
                )
            )
315
            logger.info(f"set PADDLE_TRAINERS {self.trainers} ")
316

317 318 319
        endpoints_watch = self.etcd.add_watch_callback(
            self.endpoints_path, endpoints_call_back
        )
320

321
        self.watches = [host_watch, endpoints_watch]
K
kuizhiqing 已提交
322 323
        self.launcher = None

324 325 326
    def _host_to_endpoints(
        self, ip_port_list: list, devices_per_proc: list, start_port: int = 6170
    ) -> str:
327 328 329 330 331 332 333 334 335 336
        endpoint_list = []
        for ip_port in ip_port_list:
            endpoints = ip_port.split(":")
            if len(endpoints) == 2:
                ip = endpoints[0]
                port = int(endpoints[1])
            else:
                ip = endpoints
                port = start_port

337
            ports = list(range(port, port + len(devices_per_proc)))
338 339 340 341 342
            endpoint_list.extend(["%s:%d" % (ip, port) for port in ports])

        dist_endpoints = ','.join(endpoint_list)
        return dist_endpoints

343
    def exit(self, completed=False):
344
        logger.info(f'manager exist completed {completed}')
345

K
kuizhiqing 已提交
346 347
        if self.launcher:
            self.launcher.stop()
K
kuizhiqing 已提交
348

349 350 351 352 353 354 355 356 357 358
        if not self.enable:
            return

        if completed:
            self.etcd.put(self.prefix, b'1')

        for watch in self.watches:
            self.etcd.cancel_watch(watch)
        self.etcd.delete(self.host_path)

359
        hosts = list(self.etcd.get_prefix(self.node_prefix))
360 361 362
        if len(hosts) == 0:
            self.etcd.delete_prefix(self.prefix)

363 364 365 366
    def pre_hook(self):
        if not self.args.elastic_pre_hook:
            logger.info("skip pre_hook")
            return
367
        logger.info("execute pre_hook...")
368
        current_env = copy.copy(os.environ.copy())
369 370 371 372 373 374 375
        out, err = subprocess.Popen(
            self.args.elastic_pre_hook,
            env=current_env,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            shell=True,
        ).communicate()
376
        if err:
R
Roc 已提交
377
            logger.warning("pre_hook exec failed")
378 379 380
        else:
            logger.info(f"pre_hook exec result: {out.decode('utf-8').strip()}")

381 382
    def _parse_np(self, np: str):
        """
383
        np format is "MIN" or "MIN:MAX"
384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400
        """
        np_str = np or os.getenv('PADDLE_ELASTIC_NP', "0")
        np_dict = np_str.split(":")
        min_np = max_np = 0
        if len(np_dict) == 1:
            # Fault tolerant
            min_np = int(np_dict[0])
            min_np = 1 if min_np <= 0 else min_np
            max_np = 1
        elif len(np_dict) == 2:
            # Elastic
            min_np = int(np_dict[0])
            max_np = int(np_dict[1])
            min_np = 1 if min_np <= 0 else min_np
            max_np = min_np if min_np > max_np else max_np
        else:
            raise ValueError(
401 402
                f'the np={np} needs to be in "MIN" or "MIN:MAX" format'
            )
403 404 405

        return min_np, max_np

406 407 408 409 410 411 412 413 414 415 416 417
    def _get_host(self):
        try:
            return socket.gethostbyname(socket.getfqdn(socket.gethostname()))
        except:
            return '127.0.0.1'

    def _completed(self):
        if not self.enable:
            return True

        return int(self.etcd.get(self.prefix)[0]) == 1

418
    def _match(self, host_list: list = None):
419 420
        if host_list:
            self.hosts = host_list
421
        else:
422
            self.hosts = [
423
                i[0].decode() for i in self.etcd.get_prefix(self.node_prefix)
424
            ]
425
        self.hosts = list(set(self.hosts)) if self.hosts else self.hosts
426

427 428 429 430 431
        if self.elastic_level == ElasticLevel.FAULT_TOLERANCE:
            if len(self.hosts) == self.np:
                return True
            else:
                return False
432

433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
        if self.elastic_level == ElasticLevel.ELASTIC:
            hosts_num = len(self.hosts)
            if hosts_num == self.np:
                return True

            if not self.elastic_startup_time:
                self.elastic_startup_time = time.time()
            if hosts_num == self.max_np:
                self.elastic_startup_time = None
                return True
            elif hosts_num >= self.min_np and hosts_num < self.max_np:
                interval_time = time.time() - self.elastic_startup_time
                if interval_time <= self.elastic_timeout:
                    logger.info(
                        f"wait for timeout, you can set value by PADDLE_ELASTIC_TIMEOUT, \
                        hosts_num={hosts_num}, min_np={self.min_np}, \
                        interval_time={interval_time}, elastic_timeout={self.elastic_timeout}"
                    )
                    return False
                return True
            else:
                self.elastic_startup_time = None
                return False
456

457 458 459
        return False

    def _update_endpoint(self, endpoints, hosts):
460 461
        self.etcd.put(
            self.endpoints_path,
462
            f'{endpoints}|{hosts}'.encode('latin-1'),
463
        )
464

465
    def _update_fault_tolrance(self):
466
        rank = int(os.getenv('PADDLE_TRAINER_ID', -1))
467 468 469
        logger.debug(
            f"self.curr_host={self.curr_host}, self.dist_endpoints={self.dist_endpoints}"
        )
470 471 472
        if self.curr_host in self.dist_endpoints:
            os.environ['DISTRIBUTED_TRAINER_ENDPOINTS'] = self.dist_endpoints
            os.environ['PADDLE_TRAINERS'] = self.trainers
473 474 475 476 477
            logger.info(
                "update env DISTRIBUTED_TRAINER_ENDPOINTS {} ".format(
                    self.dist_endpoints
                )
            )
478
            logger.info(f"update env PADDLE_TRAINERS {self.trainers} ")
479 480
            return

481
        # fault tolerance
482 483 484 485 486 487 488
        idx = self.hosts.index(self.curr_host)

        # swap if self.host not in the right position
        if rank >= 0:
            self.hosts[idx] = self.hosts[rank]
            self.hosts[rank] = self.curr_host
        else:
489
            os.environ['PADDLE_TRAINER_ID'] = f'{idx}'
490 491 492 493 494 495 496 497 498
        hosts = ','.join([host_port.split(":")[0] for host_port in self.hosts])
        self.args.ips = hosts
        os.environ['PADDLE_TRAINERS'] = hosts

    def _update_elastic_scale_out(self):
        host_endpoints = copy.deepcopy(self.trainer_endpoints_list)
        logger.info(
            f"elastic scale out, from {len(self.hosts)} to {self.np}, hosts={self.hosts}, host_endpoints={host_endpoints}"
        )
499

500 501 502 503 504
        for curr_host_port in self.hosts:
            if curr_host_port not in host_endpoints:
                host_endpoints.append(curr_host_port)

        os.environ['PADDLE_TRAINER_ID'] = '{}'.format(
505 506
            host_endpoints.index(self.curr_host)
        )
507
        hosts = ','.join(
508 509
            [host_port.split(":")[0] for host_port in host_endpoints]
        )
510 511 512 513 514 515 516 517 518 519 520 521
        self.args.ips = hosts
        os.environ['PADDLE_TRAINERS'] = hosts
        self.np = len(host_endpoints)
        os.environ['PADDLE_TRAINER_ENDPOINTS'] = ','.join(host_endpoints)
        os.environ['DISTRIBUTED_TRAINER_ENDPOINTS'] = self.dist_endpoints
        self.trainer_endpoints_list = host_endpoints

    def _update_elastic_scale_in(self):
        host_endpoints = copy.deepcopy(self.trainer_endpoints_list)
        logger.info(
            f"elastic scale in, from {self.np} to {len(self.hosts)}, hosts={self.hosts}, host_endpoints={host_endpoints}"
        )
522

523
        # If scale in node from the first of the rank list, you need to minimize the movement of the rank
524
        # eg:
525 526 527 528
        #   the source trainers is:10.10.10.0,10.10.10.1,10.10.10.2,10.10.10.3
        #   10.10.10.0 is removed
        #   the new trainers is:10.10.10.3,10.10.10.1,10.10.10.2
        #   In this case, the rank of 10.10.10.1 and 10.10.10.2 remains unchanged, while the rank of 10.10.10.3 is set to rank0
529
        endpoints_dict = {}
530 531 532 533 534
        unsorted_endpoints = []
        for id, host_port in enumerate(self.hosts):
            idx = host_endpoints.index(host_port)
            if idx <= len(self.hosts) - 1 and not endpoints_dict.get(idx):
                endpoints_dict[idx] = host_port
535
            else:
536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551
                unsorted_endpoints.append(host_port)

        idle_index = 0
        sorted_endpoints = []
        for idx in range(len(self.hosts)):
            if not endpoints_dict.get(idx) and len(unsorted_endpoints) > 0:
                endpoints_dict[idx] = unsorted_endpoints[idle_index]
                idle_index += 1

            sorted_endpoints.append(endpoints_dict.get(idx))

        logger.info(f"elastic scale in, sorted_endpoints={sorted_endpoints}")
        self.trainer_endpoints_list = sorted_endpoints

        ip_list = [ip_port.split(":")[0] for ip_port in sorted_endpoints]
        hosts = ','.join(ip_list)
552 553 554
        new_endpoints = self._host_to_endpoints(
            sorted_endpoints, self.devices_per_proc
        )
555 556 557

        self.args.ips = hosts
        os.environ['PADDLE_TRAINER_ID'] = '{}'.format(
558 559
            sorted_endpoints.index(self.curr_host)
        )
560 561 562 563 564 565 566 567 568 569
        os.environ['PADDLE_TRAINERS'] = hosts
        self.np = len(sorted_endpoints)
        os.environ['PADDLE_TRAINER_ENDPOINTS'] = ','.join(sorted_endpoints)
        os.environ['DISTRIBUTED_TRAINER_ENDPOINTS'] = new_endpoints
        self._update_endpoint(new_endpoints, hosts)

    def _update_hosts(self):
        assert len(self.hosts) != 0, 'hosts empty'
        if self.elastic_level == ElasticLevel.FAULT_TOLERANCE:
            self._update_fault_tolrance()
570
        else:
571 572 573 574 575 576 577 578
            # elastic
            if len(self.hosts) == self.np:
                logger.info(f"elastic startup, hosts={self.hosts}")
                self._update_fault_tolrance()

            elif len(self.hosts) > self.np:
                # scale out
                self._update_elastic_scale_out()
579
            else:
580 581
                # scale in
                self._update_elastic_scale_in()
582 583 584 585 586

    def wait(self):
        if not self.enable:
            return

K
kuizhiqing 已提交
587
        idx = 1
588 589
        while not self.stopped:
            if self._match():
590
                logger.info(f'ready with hosts {self.hosts}')
591 592
                self._update_hosts()
                return
593
            logger.info(f'not ready for np {self.np} with hosts {self.hosts}')
K
kuizhiqing 已提交
594
            idx += 1
K
kuizhiqing 已提交
595
            time.sleep(2)
596 597 598 599 600 601 602 603 604 605 606
        return

    def run(self, launcher):
        if self.stopped:
            return

        self.launcher = launcher(self.args)
        self.launcher.launch()

    def watch(self):

K
kuizhiqing 已提交
607 608 609
        if self.need_sync:
            self.need_sync = False

610 611
        while not self.stopped:
            ret = self.launcher.watch()
612
            logger.debug(f"launcher.watch():{ret}")
613 614

            if ret is not None:  # self terminated
615
                logger.info(f'job exit with code {ret}')
616 617 618 619 620
                if ret == ELASTIC_AUTO_PARALLEL_EXIT_CODE:
                    logger.info('job re-launch for auto parallel')
                    self.launcher.stop()
                    return ElasticStatus.HOLD

621 622 623 624 625
                # process is completed if ret >= 0 or error else
                completed = True if ret == 0 else False
                self.exit(completed=completed)
                if completed:
                    return ElasticStatus.COMPLETED
626
                if self.elastic_level == ElasticLevel.FAULT_TOLERANCE:
627 628 629 630
                    return ElasticStatus.RESTART
                else:
                    return ElasticStatus.ERROR

K
kuizhiqing 已提交
631
            if not self._completed() and (not self._match() or self.need_sync):
632 633 634
                self.launcher.stop()
                return ElasticStatus.HOLD

K
kuizhiqing 已提交
635
            time.sleep(2)
636

K
kuizhiqing 已提交
637 638
        if self.launcher:
            self.launcher.stop()
639

640 641 642 643 644 645 646
        return ElasticStatus.EXIT

    def signal_handler(self, sigint, frame):
        if self.enable:
            self.exit()
        self.sigint = sigint
        self.stopped = True