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

15
import copy
16
import unittest
17 18

import numpy as np
19 20

import paddle
21
import paddle.nn.functional as F
22
from paddle import nn, static
23 24 25 26 27
from paddle.distributed import fleet
from paddle.distributed.auto_parallel.dist_context import (
    DistributedContext,
    set_default_distributed_context,
)
28
from paddle.distributed.auto_parallel.process_mesh import ProcessMesh
29 30 31
from paddle.distributed.auto_parallel.utils import (
    _copy_dist_attr_from_cpp,
    _copy_dist_attr_from_cpp_for_graph,
32 33
    _copy_dist_attr_to_cpp,
    _copy_dist_attr_to_cpp_for_graph,
34
)
35 36
from paddle.distributed.fleet import auto
from paddle.fluid.core import OperatorDistAttr, TensorDistAttr
37 38 39

paddle.enable_static()

40 41 42 43
batch_size = 4
epoch_num = 10
hidden_size = 1024
sequence_len = 512
44
_g_process_mesh = ProcessMesh(mesh=[[0, 1], [2, 3]], dim_names=['x', 'y'])
45 46 47 48 49 50 51 52 53 54


class MLPLayer(nn.Layer):
    def __init__(
        self,
        hidden_size=1024,
        intermediate_size=4 * 1024,
        dropout_ratio=0.1,
        initializer_range=0.02,
    ):
55
        super().__init__()
56 57 58 59 60 61 62 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 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
        d_model = hidden_size
        dim_feedforward = intermediate_size
        param_initializer = nn.initializer.Normal(
            mean=0.0, std=initializer_range
        )

        self.norm = nn.LayerNorm(d_model, epsilon=1e-5)
        self.linear0 = nn.Linear(
            d_model,
            dim_feedforward,
            weight_attr=paddle.ParamAttr(initializer=param_initializer),
            bias_attr=None,
        )
        self.linear1 = nn.Linear(
            dim_feedforward,
            d_model,
            weight_attr=paddle.ParamAttr(initializer=param_initializer),
            bias_attr=None,
        )

    def forward(self, input):
        out = self.norm(input)
        auto.shard_tensor(
            self.linear0.weight,
            process_mesh=_g_process_mesh[0],
            shard_spec=[None, 'y'],
        )
        out = self.linear0(out)
        out = F.gelu(out, approximate=True)
        auto.shard_tensor(
            self.linear1.weight,
            process_mesh=_g_process_mesh[1],
            shard_spec=['y', None],
        )
        out = self.linear1(out)

        return out


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],
                [batch_size, sequence_len, 1],
            )
            yield batch_input, batch_label

    return __reader__


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 static.program_guard(train_program, start_program):

        # input
        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'
        )
        data_holder = [input, label]
        # dataloader
        dataloader = paddle.io.DataLoader.from_generator(
            feed_list=data_holder, capacity=4 * batch_size, iterable=False
        )
        dataloader.set_batch_generator(
            batch_generator_creator(), places=paddle.static.cuda_places()
        )
        # data dist_attr
        auto.shard_tensor(
            input, process_mesh=_g_process_mesh[0], shard_spec=['y', None, None]
        )
        auto.shard_tensor(
            label, process_mesh=_g_process_mesh[0], shard_spec=['y', None, None]
        )

        mlp_start = MLPLayer(
            hidden_size=hidden_size,
            intermediate_size=4 * hidden_size,
            dropout_ratio=0.1,
            initializer_range=0.02,
        )
        pred = mlp_start(input)

        mlp_mid = MLPLayer(
            hidden_size=hidden_size,
            intermediate_size=4 * hidden_size,
            dropout_ratio=0.1,
            initializer_range=0.02,
        )
        pred = mlp_mid(pred)

        mlp_end = MLPLayer(
            hidden_size=hidden_size,
            intermediate_size=4 * hidden_size,
            dropout_ratio=0.1,
            initializer_range=0.02,
        )
        pred = mlp_end(pred)

        error_cost = paddle.nn.functional.square_error_cost(pred, label)
        loss = paddle.mean(error_cost)

        optimizer = paddle.optimizer.Adam(
            learning_rate=0.00001,
            beta1=0.9,
            beta2=0.999,
            epsilon=1e-08,
            grad_clip=None,
        )

        feed_vars = {"inputs": [input], "labels": [label]}
        fetch_vars = {"loss": [loss]}

    return (
        train_program,
        start_program,
        dataloader,
        loss,
        optimizer,
        feed_vars,
        fetch_vars,
    )

195 196 197 198 199 200 201 202

class TestDistAttr(unittest.TestCase):
    def test_tensor_dist_attr_ctor(self):
        train_program = static.Program()
        start_program = static.Program()
        with static.program_guard(train_program, start_program):
            input = static.data(name="input", shape=[2, 3], dtype='float32')
        dist_attr = TensorDistAttr(input.desc)
203
        self.assertEqual(dist_attr.process_mesh, None)
204 205 206 207
        self.assertEqual(dist_attr.dims_mapping, [-1, -1])
        self.assertEqual(dist_attr.batch_dim, 0)
        self.assertEqual(dist_attr.dynamic_dims, [0, 0])

208 209 210
        dist_attr.process_mesh = None
        self.assertEqual(dist_attr.process_mesh, None)

211 212 213 214
        dist_attr.process_mesh = ProcessMesh([[0, 1, 2], [3, 4, 5]])
        dist_attr.dims_mapping = [0, -1]
        dist_attr.batch_dim = 1
        dist_attr.dynamic_dims = [1, 1]
215
        self.assertEqual(dist_attr.dims_mapping, [0, -1])
216 217 218
        self.assertEqual(
            dist_attr.process_mesh, ProcessMesh([[0, 1, 2], [3, 4, 5]])
        )
219 220 221
        self.assertEqual(dist_attr.dims_mapping, [0, -1])
        self.assertEqual(dist_attr.batch_dim, 1)
        self.assertEqual(dist_attr.dynamic_dims, [1, 1])
222
        self.assertTrue(dist_attr.verify(input.desc))
223 224 225 226 227 228 229 230 231 232 233 234 235
        self.assertTrue(str(dist_attr), str(dist_attr))

    def test_tensor_dist_attr(self):
        train_program = static.Program()
        start_program = static.Program()
        with static.program_guard(train_program, start_program):
            input = static.data(name="input", shape=[2, 3], dtype='float32')
            input1 = static.data(name="input1", shape=[2, 3], dtype='float32')
        dist_attr = input.dist_attr
        dist_attr.process_mesh = ProcessMesh([[0, 1, 2], [3, 4, 5]])
        dist_attr.dims_mapping = [0, -1]
        dist_attr.batch_dim = 1
        dist_attr.dynamic_dims = [1, 1]
236 237 238
        self.assertEqual(
            input.dist_attr.process_mesh, ProcessMesh([[0, 1, 2], [3, 4, 5]])
        )
239 240 241
        self.assertEqual(input.dist_attr.dims_mapping, [0, -1])
        self.assertEqual(input.dist_attr.batch_dim, 1)
        self.assertEqual(input.dist_attr.dynamic_dims, [1, 1])
242
        self.assertTrue(input.dist_attr.verify(input.desc))
243 244

        input1.dist_attr = dist_attr
245 246 247
        self.assertEqual(
            input1.dist_attr.process_mesh, ProcessMesh([[0, 1, 2], [3, 4, 5]])
        )
248 249 250
        self.assertEqual(input1.dist_attr.dims_mapping, [0, -1])
        self.assertEqual(input1.dist_attr.batch_dim, 1)
        self.assertEqual(input1.dist_attr.dynamic_dims, [1, 1])
251
        self.assertTrue(input1.dist_attr.verify(input.desc))
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278

    def test_operator_dist_attr_ctor(self):
        train_program = static.Program()
        start_program = static.Program()
        with static.program_guard(train_program, start_program):
            input = static.data(name="input", shape=[2, 3], dtype='float32')
            input1 = static.data(name="input1", shape=[3, 4], dtype='float32')
            output = paddle.matmul(input, input1)
        op = train_program.current_block().ops[0]
        process_mesh = ProcessMesh([[0, 1, 2], [3, 4, 5]])
        op_dist_attr = OperatorDistAttr(op.desc)

        op_dist_attr.process_mesh = process_mesh
        # Set the distributed attribute of input
        input_dist_attr = TensorDistAttr(input.desc)
        input_dist_attr.dims_mapping = [0, -1]
        op_dist_attr.set_input_dist_attr(input.name, input_dist_attr)
        # Set the distributed attribute of input1
        input1_dist_attr = TensorDistAttr(input1.desc)
        input1_dist_attr.dims_mapping = [-1, 1]
        op_dist_attr.set_input_dist_attr(input1.name, input1_dist_attr)
        # Set the distributed attribute of output
        output_dist_attr = TensorDistAttr(output.desc)
        output_dist_attr.dims_mapping = [0, 1]
        op_dist_attr.set_output_dist_attr(output.name, output_dist_attr)
        self.assertEqual(op_dist_attr.process_mesh, process_mesh)
        self.assertEqual(
279 280
            op_dist_attr.get_input_dist_attr(input.name).process_mesh,
            process_mesh,
281
        )
282
        self.assertEqual(
283 284
            op_dist_attr.get_input_dist_attr(input1.name).process_mesh,
            process_mesh,
285
        )
286
        self.assertEqual(
287
            op_dist_attr.get_output_dist_attr(output.name).process_mesh,
288 289
            process_mesh,
        )
290
        self.assertEqual(
291
            op_dist_attr.get_input_dist_attr(input.name).dims_mapping, [0, -1]
292
        )
293
        self.assertEqual(
294
            op_dist_attr.get_input_dist_attr(input1.name).dims_mapping, [-1, 1]
295
        )
296
        self.assertEqual(
297
            op_dist_attr.get_output_dist_attr(output.name).dims_mapping, [0, 1]
298
        )
299
        self.assertTrue(op_dist_attr.verify(op.desc))
300 301 302 303 304
        self.assertTrue(str(op_dist_attr), str(op_dist_attr))

        op_dist_attr = OperatorDistAttr(op.desc)
        op_dist_attr.process_mesh = process_mesh
        # Set the distributed attribute of input directly
305
        input_dist_attr = op_dist_attr.get_input_dist_attr(input.name)
306 307
        input_dist_attr.dims_mapping = [-1, 0]
        # Set the distributed attribute of input1 directly
308
        input1_dist_attr = op_dist_attr.get_input_dist_attr(input1.name)
309 310
        input1_dist_attr.dims_mapping = [0, -1]
        # Set the distributed attribute of output directly
311
        output_dist_attr = op_dist_attr.get_output_dist_attr(output.name)
312 313 314 315 316 317 318 319
        output_dist_attr.dims_mapping = [-1, -1]
        self.assertEqual(op_dist_attr.process_mesh, process_mesh)
        self.assertEqual(input_dist_attr.process_mesh, process_mesh)
        self.assertEqual(input1_dist_attr.process_mesh, process_mesh)
        self.assertEqual(output_dist_attr.process_mesh, process_mesh)
        self.assertEqual(input_dist_attr.dims_mapping, [-1, 0])
        self.assertEqual(input1_dist_attr.dims_mapping, [0, -1])
        self.assertEqual(output_dist_attr.dims_mapping, [-1, -1])
320
        self.assertTrue(op_dist_attr.verify(op.desc))
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
        self.assertTrue(str(op_dist_attr), str(op_dist_attr))

    def test_operator_dist_attr(self):
        train_program = static.Program()
        start_program = static.Program()
        with static.program_guard(train_program, start_program):
            input = static.data(name="input", shape=[2, 3], dtype='float32')
            input1 = static.data(name="input1", shape=[3, 4], dtype='float32')
            output = paddle.matmul(input, input1)
        op = train_program.current_block().ops[0]
        process_mesh = ProcessMesh([[0, 1, 2], [3, 4, 5]])
        op_dist_attr = op.dist_attr

        op_dist_attr.process_mesh = process_mesh
        # Set the distributed attribute of input
        input_dist_attr = TensorDistAttr(input.desc)
        input_dist_attr.dims_mapping = [0, -1]
        op_dist_attr.set_input_dist_attr(input.name, input_dist_attr)
        # Set the distributed attribute of input1
        input1_dist_attr = TensorDistAttr(input1.desc)
        input1_dist_attr.dims_mapping = [-1, 1]
        op_dist_attr.set_input_dist_attr(input1.name, input1_dist_attr)
        # Set the distributed attribute of output
        output_dist_attr = TensorDistAttr(output.desc)
        output_dist_attr.dims_mapping = [0, 1]
        op_dist_attr.set_output_dist_attr(output.name, output_dist_attr)

        self.assertEqual(op.desc.dist_attr.process_mesh, process_mesh)
        self.assertEqual(
350 351
            op.dist_attr.get_input_dist_attr(input.name).process_mesh,
            process_mesh,
352
        )
353
        self.assertEqual(
354 355
            op.dist_attr.get_input_dist_attr(input1.name).process_mesh,
            process_mesh,
356
        )
357
        self.assertEqual(
358
            op.dist_attr.get_input_dist_attr(input.name).dims_mapping, [0, -1]
359
        )
360
        self.assertEqual(
361
            op.dist_attr.get_input_dist_attr(input.name).dims_mapping, [0, -1]
362
        )
363
        self.assertEqual(
364 365
            op.desc.dist_attr.get_input_dist_attr(input1.name).dims_mapping,
            [-1, 1],
366
        )
367
        self.assertEqual(
368
            op.dist_attr.get_output_dist_attr(output.name).dims_mapping, [0, 1]
369
        )
370
        self.assertTrue(op.desc.dist_attr.verify(op.desc))
371 372 373 374 375 376
        self.assertTrue(str(op_dist_attr), str(op_dist_attr))

        op.dist_attr = OperatorDistAttr(op.desc)
        self.assertEqual(op.desc.dist_attr, OperatorDistAttr(op.desc))


377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451
class TestDistAttrConversion(unittest.TestCase):
    def test_dist_attr_conversion_for_program(self):
        set_default_distributed_context(DistributedContext())
        (
            train_program,
            start_program,
            dataloader,
            loss,
            optimizer,
            feed_vars,
            fetch_vars,
        ) = get_program()
        dist_context = DistributedContext(
            train_program, start_program, optimizer, loss, feed_vars, fetch_vars
        )
        dist_context.initialize()
        original_dist_tensors = copy.deepcopy(
            dist_context._dist_tensors_for_program
        )
        original_dist_ops = copy.deepcopy(dist_context._dist_ops_for_program)

        _copy_dist_attr_to_cpp(dist_context)
        _copy_dist_attr_from_cpp(dist_context)

        for dist_tensor in dist_context._dist_tensors_for_program.values():
            original_dist_tensor = original_dist_tensors[
                dist_tensor.serial_tensor.desc.original_id()
            ]
            self.assertEqual(
                dist_tensor.dist_attr, original_dist_tensor.dist_attr
            )

        for dist_op in dist_context._dist_ops_for_program.values():
            original_dist_op = original_dist_ops[
                dist_op.serial_op.desc.original_id()
            ]
            self.assertEqual(dist_op.dist_attr, original_dist_op.dist_attr)

    def test_dist_attr_conversion_for_graph(self):
        set_default_distributed_context(DistributedContext())
        (
            train_program,
            start_program,
            dataloader,
            loss,
            optimizer,
            feed_vars,
            fetch_vars,
        ) = get_program()
        dist_context = DistributedContext(
            train_program, start_program, optimizer, loss, feed_vars, fetch_vars
        )
        dist_context.initialize()
        original_dist_tensors = copy.deepcopy(
            dist_context._dist_tensors_for_graph
        )
        original_dist_ops = copy.deepcopy(dist_context._dist_ops_for_graph)

        _copy_dist_attr_to_cpp_for_graph(dist_context)
        _copy_dist_attr_from_cpp_for_graph(dist_context)

        for (
            node_id,
            dist_tensor,
        ) in dist_context._dist_tensors_for_graph.items():
            original_dist_tensor = original_dist_tensors[node_id]
            self.assertEqual(
                dist_tensor.dist_attr, original_dist_tensor.dist_attr
            )

        for node_id, dist_op in dist_context._dist_ops_for_graph.items():
            original_dist_op = original_dist_ops[node_id]
            self.assertEqual(dist_op.dist_attr, original_dist_op.dist_attr)


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