test_while_op_partition.py 15.9 KB
Newer Older
1
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
2
#
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
#
7
#     http://www.apache.org/licenses/LICENSE-2.0
8
#
9 10 11 12 13 14 15
# 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
16

17
import numpy as np
18 19

import paddle
20
import paddle.nn.functional as F
21
from paddle import fluid, nn, static
22
from paddle.distributed import fleet
23
from paddle.distributed.auto_parallel.completion import Completer
24 25 26
from paddle.distributed.auto_parallel.dist_context import (
    get_default_distributed_context,
)
27 28 29
from paddle.distributed.auto_parallel.partitioner import Partitioner
from paddle.distributed.auto_parallel.utils import make_data_unshard
from paddle.distributed.fleet import auto
30 31 32 33 34 35 36

paddle.enable_static()

batch_size = 4
epoch_num = 10
hidden_size = 1024
sequence_len = 512
37
_g_process_mesh = auto.ProcessMesh([0, 1], dim_names=['x'])
38 39 40 41 42 43 44 45 46 47 48 49 50


def get_random_inputs_and_labels(input_shape, label_shape):
    input = np.random.random(size=input_shape).astype('float32')
    label = np.random.random(size=label_shape).astype('float32')
    return input, label


def batch_generator_creator():
    def __reader__():
        for _ in range(batch_size):
            batch_input, batch_label = get_random_inputs_and_labels(
                [batch_size, sequence_len, hidden_size],
51 52
                [batch_size, sequence_len, 1],
            )
53 54 55 56 57 58
            yield batch_input, batch_label

    return __reader__


class MLPLayer(nn.Layer):
59 60 61 62 63 64 65
    def __init__(
        self,
        hidden_size=1024,
        intermediate_size=4 * 1024,
        dropout_ratio=0.1,
        initializer_range=0.02,
    ):
66
        super().__init__()
67 68
        d_model = hidden_size
        dim_feedforward = intermediate_size
69 70 71
        param_initializer = nn.initializer.Normal(
            mean=0.0, std=initializer_range
        )
72 73 74 75 76 77

        self.norm = nn.LayerNorm(d_model, epsilon=1e-5)
        self.linear0 = nn.Linear(
            d_model,
            dim_feedforward,
            weight_attr=paddle.ParamAttr(initializer=param_initializer),
78 79
            bias_attr=None,
        )
80 81 82 83
        self.linear1 = nn.Linear(
            dim_feedforward,
            d_model,
            weight_attr=paddle.ParamAttr(initializer=param_initializer),
84 85
            bias_attr=None,
        )
86 87 88

    def forward(self, input):

89 90 91 92 93 94
        auto.shard_tensor(self.norm.weight, _g_process_mesh, [None])
        auto.shard_tensor(self.norm.bias, _g_process_mesh, [None])
        auto.shard_tensor(self.linear0.weight, _g_process_mesh, [None, 'x'])
        auto.shard_tensor(self.linear0.bias, _g_process_mesh, ['x'])
        auto.shard_tensor(self.linear1.weight, _g_process_mesh, ['x', None])
        auto.shard_tensor(self.linear1.bias, _g_process_mesh, [None])
95 96

        out = self.norm(input)
97
        auto.shard_tensor(out, _g_process_mesh, [None, None, None])
98
        out = self.linear0(out)
99
        auto.shard_tensor(out, _g_process_mesh, [None, None, 'x'])
100
        out = F.gelu(out, approximate=True)
101
        auto.shard_tensor(out, _g_process_mesh, [None, None, 'x'])
102
        out = self.linear1(out)
103
        auto.shard_tensor(out, _g_process_mesh, [None, None, None])
104 105 106 107 108 109 110 111 112 113 114 115 116 117

        return out


def get_program():
    dist_strategy = fleet.DistributedStrategy()
    dist_strategy.semi_auto = True
    # fleet.init(is_collective=True, strategy=dist_strategy)

    train_program = static.Program()
    start_program = static.Program()
    with fluid.program_guard(train_program, start_program):

        # 循环计数器
118
        i = paddle.tensor.fill_constant(shape=[1], dtype='int64', value=0)
119
        auto.shard_tensor(i, _g_process_mesh, [None])
120 121

        # 循环次数
122
        loop_len = paddle.tensor.fill_constant(
123 124
            shape=[1], dtype='int64', value=epoch_num
        )
125
        auto.shard_tensor(loop_len, _g_process_mesh, [None])
126 127

        # input
128 129 130 131 132 133 134 135
        input = static.data(
            name="input",
            shape=[batch_size, sequence_len, hidden_size],
            dtype='float32',
        )
        label = static.data(
            name="label", shape=[batch_size, sequence_len, 1], dtype='float32'
        )
136

137 138
        data_holder = [input, label]
        # dataloader
139
        dataloader = fluid.io.DataLoader.from_generator(
140 141 142 143 144
            feed_list=data_holder, capacity=4 * batch_size, iterable=False
        )
        dataloader.set_batch_generator(
            batch_generator_creator(), places=paddle.static.cuda_places()
        )
145
        # data dist_attr
146 147
        auto.shard_tensor(input, _g_process_mesh, [None, None, None])
        auto.shard_tensor(label, _g_process_mesh, [None, None, None])
148

149 150
        # fill constant bsz like
        tmp = paddle.fluid.layers.fill_constant_batch_size_like(
151 152
            input=input, shape=[-1, 16, 0, 48], dtype='float32', value=0
        )
153
        auto.shard_tensor(tmp, _g_process_mesh, [None, 'x', None, None])
154 155

        # model
156 157 158 159 160 161
        mlp_start = MLPLayer(
            hidden_size=hidden_size,
            intermediate_size=4 * hidden_size,
            dropout_ratio=0.1,
            initializer_range=0.02,
        )
162 163
        pred = mlp_start(input)

164
        input_array = paddle.tensor.array_write(pred, i)
165 166 167 168 169 170
        # TODO: check whether this annotation is needed
        # auto.shard_tensor(input_array,
        #                   dist_attr={
        #                       "process_mesh": _g_process_mesh,
        #                       "dims_mapping": [-1, -1, -1]
        #                   })
171

L
LiYuRio 已提交
172
        cond = paddle.less_than(x=i, y=loop_len)
173
        auto.shard_tensor(cond, _g_process_mesh, [None])
174

175
        while_op = paddle.static.nn.control_flow.While(cond=cond)
176 177
        with while_op.block():

178
            pre_input = paddle.tensor.array_read(array=input_array, i=i)
179
            auto.shard_tensor(pre_input, _g_process_mesh, [None, None, None])
180

181 182 183 184 185 186
            mlp_while = MLPLayer(
                hidden_size=hidden_size,
                intermediate_size=4 * hidden_size,
                dropout_ratio=0.1,
                initializer_range=0.02,
            )
187 188 189
            cur_pred = mlp_while(pre_input)

            # 更新循环条件
190
            i = paddle.increment(x=i, value=1)
191
            paddle.tensor.array_write(cur_pred, array=input_array, i=i)
L
LiYuRio 已提交
192
            paddle.assign(paddle.less_than(x=i, y=loop_len), cond)
193

194
        end_pred = paddle.tensor.array_read(array=input_array, i=i)
195
        auto.shard_tensor(end_pred, _g_process_mesh, [None, None, None])
196

197 198 199 200 201 202
        mlp_end = MLPLayer(
            hidden_size=hidden_size,
            intermediate_size=4 * hidden_size,
            dropout_ratio=0.1,
            initializer_range=0.02,
        )
203 204 205
        pred = mlp_end(end_pred)

        error_cost = paddle.nn.functional.square_error_cost(pred, label)
206
        auto.shard_tensor(error_cost, _g_process_mesh, [None, None, None])
207 208

        loss = paddle.mean(error_cost)
209
        auto.shard_tensor(loss, _g_process_mesh, [])
210 211 212 213 214

    return train_program, start_program, dataloader, i, loss


def completion(train_program, start_program, dist_context):
215 216 217 218 219 220 221 222 223 224 225
    # blocks = train_program.blocks
    # # completion tensors
    # for block in blocks:
    #     for op in block.ops:
    #         if op.type == "layer_norm":
    #             for out_name in op.output_arg_names:
    #                 out_var = block.vars[out_name]
    #                 tensor_dist_attr = dist_context.get_tensor_dist_attr_for_program(
    #                     out_var)
    #                 if tensor_dist_attr:
    #                     continue
226
    #                 tensor_dist_attr = TensorDistAttr()
227 228 229 230 231 232 233 234
    #                 tensor_dist_attr.process_mesh = _g_process_mesh
    #                 tensor_dist_attr.dims_mapping = [-1]
    #                 dist_context.set_tensor_dist_attr_for_program(
    #                     out_var, tensor_dist_attr)

    #         elif op.type == "elementwise_sub":
    #             for out_name in op.output_arg_names:
    #                 out_var = block.vars[out_name]
235
    #                 tensor_dist_attr = TensorDistAttr()
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
    #                 tensor_dist_attr.process_mesh = _g_process_mesh
    #                 tensor_dist_attr.dims_mapping = [-1, -1, -1]
    #                 dist_context.set_tensor_dist_attr_for_program(
    #                     out_var, tensor_dist_attr)

    #         elif op.type == "matmul_v2":
    #             col = False
    #             for in_name in op.input_arg_names:
    #                 if ".w_" not in in_name:
    #                     continue
    #                 if in_name not in block.vars:
    #                     in_var = blocks[0].vars[in_name]
    #                 else:
    #                     in_var = block.vars[in_name]
    #                 tensor_dist_attr = dist_context.get_tensor_dist_attr_for_program(
    #                     in_var)
    #                 assert tensor_dist_attr is not None
    #                 if tensor_dist_attr.dims_mapping == [-1, 0]:
    #                     col = True
    #             for out_name in op.output_arg_names:
    #                 out_var = block.vars[out_name]
    #                 tensor_dist_attr = dist_context.get_tensor_dist_attr_for_program(
    #                     out_var)
    #                 if tensor_dist_attr:
    #                     continue
261
    #                 tensor_dist_attr = TensorDistAttr()
262 263 264 265 266 267 268 269 270 271
    #                 tensor_dist_attr.process_mesh = _g_process_mesh
    #                 if col:
    #                     tensor_dist_attr.dims_mapping = [-1, -1, 0]
    #                 else:
    #                     tensor_dist_attr.dims_mapping = [-1, -1, -1]
    #                 dist_context.set_tensor_dist_attr_for_program(
    #                     out_var, tensor_dist_attr)
    #         elif op.type == "while":
    #             out_name = op.desc.output("StepScopes")[0]
    #             out_var = block.vars[out_name]
272
    #             tensor_dist_attr = TensorDistAttr()
273 274 275 276 277 278 279 280
    #             tensor_dist_attr.process_mesh = _g_process_mesh
    #             tensor_dist_attr.dims_mapping = [-1]
    #             dist_context.set_tensor_dist_attr_for_program(out_var,
    #                                                           tensor_dist_attr)

    # # completion ops
    # for block in blocks:
    #     for op in block.ops:
281
    #         op_dist_attr = OperatorDistAttr()
282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351
    #         op_dist_attr.process_mesh = _g_process_mesh
    #         if op.type == "create_by_read" or op.type == "create_double_buffer_reader":
    #             for in_name in op.input_arg_names:
    #                 op_dist_attr.set_input_dims_mapping(in_name, [])
    #             for out_name in op.output_arg_names:
    #                 op_dist_attr.set_output_dims_mapping(out_name, [])
    #         elif op.type == "read":
    #             for in_name in op.input_arg_names:
    #                 op_dist_attr.set_output_dims_mapping(in_name, [])
    #             for out_name in op.output_arg_names:
    #                 out_var = block.vars[out_name]
    #                 out_dist_attr = dist_context.get_tensor_dist_attr_for_program(
    #                     out_var)
    #                 op_dist_attr.set_output_dist_attr(out_name, out_dist_attr)
    #         elif op.type == "while":
    #             for in_name in op.input_arg_names:
    #                 in_var = block.vars[in_name]
    #                 in_dist_attr = dist_context.get_tensor_dist_attr_for_program(
    #                     in_var)
    #                 op_dist_attr.set_input_dist_attr(in_name, in_dist_attr)
    #             for out_name in op.output_arg_names:
    #                 if out_name == op.desc.output("StepScopes")[0]:
    #                     op_dist_attr.set_output_dims_mapping(out_name, [])
    #                 else:
    #                     out_var = block.vars[out_name]
    #                     out_dist_attr = dist_context.get_tensor_dist_attr_for_program(
    #                         out_var)
    #                     op_dist_attr.set_output_dist_attr(out_name,
    #                                                       out_dist_attr)
    #         else:
    #             for in_name in op.input_arg_names:
    #                 if in_name == "lod_tensor_blocking_queue_0":
    #                     continue
    #                 if in_name not in block.vars:
    #                     in_var = blocks[0].vars[in_name]
    #                 else:
    #                     in_var = block.vars[in_name]
    #                 in_dist_attr = dist_context.get_tensor_dist_attr_for_program(
    #                     in_var)
    #                 op_dist_attr.set_input_dist_attr(in_name, in_dist_attr)
    #             for out_name in op.output_arg_names:
    #                 if out_name not in block.vars:
    #                     out_var = blocks[0].vars[out_name]
    #                 else:
    #                     out_var = block.vars[out_name]
    #                 out_dist_attr = dist_context.get_tensor_dist_attr_for_program(
    #                     out_var)
    #                 op_dist_attr.set_output_dist_attr(out_name, out_dist_attr)

    #         if op.type == "matmul_v2":
    #             op_dist_attr.impl_type = "matmul_v2"
    #             for in_name in op_dist_attr.inputs_dist_attrs.keys():
    #                 in_dist_attr = op_dist_attr.inputs_dist_attrs[in_name]
    #                 if ".w_" in in_name and in_dist_attr.dims_mapping[-1] == 0:
    #                     op_dist_attr.impl_idx = 0
    #                 else:
    #                     op_dist_attr.impl_idx = 1
    #         elif op.type == "fill_constant_batch_size_like":
    #             op_dist_attr.impl_type = "fill_constant_batch_size_like"
    #             op_dist_attr.impl_idx = 0
    #         else:
    #             op_dist_attr.impl_type = "default"
    #             op_dist_attr.impl_idx = 0

    #         dist_context.set_op_dist_attr_for_program(op, op_dist_attr)
    #         make_data_unshard(train_program, start_program, dist_context)

    completer = Completer(dist_context)
    train_program = completer.complete_forward_annotation(train_program)
    make_data_unshard(train_program, start_program, dist_context)
352 353 354 355 356 357 358 359 360 361

    return train_program, start_program


def partition(train_program, start_program, dist_context):

    # optimizer = paddle.optimizer.SGD(learning_rate=0.00001)
    rank = paddle.distributed.get_rank()
    partitioner = Partitioner(dist_context, rank)
    dist_main_prog, dist_startup_prog, _ = partitioner.partition(
362 363
        train_program, start_program, []
    )
364 365 366 367 368 369 370 371 372

    return dist_main_prog, dist_startup_prog


class TestMLP(unittest.TestCase):
    def test_partitioner(self):

        train_program, start_program, dataloader, i, loss = get_program()
        dist_context = get_default_distributed_context()
373 374 375
        train_program, start_program = completion(
            train_program, start_program, dist_context
        )
376 377
        dist_context.block_state.parse_forward_blocks(train_program)

378 379 380
        dist_main_prog, dist_startup_prog = partition(
            train_program, start_program, dist_context
        )
381
        global_block_ops = dist_main_prog.blocks[0].ops
382 383 384 385 386 387

        fill_op = None
        for op in global_block_ops:
            if op.type == "fill_constant_batch_size_like":
                fill_op = op

388 389 390 391 392 393 394
        global_block_ops = [op.type for op in global_block_ops]
        sub_block_ops = dist_main_prog.blocks[1].ops
        sub_block_ops = [op.type for op in sub_block_ops]

        self.assertTrue("c_allreduce_sum" in global_block_ops)
        self.assertTrue("c_allreduce_sum" in sub_block_ops)

395 396
        # test fill_constant_batch_size_like

397
        self.assertIsNotNone(fill_op)
398 399 400 401
        ref_shape = [-1, 8, 0, 48]
        shape = fill_op.attr("shape")
        self.assertTrue(ref_shape == shape)

402 403 404

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