auto_parallel_sharding.py 43.8 KB
Newer Older
J
JZ-LIANG 已提交
1
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
2
#
J
JZ-LIANG 已提交
3 4 5
# 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
6
#
J
JZ-LIANG 已提交
7
#     http://www.apache.org/licenses/LICENSE-2.0
8
#
J
JZ-LIANG 已提交
9 10 11 12 13 14
# 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 logging
16
from functools import reduce
17 18

import paddle
19 20
from paddle.distributed.auto_parallel.operators.common import (
    is_data_parallel_reduce_op,
21
    is_parameter_related,
22
)
23
from paddle.distributed.auto_parallel.process_group import new_process_group
24 25
from paddle.distributed.auto_parallel.utils import (
    _get_comm_group,
26 27
    get_logger,
    get_var_numel,
28 29 30
    naive_set_dist_op_attr_for_program_by_mesh_and_mapping,
    set_var_dist_attr,
)
31 32 33 34 35 36 37 38 39 40
from paddle.distributed.fleet.meta_optimizers.common import (
    is_backward_op,
    is_optimizer_op,
)
from paddle.distributed.fleet.meta_optimizers.sharding.utils import get_var_size
from paddle.fluid import unique_name
from paddle.fluid.framework import default_main_program, default_startup_program
from paddle.framework import core

from .pass_base import PassBase, register_pass
J
JZ-LIANG 已提交
41 42 43

OpRole = core.op_proto_and_checker_maker.OpRole
OP_ROLE_KEY = core.op_proto_and_checker_maker.kOpRoleAttrName()
44
_skip_ops = [
45 46 47 48 49 50 51
    'create_py_reader',
    'create_double_buffer_reader',
    'read',
    'slice',
    'split',
    'assign',
    "send_v2",
52
]
J
JZ-LIANG 已提交
53 54
# update here to support new optimizers
_supported_optimizer_type = [
55 56 57 58 59 60 61 62 63 64
    "adam",
    "adamax",
    "adamw",
    "decayed_adagrad",
    "momentum",
    "dgc_momentum",
    "lars_momentum",
    "merged_momentum",
    "lamb",
    "sgd",
J
JZ-LIANG 已提交
65 66
]

67 68
_logger = get_logger(logging.INFO)

J
JZ-LIANG 已提交
69

70
def _is_reshard_op(op):
71 72 73
    return op.desc.has_attr(
        "op_namescope"
    ) and "/auto_parallel/reshard" in op.desc.attr('op_namescope')
74 75


J
JZ-LIANG 已提交
76 77 78
# NOTE we add the "auto_parallel" prefix to the pass in order to
# indicate that this pass should obey some constrains by auto_parallel
# for example all ops and vars should has dist attr before and after pass
79
# should use dist op instead of custom comm op
J
JZ-LIANG 已提交
80 81 82
@register_pass("auto_parallel_sharding")
class ShardingPass(PassBase):
    def __init__(self):
83
        super().__init__()
J
JZ-LIANG 已提交
84 85
        self.set_attr("dist_context", None)
        self.set_attr("stage", None)
Z
zhaoyingli 已提交
86 87
        self.set_attr("sharding_degree", None)  # for parallelizer
        self.set_attr("degree", None)  # for parallelizer_v2
88 89 90
        self.set_attr("overlap_grad_comm", None)
        self.set_attr("bucket_size_numel", None)
        self.set_attr("partition_algor", None)
J
JZ-LIANG 已提交
91 92 93 94 95 96 97
        self.set_attr("params_grads", [])
        self.set_attr("global_rank", -1)
        self.dp_groups = set()
        self.sharding_infos = []
        self.varname_to_sharding_info = {}
        self.partial_sharding = False
        self.outer_dp_group = None
98
        self.shared_params_grads = []
J
JZ-LIANG 已提交
99 100 101 102 103 104 105

    def _check_self(self):
        if self.get_attr("dist_context") is None:
            return False

        if self.get_attr("stage") not in [1, 2, 3]:
            return False
Z
zhaoyingli 已提交
106
        if self.get_attr("sharding_degree") is not None:
107 108 109
            if (
                not isinstance(self.get_attr("sharding_degree"), int)
            ) or self.get_attr("sharding_degree") <= 1:
Z
zhaoyingli 已提交
110 111
                return False
        elif self.get_attr("degree") is not None:
112 113 114
            if (not isinstance(self.get_attr("degree"), int)) or self.get_attr(
                "degree"
            ) <= 1:
Z
zhaoyingli 已提交
115 116
                return False
        else:
J
JZ-LIANG 已提交
117 118 119
            return False
        if len(self.get_attr("params_grads")) <= 0:
            return False
120 121 122
        if (not isinstance(self.get_attr("global_rank"), int)) or self.get_attr(
            "global_rank"
        ) < 0:
J
JZ-LIANG 已提交
123
            return False
124 125 126 127 128 129
        if self.get_attr("overlap_grad_comm") is None:
            return False
        if self.get_attr("bucket_size_numel") is None:
            return False
        if self.get_attr("partition_algor") is None:
            return False
J
JZ-LIANG 已提交
130 131 132 133 134 135 136 137

        return True

    def _check_conflict(self, other_pass):
        return True

    def _apply_single_impl(self, main_program, startup_program, context):
        self._dist_context = self.get_attr("dist_context")
Z
zhaoyingli 已提交
138
        self.sharding_world_size = int(
139 140
            self.get_attr("sharding_degree") or self.get_attr("degree")
        )
J
JZ-LIANG 已提交
141 142
        self.stage = int(self.get_attr("stage"))
        self.global_rank = int(self.get_attr("global_rank"))
143 144 145
        self.overlap_grad_comm = self.get_attr("overlap_grad_comm")
        self.bucket_size_numel = int(self.get_attr("bucket_size_numel"))
        self.partition_algor = self.get_attr("partition_algor")
J
JZ-LIANG 已提交
146
        params_grads = self.get_attr("params_grads")
147 148 149 150
        main_block, startup_block = (
            main_program.global_block(),
            startup_program.global_block(),
        )
J
JZ-LIANG 已提交
151

152 153 154 155 156 157 158 159
        # NOTE Multi / Sub-Block Support
        # we assume that only parameter are present and partitioned in main_block,
        # there is NO new param in sub_block, and all params in sub_block follows the same
        # partition as main_block. the above contraint fullfill the 3 most common use-cases in Paddle sub_block:
        # 1. subblock for lr scheduler
        # 2. sub-block uses the same or partial network of main-block, e.g. GPT3 generation model
        # 3. sub-block used for double backward

J
JZ-LIANG 已提交
160
        self._build_sharding_groups(main_block, params_grads)
161 162 163 164
        for block in main_program.blocks:
            self._shard_optimizer(block, startup_block, params_grads, context)
            self._shard_gradient_synchronization(block)
            self._shard_parameter(block, startup_block)
J
JZ-LIANG 已提交
165

166
        context.set_attr("params_grads", self.shared_params_grads)
167
        self._optimization_pass(main_program, startup_program)
168

J
JZ-LIANG 已提交
169 170
    def _build_sharding_groups(self, main_block, params_grads):
        self._collective_data_parallel_groups(main_block)
171
        self._build_sharding_infos(main_block, params_grads)
J
JZ-LIANG 已提交
172 173 174

    def _collective_data_parallel_groups(self, main_block):
        for op in main_block.ops:
J
JZ-LIANG 已提交
175
            if not _is_forward_op(op) or op.type in _skip_ops:
J
JZ-LIANG 已提交
176
                continue
177 178 179 180
            # NOTE: there aren't dist_attr in the ops which reshard insert,
            # and should be skip in sharding.
            if _is_reshard_op(op):
                continue
J
JZ-LIANG 已提交
181
            group = _inference_data_parallel_group_for_operator(
182 183
                self.global_rank, op, self._dist_context
            )
J
JZ-LIANG 已提交
184 185 186
            if group is not None:
                self.dp_groups.add(group)

187
        # TODO(JZ-LIANG) allow more than one dp groups in network, support more general distribution
J
JZ-LIANG 已提交
188 189 190
        # genetated by auto search
        if len(self.dp_groups) != 1:
            raise NotImplementedError(
191 192 193 194
                "So far Only and Exactly one data parallel group in network are supported, but got [{}] different data parallel groups".format(
                    len(self.dp_groups)
                )
            )
J
JZ-LIANG 已提交
195

196 197 198 199 200 201
    def _build_sharding_infos(self, main_block, params_grads):

        # order params
        params_grads = re_order_program(
            main_block, params_grads, self._dist_context
        )
J
JZ-LIANG 已提交
202

203
        # partition
J
JZ-LIANG 已提交
204 205
        for dp_group in self.dp_groups:

206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
            assert (
                dp_group.nranks >= self.sharding_world_size
            ), "sharding world size [{}] should not larger than dp world size [{}]".format(
                self.sharding_world_size, dp_group.nranks
            )
            assert (
                dp_group.nranks % self.sharding_world_size == 0
            ), "sharding world size [{}] should be divisible by dp world size [{}]".format(
                self.sharding_world_size, dp_group.nranks
            )
            assert (
                self.global_rank in dp_group.ranks
            ), "current ranks [{}] does NOT belong to the data parallel group [{}]".format(
                self.global_rank, dp_group.ranks
            )
            assert (
                len(params_grads) >= self.sharding_world_size
            ), "number of parameters [{}] is not enough to be shard among [{}] ranks".format(
                len(params_grads), self.sharding_world_size
            )
J
JZ-LIANG 已提交
226

227
            # sharding hybrid data parallel: partial sharding param within
J
JZ-LIANG 已提交
228 229
            if dp_group.nranks > self.sharding_world_size:
                self.partial_sharding = True
230 231 232
                assert (
                    len(self.dp_groups) == 1
                ), "hybrid sharding and data parallelism are supported only when there is excatly one data parallel group in the network"
J
JZ-LIANG 已提交
233
                outer_dp_group, sharding_group = _get_dp_and_sharding_groups(
234 235
                    dp_group.ranks, self.sharding_world_size, self.global_rank
                )
J
JZ-LIANG 已提交
236 237 238 239 240
                sharding_group = new_process_group(sharding_group)
                self.outer_dp_group = new_process_group(outer_dp_group)
            else:
                sharding_group = dp_group

241
            self._dist_context._sharding_group = sharding_group
J
JZ-LIANG 已提交
242
            # TODO(JZ-LIANG) when support multiple dp groups in future, should group param and bind them to corresponding dp group
243
            sharding_info = ShardingInfo(
244 245 246 247
                sharding_group,
                self.global_rank,
                params_grads,
                self.partition_algor,
248
            )
J
JZ-LIANG 已提交
249
            self.sharding_infos.append(sharding_info)
250
            for param in sharding_info.params:
J
JZ-LIANG 已提交
251 252
                self.varname_to_sharding_info[param.name] = sharding_info

253 254 255
    def _shard_optimizer(
        self, main_block, startup_block, params_grads, pass_context
    ):
J
JZ-LIANG 已提交
256 257 258 259 260 261 262 263
        """
        sharding all optimizer related ops and vars, include:
        gradient clip ops & vars
        weight decay ops & vars
        optimizer ops and states
        """
        self._shard_amp_related_op_and_vars(main_block, pass_context)
        self._shard_weight_decay(main_block)
264
        # self._shard_gradient_clip(main_block)
J
JZ-LIANG 已提交
265 266 267 268 269 270 271 272 273 274 275 276
        self._shard_optimizer_ops_and_states(main_block, startup_block)
        self._insert_optimizer_broadcasts(main_block, startup_block)

    def _shard_amp_related_op_and_vars(self, main_block, pass_context):

        if self.stage < 2:
            return

        for idx, op in reversed(list(enumerate(main_block.ops))):
            # shard amp related param_grad cast
            if _is_param_grad_fp32_cast_op(main_block, op):
                output_name = op.output_arg_names[0]
277
                param_name = output_name[: output_name.find("@")]
J
JZ-LIANG 已提交
278 279 280 281 282 283 284 285
                if not self._is_parameter_in_local_shard(param_name):
                    main_block._remove_op(idx, sync=False)
                    main_block._remove_var(output_name, sync=False)

            # shard check nan inf
            elif op.type in ["check_finite_and_unscale", "update_loss_scaling"]:
                reversed_x = []
                for input_name in op.desc.input('X'):
286
                    param_name = input_name[: input_name.find("@")]
J
JZ-LIANG 已提交
287 288 289

                    if self._is_parameter_in_local_shard(param_name):
                        reversed_x.append(input_name)
290 291 292 293 294 295 296 297

                # NOTE: When `reversed_x` is [], check_finite_and_unscale will be replaced by `fill_constant` op.
                # The output of check_finite_and_unscale is be set False
                if reversed_x:
                    op.desc.set_input('X', reversed_x)
                    op.desc.set_output('Out', reversed_x)
                else:
                    if op.type == "check_finite_and_unscale":
298
                        op_role = op.attr('op_role')
299 300 301 302 303 304 305 306 307 308 309
                        out_name = op.output_arg_names[0]
                        out_var = main_block.vars[out_name]
                        main_block._remove_op(idx, sync=False)
                        main_block._insert_op_without_sync(
                            idx,
                            type="fill_constant",
                            outputs={"Out": out_var},
                            attrs={
                                "shape": out_var.shape,
                                "dtype": out_var.dtype,
                                "value": 0,
310
                                OP_ROLE_KEY: op_role,
311 312
                            },
                        )
313 314
                    else:
                        main_block._remove_op(idx, sync=False)
J
JZ-LIANG 已提交
315 316 317 318 319 320 321 322 323

        main_block._sync_with_cpp()

    def _shard_gradient_clip(self, main_block):

        if self.stage < 2:
            return

        # TODO (JZ-LIANG) support calculate global norm with tensor parallelism
J
JZ-LIANG 已提交
324 325 326 327
        removed_op_type = ['elementwise_mul', 'squared_l2_norm', 'clip_by_norm']
        removed_op_idx = set()
        removed_tmp_var = set()

J
JZ-LIANG 已提交
328 329 330 331
        for idx, op in list(enumerate(main_block.ops)):
            if not _is_gradient_clip_op(op):
                continue

J
JZ-LIANG 已提交
332 333
            if op.type in removed_op_type:
                input_name = op.input("X")[0]
334
                param_name = input_name[: input_name.find("@GRAD")]
J
JZ-LIANG 已提交
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349
                if not self._is_parameter_in_local_shard(param_name):
                    removed_op_idx.add(idx)
                    if op.type in ['squared_l2_norm', 'clip_by_norm']:
                        for output_name in op.output_arg_names:
                            removed_tmp_var.add(output_name)

        for idx, op in reversed(list(enumerate(main_block.ops))):
            if not _is_gradient_clip_op(op):
                continue
            if idx in removed_op_idx:
                main_block._remove_op(idx, sync=False)

        for varname in removed_tmp_var:
            main_block._remove_var(varname, sync=False)

J
JZ-LIANG 已提交
350 351 352 353 354 355 356 357 358 359
        for idx, op in list(enumerate(main_block.ops)):
            if not _is_gradient_clip_op(op):
                continue
            if op.type == 'sum':
                reserved_vars = []
                for input_name in op.input_arg_names:
                    if input_name not in removed_tmp_var:
                        reserved_vars.append(input_name)
                op.desc.set_input("X", reserved_vars)

360
                sum_op_output = op.output_arg_names[0]
J
JZ-LIANG 已提交
361 362
                for i, sharding_info in enumerate(self.sharding_infos):
                    new_op = main_block._insert_op(
J
JZ-LIANG 已提交
363
                        idx + i + 1,
J
JZ-LIANG 已提交
364 365 366 367 368 369 370 371
                        type='c_allreduce_sum',
                        inputs={'X': [sum_op_output]},
                        outputs={'Out': [sum_op_output]},
                        attrs={
                            'ring_id': sharding_info.group.id,
                            'op_namescope': "/gradient_clip_model_parallelism",
                            'use_calc_stream': True,
                            OP_ROLE_KEY: OpRole.Optimize,
372 373 374 375 376 377 378
                        },
                    )
                    dist_attr = (
                        self._dist_context.get_tensor_dist_attr_for_program(
                            main_block.var(sum_op_output)
                        )
                    )
379 380 381 382
                    # assert dist_attr is not None
                    # naive_set_dist_op_attr_for_program_by_mesh_and_mapping(
                    #     new_op, dist_attr.process_mesh, dist_attr.dims_mapping,
                    #     self._dist_context)
J
JZ-LIANG 已提交
383 384 385 386 387 388 389 390 391 392 393 394 395 396
                break

        main_block._sync_with_cpp()

    def _shard_weight_decay(self, main_block):

        if self.stage < 2:
            return

        for idx, op in reversed(list(enumerate(main_block.ops))):
            if not _is_weight_decay_op(op):
                continue
            else:
                raise NotImplementedError(
397 398
                    "weight decay is NOT supported by now"
                )
J
JZ-LIANG 已提交
399 400 401 402 403 404 405 406 407 408 409 410 411 412
        main_block._sync_with_cpp()

    def _shard_optimizer_ops_and_states(self, main_block, startup_block):

        should_removed_optimizer_states = []
        for idx, op in reversed(list(enumerate(main_block.ops))):
            if not is_optimizer_op(op):
                break

            if op.type in _supported_optimizer_type:
                assert "Param" in op.input_names
                assert len(op.input("Param")) == 1
                param_name = op.input("Param")[0]
                if not self._is_parameter_in_local_shard(param_name):
413 414 415 416 417 418 419
                    should_removed_optimizer_states.extend(
                        [
                            varname
                            for varname in op.output_arg_names
                            if varname != param_name
                        ]
                    )
J
JZ-LIANG 已提交
420
                    main_block._remove_op(idx, sync=False)
421 422
                else:
                    self.shared_params_grads.append(
423 424
                        self._get_param_grad(param_name)
                    )
J
JZ-LIANG 已提交
425 426

        for idx, op in reversed(list(enumerate(startup_block.ops))):
427 428 429 430
            if (
                len(op.output_arg_names) == 1
                and op.output_arg_names[0] in should_removed_optimizer_states
            ):
J
JZ-LIANG 已提交
431 432 433 434 435 436 437 438 439 440 441 442 443
                startup_block._remove_op(idx, sync=False)

        for varname in should_removed_optimizer_states:
            if main_block.has_var(varname):
                main_block._remove_var(varname, sync=False)
            if startup_block.has_var(varname):
                startup_block._remove_var(varname, sync=False)

        main_block._sync_with_cpp()
        startup_block._sync_with_cpp()

    def _insert_optimizer_broadcasts(self, main_block, startup_block):

444
        if self.stage > 2 or self.bucket_size_numel > 1:
J
JZ-LIANG 已提交
445 446 447 448 449 450 451
            return

        for sharding_info in self.sharding_infos:
            for param in sharding_info.params:
                assert main_block.has_var(param.name)
                assert startup_block.has_var(param.name)

452 453 454 455 456 457 458 459 460 461 462 463 464 465
                new_op = main_block.append_op(
                    type='c_broadcast',
                    inputs={'X': param},
                    outputs={'Out': param},
                    attrs={
                        'ring_id': sharding_info.group.id,
                        'root': sharding_info.get_var_rank(param.name),
                        'use_calc_stream': True,
                        OP_ROLE_KEY: OpRole.Optimize,
                    },
                )
                param_dist_attr = (
                    self._dist_context.get_tensor_dist_attr_for_program(param)
                )
J
JZ-LIANG 已提交
466 467
                assert param_dist_attr is not None
                naive_set_dist_op_attr_for_program_by_mesh_and_mapping(
468 469 470 471 472
                    new_op,
                    param_dist_attr.process_mesh,
                    param_dist_attr.dims_mapping,
                    self._dist_context,
                )
J
JZ-LIANG 已提交
473 474 475 476 477 478 479
        main_block._sync_with_cpp()

    def _is_parameter_in_local_shard(self, param_name):
        assert param_name in self.varname_to_sharding_info
        sharding_info = self.varname_to_sharding_info[param_name]
        return sharding_info.is_in_local_shard(param_name)

480 481 482 483 484 485 486
    def _get_param_grad(self, param_name):
        assert param_name in self.varname_to_sharding_info
        sharding_info = self.varname_to_sharding_info[param_name]
        p_g = sharding_info.get_param_grad(param_name)
        assert p_g is not None
        return p_g

J
JZ-LIANG 已提交
487 488 489 490 491 492 493
    def _shard_gradient_synchronization(self, main_block):

        if self.stage < 2:
            return

        dp_ring_ids = [group.id for group in self.dp_groups]
        for idx, op in reversed(list(enumerate(main_block.ops))):
494
            if _is_param_grad_allreduce_op(op, main_block):
J
JZ-LIANG 已提交
495 496 497
                input_name = op.input_arg_names[0]
                base_name = _get_base_name_from_grad_name(input_name)
                sharding_info = self.varname_to_sharding_info[base_name]
498 499 500 501 502 503 504 505 506 507 508 509
                _insert_reduce_op(
                    main_block,
                    idx,
                    input_name,
                    sharding_info.group.id,
                    sharding_info.get_var_rank(base_name),
                    self._dist_context,
                )
                if (
                    not self.partial_sharding
                    or not sharding_info.is_in_local_shard(base_name)
                ):
J
JZ-LIANG 已提交
510 511 512 513
                    main_block._remove_op(idx + 1, sync=False)
                else:
                    op._set_attr("ring_id", self.outer_dp_group.id)

514 515 516 517 518 519 520 521 522 523 524
            # NOTE:
            # var@GRAD = sum(var@GRAD@RENAME@0, var@GRAD@RENAME@1)
            # If the var is not in local rank and it is output of many ops, or the var is renamed in another words,
            # the sum op should be removed.
            if _is_param_grad_sum_op(op, main_block):
                out_name = op.output_arg_names[0]
                base_name = _get_base_name_from_grad_name(out_name)
                sharding_info = self.varname_to_sharding_info[base_name]
                if not sharding_info.is_in_local_shard(base_name):
                    main_block._remove_op(idx, sync=False)

J
JZ-LIANG 已提交
525 526 527 528 529 530 531 532 533
        main_block._sync_with_cpp()

    def _shard_parameter(self, main_block, startup_block):

        if self.stage < 3:
            return

        dp_ring_ids = [group.id for group in self.dp_groups]
        for sharding_info in self.sharding_infos:
534 535 536 537
            (
                need_broadcast_vars,
                param_usage,
            ) = sharding_info.get_broadcast_vars_and_param_usage(main_block)
J
JZ-LIANG 已提交
538 539
            not_used_param_nane = []
            for param_name in param_usage:
540 541 542 543 544
                if (
                    param_usage[param_name] == 0
                    and sharding_info.get_var_rank(param_name)
                    != sharding_info.local_rank
                ):
J
JZ-LIANG 已提交
545 546 547 548 549 550
                    not_used_param_nane.append(param_name)

            for idx, op in reversed(list(enumerate(main_block.ops))):
                if is_optimizer_op(op):
                    continue

551
                for input_name in op.input_arg_names:
552 553
                    # NOTE hack for embedding op when AMP 02-3
                    # paddle amp force embedding (lookup table) to be run on fp32
554 555 556
                    if _is_param_fp16_cast_op(
                        main_block, op, sharding_info.param_names
                    ):
J
JZ-LIANG 已提交
557 558 559 560 561 562 563
                        continue
                    if input_name not in need_broadcast_vars:
                        continue
                    root_rank = sharding_info.get_var_rank(input_name)
                    if root_rank == sharding_info.local_rank:
                        broadcast_varname = input_name
                    else:
564 565 566
                        broadcast_varname = unique_name.generate(
                            input_name + "@BroadCast"
                        )
J
JZ-LIANG 已提交
567
                        input_var = main_block.var(input_name)
568 569 570 571 572 573 574 575 576 577 578
                        new_var = main_block.create_var(
                            name=broadcast_varname,
                            shape=input_var.shape,
                            dtype=input_var.dtype,
                            persistable=False,
                        )
                        ref_dist_attr = (
                            self._dist_context.get_tensor_dist_attr_for_program(
                                input_var
                            )
                        )
J
JZ-LIANG 已提交
579
                        out_var_dist_attr = set_var_dist_attr(
580 581
                            self._dist_context,
                            new_var,
J
JZ-LIANG 已提交
582
                            ref_dist_attr.dims_mapping,
583 584
                            ref_dist_attr.process_mesh,
                        )
J
JZ-LIANG 已提交
585 586
                        op._rename_input(input_name, broadcast_varname)

587 588 589 590 591 592 593 594 595 596
                    _insert_init_and_broadcast_op(
                        main_block,
                        idx,
                        broadcast_varname,
                        sharding_info.local_rank,
                        root_rank,
                        sharding_info.group.id,
                        op.attr('op_role'),
                        self._dist_context,
                    )
J
JZ-LIANG 已提交
597 598 599 600 601 602 603 604 605 606 607 608 609 610

            for idx, op in reversed(list(enumerate(main_block.ops))):
                if op.type != "cast":
                    continue
                input_name = op.input_arg_names[0]
                output_name = op.output_arg_names[0]
                if input_name in not_used_param_nane:
                    main_block._remove_op(idx, sync=False)
                    main_block._remove_var(output_name, sync=False)

            for idx, op in reversed(list(enumerate(startup_block.ops))):
                assert len(op.output_arg_names) == 1
                output_name = op.output_arg_names[0]

611 612 613 614 615 616 617 618 619
                if (
                    op.type == "c_broadcast"
                    and op.attr("ring_id") in dp_ring_ids
                ):
                    if (
                        self.outer_dp_group
                        and sharding_info.get_var_rank(output_name)
                        == sharding_info.local_rank
                    ):
J
JZ-LIANG 已提交
620 621 622 623 624
                        op._set_attr("ring_id", self.outer_dp_group.id)
                    else:
                        startup_block._remove_op(idx, sync=False)
                    continue

625 626 627 628 629 630
                if (
                    op.type != "c_broadcast"
                    and output_name in param_usage
                    and sharding_info.get_var_rank(output_name)
                    != sharding_info.local_rank
                ):
J
JZ-LIANG 已提交
631 632
                    startup_block._remove_op(idx, sync=False)

J
JZ-LIANG 已提交
633
            for param_name in param_usage:
634 635 636 637
                if (
                    sharding_info.get_var_rank(param_name)
                    != sharding_info.local_rank
                ):
J
JZ-LIANG 已提交
638 639
                    main_block._remove_var(param_name, sync=False)
                    startup_block._remove_var(param_name, sync=False)
J
JZ-LIANG 已提交
640 641 642 643

        main_block._sync_with_cpp()
        startup_block._sync_with_cpp()

644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661
    def _optimization_pass(self, main_program, startup_program):

        with paddle.static.program_guard(main_program, startup_program):
            if self.overlap_grad_comm:
                _fuse_overlap_gradient_comm()
            # TODO support multiple sub_blocks
            if self.bucket_size_numel > 1:
                if self.stage == 2:
                    _fuse_overlap_parameter_comm_stage_two(
                        self.sharding_infos,
                        self._dist_context,
                        fuse_size=self.bucket_size_numel,
                    )
                elif self.stage == 3:
                    _fuse_overlap_parameter_comm_stage_three(
                        self.sharding_infos, fuse_size=self.bucket_size_numel
                    )

J
JZ-LIANG 已提交
662

663 664 665 666 667 668 669 670 671 672
def _insert_init_and_broadcast_op(
    block,
    insert_idx,
    varname,
    local_rank,
    root_rank,
    ring_id,
    op_role,
    dist_context,
):
J
JZ-LIANG 已提交
673 674 675 676 677
    """
    empty op for initialization
    """
    broadcast_var = block.var(varname)
    broadcast_var_dist_attr = dist_context.get_tensor_dist_attr_for_program(
678 679 680 681 682 683 684 685 686 687 688 689 690 691 692
        broadcast_var
    )

    new_op = block._insert_op_without_sync(
        insert_idx,
        type='c_broadcast',
        inputs={'X': varname},
        outputs={'Out': varname},
        attrs={
            'ring_id': ring_id,
            'root': root_rank,
            'use_calc_stream': True,
            OP_ROLE_KEY: op_role,
        },
    )
J
JZ-LIANG 已提交
693
    naive_set_dist_op_attr_for_program_by_mesh_and_mapping(
694 695 696 697 698
        new_op,
        broadcast_var_dist_attr.process_mesh,
        broadcast_var_dist_attr.dims_mapping,
        dist_context,
    )
J
JZ-LIANG 已提交
699 700 701 702 703 704 705 706 707
    if local_rank != root_rank:

        new_op = block._insert_op_without_sync(
            insert_idx,
            type="empty",
            outputs={"Out": broadcast_var.name},
            attrs={
                "shape": broadcast_var.shape,
                "dtype": broadcast_var.dtype,
708 709 710
                OP_ROLE_KEY: op_role,
            },
        )
J
JZ-LIANG 已提交
711
        naive_set_dist_op_attr_for_program_by_mesh_and_mapping(
712 713 714 715 716
            new_op,
            broadcast_var_dist_attr.process_mesh,
            broadcast_var_dist_attr.dims_mapping,
            dist_context,
        )
J
JZ-LIANG 已提交
717 718 719
    return


720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744
def _insert_reduce_op(
    block,
    insert_idx,
    reduce_var,
    ring_id,
    root_id,
    dist_context,
    op_role=OpRole.Backward,
    use_calc_stream=True,
):
    assert (
        root_id >= 0
    ), "root id should be a positive int, but now root id is {}".format(root_id)
    new_op = block._insert_op_without_sync(
        insert_idx,
        type='c_reduce_sum',
        inputs={'X': [reduce_var]},
        outputs={'Out': [reduce_var]},
        attrs={
            'ring_id': ring_id,
            'root_id': root_id,
            'use_calc_stream': use_calc_stream,
            OP_ROLE_KEY: op_role,
        },
    )
J
JZ-LIANG 已提交
745 746

    dist_attr = dist_context.get_tensor_dist_attr_for_program(
747 748
        block.var(reduce_var)
    )
J
JZ-LIANG 已提交
749
    naive_set_dist_op_attr_for_program_by_mesh_and_mapping(
750 751
        new_op, dist_attr.process_mesh, dist_attr.dims_mapping, dist_context
    )
J
JZ-LIANG 已提交
752 753 754 755 756 757 758 759 760 761 762 763 764 765


def _get_dp_and_sharding_groups(origin_group, sharding_group_size, rank):
    dp_axis = 0
    sharding_axis = 1
    shape = [len(origin_group) // sharding_group_size, sharding_group_size]

    dp_group = _get_comm_group(origin_group, shape, dp_axis, rank)
    sharding_group = _get_comm_group(origin_group, shape, sharding_axis, rank)

    return dp_group, sharding_group


def _is_gradient_clip_op(op):
766 767 768
    return op.desc.has_attr("op_namescope") and op.desc.attr(
        "op_namescope"
    ).startswith("/gradient_clip")
J
JZ-LIANG 已提交
769 770 771


def _is_weight_decay_op(op):
772 773 774
    return op.desc.has_attr("op_namescope") and op.desc.attr(
        "op_namescope"
    ).startswith("/regularization")
J
JZ-LIANG 已提交
775 776 777 778 779


def _is_param_grad_fp32_cast_op(block, op):
    if not is_backward_op(op):
        return False
780 781 782
    if not _is_desired_cast_op(
        block, op, core.VarDesc.VarType.FP16, core.VarDesc.VarType.FP32
    ):
J
JZ-LIANG 已提交
783
        return False
784
    output_name = op.output_arg_names[0]
785
    base_name = output_name[: output_name.find("@")]
J
JZ-LIANG 已提交
786 787 788 789 790 791 792 793 794 795 796
    if not block.has_var(base_name):
        return False
    return block.var(base_name).is_parameter


def _is_param_fp16_cast_op(block, op, params):

    if is_optimizer_op(op):
        return False
    if not _is_desired_cast_op(block, op):
        return False
797
    input_name = op.input_arg_names[0]
J
JZ-LIANG 已提交
798 799 800 801 802
    if input_name not in params:
        return False
    return True


803 804 805 806 807 808
def _is_desired_cast_op(
    block,
    op,
    src_var_type=core.VarDesc.VarType.FP32,
    dst_var_type=core.VarDesc.VarType.FP16,
):
J
JZ-LIANG 已提交
809 810
    if op.type != "cast":
        return False
811 812 813 814
    assert len(op.input_arg_names) == 1
    assert len(op.output_arg_names) == 1
    input_var = block.var(op.input_arg_names[0])
    output_var = block.var(op.output_arg_names[0])
J
JZ-LIANG 已提交
815

816
    if input_var.dtype != src_var_type or output_var.dtype != dst_var_type:
J
JZ-LIANG 已提交
817 818 819 820 821 822 823 824
        return False

    return True


def _get_base_name_from_grad_name(grad_name):
    base_name = None
    if ".cast_fp16@GRAD" in grad_name:
825
        base_name = grad_name[: grad_name.find(".cast_fp16@GRAD")]
J
JZ-LIANG 已提交
826
    elif "@GRAD" in grad_name:
827
        base_name = grad_name[: grad_name.find("@GRAD")]
J
JZ-LIANG 已提交
828 829 830
    return base_name


831 832 833 834 835 836 837 838 839 840 841 842 843 844
def _is_param_grad_allreduce_op(op, block):

    if not is_data_parallel_reduce_op(op):
        return False

    output_name = op.output_arg_names[0]
    base_name = _get_base_name_from_grad_name(output_name)

    if not block.has_var(base_name):
        return False

    return block.var(base_name).is_parameter


845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860
def _is_param_grad_sum_op(op, block):

    if not is_backward_op(op):
        return False
    if op.type != "sum":
        return False

    output_name = op.output_arg_names[0]
    base_name = _get_base_name_from_grad_name(output_name)

    if not block.has_var(base_name):
        return False

    return block.var(base_name).is_parameter


J
JZ-LIANG 已提交
861 862 863 864
def _is_forward_op(op):
    return op.attr("op_role") == 0


J
JZ-LIANG 已提交
865 866 867 868 869 870 871 872 873 874 875 876
def _inference_data_parallel_group_for_operator(rank_id, op, dist_context):

    dp_group = None
    for input_name in op.input_arg_names:
        if not is_parameter_related(input_name, op.block):
            dist_attr = dist_context.get_op_dist_attr_for_program(op)
            process_mesh = dist_attr.process_mesh
            input_dim_mapping = dist_attr.get_input_dims_mapping(input_name)
            mesh_shape = process_mesh.topology
            # TODO(JZ-LIANG) replace with specific batch size dimension
            batch_size_axis = input_dim_mapping[0]
            if batch_size_axis > -1 and mesh_shape[batch_size_axis] > 1:
877 878 879 880 881 882
                group_ranks = _get_comm_group(
                    process_mesh.processes,
                    process_mesh.topology,
                    batch_size_axis,
                    rank_id,
                )
J
JZ-LIANG 已提交
883 884 885 886 887 888
                dp_group = new_process_group(group_ranks)
                break

    return dp_group


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
def partition_by_use_order(params, group_size):
    """
    shard the continouse param into same rank and divide the forward&backward computation into segement,
    which will favor the fuse pass in later.

    we assume that the params is already sorted by utilization order.
    """
    mapping = {}
    total_param_mem = 0.0
    param2mem = []
    for param in params:
        mem = get_var_size(param)
        total_param_mem += mem
        param2mem.append((param, mem))
    mapping = {x: [] for x in range(group_size)}
    cur_rank = 0
    mem_accu = 0.0
    for param, mem in param2mem:
        if mem_accu > total_param_mem * 1.0 * (cur_rank + 1) / group_size:
            cur_rank += 1
        mapping[cur_rank].append(param)
        mem_accu += mem

    return mapping


def partition_by_greedy_even(params, group_size):
    """
    use greedy alogrithm to partition parameter as even as possible.
    """
J
JZ-LIANG 已提交
919 920 921 922 923 924 925 926
    mapping = {}
    for rank_ in range(group_size):
        mapping[rank_] = []
    sizes = [0] * group_size
    for param in params:
        rank = sizes.index(min(sizes))
        mapping[rank].append(param)
        numel = reduce(lambda x, y: x * y, param.shape)
927 928 929 930 931
        assert (
            numel > 0
        ), "param [{}] should larger than 0, but it is [{}]".format(
            param.name, numel
        )
J
JZ-LIANG 已提交
932 933 934 935 936
        sizes[rank] += numel

    return mapping


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 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 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 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142
def partition_parameters(params, group_size, algor="greedy_even"):
    if algor == "greedy_even":
        rank_to_params = partition_by_greedy_even(params, group_size)
    else:
        rank_to_params = partition_by_use_order(params, group_size)

    _logger.info("Sharding Parameter Partition:")
    for k, v in rank_to_params.items():
        _logger.info(
            "Rank:{}, Parameter Size:{} MB.".format(
                k, sum([get_var_size(var) for var in v])
            )
        )
        _logger.info("Params in this rank: {}.".format([var.name for var in v]))

    return rank_to_params


def re_order_program(block, param_grads, dist_context):

    # record order
    pname_to_pg_pairs = {}
    for p, g in param_grads:
        pname_to_pg_pairs[p.name] = (p, g)

    use_order = []
    for op in block.ops:
        for input_name in op.input_arg_names:
            if (input_name in pname_to_pg_pairs) and (
                input_name not in use_order
            ):
                use_order.append(input_name)
        if len(use_order) == len(pname_to_pg_pairs):
            break

    # reorder optimzier
    last_op = block.ops[-1]
    pname_to_op = {}
    num_ops = len(block.ops)
    remove_op_indices = []
    # TODO support case when optimizer is not the last op
    if is_optimizer_op(last_op) and last_op.type in _supported_optimizer_type:
        # record optimizer
        for idx, op in reversed(list(enumerate(block.ops))):
            if op.type not in _supported_optimizer_type:
                break
            assert len(op.input("Param")) == 1
            pname_to_op[op.input("Param")[0]] = op
            remove_op_indices.append(idx)
        assert len(use_order) == len(pname_to_op)

        # append new opts
        for pname in use_order:
            new_op = block.append_op(type='nop')
            new_op.desc.copy_from(pname_to_op[pname].desc)
            dist_context.set_op_dist_attr_for_program(
                new_op,
                dist_context.get_op_dist_attr_for_program(pname_to_op[pname]),
            )

        # remove old opts
        for idx in remove_op_indices:
            block._remove_op(idx, sync=False)

        block._sync_with_cpp()
        assert len(block.ops) == num_ops

    # TODO reorder gradient clip order
    _logger.info(
        "Sharding the Order of param being used: {}.".format(use_order)
    )
    return [pname_to_pg_pairs[p] for p in use_order]


def group_param(sharding_info, fuse_size):
    """
    param are group by:
    rank id
    fuse_size
    dtype
    """
    group_to_param_map = {}
    param_to_group_map = {}
    bucket = []
    cur_group = ParameterGroup(fuse_size)
    for param in sharding_info.params:
        rank = sharding_info.get_var_rank(param.name)

        if cur_group.acceptable(param, rank):
            cur_group.collect(param, rank)
        else:
            cur_group = ParameterGroup(fuse_size)
            cur_group.collect(param, rank)

        if cur_group in group_to_param_map:
            group_to_param_map[cur_group].append(param.name)
        else:
            group_to_param_map[cur_group] = [param.name]

        param_to_group_map[param.name] = cur_group

    return group_to_param_map, param_to_group_map


def _fuse_overlap_gradient_comm():
    pass


def _fuse_overlap_parameter_comm_stage_two(
    sharding_infos, dist_context, fuse_size
):

    assert (
        len(sharding_infos) == 1
    ), "fuse overlap optimization only support one sharding group right now, but got [{}].".format(
        len(sharding_infos)
    )
    sharding_info = sharding_infos[0]

    main_block = default_main_program().global_block()
    startup_block = default_startup_program().global_block()

    group_to_param_map, param_to_group_map = group_param(
        sharding_info, fuse_size
    )
    _logger.info("Sharding Stage2 Optimization:")
    _logger.info(
        "Bucket size is [{}], [{}] Parameters are fused into [{}] Buckets".format(
            fuse_size,
            len(param_to_group_map.keys()),
            len(group_to_param_map.keys()),
        )
    )
    for i, group in enumerate(group_to_param_map.keys()):

        assert len(group) >= 1
        if len(group) > 1:
            coalesce_var_name = unique_name.generate(
                'coalecse_param_{}'.format(i)
            )
            startup_block.create_var(
                name=coalesce_var_name,
                dtype=group.dtype,
                persistable=True,
                stop_gradient=True,
            )
            group.coalesce_var = main_block.create_var(
                name=coalesce_var_name,
                dtype=group.dtype,
                persistable=True,
                stop_gradient=True,
            )
            startup_block.append_op(
                type="coalesce_tensor",
                inputs={"Input": group.params},
                outputs={
                    "Output": group.params,
                    "FusedOutput": group.coalesce_var,
                },
                attrs={
                    "copy_data": True,
                    "use_align": True,
                    "dtype": group.dtype,
                    OP_ROLE_KEY: OpRole.Forward,
                },
            )
        else:
            group.coalesce_var = group.params[0]
        _logger.info(
            "Bucket[{}] size [{}]MB : {}".format(
                i,
                sum([get_var_size(p) for p in group.params]),
                [p.name for p in group.params],
            )
        )

        # TODO Overlap broadcast with opt and next forward
        new_op = main_block.append_op(
            type='c_broadcast',
            inputs={'X': group.coalesce_var},
            outputs={'Out': group.coalesce_var},
            attrs={
                'ring_id': sharding_info.group.id,
                'root': group.rank,
                'use_calc_stream': True,
                OP_ROLE_KEY: OpRole.Optimize,
            },
        )

        # NOTE the current dist context lack the presentation for bucket tensor which
        # composes many tensor with different dims_mapping. we assign a fake dist attr
        # for it currently.


def _fuse_overlap_parameter_comm_stage_three(sharding_infos, fuse_size):

    assert (
        len(sharding_infos) == 1
    ), "fuse overlap optimization only support one sharding group right now, but got [{}].".format(
        len(sharding_infos)
    )
    sharding_info = sharding_infos[0]


class ShardingInfo(object):
    def __init__(self, group, rank, params_grads, partition_algor):
J
JZ-LIANG 已提交
1143
        self.group = group
1144
        self.params_grads = dict([(p.name, (p, g)) for p, g in params_grads])
1145 1146 1147
        assert len(self.params_grads) == len(
            set(self.params_grads)
        ), "found duplicated param in params_grads"
1148 1149

        self.params = [p for p, _ in params_grads]
J
JZ-LIANG 已提交
1150 1151 1152 1153
        self.param_names = [p.name for p in self.params]
        self.group_size = group.nranks
        self.global_rank = rank
        self.local_rank = group.ranks.index(self.global_rank)
1154
        self.partition_algor = partition_algor
J
JZ-LIANG 已提交
1155
        # rank in below mapping are local rank in this sharding group
1156 1157 1158
        self.rank_to_params = partition_parameters(
            self.params, self.group_size, self.partition_algor
        )
J
JZ-LIANG 已提交
1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175
        # include fp32 and fp16 param
        self.param_to_rank = dict()
        self._map_param_to_rank()

    def _map_param_to_rank(self):
        """
        mapping parameters to the rank which holds it.
        """
        for rank, params in self.rank_to_params.items():
            for param in params:
                self.param_to_rank[param.name] = rank

    def get_var_rank(self, varname):
        if varname in self.param_to_rank:
            return self.param_to_rank[varname]
        return -1

1176
    # determine fp32 and fp16 (cast) param
J
JZ-LIANG 已提交
1177 1178 1179
    def is_in_local_shard(self, param_name):
        return self.get_var_rank(param_name) == self.local_rank

1180 1181 1182 1183
    # NOTE the follwo logic is designed for supporting AMP O1 when
    # the param would be cast to fp16 before used for caculation.
    # and sharding should only broadcast the casted fp16 param
    # instead of the origin fp32 version param.
J
JZ-LIANG 已提交
1184 1185 1186 1187 1188 1189 1190 1191 1192
    def get_broadcast_vars_and_param_usage(self, block):
        broadcast_vars = set([])
        fp16_params = set([])
        fp16_to_fp32 = {}

        param_usage = {x: 0 for x in self.param_names}
        for op in block.ops:
            if is_optimizer_op(op):
                continue
1193
            for input_name in op.input_arg_names:
J
JZ-LIANG 已提交
1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211
                if input_name in self.param_names:
                    param_usage[input_name] += 1

        for op in block.ops:
            if not _is_param_fp16_cast_op(block, op, self.param_names):
                continue
            input_name = op.input_arg_names[0]
            output_name = op.output_arg_names[0]
            broadcast_vars.add(output_name)
            fp16_params.add(output_name)
            fp16_to_fp32[output_name] = input_name
            param_usage[input_name] -= 1
            self.param_to_rank[output_name] = self.param_to_rank[input_name]

        for param, usage in param_usage.items():
            if usage > 0:
                broadcast_vars.add(param)
        return broadcast_vars, param_usage
1212 1213 1214 1215

    def get_param_grad(self, param_name):
        if not self.is_in_local_shard(param_name):
            raise ValueError(
1216 1217
                "param[{}] not in current rank.".format(param_name)
            )
1218 1219 1220
        if param_name not in self.params_grads:
            raise ValueError('param[{}] not in params_grads'.format(param_name))
        return self.params_grads.get(param_name, None)
1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251


class ParameterGroup(object):
    def __init__(self, max_size):
        self.max_siez = max_size
        self.dtype = None
        self.rank = -1
        self.numel = 0
        self.params = []
        self.coalesce_var = None

    def acceptable(self, param, rank):
        if self.numel == 0:
            return True
        else:
            if param.dtype != self.dtype:
                return False
            if rank != self.rank:
                return False
            if self.numel + get_var_numel(param) > self.max_siez:
                return False
            return True

    def collect(self, param, rank):
        self.dtype = param.dtype
        self.rank = rank
        self.numel += get_var_numel(param)
        self.params.append(param)

    def __len__(self):
        return len(self.params)