test_auto_parallel_partitioner.py 48.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import unittest
import unittest.mock

import paddle
import paddle.nn.functional as F
20
from paddle import nn, static, tensor, utils
21
from paddle.distributed import fleet
22
from paddle.distributed.auto_parallel.completion import Completer
23
from paddle.distributed.auto_parallel.dist_context import DistributedContext
24
from paddle.distributed.auto_parallel.partitioner import Partitioner
25
from paddle.distributed.auto_parallel.process_group import new_process_group
26 27
from paddle.distributed.auto_parallel.utils import _get_comm_group
from paddle.distributed.fleet import auto
28 29

paddle.enable_static()
30
_global_parallel_strategy = None
31 32 33 34 35 36 37 38
_global_process_mesh = None


def get_programs(annotated_func):
    train_program = static.Program()
    start_program = static.Program()
    dist_context = DistributedContext()
    global _global_process_mesh
39
    dist_context.process_mesh = _global_process_mesh
40
    train_program, start_program = annotated_func(train_program, start_program)
41 42
    completer = Completer(dist_context)
    complete_train_program = completer.complete_forward_annotation(
43 44
        train_program
    )
45
    dist_context.block_state.parse_forward_blocks(complete_train_program)
46 47 48

    rank_id = 3
    dist_strategy = fleet.DistributedStrategy()
49
    partitioner = Partitioner(dist_context, rank_id)
50 51 52 53 54
    (
        test_auto_parallel_dist_main_prog,
        test_auto_parallel_dist_startup_prog,
        _,
    ) = partitioner.partition(complete_train_program, start_program, [])
55

56 57 58 59 60 61 62
    return (
        complete_train_program,
        start_program,
        test_auto_parallel_dist_main_prog,
        test_auto_parallel_dist_startup_prog,
        dist_context,
    )
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92


def is_all_parameters_shape_equal(prog1, prog2):

    params1 = prog1.all_parameters()
    params2 = prog2.all_parameters()
    params1.sort(key=lambda x: x.name)
    params2.sort(key=lambda x: x.name)
    shape1 = [tensor.shape for tensor in params1]
    shape2 = [tensor.shape for tensor in params2]

    if len(shape1) != len(shape2):
        return False
    for i in range(len(shape1)):
        if shape1[i] != shape2[i]:
            return False
    return True


def check_tensor_split(prog1, varnames1, prog2, varnames2, axis, nsplit):

    for i in range(len(varnames1)):
        var1 = prog1.global_block().var(varnames1[i])
        var2 = prog2.global_block().var(varnames2[i])
        if var1.shape[axis] != (var2.shape[axis] // nsplit):
            return False

    return True


93 94 95 96 97 98 99 100 101 102
def initialization_check(
    mode,
    dist_context,
    dist_startup_prog,
    serial_startup_prog,
    var_need_broadcast,
    process_mesh,
    mp_parallel_axis,
    dp_parallel_axis,
):
103
    if 'mp' in mode:
104
        group_ranks = _get_comm_group(
105
            process_mesh.process_ids, process_mesh.shape, mp_parallel_axis, 3
106
        )
107 108
        mp_ring_id = new_process_group(group_ranks).id
        broadcast_ops = [
109 110 111 112 113 114
            op
            for op in dist_startup_prog.global_block().ops
            if (
                op.type == "c_broadcast"
                and op.desc.attr("ring_id") == mp_ring_id
            )
115 116
        ]
        broadcast_varnames = sorted(
117 118
            [op.desc.output_arg_names()[0] for op in broadcast_ops]
        )
119 120 121 122
        if broadcast_varnames != var_need_broadcast:
            return False

    if 'dp' in mode:
123
        group_ranks = _get_comm_group(
124
            process_mesh.process_ids, process_mesh.shape, dp_parallel_axis, 3
125
        )
126 127
        dp_ring_id = new_process_group(group_ranks).id
        nparam = len(serial_startup_prog.all_parameters())
128 129 130 131 132 133 134 135 136 137
        nbroadcast_dp = len(
            [
                op
                for op in dist_startup_prog.global_block().ops
                if (
                    op.type == "c_broadcast"
                    and op.desc.attr("ring_id") == dp_ring_id
                )
            ]
        )
138 139 140 141
        if nparam != nbroadcast_dp:
            return False

    if "dp" in mode and 'mp' in mode:
142 143 144 145 146 147 148
        nbroadcast = len(
            [
                op
                for op in dist_startup_prog.global_block().ops
                if op.type == "c_broadcast"
            ]
        )
149 150 151 152 153 154
        if len(var_need_broadcast) + nbroadcast_dp != nbroadcast:
            return False

    return True


155 156 157
def get_input_var_dist_attr(op, main_program, dist_context):
    varname = op.desc.input_arg_names()
    var = main_program.global_block().var(varname[0])
158
    dist_attr = dist_context.get_tensor_dist_attr_for_program(var)
159 160 161 162 163 164
    return dist_attr


def get_output_var_dist_attr(op, main_program, dist_context):
    varname = op.desc.output_arg_names()
    var = main_program.global_block().var(varname[0])
165
    dist_attr = dist_context.get_tensor_dist_attr_for_program(var)
166 167 168 169 170
    return dist_attr


def check_equal_var_dist_attr(serial_dist_attr, dist_attr):
    equal = True
171 172 173 174
    if (
        serial_dist_attr.process_mesh != dist_attr.process_mesh
        or serial_dist_attr.dims_mapping != dist_attr.dims_mapping
    ):
175 176 177 178
        equal = False
    return equal


179 180 181
def check_equal_dist_op_attr(
    dist_context, dist_main_prog, serial_op, dist_ops, dist_op_idx
):
182 183
    equal = True
    # get serial op's process_mesh and impl_idx
184 185 186
    serial_op_dist_attr = dist_context.get_op_dist_attr_for_program(serial_op)
    serial_process_mesh = serial_op_dist_attr.process_mesh
    serial_impl_idx = serial_op_dist_attr.impl_idx
187 188 189

    # check dist_attr between serial op and dist op
    for i in dist_op_idx:
190
        op_dist_attr = dist_context.get_op_dist_attr_for_program(dist_ops[i])
191 192
        for in_varname in dist_ops[i].desc.input_arg_names():
            in_var = dist_main_prog.global_block().var(in_varname)
193
            tensor_dist_attr = dist_context.get_tensor_dist_attr_for_program(
194 195
                in_var
            )
196
            tensor_dims_mapping = tensor_dist_attr.dims_mapping
197
            in_var_dims_mapping = op_dist_attr.get_input_dims_mapping(
198 199
                in_varname
            )
200 201 202 203
            if tensor_dims_mapping != in_var_dims_mapping:
                equal = False
        for out_varname in dist_ops[i].desc.output_arg_names():
            out_var = dist_main_prog.global_block().var(out_varname)
204
            tensor_dist_attr = dist_context.get_tensor_dist_attr_for_program(
205 206
                out_var
            )
207
            tensor_dims_mapping = tensor_dist_attr.dims_mapping
208
            out_var_dims_mapping = op_dist_attr.get_output_dims_mapping(
209 210
                out_varname
            )
211 212
            if tensor_dims_mapping != out_var_dims_mapping:
                equal = False
213 214
        dist_op_process_mesh = op_dist_attr.process_mesh
        dist_op_impl_idx = op_dist_attr.impl_idx
215 216 217 218 219
        if (
            serial_op.desc.id() == dist_ops[i].desc.id()
            or serial_process_mesh != dist_op_process_mesh
            or serial_impl_idx != dist_op_impl_idx
        ):
220 221 222 223 224
            equal = False

    return equal


225 226 227
def distributed_attr_check_for_dist_op(
    serial_main_prog, dist_main_prog, dist_context, serial_op_idx, dist_op_idx
):
228 229 230 231 232 233 234 235 236 237 238

    equal = True
    serial_ops = serial_main_prog.global_block().ops
    dist_ops = dist_main_prog.global_block().ops

    for i in range(len(serial_op_idx)):
        serial_op = serial_ops[serial_op_idx[i]]
        dist_op_0 = dist_ops[dist_op_idx[i][0]]
        if dist_op_0.type == "c_identity":
            # serial op input's dist_attr
            serial_in_dist_attr = get_input_var_dist_attr(
239 240
                serial_op, serial_main_prog, dist_context
            )
241 242
            # c_identity output's(new var) dist_attr
            identity_out_dist_attr = get_output_var_dist_attr(
243 244
                dist_op_0, dist_main_prog, dist_context
            )
245
            # check var dist_attr
246 247 248
            equal = check_equal_var_dist_attr(
                serial_in_dist_attr, identity_out_dist_attr
            )
249 250 251
        else:
            # serial op output's dist_attr
            serial_out_dist_attr = get_output_var_dist_attr(
252 253
                serial_op, serial_main_prog, dist_context
            )
254
            # dist op output's(new var) dist_attr
255 256 257
            out_dist_attr = get_output_var_dist_attr(
                dist_op_0, dist_main_prog, dist_context
            )
258
            # check var dist_attr
259 260 261
            equal = check_equal_var_dist_attr(
                serial_out_dist_attr, out_dist_attr
            )
262

263
        # check op's dist_attr
264 265 266
        equal = check_equal_dist_op_attr(
            dist_context, dist_main_prog, serial_op, dist_ops, dist_op_idx[i]
        )
267 268 269 270 271 272 273

    return equal


def distributed_attr_check_for_program(dist_main_prog, dist_context):
    have_dist_attr = True
    for block in dist_main_prog.blocks:
274 275
        for var in block.vars.values():
            var_dist_attr = dist_context.get_tensor_dist_attr_for_program(var)
276 277 278 279
            if var_dist_attr is None:
                have_dist_attr = False

        for op in block.ops:
280
            op_dist_attr = dist_context.get_op_dist_attr_for_program(op)
281 282 283 284 285 286
            if op_dist_attr is None:
                have_dist_attr = False

    return have_dist_attr


287
class MLPLayer(nn.Layer):
288 289 290 291 292 293 294
    def __init__(
        self,
        hidden_size=1024,
        intermediate_size=4 * 1024,
        dropout_ratio=0.1,
        initializer_range=0.02,
    ):
295
        super().__init__()
296 297
        d_model = hidden_size
        dim_feedforward = intermediate_size
298
        weight_attr = paddle.ParamAttr(
299 300
            initializer=nn.initializer.Normal(mean=0.0, std=initializer_range)
        )
301 302
        bias_attr = None

303 304 305 306 307 308
        self.linear0 = nn.Linear(
            d_model, dim_feedforward, weight_attr, bias_attr=bias_attr
        )
        self.linear1 = nn.Linear(
            dim_feedforward, d_model, weight_attr, bias_attr=bias_attr
        )
309 310 311 312
        self.norm = nn.LayerNorm(d_model, epsilon=1e-5)
        self.dropout = nn.Dropout(dropout_ratio, mode="upscale_in_train")

    def forward(self, input):
313
        if _global_parallel_strategy in ["mp", "dp_mp"]:
314 315 316 317 318 319 320 321 322 323
            auto.shard_tensor(
                self.linear0.weight,
                process_mesh=_global_process_mesh,
                shard_spec=[None, "mp"],
            )
            auto.shard_tensor(
                self.linear1.weight,
                process_mesh=_global_process_mesh,
                shard_spec=["mp", None],
            )
324
        else:
325 326 327 328 329 330 331 332 333 334
            auto.shard_tensor(
                self.linear0.weight,
                process_mesh=_global_process_mesh,
                shard_spec=[None, None],
            )
            auto.shard_tensor(
                self.linear1.weight,
                process_mesh=_global_process_mesh,
                shard_spec=[None, None],
            )
335 336 337 338 339 340 341 342 343 344 345

        out = self.norm(input)
        out = self.linear0(out)
        out = F.gelu(out, approximate=True)
        out = self.linear1(out)
        out = self.dropout(out)

        return out


def mlp_pretrain_forward(train_program, start_program):
346 347 348
    with static.program_guard(
        train_program, start_program
    ), utils.unique_name.guard():
349 350 351
        batch_size = 4
        hidden_size = 1024
        sequence_len = 512
352 353 354 355 356
        input = static.data(
            name="input",
            shape=[batch_size, sequence_len, hidden_size],
            dtype='float32',
        )
357

358
        if _global_parallel_strategy in ["dp", "dp_mp"]:
359 360 361 362 363 364 365 366 367 368 369 370
            auto.shard_tensor(
                input,
                process_mesh=_global_process_mesh,
                shard_spec=["dp", None, None],
            )

        mlp = MLPLayer(
            hidden_size=hidden_size,
            intermediate_size=4 * hidden_size,
            dropout_ratio=0.1,
            initializer_range=0.02,
        )
371 372 373 374 375 376
        out = mlp(input)
    return train_program, start_program


class TestMLPAutoPartitioner(unittest.TestCase):
    def test_mlp_dp(self):
377 378
        global _global_parallel_strategy
        _global_parallel_strategy = "dp"
379
        global _global_process_mesh
380 381 382 383 384 385 386 387 388 389 390
        _global_process_mesh = auto.ProcessMesh(
            mesh=[0, 1, 2, 3], dim_names=["dp"]
        )

        (
            serial_main_prog,
            serial_startup_prog,
            dist_main_prog,
            dist_startup_prog,
            dist_context,
        ) = get_programs(mlp_pretrain_forward)
391 392 393

        # parameter should not be partitioned
        self.assertTrue(
394 395
            is_all_parameters_shape_equal(serial_main_prog, dist_main_prog)
        )
396
        self.assertTrue(
397 398 399 400
            is_all_parameters_shape_equal(
                serial_startup_prog, dist_startup_prog
            )
        )
401 402 403 404 405 406 407 408

        # op in main prog should be the same
        serial_ops = serial_main_prog.global_block().ops
        dist_ops = dist_main_prog.global_block().ops
        serial_ops = [op.type for op in serial_ops]
        dist_ops = [op.type for op in dist_ops]
        self.assertTrue(serial_ops == dist_ops)

409
        # parameter initialization
410 411
        var_need_broadcast = []
        self.assertTrue(
412 413 414 415 416 417 418 419 420 421 422
            initialization_check(
                _global_parallel_strategy,
                dist_context,
                dist_startup_prog,
                serial_startup_prog,
                var_need_broadcast,
                _global_process_mesh,
                mp_parallel_axis=None,
                dp_parallel_axis=0,
            )
        )
423 424

    def test_mlp_mp(self):
425 426
        global _global_parallel_strategy
        _global_parallel_strategy = "mp"
427
        global _global_process_mesh
428 429 430 431 432 433 434 435 436 437
        _global_process_mesh = auto.ProcessMesh(
            mesh=[0, 1, 2, 3], dim_names=["mp"]
        )
        (
            serial_main_prog,
            serial_startup_prog,
            dist_main_prog,
            dist_startup_prog,
            dist_context,
        ) = get_programs(mlp_pretrain_forward)
438 439 440 441 442 443

        # param should be partition
        nrank = 4
        # col parallel
        weights = ['linear_0.w_0']
        self.assertTrue(
444 445 446 447
            check_tensor_split(
                dist_main_prog, weights, serial_main_prog, weights, 1, nrank
            )
        )
448 449
        weights = ['linear_0.b_0']
        self.assertTrue(
450 451 452 453
            check_tensor_split(
                dist_main_prog, weights, serial_main_prog, weights, 0, nrank
            )
        )
454 455 456
        # row parallel
        weights = ['linear_1.w_0']
        self.assertTrue(
457 458 459 460
            check_tensor_split(
                dist_main_prog, weights, serial_main_prog, weights, 0, nrank
            )
        )
461 462
        weights = ['linear_1.b_0']
        self.assertTrue(
463 464 465 466
            check_tensor_split(
                dist_main_prog, weights, serial_main_prog, weights, 0, 1
            )
        )
467 468 469 470 471

        # row and col allreduce
        dist_ops = dist_main_prog.global_block().ops
        dist_ops = [op.type for op in dist_ops]
        ref_ops = [
472 473 474 475 476 477 478 479 480
            'layer_norm',
            'c_identity',
            'matmul_v2',
            'elementwise_add',
            'gelu',
            'matmul_v2',
            'c_allreduce_sum',
            'elementwise_add',
            'dropout',
481 482 483
        ]
        self.assertTrue(dist_ops == ref_ops)

484
        # parameter initialization
485
        var_need_broadcast = sorted(
486 487
            ['layer_norm_0.b_0', 'layer_norm_0.w_0', 'linear_1.b_0']
        )
488
        self.assertTrue(
489 490 491 492 493 494 495 496 497 498 499
            initialization_check(
                _global_parallel_strategy,
                dist_context,
                dist_startup_prog,
                serial_startup_prog,
                var_need_broadcast,
                _global_process_mesh,
                mp_parallel_axis=0,
                dp_parallel_axis=None,
            )
        )
500

501 502
        # check var and op all have dist_attr in dist_main_program
        self.assertTrue(
503 504
            distributed_attr_check_for_program(dist_main_prog, dist_context)
        )
505 506 507 508
        # check distribured attr for dist op
        serial_op_idx = [1, 4]
        dist_op_idx = [[1, 2], [5, 6]]
        self.assertTrue(
509 510 511 512 513 514 515 516
            distributed_attr_check_for_dist_op(
                serial_main_prog,
                dist_main_prog,
                dist_context,
                serial_op_idx,
                dist_op_idx,
            )
        )
517

518
    def test_mlp_dp_mp(self):
519 520
        global _global_parallel_strategy
        _global_parallel_strategy = "dp_mp"
521
        global _global_process_mesh
522 523 524 525 526 527 528 529 530 531
        _global_process_mesh = auto.ProcessMesh(
            mesh=[[0, 1, 2, 3], [4, 5, 6, 7]], dim_names=["dp", "mp"]
        )
        (
            serial_main_prog,
            serial_startup_prog,
            dist_main_prog,
            dist_startup_prog,
            dist_context,
        ) = get_programs(mlp_pretrain_forward)
532 533 534 535 536 537

        # param should be partition
        nrank = 4
        # col parallel
        weights = ['linear_0.w_0']
        self.assertTrue(
538 539 540 541
            check_tensor_split(
                dist_main_prog, weights, serial_main_prog, weights, 1, nrank
            )
        )
542 543
        weights = ['linear_0.b_0']
        self.assertTrue(
544 545 546 547
            check_tensor_split(
                dist_main_prog, weights, serial_main_prog, weights, 0, nrank
            )
        )
548 549 550
        # row parallel
        weights = ['linear_1.w_0']
        self.assertTrue(
551 552 553 554
            check_tensor_split(
                dist_main_prog, weights, serial_main_prog, weights, 0, nrank
            )
        )
555 556
        weights = ['linear_1.b_0']
        self.assertTrue(
557 558 559 560
            check_tensor_split(
                dist_main_prog, weights, serial_main_prog, weights, 0, 1
            )
        )
561 562 563 564 565

        # row and col allreduce
        dist_ops = dist_main_prog.global_block().ops
        dist_ops = [op.type for op in dist_ops]
        ref_ops = [
566 567 568 569 570 571 572 573 574
            'layer_norm',
            'c_identity',
            'matmul_v2',
            'elementwise_add',
            'gelu',
            'matmul_v2',
            'c_allreduce_sum',
            'elementwise_add',
            'dropout',
575 576 577 578 579
        ]
        self.assertTrue(dist_ops == ref_ops)

        # parameter initialization
        var_need_broadcast = sorted(
580 581
            ['layer_norm_0.b_0', 'layer_norm_0.w_0', 'linear_1.b_0']
        )
582
        self.assertTrue(
583 584 585 586 587 588 589 590 591 592 593
            initialization_check(
                _global_parallel_strategy,
                dist_context,
                dist_startup_prog,
                serial_startup_prog,
                var_need_broadcast,
                _global_process_mesh,
                mp_parallel_axis=1,
                dp_parallel_axis=0,
            )
        )
594

595 596
        # check var and op all have dist_attr in dist_main_program
        self.assertTrue(
597 598
            distributed_attr_check_for_program(dist_main_prog, dist_context)
        )
599 600 601 602
        # check distribured attr for dist op
        serial_op_idx = [1, 4]
        dist_op_idx = [[1, 2], [5, 6]]
        self.assertTrue(
603 604 605 606 607 608 609 610
            distributed_attr_check_for_dist_op(
                serial_main_prog,
                dist_main_prog,
                dist_context,
                serial_op_idx,
                dist_op_idx,
            )
        )
611

612 613

class AttentionLayer(nn.Layer):
614 615 616 617 618 619 620 621 622
    def __init__(
        self,
        hidden_size=1024,
        sequence_len=512,
        intermediate_size=4 * 1024,
        num_heads=16,
        dropout_ratio=0.1,
        initializer_range=0.02,
    ):
623
        super().__init__()
624 625 626 627 628 629 630
        self.hidden_size = hidden_size
        self.sequence_len = sequence_len
        self.embed_dim = self.hidden_size
        self.kdim = self.embed_dim
        self.vdim = self.embed_dim
        self.num_heads = num_heads
        self.head_dim = self.embed_dim // self.num_heads
631 632 633
        assert (
            self.head_dim * self.num_heads == self.embed_dim
        ), "embed_dim must be divisible by num_heads"
634 635 636 637
        self.dropout_ratio = dropout_ratio
        self.initializer_range = initializer_range
        self.training = True
        self.attn_mask = None
638
        weight_attr = paddle.ParamAttr(
639 640
            initializer=nn.initializer.Normal(mean=0.0, std=initializer_range)
        )
641 642
        bias_attr = None

643 644 645 646 647 648 649 650 651 652 653 654
        self.q_proj = nn.Linear(
            self.embed_dim, self.embed_dim, weight_attr, bias_attr=bias_attr
        )
        self.k_proj = nn.Linear(
            self.kdim, self.embed_dim, weight_attr, bias_attr=bias_attr
        )
        self.v_proj = nn.Linear(
            self.vdim, self.embed_dim, weight_attr, bias_attr=bias_attr
        )
        self.out_proj = nn.Linear(
            self.embed_dim, self.embed_dim, weight_attr, bias_attr=bias_attr
        )
655 656

    def forward(self, input):
657
        if _global_parallel_strategy in ["dp", "dp_mp"]:
658 659 660 661 662
            auto.shard_tensor(
                input,
                process_mesh=_global_process_mesh,
                shard_spec=["dp", None, None],
            )
663 664 665 666 667 668 669 670

        q = self.q_proj(input)
        q = tensor.reshape(x=q, shape=[0, 0, self.num_heads, self.head_dim])
        q = tensor.transpose(x=q, perm=[0, 2, 1, 3])

        k = self.k_proj(input)
        v = self.v_proj(input)

671
        if _global_parallel_strategy in ["mp", "dp_mp"]:
672 673 674 675 676 677 678 679 680 681 682 683 684 685 686
            auto.shard_tensor(
                self.q_proj.weight,
                process_mesh=_global_process_mesh,
                shard_spec=[None, "mp"],
            )
            auto.shard_tensor(
                self.k_proj.weight,
                process_mesh=_global_process_mesh,
                shard_spec=[None, "mp"],
            )
            auto.shard_tensor(
                self.v_proj.weight,
                process_mesh=_global_process_mesh,
                shard_spec=[None, "mp"],
            )
687 688 689 690 691 692 693

        k = tensor.reshape(x=k, shape=[0, 0, self.num_heads, self.head_dim])
        k = tensor.transpose(x=k, perm=[0, 2, 1, 3])
        v = tensor.reshape(x=v, shape=[0, 0, self.num_heads, self.head_dim])
        v = tensor.transpose(x=v, perm=[0, 2, 1, 3])

        # scale dot product attention
K
kangguangli 已提交
694 695
        product = tensor.matmul(x=q, y=k, transpose_y=True)
        product = tensor.scale(product, scale=self.head_dim**-0.5)
696 697 698 699 700 701 702

        if self.attn_mask is not None:
            product = product + self.attn_mask

        weights = F.softmax(product)

        if self.dropout_ratio:
703 704 705 706 707 708
            weights = F.dropout(
                weights,
                self.dropout_ratio,
                training=self.training,
                mode="upscale_in_train",
            )
709 710 711 712 713 714 715 716 717

        out = tensor.matmul(weights, v)

        # combine heads
        out = tensor.transpose(out, perm=[0, 2, 1, 3])
        out = tensor.reshape(x=out, shape=[0, 0, out.shape[2] * out.shape[3]])

        # project to output
        out = self.out_proj(out)
718 719

        if _global_parallel_strategy in ["mp", "dp_mp"]:
720 721 722 723 724
            auto.shard_tensor(
                self.out_proj.weight,
                process_mesh=_global_process_mesh,
                shard_spec=["mp", None],
            )
725 726 727 728 729

        return out


def attn_pretrain_forward(train_program, start_program):
730 731 732
    with static.program_guard(
        train_program, start_program
    ), utils.unique_name.guard():
733 734 735
        batch_size = 4
        hidden_size = 1024
        sequence_len = 512
736 737 738 739 740 741 742 743 744 745 746 747 748
        input = static.data(
            name="query",
            shape=[batch_size, sequence_len, hidden_size],
            dtype='float32',
        )
        attn = AttentionLayer(
            hidden_size=hidden_size,
            sequence_len=sequence_len,
            intermediate_size=4 * hidden_size,
            num_heads=16,
            dropout_ratio=0.1,
            initializer_range=0.02,
        )
749 750 751 752 753 754 755
        out = attn(input)

    return train_program, start_program


class TestAttentionAutoPartitioner(unittest.TestCase):
    def test_attn_dp(self):
756 757
        global _global_parallel_strategy
        _global_parallel_strategy = "dp"
758
        global _global_process_mesh
759 760 761 762 763 764 765 766 767 768 769
        _global_process_mesh = auto.ProcessMesh(
            mesh=[0, 1, 2, 3], dim_names=["dp"]
        )

        (
            serial_main_prog,
            serial_startup_prog,
            dist_main_prog,
            dist_startup_prog,
            dist_context,
        ) = get_programs(attn_pretrain_forward)
770 771
        # parameter should not be partitioned
        self.assertTrue(
772 773
            is_all_parameters_shape_equal(serial_main_prog, dist_main_prog)
        )
774
        self.assertTrue(
775 776 777 778
            is_all_parameters_shape_equal(
                serial_startup_prog, dist_startup_prog
            )
        )
779 780 781 782 783 784 785 786

        # op in main prog should be the same
        serial_ops = serial_main_prog.global_block().ops
        dist_ops = dist_main_prog.global_block().ops
        serial_ops = [op.type for op in serial_ops]
        dist_ops = [op.type for op in dist_ops]
        self.assertTrue(serial_ops == dist_ops)

787
        # parameter initialization
788 789
        var_need_broadcast = []
        self.assertTrue(
790 791 792 793 794 795 796 797 798 799 800
            initialization_check(
                _global_parallel_strategy,
                dist_context,
                dist_startup_prog,
                serial_startup_prog,
                var_need_broadcast,
                _global_process_mesh,
                mp_parallel_axis=None,
                dp_parallel_axis=0,
            )
        )
801 802

    def test_attn_mp(self):
803 804
        global _global_parallel_strategy
        _global_parallel_strategy = "mp"
805
        global _global_process_mesh
806 807 808 809 810 811 812 813 814 815 816
        _global_process_mesh = auto.ProcessMesh(
            mesh=[0, 1, 2, 3], dim_names=["mp"]
        )

        (
            serial_main_prog,
            serial_startup_prog,
            dist_main_prog,
            dist_startup_prog,
            dist_context,
        ) = get_programs(attn_pretrain_forward)
817 818 819 820 821 822

        # param should be partition
        nrank = 4
        # col parallel
        weights = ['linear_0.w_0', 'linear_1.w_0', 'linear_2.w_0']
        self.assertTrue(
823 824 825 826
            check_tensor_split(
                dist_main_prog, weights, serial_main_prog, weights, 1, nrank
            )
        )
827 828
        weights = ['linear_0.b_0', 'linear_1.b_0', 'linear_2.b_0']
        self.assertTrue(
829 830 831 832
            check_tensor_split(
                dist_main_prog, weights, serial_main_prog, weights, 0, nrank
            )
        )
833 834 835
        # row parallel
        weights = ['linear_3.w_0']
        self.assertTrue(
836 837 838 839
            check_tensor_split(
                dist_main_prog, weights, serial_main_prog, weights, 0, nrank
            )
        )
840 841
        weights = ['linear_3.b_0']
        self.assertTrue(
842 843 844 845
            check_tensor_split(
                dist_main_prog, weights, serial_main_prog, weights, 0, 1
            )
        )
846 847 848 849 850

        # row and col allreduce
        dist_ops = dist_main_prog.global_block().ops
        dist_ops = [op.type for op in dist_ops]
        ref_ops = [
851 852 853 854 855 856 857 858 859 860 861 862 863 864 865
            'c_identity',
            'matmul_v2',
            'elementwise_add',
            'reshape2',
            'transpose2',
            'c_identity',
            'matmul_v2',
            'elementwise_add',
            'c_identity',
            'matmul_v2',
            'elementwise_add',
            'reshape2',
            'transpose2',
            'reshape2',
            'transpose2',
K
kangguangli 已提交
866 867
            'matmul_v2',
            "scale",
868 869 870 871 872 873 874 875
            'softmax',
            'dropout',
            'matmul_v2',
            'transpose2',
            'reshape2',
            'matmul_v2',
            'c_allreduce_sum',
            'elementwise_add',
876 877 878
        ]
        self.assertTrue(dist_ops == ref_ops)

879
        # parameter initialization
880 881
        var_need_broadcast = ['linear_3.b_0']
        self.assertTrue(
882 883 884 885 886 887 888 889 890 891 892
            initialization_check(
                _global_parallel_strategy,
                dist_context,
                dist_startup_prog,
                serial_startup_prog,
                var_need_broadcast,
                _global_process_mesh,
                mp_parallel_axis=0,
                dp_parallel_axis=None,
            )
        )
893

894 895
        # check var and op all have dist_attr in dist_main_program
        self.assertTrue(
896 897
            distributed_attr_check_for_program(dist_main_prog, dist_context)
        )
898 899 900 901
        # check distribured attr for dist op
        serial_op_idx = [0, 4, 6, 18]
        dist_op_idx = [[0, 1], [5, 6], [8, 9], [21, 22]]
        self.assertTrue(
902 903 904 905 906 907 908 909
            distributed_attr_check_for_dist_op(
                serial_main_prog,
                dist_main_prog,
                dist_context,
                serial_op_idx,
                dist_op_idx,
            )
        )
910

911
    def test_attn_dp_mp(self):
912 913
        global _global_parallel_strategy
        _global_parallel_strategy = "dp_mp"
914
        global _global_process_mesh
915 916 917 918 919 920 921 922 923 924 925
        _global_process_mesh = auto.ProcessMesh(
            mesh=[[0, 1, 2, 3], [4, 5, 6, 7]], dim_names=["dp", "mp"]
        )

        (
            serial_main_prog,
            serial_startup_prog,
            dist_main_prog,
            dist_startup_prog,
            dist_context,
        ) = get_programs(attn_pretrain_forward)
926 927 928 929 930 931

        # param should be partition
        nrank = 4
        # col parallel
        weights = ['linear_0.w_0', 'linear_1.w_0', 'linear_2.w_0']
        self.assertTrue(
932 933 934 935
            check_tensor_split(
                dist_main_prog, weights, serial_main_prog, weights, 1, nrank
            )
        )
936 937
        weights = ['linear_0.b_0', 'linear_1.b_0', 'linear_2.b_0']
        self.assertTrue(
938 939 940 941
            check_tensor_split(
                dist_main_prog, weights, serial_main_prog, weights, 0, nrank
            )
        )
942 943 944
        # row parallel
        weights = ['linear_3.w_0']
        self.assertTrue(
945 946 947 948
            check_tensor_split(
                dist_main_prog, weights, serial_main_prog, weights, 0, nrank
            )
        )
949 950
        weights = ['linear_3.b_0']
        self.assertTrue(
951 952 953 954
            check_tensor_split(
                dist_main_prog, weights, serial_main_prog, weights, 0, 1
            )
        )
955 956 957 958 959

        # row and col allreduce
        dist_ops = dist_main_prog.global_block().ops
        dist_ops = [op.type for op in dist_ops]
        ref_ops = [
960 961 962 963 964 965 966 967 968 969 970 971 972 973 974
            'c_identity',
            'matmul_v2',
            'elementwise_add',
            'reshape2',
            'transpose2',
            'c_identity',
            'matmul_v2',
            'elementwise_add',
            'c_identity',
            'matmul_v2',
            'elementwise_add',
            'reshape2',
            'transpose2',
            'reshape2',
            'transpose2',
K
kangguangli 已提交
975 976
            'matmul_v2',
            "scale",
977 978 979 980 981 982 983 984
            'softmax',
            'dropout',
            'matmul_v2',
            'transpose2',
            'reshape2',
            'matmul_v2',
            'c_allreduce_sum',
            'elementwise_add',
985 986 987
        ]
        self.assertTrue(dist_ops == ref_ops)

988
        # parameter initialization
989 990
        var_need_broadcast = ['linear_3.b_0']
        self.assertTrue(
991 992 993 994 995 996 997 998 999 1000 1001
            initialization_check(
                _global_parallel_strategy,
                dist_context,
                dist_startup_prog,
                serial_startup_prog,
                var_need_broadcast,
                _global_process_mesh,
                mp_parallel_axis=1,
                dp_parallel_axis=0,
            )
        )
1002

1003 1004
        # check var and op all have dist_attr in dist_main_program
        self.assertTrue(
1005 1006
            distributed_attr_check_for_program(dist_main_prog, dist_context)
        )
1007 1008 1009 1010
        # check distribured attr for dist op
        serial_op_idx = [0, 4, 6, 18]
        dist_op_idx = [[0, 1], [5, 6], [8, 9], [21, 22]]
        self.assertTrue(
1011 1012 1013 1014 1015 1016 1017 1018
            distributed_attr_check_for_dist_op(
                serial_main_prog,
                dist_main_prog,
                dist_context,
                serial_op_idx,
                dist_op_idx,
            )
        )
1019

1020 1021

class DecoderLayer(nn.Layer):
1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032
    def __init__(
        self,
        vocab_size=32768,
        hidden_size=1024,
        sequence_len=512,
        max_position_embeddings=512,
        intermediate_size=4 * 1024,
        num_heads=16,
        dropout_ratio=0.1,
        initializer_range=0.02,
    ):
1033
        super().__init__()
1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047
        self.vocab_size = vocab_size
        self.hidden_size = hidden_size
        self.max_position_embeddings = max_position_embeddings
        self.sequence_len = sequence_len
        self.embed_dim = self.hidden_size
        self.kdim = self.embed_dim
        self.vdim = self.embed_dim
        self.num_heads = num_heads
        self.dropout_ratio = dropout_ratio
        self.initializer_range = initializer_range
        self.training = True
        self.attn_mask = None

        self.head_dim = self.embed_dim // self.num_heads
1048 1049 1050
        assert (
            self.head_dim * self.num_heads == self.embed_dim
        ), "embed_dim must be divisible by num_heads"
1051 1052 1053
        self.word_embeddings = nn.Embedding(
            self.vocab_size,
            self.hidden_size,
1054 1055 1056 1057 1058 1059 1060
            weight_attr=paddle.ParamAttr(
                name="word_embeddings",
                initializer=nn.initializer.Normal(
                    mean=0.0, std=self.initializer_range
                ),
            ),
        )
1061 1062 1063
        self.position_embeddings = nn.Embedding(
            self.max_position_embeddings,
            self.hidden_size,
1064 1065 1066 1067 1068 1069 1070
            weight_attr=paddle.ParamAttr(
                name="pos_embeddings",
                initializer=nn.initializer.Normal(
                    mean=0.0, std=self.initializer_range
                ),
            ),
        )
1071

1072 1073 1074 1075 1076
        weight_attr = paddle.ParamAttr(
            initializer=nn.initializer.Normal(
                mean=0.0, std=self.initializer_range
            )
        )
1077
        bias_attr = None
1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089
        self.q_proj = nn.Linear(
            self.embed_dim, self.embed_dim, weight_attr, bias_attr=bias_attr
        )
        self.k_proj = nn.Linear(
            self.kdim, self.embed_dim, weight_attr, bias_attr=bias_attr
        )
        self.v_proj = nn.Linear(
            self.vdim, self.embed_dim, weight_attr, bias_attr=bias_attr
        )
        self.out_proj = nn.Linear(
            self.embed_dim, self.embed_dim, weight_attr, bias_attr=bias_attr
        )
1090 1091 1092 1093

        intermediate_size = 4 * self.hidden_size
        d_model = self.hidden_size
        dim_feedforward = intermediate_size
1094 1095 1096 1097 1098
        weight_attr = paddle.ParamAttr(
            initializer=nn.initializer.Normal(
                mean=0.0, std=self.initializer_range
            )
        )
1099
        bias_attr = None
1100 1101 1102 1103 1104 1105
        self.linear0 = nn.Linear(
            d_model, dim_feedforward, weight_attr, bias_attr=bias_attr
        )
        self.linear1 = nn.Linear(
            dim_feedforward, d_model, weight_attr, bias_attr=bias_attr
        )
1106 1107 1108 1109 1110 1111
        self.norm = nn.LayerNorm(d_model, epsilon=1e-5)
        self.dropout1 = nn.Dropout(self.dropout_ratio)
        self.dropout2 = nn.Dropout(self.dropout_ratio, mode="upscale_in_train")
        self.dropout3 = nn.Dropout(self.dropout_ratio, mode="upscale_in_train")

    def forward(self, input_ids, position_ids):
1112
        if _global_parallel_strategy in ["dp", "dp_mp"]:
1113 1114 1115 1116 1117
            auto.shard_tensor(
                input_ids,
                process_mesh=_global_process_mesh,
                shard_spec=["dp", None],
            )
1118 1119 1120 1121

        input_embeddings = self.word_embeddings(input_ids)
        position_embeddings = self.position_embeddings(position_ids)

1122
        if _global_parallel_strategy in ["mp", "dp_mp"]:
1123 1124 1125 1126 1127
            auto.shard_tensor(
                self.word_embeddings.weight,
                process_mesh=_global_process_mesh,
                shard_spec=["mp", None],
            )
1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142

        embeddings = input_embeddings + position_embeddings
        embeddings = self.dropout1(embeddings)

        # Pre-norm
        target = self.norm(embeddings)

        # The following is the attention part
        q = self.q_proj(target)
        q = tensor.reshape(x=q, shape=[0, 0, self.num_heads, self.head_dim])
        q = tensor.transpose(x=q, perm=[0, 2, 1, 3])

        k = self.k_proj(target)
        v = self.v_proj(target)

1143
        if _global_parallel_strategy in ["mp", "dp_mp"]:
1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158
            auto.shard_tensor(
                self.q_proj.weight,
                process_mesh=_global_process_mesh,
                shard_spec=[None, "mp"],
            )
            auto.shard_tensor(
                self.k_proj.weight,
                process_mesh=_global_process_mesh,
                shard_spec=[None, "mp"],
            )
            auto.shard_tensor(
                self.v_proj.weight,
                process_mesh=_global_process_mesh,
                shard_spec=[None, "mp"],
            )
1159 1160 1161 1162 1163 1164 1165

        k = tensor.reshape(x=k, shape=[0, 0, self.num_heads, self.head_dim])
        k = tensor.transpose(x=k, perm=[0, 2, 1, 3])
        v = tensor.reshape(x=v, shape=[0, 0, self.num_heads, self.head_dim])
        v = tensor.transpose(x=v, perm=[0, 2, 1, 3])

        # scale dot product attention
K
kangguangli 已提交
1166 1167
        product = tensor.matmul(x=q, y=k, transpose_y=True)
        product = tensor.scale(product, scale=self.head_dim**-0.5)
1168 1169 1170 1171 1172 1173 1174

        if self.attn_mask is not None:
            product = product + self.attn_mask

        weights = F.softmax(product)

        if self.dropout_ratio:
1175 1176 1177 1178 1179 1180
            weights = F.dropout(
                weights,
                self.dropout_ratio,
                training=self.training,
                mode="upscale_in_train",
            )
1181 1182 1183 1184 1185 1186 1187 1188 1189 1190

        out = tensor.matmul(weights, v)

        # combine heads
        out = tensor.transpose(out, perm=[0, 2, 1, 3])
        out = tensor.reshape(x=out, shape=[0, 0, out.shape[2] * out.shape[3]])

        # project to output
        out = self.out_proj(out)

1191
        if _global_parallel_strategy in ["mp", "dp_mp"]:
1192 1193 1194 1195 1196
            auto.shard_tensor(
                self.out_proj.weight,
                process_mesh=_global_process_mesh,
                shard_spec=["mp", None],
            )
1197
        else:
1198 1199 1200 1201 1202
            auto.shard_tensor(
                self.out_proj.weight,
                process_mesh=_global_process_mesh,
                shard_spec=[None, None],
            )
1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214

        # Add residual
        residual = embeddings + self.dropout2(out)

        # Pre-norm
        out0 = self.norm(residual)

        # The following is the MLP part
        out1 = self.linear0(out0)
        out2 = F.gelu(out1, approximate=True)
        out3 = self.linear1(out2)

1215
        if _global_parallel_strategy in ["mp", "dp_mp"]:
1216 1217 1218 1219 1220 1221 1222 1223 1224 1225
            auto.shard_tensor(
                self.linear0.weight,
                process_mesh=_global_process_mesh,
                shard_spec=[None, "mp"],
            )
            auto.shard_tensor(
                self.linear1.weight,
                process_mesh=_global_process_mesh,
                shard_spec=["mp", None],
            )
1226 1227 1228 1229 1230 1231 1232

        # Add residual
        final = residual + self.dropout3(out3)
        return final


def decoder_pretrain_forward(train_program, start_program):
1233 1234 1235
    with static.program_guard(
        train_program, start_program
    ), utils.unique_name.guard():
1236 1237 1238
        batch_size = 4
        hidden_size = 1024
        sequence_len = 512
1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254
        input_ids = static.data(
            name="input_ids", shape=[batch_size, sequence_len], dtype='int64'
        )
        position_ids = static.data(
            name="position_ids", shape=[batch_size, sequence_len], dtype='int64'
        )
        decoder = DecoderLayer(
            vocab_size=32768,
            hidden_size=hidden_size,
            sequence_len=sequence_len,
            max_position_embeddings=512,
            intermediate_size=4 * hidden_size,
            num_heads=16,
            dropout_ratio=0.1,
            initializer_range=0.02,
        )
1255 1256 1257 1258 1259 1260 1261
        out = decoder(input_ids, position_ids)

    return train_program, start_program


class TestDecoderLayerPartitioner(unittest.TestCase):
    def test_decoder_dp_mp(self):
1262 1263
        global _global_parallel_strategy
        _global_parallel_strategy = "dp_mp"
1264
        global _global_process_mesh
1265 1266 1267 1268 1269 1270 1271 1272 1273 1274
        _global_process_mesh = auto.ProcessMesh(
            mesh=[[0, 1, 2, 3], [4, 5, 6, 7]], dim_names=["dp", "mp"]
        )
        (
            serial_main_prog,
            serial_startup_prog,
            dist_main_prog,
            dist_startup_prog,
            dist_context,
        ) = get_programs(decoder_pretrain_forward)
1275 1276 1277 1278 1279

        # param should be partition
        nrank = 4
        # col parallel
        weights = [
1280 1281 1282 1283
            'linear_0.w_0',
            'linear_1.w_0',
            'linear_2.w_0',
            'linear_4.w_0',
1284 1285
        ]
        self.assertTrue(
1286 1287 1288 1289
            check_tensor_split(
                dist_main_prog, weights, serial_main_prog, weights, 1, nrank
            )
        )
1290
        weights = [
1291 1292 1293 1294
            'linear_0.b_0',
            'linear_1.b_0',
            'linear_2.b_0',
            'linear_4.b_0',
1295 1296
        ]
        self.assertTrue(
1297 1298 1299 1300
            check_tensor_split(
                dist_main_prog, weights, serial_main_prog, weights, 0, nrank
            )
        )
1301 1302 1303
        # row parallel
        weights = ['word_embeddings', 'linear_3.w_0', 'linear_5.w_0']
        self.assertTrue(
1304 1305 1306 1307
            check_tensor_split(
                dist_main_prog, weights, serial_main_prog, weights, 0, nrank
            )
        )
1308
        weights = [
1309 1310 1311 1312 1313
            'linear_3.b_0',
            'pos_embeddings',
            'layer_norm_0.b_0',
            'layer_norm_0.w_0',
            'linear_5.b_0',
1314 1315
        ]
        self.assertTrue(
1316 1317 1318 1319
            check_tensor_split(
                dist_main_prog, weights, serial_main_prog, weights, 0, 1
            )
        )
1320 1321 1322 1323 1324

        # row and col allreduce
        dist_ops = dist_main_prog.global_block().ops
        dist_ops = [op.type for op in dist_ops]
        ref_ops = [
1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345
            'c_embedding',
            'c_allreduce_sum',
            'lookup_table_v2',
            'elementwise_add',
            'dropout',
            'layer_norm',
            'c_identity',
            'matmul_v2',
            'elementwise_add',
            'reshape2',
            'transpose2',
            'c_identity',
            'matmul_v2',
            'elementwise_add',
            'c_identity',
            'matmul_v2',
            'elementwise_add',
            'reshape2',
            'transpose2',
            'reshape2',
            'transpose2',
K
kangguangli 已提交
1346 1347
            'matmul_v2',
            "scale",
1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367
            'softmax',
            'dropout',
            'matmul_v2',
            'transpose2',
            'reshape2',
            'matmul_v2',
            'c_allreduce_sum',
            'elementwise_add',
            'dropout',
            'elementwise_add',
            'layer_norm',
            'c_identity',
            'matmul_v2',
            'elementwise_add',
            'gelu',
            'matmul_v2',
            'c_allreduce_sum',
            'elementwise_add',
            'dropout',
            'elementwise_add',
1368 1369 1370
        ]
        self.assertTrue(dist_ops == ref_ops)

1371
        # parameter initialization
1372 1373 1374 1375 1376 1377 1378 1379 1380
        var_need_broadcast = sorted(
            [
                'linear_3.b_0',
                'pos_embeddings',
                'layer_norm_0.b_0',
                'layer_norm_0.w_0',
                'linear_5.b_0',
            ]
        )
1381
        self.assertTrue(
1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392
            initialization_check(
                _global_parallel_strategy,
                dist_context,
                dist_startup_prog,
                serial_startup_prog,
                var_need_broadcast,
                _global_process_mesh,
                mp_parallel_axis=1,
                dp_parallel_axis=0,
            )
        )
1393

1394 1395
        # check var and op all have dist_attr in dist_main_program
        self.assertTrue(
1396 1397
            distributed_attr_check_for_program(dist_main_prog, dist_context)
        )
1398
        # check distribured attr
K
kangguangli 已提交
1399
        serial_op_idx = [0, 5, 9, 11, 24, 29, 32]
1400 1401 1402 1403 1404
        dist_op_idx = [
            [0, 1],
            [6, 7],
            [11, 12],
            [14, 15],
K
kangguangli 已提交
1405 1406 1407
            [28, 29],
            [34, 35],
            [38, 39],
1408
        ]
1409
        self.assertTrue(
1410 1411 1412 1413 1414 1415 1416 1417
            distributed_attr_check_for_dist_op(
                serial_main_prog,
                dist_main_prog,
                dist_context,
                serial_op_idx,
                dist_op_idx,
            )
        )
1418

1419
    def test_decoder_noparallel(self):
1420 1421
        global _global_parallel_strategy
        _global_parallel_strategy = "None"
1422
        global _global_process_mesh
1423 1424 1425 1426 1427 1428 1429 1430 1431 1432
        _global_process_mesh = auto.ProcessMesh(
            mesh=[[0, 1, 2, 3], [4, 5, 6, 7]], dim_names=["x", "y"]
        )
        (
            serial_main_prog,
            serial_startup_prog,
            dist_main_prog,
            dist_startup_prog,
            dist_context,
        ) = get_programs(decoder_pretrain_forward)
1433 1434 1435 1436 1437

        # param should be partition
        nrank = 1
        # col parallel
        weights = [
1438 1439 1440 1441
            'linear_0.w_0',
            'linear_1.w_0',
            'linear_2.w_0',
            'linear_4.w_0',
1442 1443
        ]
        self.assertTrue(
1444 1445 1446 1447
            check_tensor_split(
                dist_main_prog, weights, serial_main_prog, weights, 1, nrank
            )
        )
1448
        weights = [
1449 1450 1451 1452
            'linear_0.b_0',
            'linear_1.b_0',
            'linear_2.b_0',
            'linear_4.b_0',
1453 1454
        ]
        self.assertTrue(
1455 1456 1457 1458
            check_tensor_split(
                dist_main_prog, weights, serial_main_prog, weights, 0, nrank
            )
        )
1459 1460 1461
        # row parallel
        weights = ['word_embeddings', 'linear_3.w_0', 'linear_5.w_0']
        self.assertTrue(
1462 1463 1464 1465
            check_tensor_split(
                dist_main_prog, weights, serial_main_prog, weights, 0, nrank
            )
        )
1466
        weights = [
1467 1468 1469 1470 1471
            'linear_3.b_0',
            'pos_embeddings',
            'layer_norm_0.b_0',
            'layer_norm_0.w_0',
            'linear_5.b_0',
1472 1473
        ]
        self.assertTrue(
1474 1475 1476 1477
            check_tensor_split(
                dist_main_prog, weights, serial_main_prog, weights, 0, 1
            )
        )
1478 1479 1480 1481 1482

        # row and col allreduce
        dist_ops = dist_main_prog.global_block().ops
        dist_ops = [op.type for op in dist_ops]
        ref_ops = [
1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499
            'lookup_table_v2',
            'lookup_table_v2',
            'elementwise_add',
            'dropout',
            'layer_norm',
            'matmul_v2',
            'elementwise_add',
            'reshape2',
            'transpose2',
            'matmul_v2',
            'elementwise_add',
            'matmul_v2',
            'elementwise_add',
            'reshape2',
            'transpose2',
            'reshape2',
            'transpose2',
K
kangguangli 已提交
1500 1501
            'matmul_v2',
            "scale",
1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518
            'softmax',
            'dropout',
            'matmul_v2',
            'transpose2',
            'reshape2',
            'matmul_v2',
            'elementwise_add',
            'dropout',
            'elementwise_add',
            'layer_norm',
            'matmul_v2',
            'elementwise_add',
            'gelu',
            'matmul_v2',
            'elementwise_add',
            'dropout',
            'elementwise_add',
1519 1520 1521 1522 1523
        ]
        self.assertTrue(dist_ops == ref_ops)
        dist_ops = dist_startup_prog.global_block().ops
        dist_ops = [op.type for op in dist_ops]
        ref_ops = [
1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571
            'gaussian_random',
            'gaussian_random',
            'gaussian_random',
            'fill_constant',
            'gaussian_random',
            'fill_constant',
            'gaussian_random',
            'fill_constant',
            'gaussian_random',
            'fill_constant',
            'gaussian_random',
            'fill_constant',
            'gaussian_random',
            'fill_constant',
            'fill_constant',
            'fill_constant',
            'c_broadcast',
            'c_broadcast',
            'c_broadcast',
            'c_broadcast',
            'c_broadcast',
            'c_broadcast',
            'c_broadcast',
            'c_broadcast',
            'c_broadcast',
            'c_broadcast',
            'c_broadcast',
            'c_broadcast',
            'c_broadcast',
            'c_broadcast',
            'c_broadcast',
            'c_broadcast',
            'c_broadcast',
            'c_broadcast',
            'c_broadcast',
            'c_broadcast',
            'c_broadcast',
            'c_broadcast',
            'c_broadcast',
            'c_broadcast',
            'c_broadcast',
            'c_broadcast',
            'c_broadcast',
            'c_broadcast',
            'c_broadcast',
            'c_broadcast',
            'c_broadcast',
            'c_broadcast',
1572 1573 1574 1575 1576 1577
        ]
        self.assertTrue(dist_ops == ref_ops)


if __name__ == "__main__":
    unittest.main()