collective.py 36.1 KB
Newer Older
1
#   Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
2 3 4 5 6 7 8 9 10 11 12 13 14
#
# 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 os
16

17 18 19 20 21 22
from paddle.distributed.fleet.base.private_helper_function import (
    wait_server_ready,
)
from paddle.fluid import unique_name
from paddle.framework import core
from paddle.static import default_main_program, default_startup_program
23 24 25 26

OpRole = core.op_proto_and_checker_maker.OpRole


27
class Collective:
28
    ''' '''
29

30 31
    def __init__(self, nrings):
        self.nrings = nrings
32 33
        self.endpoints = None
        self.current_endpoint = None
F
Fan Zhang 已提交
34
        self.other_endpoints = None
35 36 37 38 39 40 41 42
        self.nranks = None
        self.rank = None
        self.startup_program = None
        self.main_program = None
        op_maker = core.op_proto_and_checker_maker
        self.op_role_key = op_maker.kOpRoleAttrName()
        self.op_role_var_key = op_maker.kOpRoleVarAttrName()

43 44 45 46 47 48 49 50 51
    def transpile(
        self,
        startup_program,
        main_program,
        rank,
        endpoints,
        current_endpoint,
        wait_port,
    ):
52 53 54 55 56 57 58 59 60 61 62 63 64
        # in case of '127.0.0.1:6700,127.0.0.1:6701,...'
        if isinstance(endpoints, str):
            endpoints = endpoints.split(',')

        self.startup_program = startup_program
        if startup_program is None:
            self.startup_program = default_startup_program()

        self.main_program = main_program
        if main_program is None:
            self.main_program = default_main_program()

        self.nranks = len(endpoints)
65 66 67 68 69
        if (
            self.nranks == 1
            and self.mode != "single_process_multi_thread"
            and self.mode != "box"
        ):
70 71 72 73 74 75 76
            raise ValueError('the number of endpoints must > 1')

        if rank < 0:
            raise ValueError('rank must >= 0')
        self.rank = rank

        if current_endpoint not in endpoints:
77 78 79 80 81
            raise ValueError(
                'current endpoint %s is not in %s',
                current_endpoint,
                str(endpoints),
            )
82 83 84 85

        self.endpoints = endpoints
        self.current_endpoint = current_endpoint

F
Fan Zhang 已提交
86 87 88 89 90 91
        if current_endpoint:
            nranks = len(endpoints)
            other_endpoints = endpoints[:]
            other_endpoints.remove(current_endpoint)
            self.other_endpoints = other_endpoints

92 93 94 95 96 97 98 99 100 101 102 103
        self.wait_port = wait_port

        self.startup_program._origin_program = self.startup_program.clone()
        self._transpile_startup_program()

        self.main_program._origin_program = self.main_program.clone()
        self._transpile_main_program()

    def _transpile_main_program(self):
        raise NotImplementedError('call the inherited method of subclasses')

    def _transpile_startup_program(self):
104
        for ring_id in range(self.nrings):
105 106 107 108 109 110 111 112
            self._init_communicator(
                self.startup_program,
                self.current_endpoint,
                self.endpoints,
                self.rank,
                ring_id,
                self.wait_port,
            )
113 114
        self._broadcast_params()

115 116 117 118 119 120 121 122 123 124
    def _init_communicator(
        self,
        program,
        current_endpoint,
        endpoints,
        rank,
        ring_id,
        wait_port,
        has_multitrainer=False,
    ):
125 126 127
        nranks = len(endpoints)
        other_endpoints = endpoints[:]
        other_endpoints.remove(current_endpoint)
128 129
        block = program.global_block()

130 131 132 133
        if rank == 0 and wait_port:
            wait_server_ready(other_endpoints)

        block = program.global_block()
134
        if core.is_compiled_with_npu():
135 136 137 138 139
            hccl_id_var = block.create_var(
                name=unique_name.generate('hccl_id'),
                persistable=True,
                type=core.VarDesc.VarType.RAW,
            )
140
            endpoint_to_index_map = {e: idx for idx, e in enumerate(endpoints)}
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163
            block.append_op(
                type='c_gen_hccl_id',
                inputs={},
                outputs={'Out': hccl_id_var},
                attrs={
                    'rank': rank,
                    'endpoint': current_endpoint,
                    'other_endpoints': other_endpoints,
                    self.op_role_key: OpRole.Forward,
                },
            )
            block.append_op(
                type='c_comm_init_hccl',
                inputs={'X': hccl_id_var},
                outputs={},
                attrs={
                    'rank': rank,
                    'ring_id': ring_id,
                    'device_id': int(os.getenv("FLAGS_selected_npus")),
                    'rank_ids': nranks,
                    self.op_role_key: OpRole.Forward,
                },
            )
164
        elif core.is_compiled_with_cuda():
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
            nccl_id_var = block.create_var(
                name=unique_name.generate('nccl_id'),
                persistable=True,
                type=core.VarDesc.VarType.RAW,
            )
            block.append_op(
                type='c_gen_nccl_id',
                inputs={},
                outputs={'Out': nccl_id_var},
                attrs={
                    'rank': rank,
                    'endpoint': current_endpoint,
                    'other_endpoints': other_endpoints,
                    self.op_role_key: OpRole.Forward,
                },
            )
Y
yaoxuefeng 已提交
181
            if not has_multitrainer:
182 183 184 185 186 187 188 189 190 191 192
                block.append_op(
                    type='c_comm_init',
                    inputs={'X': nccl_id_var},
                    outputs={},
                    attrs={
                        'nranks': nranks,
                        'rank': rank,
                        'ring_id': ring_id,
                        self.op_role_key: OpRole.Forward,
                    },
                )
Y
yaoxuefeng 已提交
193
            else:
194 195 196 197 198 199 200 201 202 203 204
                block.append_op(
                    type='c_comm_init_multitrainer',
                    inputs={'X': nccl_id_var},
                    outputs={},
                    attrs={
                        'ntrainers': nranks,
                        'trainer_id': rank,
                        'ring_id': ring_id,
                        self.op_role_key: OpRole.Forward,
                    },
                )
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
        elif core.is_compiled_with_xpu():
            bkcl_id_var = block.create_var(
                name=unique_name.generate('bkcl_id'),
                persistable=True,
                type=core.VarDesc.VarType.RAW,
            )
            block.append_op(
                type='c_gen_bkcl_id',
                inputs={},
                outputs={'Out': bkcl_id_var},
                attrs={
                    'rank': rank,
                    'endpoint': current_endpoint,
                    'other_endpoints': other_endpoints,
                    self.op_role_key: OpRole.Forward,
                },
            )
            block.append_op(
                type='c_comm_init',
                inputs={'X': bkcl_id_var},
                outputs={},
                attrs={
                    'nranks': nranks,
                    'rank': rank,
                    'ring_id': ring_id,
                    self.op_role_key: OpRole.Forward,
                },
            )
233 234 235

    def _broadcast_params(self):
        block = self.startup_program.global_block()
236 237
        ring_id = -1
        for param in block.iter_parameters():
238 239 240
            if param.is_distributed:
                continue

241
            ring_id = (ring_id + 1) % self.nrings
242 243 244 245 246 247 248 249 250 251
            block.append_op(
                type='c_broadcast',
                inputs={'X': param},
                outputs={'Out': param},
                attrs={
                    'ring_id': ring_id,
                    'root': 0,
                    self.op_role_key: OpRole.Forward,
                },
            )
252 253

        for ring_id in range(self.nrings):
254 255 256 257 258 259
            block.append_op(
                type='c_sync_comm_stream',
                inputs={'X': param},
                outputs={'Out': param},
                attrs={'ring_id': ring_id, self.op_role_key: OpRole.Forward},
            )
260 261 262 263 264 265 266 267

    def _is_loss_grad_op(self, op):
        if self.op_role_key not in op.attr_names:
            return False
        op_role = int(op.all_attrs()[self.op_role_key])
        return op_role & int(OpRole.Backward) and op_role & int(OpRole.Loss)

    def _is_backward_op(self, op):
268 269 270
        return self.op_role_key in op.attr_names and int(
            op.all_attrs()[self.op_role_key]
        ) & int(OpRole.Backward)
271 272

    def _is_update_op(self, op):
273 274 275 276 277
        return (
            'Param' in op.input_names
            and 'Grad' in op.input_names
            and "LearningRate" in op.input_names
        )
278 279

    def _is_optimizer_op(self, op):
280 281 282
        return self.op_role_key in op.attr_names and int(
            op.all_attrs()[self.op_role_key]
        ) & int(OpRole.Optimize)
283 284 285


class GradAllReduce(Collective):
286
    ''' '''
287

288 289
    def __init__(self, nrings=2):
        Collective.__init__(self, nrings)
H
hutuxian 已提交
290
        self.mode = "grad_allreduce"
291 292 293 294 295 296 297 298 299 300 301 302 303 304

    def _transpile_main_program(self):
        self._insert_scale_loss_grad_ops()
        self._insert_allreduce_ops()

    def _insert_scale_loss_grad_ops(self):
        '''
        In order to keep the learning rate consistent in different numbers of
        training workers, we scale the loss grad by the number of workers
        '''
        block = self.main_program.global_block()
        for idx, op in reversed(list(enumerate(block.ops))):
            if self._is_loss_grad_op(op):
                loss_grad_var = block.vars[op.output_arg_names[0]]
305 306 307 308 309 310 311 312 313 314
                block._insert_op(
                    idx + 1,
                    type='scale',
                    inputs={'X': loss_grad_var},
                    outputs={'Out': loss_grad_var},
                    attrs={
                        'scale': 1.0 / self.nranks,
                        self.op_role_key: OpRole.Backward,
                    },
                )
315 316 317

    def _insert_allreduce_ops(self):
        block = self.main_program.global_block()
318 319
        ring_id = -1
        grad = None
320
        for idx, op in reversed(list(enumerate(block.ops))):
321 322 323 324
            if (
                self._is_backward_op(op)
                and self.op_role_var_key in op.attr_names
            ):
325 326 327 328 329 330
                op_role_var = op.all_attrs()[self.op_role_var_key]

                if len(op_role_var) == 0:
                    continue
                assert len(op_role_var) % 2 == 0

331
                offset = idx
332
                for i in range(0, len(op_role_var), 2):
333 334
                    param = block.vars[op_role_var[i]]
                    grad = block.vars[op_role_var[i + 1]]
335 336 337
                    if param.is_distributed:
                        continue

338 339 340 341 342 343 344
                    if offset == idx:
                        offset += 1
                        block._insert_op(
                            offset,
                            type='c_sync_calc_stream',
                            inputs={'X': grad},
                            outputs={'Out': grad},
345 346
                            attrs={self.op_role_key: OpRole.Backward},
                        )
347 348 349 350 351
                        offset += 1

                    # As we search ops reversedly, we should insert c_allreduce_sum
                    # op in the same way to keep the ring_id alternate
                    ring_id = (ring_id + 1) % self.nrings
352 353 354 355 356 357 358 359 360 361
                    block._insert_op(
                        offset,
                        type='c_allreduce_sum',
                        inputs={'X': grad},
                        outputs={'Out': grad},
                        attrs={
                            'ring_id': ring_id,
                            self.op_role_key: OpRole.Backward,
                        },
                    )
362 363 364

        if grad is None:
            return
365 366 367

        for idx, op in enumerate(block.ops):
            if self._is_optimizer_op(op):
368
                for ring_id in range(self.nrings):
369 370 371 372 373 374 375 376 377 378
                    block._insert_op(
                        idx + ring_id,
                        type='c_sync_comm_stream',
                        inputs={'X': grad},
                        outputs={'Out': grad},
                        attrs={
                            'ring_id': ring_id,
                            self.op_role_key: OpRole.Backward,
                        },
                    )
379 380 381 382
                break


class LocalSGD(Collective):
383
    ''' '''
384

385 386
    def __init__(self, nrings=2):
        Collective.__init__(self, nrings)
387
        self.snapshot_key = '@SNAPSHOT'
H
hutuxian 已提交
388
        self.mode = "local_sgd"
389 390 391 392 393

    def _transpile_startup_program(self):
        Collective._transpile_startup_program(self)

        block = self.startup_program.global_block()
394
        non_dist_params = []
395
        for param in block.iter_parameters():
396 397
            if not param.is_distributed:
                non_dist_params.append(param)
398

399
        for param in non_dist_params:
400 401 402 403 404 405 406 407 408 409 410 411
            snapshot = block.create_var(
                name=self.snapshot_name(param.name),
                shape=param.shape,
                persistable=True,
                stop_gradient=True,
            )
            block.append_op(
                type='assign',
                inputs={'X': [param]},
                outputs={'Out': [snapshot]},
                attrs={self.op_role_key: OpRole.Forward},
            )
412 413 414 415 416 417 418

    def snapshot_name(self, param_name):
        return param_name + self.snapshot_key

    def _transpile_main_program(self):
        block = self.main_program.global_block()
        ordered_param_snapshot = []
419
        ring_id = -1
420 421 422
        for idx, op in reversed(list(enumerate(block.ops))):
            if self._is_update_op(op):
                param = block.vars[op.input('Param')[0]]
423 424 425
                if param.is_distributed:
                    continue

426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447
                snapshot = block.create_var(
                    name=self.snapshot_name(param.name),
                    shape=param.shape,
                    persistable=True,
                    stop_gradient=True,
                    dtype=param.dtype,
                )

                block._insert_op(
                    idx + 1,
                    type='elementwise_sub',
                    inputs={'X': [snapshot], 'Y': [param]},
                    outputs={'Out': [param]},
                    attrs={self.op_role_key: OpRole.Optimize},
                )
                block._insert_op(
                    idx + 2,
                    type='c_sync_calc_stream',
                    inputs={'X': param},
                    outputs={'Out': param},
                    attrs={self.op_role_key: OpRole.Optimize},
                )
448
                ring_id = (ring_id + 1) % self.nrings
449 450 451 452 453 454 455 456 457 458
                block._insert_op(
                    idx + 3,
                    type='c_allreduce_sum',
                    inputs={'X': [param]},
                    outputs={'Out': [param]},
                    attrs={
                        'ring_id': ring_id,
                        self.op_role_key: OpRole.Optimize,
                    },
                )
459 460 461

                ordered_param_snapshot.append((param, snapshot))

462
        for ring_id in range(self.nrings):
463 464 465 466 467 468
            block.append_op(
                type='c_sync_comm_stream',
                inputs={'X': param},
                outputs={'Out': param},
                attrs={'ring_id': ring_id, self.op_role_key: OpRole.Optimize},
            )
469 470 471 472

        for param_snapshot in reversed(ordered_param_snapshot):
            param = param_snapshot[0]
            snapshot = param_snapshot[1]
473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493
            block.append_op(
                type='scale',
                inputs={'X': [param]},
                outputs={'Out': [param]},
                attrs={
                    'scale': 1.0 / self.nranks,
                    self.op_role_key: OpRole.Optimize,
                },
            )
            block.append_op(
                type='elementwise_sub',
                inputs={'X': [snapshot], 'Y': [param]},
                outputs={'Out': [param]},
                attrs={self.op_role_key: OpRole.Optimize},
            )
            block.append_op(
                type='assign',
                inputs={'X': [param]},
                outputs={'Out': [snapshot]},
                attrs={self.op_role_key: OpRole.Optimize},
            )
H
hutuxian 已提交
494 495 496


class SingleProcessMultiThread(GradAllReduce):
L
lxsbupt 已提交
497 498 499
    """
    single process multi thread mode
    """
H
hutuxian 已提交
500 501

    def __init__(self):
H
hutuxian 已提交
502
        GradAllReduce.__init__(self, 1)
H
hutuxian 已提交
503
        self.mode = "single_process_multi_thread"
L
lxsbupt 已提交
504 505 506 507 508
        self.fuse_allreduce = int(os.getenv("PADDLE_FUSE_ALLREDUCE", "1"))
        self.loss_scale = int(os.getenv("PADDLE_LOSS_SCALE", "1"))
        self.gpu_nums = len(
            os.getenv("FLAGS_selected_gpus", "0,1,2,3,4,5,6,7").split(",")
        )
H
hutuxian 已提交
509 510

    def _transpile_startup_program(self):
L
lxsbupt 已提交
511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539
        nodes_num = 0
        if len(self.endpoints) > 1:
            nodes_num = len(set([x.split(':')[0] for x in self.endpoints]))
        # diffent ip num is multi node
        if nodes_num > 1:
            self.nranks = nodes_num
            print("begin to _transpile_startup_program for multi-node")
            print("current_endpoint: ", self.current_endpoint)
            print("total endpoints: ", self.endpoints)
            print("rank: %d, ring_id: %d" % (self.rank, self.nrings))
            for ring_id in range(self.nrings):
                self._init_communicator(
                    self.startup_program,
                    self.current_endpoint,
                    self.endpoints,
                    self.rank,
                    ring_id,
                    self.wait_port,
                    True,
                )
        else:
            self.nranks = 1
            print("begin to _transpile_startup_program for single-node")
            block = self.startup_program.global_block()
            block.append_op(type='c_comm_init_all', attrs={'ring_id': 0})

    def _transpile_main_program(self):
        # not need loss scale and no dense param
        param_cnt = self._get_update_param_count()
540
        if self.loss_scale == 0 and param_cnt == 0:
L
lxsbupt 已提交
541 542 543 544
            return
        # scale loss
        self._insert_scale_loss_grad_ops()
        # no param
545
        if param_cnt == 0:
L
lxsbupt 已提交
546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563
            return
        # fuse allreduce
        if self.fuse_allreduce > 0:
            print("begin used fuse_allreduce param count = %s" % (param_cnt))
            # use fuse allreduce
            self._insert_fuse_allreduce_ops()
        else:
            self._insert_allreduce_ops()

    def _get_update_param_count(self):
        """
        get need update param count
        """
        param_count = 0
        block = self.main_program.global_block()
        for idx, op in reversed(list(enumerate(block.ops))):
            if not self._is_backward_op(op):
                continue
564
            if self.op_role_var_key not in op.attr_names:
L
lxsbupt 已提交
565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680
                continue
            op_role_var = op.all_attrs()[self.op_role_var_key]
            if len(op_role_var) == 0:
                continue

            assert len(op_role_var) % 2 == 0
            for i in range(0, len(op_role_var), 2):
                param = block.vars[op_role_var[i]]
                if param.is_distributed:
                    continue
                param_count = param_count + 1

        return param_count

    def _insert_scale_loss_grad_ops(self):
        '''
        In order to keep the learning rate consistent in different numbers of
        training workers, we scale the loss grad by the number of workers
        '''
        scale = 1.0 / self.nranks / self.gpu_nums
        print("begin _insert_scale_loss_grad_ops scale = %s" % (scale))
        block = self.main_program.global_block()
        for idx, op in reversed(list(enumerate(block.ops))):
            if not self._is_loss_grad_op(op):
                continue
            loss_grad_var = block.vars[op.output_arg_names[0]]
            block._insert_op(
                idx + 1,
                type='scale',
                inputs={'X': loss_grad_var},
                outputs={'Out': loss_grad_var},
                attrs={'scale': scale, self.op_role_key: OpRole.Backward},
            )

    def _insert_fuse_allreduce_ops(self):
        """
        insert coalesce_tensor and all reduce ops
        """
        block = self.main_program.global_block()
        ring_id = -1
        grad = None
        input_grads = []
        global_offset = 0  # find insert offset of fuse tensor, after the max dense grad offset
        for idx, op in reversed(list(enumerate(block.ops))):
            if (
                self._is_backward_op(op)
                and self.op_role_var_key in op.attr_names
            ):
                op_role_var = op.all_attrs()[self.op_role_var_key]
                if len(op_role_var) == 0:
                    continue
                assert len(op_role_var) % 2 == 0
                offset = idx
                for i in range(0, len(op_role_var), 2):
                    param = block.vars[op_role_var[i]]
                    grad = block.vars[op_role_var[i + 1]]
                    if param.is_distributed:
                        continue
                    if offset == idx:
                        input_grads.append(grad)
                        global_offset = max(global_offset, offset + 1)
        if grad is None:
            return

        # init output_grads
        output_grads = input_grads
        # init fused_output with temp shape, it will calculate real shape depend on inputs
        fused_output = block.create_var(
            name="fused_output",
            shape=[1],
            persistable=False,
            dtype=core.VarDesc.VarType.FP32,
            stop_gradient=True,
        )
        # fuse all grad tensors
        coalesce_tensor_attrs = {
            "copy_data": True,
            "set_constant": False,
            "dtype": core.VarDesc.VarType.FP32,
        }
        block._insert_op(
            global_offset,
            type='coalesce_tensor',
            inputs={'Input': input_grads},
            outputs={'Output': output_grads, 'FusedOutput': fused_output},
            attrs=coalesce_tensor_attrs,
        )
        global_offset += 1
        # grads aggregation of multi-gpus
        block._insert_op(
            global_offset,
            type='c_sync_calc_stream',
            inputs={'X': fused_output},
            outputs={'Out': fused_output},
            attrs={self.op_role_key: OpRole.Backward},
        )
        global_offset += 1
        ring_id = (ring_id + 1) % self.nrings
        block._insert_op(
            global_offset,
            type='c_allreduce_sum',
            inputs={'X': fused_output},
            outputs={'Out': fused_output},
            attrs={'ring_id': ring_id, self.op_role_key: OpRole.Backward},
        )
        global_offset += 1

        # sync before adam
        block._insert_op(
            global_offset,
            type='c_sync_comm_stream',
            inputs={'X': fused_output},
            outputs={'Out': fused_output},
            attrs={'ring_id': ring_id, self.op_role_key: OpRole.Backward},
        )
        global_offset += 1
681 682 683


class MultiThread(GradAllReduce):
684
    ''' '''
685

D
danleifeng 已提交
686
    def __init__(self, nrings=1, trans_mode="all_reduce"):
687
        GradAllReduce.__init__(self, nrings)
D
danleifeng 已提交
688 689 690
        self.mode = "box"
        self.trans_mode = trans_mode
        self.fuse_grad_size_in_num = 128
691 692 693
        gpu_nums = os.getenv("FLAGS_selected_gpus", "0,1,2,3,4,5,6,7,8").split(
            ","
        )
D
danleifeng 已提交
694
        self.gpu_num = len(gpu_nums)
695 696 697 698 699 700 701 702

    def _transpile_startup_program(self):
        if len(self.endpoints) > 1:
            print("begin to _transpile_startup_program for multi-node")
            print("current_endpoint: ", self.current_endpoint)
            print("total endpoints: ", self.endpoints)
            print("rank: %d, ring_id: %d" % (self.rank, self.nrings))
            for ring_id in range(self.nrings):
703 704 705 706 707 708 709 710 711
                self._init_communicator(
                    self.startup_program,
                    self.current_endpoint,
                    self.endpoints,
                    self.rank,
                    ring_id,
                    self.wait_port,
                    True,
                )
712

713
        else:
F
Fan Zhang 已提交
714 715
            if "xpu" in self.trans_mode:
                print(
716 717
                    "begin to _transpile_startup_program for single-node in XPU"
                )
F
Fan Zhang 已提交
718 719
                block = self.startup_program.global_block()
                block.append_op(
720
                    type='c_comm_init_all',
F
Fan Zhang 已提交
721
                    attrs={
722 723 724 725 726 727 728 729
                        'devices': list(
                            map(
                                int, os.getenv("FLAGS_selected_gpus").split(",")
                            )
                        ),
                        'ring_id': 0,
                    },
                )
F
Fan Zhang 已提交
730 731 732 733
            else:
                print("begin to _transpile_startup_program for single-node")
                block = self.startup_program.global_block()
                block.append_op(type='c_comm_init_all', attrs={'ring_id': 0})
D
danleifeng 已提交
734 735 736 737 738 739 740 741 742 743 744

    def _transpile_main_program(self):
        self._insert_scale_loss_grad_ops()
        if self.trans_mode == "all_gather":
            print("begin to transpile in all-gather mode")
            self.allgather_ranks = self.nranks * self.gpu_num
            self._insert_allgather_ops()
            self._update_adam_ops()
        elif self.trans_mode == "fuse_all_reduce":
            print("begin to transpile in fuse all-reduce mode")
            self._insert_fuse_allreduce_ops()
745 746 747 748
        elif (
            self.trans_mode == "all_reduce_xpu"
            and len(os.getenv("FLAGS_selected_gpus").split(",")) == 1
        ):
749 750 751
            print(
                "skip transpile in all-reduce-xpu mode when number of devices is only one"
            )
D
danleifeng 已提交
752 753 754 755 756 757 758 759 760 761 762 763
        else:
            print("begin to transpile in all-reduce mode")
            self._insert_allreduce_ops()

    def _insert_allgather_ops(self):
        """
        insert allgather op to the main_program
        """
        block = self.main_program.global_block()
        ring_id = -1
        grad = None
        for idx, op in reversed(list(enumerate(block.ops))):
764 765 766 767
            if (
                self._is_backward_op(op)
                and self.op_role_var_key in op.attr_names
            ):
D
danleifeng 已提交
768 769 770 771 772 773 774 775 776 777 778 779 780
                op_role_var = op.all_attrs()[self.op_role_var_key]
                if len(op_role_var) == 0:
                    continue
                assert len(op_role_var) % 2 == 0

                offset = idx
                for i in range(0, len(op_role_var), 2):
                    param = block.vars[op_role_var[i]]
                    new_grad_var = block.create_var(
                        name=op_role_var[i] + "_allgather",
                        shape=[self.allgather_ranks] + list(param.shape),
                        persistable=False,
                        dtype=core.VarDesc.VarType.FP32,
781 782
                        stop_gradient=True,
                    )
D
danleifeng 已提交
783 784 785 786 787 788 789 790 791 792 793
                    grad = block.vars[op_role_var[i + 1]]
                    if param.is_distributed:  # no need to care: used in PLSC
                        continue

                    if offset == idx:
                        offset += 1
                        block._insert_op(
                            offset,
                            type='c_sync_calc_stream',
                            inputs={'X': grad},
                            outputs={'Out': grad},
794 795
                            attrs={self.op_role_key: OpRole.Backward},
                        )
D
danleifeng 已提交
796 797 798 799 800
                        offset += 1

                    # As we search ops reversedly, we should insert c_allgather
                    # op in the same way to keep the ring_id alternate
                    ring_id = (ring_id + 1) % self.nrings
801 802 803 804 805 806 807 808 809 810 811
                    block._insert_op(
                        offset,
                        type='c_allgather',
                        inputs={'X': grad},
                        outputs={'Out': new_grad_var},
                        attrs={
                            'nranks': self.allgather_ranks,
                            'ring_id': ring_id,
                            self.op_role_key: OpRole.Backward,
                        },
                    )
D
danleifeng 已提交
812 813 814 815 816 817 818

        if grad is None:
            return

        for idx, op in enumerate(block.ops):
            if self._is_optimizer_op(op):
                for ring_id in range(self.nrings):
819 820 821 822 823 824 825 826 827 828
                    block._insert_op(
                        idx + ring_id,
                        type='c_sync_comm_stream',
                        inputs={'X': grad},
                        outputs={'Out': grad},
                        attrs={
                            'ring_id': ring_id,
                            self.op_role_key: OpRole.Backward,
                        },
                    )
D
danleifeng 已提交
829 830 831 832 833 834 835 836 837 838 839
                break

    def _update_adam_ops(self):
        """
        remove the original adam op, and add new adam ops
        """
        block = self.main_program.global_block()

        for idx, op in reversed(list(enumerate(block.ops))):
            if self._is_optimizer_op(op):
                offset = idx
840 841 842
                if (
                    op.type != 'adam' and op.type != 'lamb'
                ):  # filter out scale op
D
danleifeng 已提交
843 844 845 846 847 848 849 850
                    continue
                param_name = op.input("Param")[0]
                inputs = {
                    "Param": block.vars[op.input("Param")[0]],
                    "LearningRate": block.vars[op.input("LearningRate")[0]],
                    "Moment1": block.vars[op.input("Moment1")[0]],
                    "Moment2": block.vars[op.input("Moment2")[0]],
                    "Beta1Pow": block.vars[op.input("Beta1Pow")[0]],
851
                    "Beta2Pow": block.vars[op.input("Beta2Pow")[0]],
D
danleifeng 已提交
852 853 854 855 856 857
                }
                outputs = {
                    "ParamOut": block.vars[op.output("ParamOut")[0]],
                    "Moment1Out": block.vars[op.output("Moment1Out")[0]],
                    "Moment2Out": block.vars[op.output("Moment2Out")[0]],
                    "Beta1PowOut": block.vars[op.output("Beta1PowOut")[0]],
858
                    "Beta2PowOut": block.vars[op.output("Beta2PowOut")[0]],
D
danleifeng 已提交
859 860
                }
                attrs = {
861 862 863 864 865 866 867
                    "epsilon": op.attr('epsilon'),
                    "beta1": op.attr('beta1'),
                    "beta2": op.attr('beta2'),
                    "lazy_mode": op.attr('lazy_mode'),
                    "min_row_size_to_use_multithread": op.attr(
                        'min_row_size_to_use_multithread'
                    ),
D
danleifeng 已提交
868 869 870 871 872 873 874
                }
                split_vars = [
                    block.create_var(
                        name=param_name + "_" + str(i),
                        shape=block.vars[op.input("Param")[0]].shape,
                        persistable=False,
                        dtype=core.VarDesc.VarType.FP32,
875 876 877
                        stop_gradient=True,
                    )
                    for i in range(self.allgather_ranks)
D
danleifeng 已提交
878
                ]
879 880 881 882 883 884 885 886 887
                block._insert_op(
                    offset,
                    type="split",
                    inputs={
                        'X': block.vars[op.input("Param")[0] + "_allgather"]
                    },
                    outputs={'Out': split_vars},
                    attrs={'num': self.allgather_ranks, 'axis': 0},
                )
D
danleifeng 已提交
888 889 890 891
                offset += 1

                for i in range(self.allgather_ranks):
                    inputs["Grad"] = split_vars[i]
892 893 894 895 896 897 898
                    block._insert_op(
                        offset,
                        type=op.type,
                        inputs=inputs,
                        outputs=outputs,
                        attrs=attrs,
                    )
D
danleifeng 已提交
899 900 901 902 903 904 905 906 907 908 909 910 911 912
                    offset += 1
                # remove the original adam op
                block._remove_op(offset)

    def _insert_fuse_allreduce_ops(self):
        """
        insert coalesce_tensor and all reduce ops
        """
        block = self.main_program.global_block()
        ring_id = 0 % self.nrings
        grad = None
        param_grads = []
        # find all grad params
        for op in reversed(block.ops):
913 914 915 916
            if (
                self._is_backward_op(op)
                and self.op_role_var_key in op.attr_names
            ):
D
danleifeng 已提交
917 918 919
                op_role_var = op.all_attrs()[self.op_role_var_key]
                if len(op_role_var) == 0:
                    continue
920 921 922 923
                assert len(op_role_var) % 2 == 0, (
                    "vars need to be one param var followed by one grad var, "
                    "but got odd number of vars"
                )
D
danleifeng 已提交
924 925 926 927 928 929 930 931 932 933 934 935 936 937 938
                for i in range(0, len(op_role_var), 2):
                    param_name = op_role_var[i]
                    param = block.var(param_name)
                    grad_name = op_role_var[i + 1]
                    grad = block.var(grad_name)
                    if param.is_distributed:
                        continue
                    param_grads.append(grad)
        if grad is None:
            return

        segments = []
        last_dtype = None
        # split the grad based on dtype and fused size
        for var in param_grads:
939 940 941 942 943
            if (
                len(segments) == 0
                or len(segments[-1]) == self.fuse_grad_size_in_num
                or var.dtype != last_dtype
            ):
D
danleifeng 已提交
944 945 946 947 948 949 950 951 952 953
                segments.append([var])
                last_dtype = var.dtype
            else:
                segments[-1].append(var)

        fused_vars = []
        for idx, op in enumerate(block.ops):
            if self._is_optimizer_op(op):
                for segment in segments:
                    # insert coalesce tensor
954 955 956 957 958 959 960 961
                    tmp_var = block.create_var(
                        name=unique_name.generate(
                            'FusedOutput_{}'.format(segment[0].name)
                        ),
                        dtype=segment[0].dtype,
                        persistable=False,
                        stop_gradient=True,
                    )
D
danleifeng 已提交
962
                    fused_vars.append(tmp_var)
963 964 965 966 967 968 969 970 971 972 973 974
                    block._insert_op(
                        idx,
                        type="coalesce_tensor",
                        inputs={"Input": segment},
                        outputs={"Output": segment, "FusedOutput": tmp_var},
                        attrs={
                            "copy_data": True,
                            "use_align": True,
                            "dtype": segment[0].dtype,
                            self.op_role_key: OpRole.Backward,
                        },
                    )
D
danleifeng 已提交
975 976 977 978 979 980
                break

        # insert the allreduce_sum op
        for idx, op in enumerate(block.ops):
            if self._is_optimizer_op(op):
                for fused_var in fused_vars:
981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998
                    block._insert_op(
                        idx,
                        type='c_allreduce_sum',
                        inputs={'X': fused_var},
                        outputs={'Out': fused_var},
                        attrs={
                            'ring_id': ring_id,
                            'use_calc_stream': False,
                            self.op_role_key: OpRole.Backward,
                        },
                    )
                    block._insert_op(
                        idx,
                        type='c_sync_calc_stream',
                        inputs={'X': fused_var},
                        outputs={'Out': fused_var},
                        attrs={self.op_role_key: OpRole.Backward},
                    )
D
danleifeng 已提交
999 1000 1001 1002 1003 1004 1005 1006 1007
                break

        if len(fused_vars) == 0:
            block._sync_with_cpp()
            return

        # insert the sync comm op
        for idx, op in enumerate(block.ops):
            if self._is_optimizer_op(op):
1008 1009 1010 1011 1012 1013 1014 1015 1016 1017
                block._insert_op(
                    idx,
                    type='c_sync_comm_stream',
                    inputs={'X': fused_vars[0]},
                    outputs={'Out': fused_vars[0]},
                    attrs={
                        'ring_id': ring_id,
                        self.op_role_key: OpRole.Backward,
                    },
                )
D
danleifeng 已提交
1018 1019
                break
        block._sync_with_cpp()