test_auto_parallel_mapper.py 18.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#   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.

15 16
import json
import os
17
import tempfile
18
import unittest
19

20 21 22 23
import numpy as np

import paddle
import paddle.fluid as fluid
24
import paddle.nn as nn
25 26
import paddle.nn.functional as F
import paddle.static as static
27
import paddle.utils as utils
28
from paddle.distributed import fleet
29
from paddle.distributed.auto_parallel.cluster import Cluster
30
from paddle.distributed.auto_parallel.completion import Completer
31
from paddle.distributed.auto_parallel.dist_context import DistributedContext
32 33 34 35 36 37
from paddle.distributed.auto_parallel.mapper import (
    get_comm_volume,
    get_dtype_bytes,
    mapping,
)
from paddle.distributed.auto_parallel.parallelizer import AutoParallelizer
38
from paddle.distributed.auto_parallel.partitioner import Partitioner
39
from paddle.distributed.auto_parallel.reshard import Resharder
40 41 42
from paddle.distributed.fleet import auto
from paddle.fluid import core, layers
from paddle.fluid.initializer import NumpyArrayInitializer
43

44 45 46
if os.getenv("CUDA_VISIBLE_DEVICES") is not None:
    os.environ["CUDA_VISIBLE_DEVICES"] = ""

47 48 49 50 51 52 53 54 55 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
paddle.enable_static()
_global_parallel_strategy = None
_global_process_mesh = None
_global_num_stages = None

cluster_json = """
{
  "machines": [
    {
      "hostname": "machine0",
      "addr": "0.0.0.1",
      "port": "768",
      "devices": [
        {
          "global_id": 0,
          "local_id": 0,
          "type": "GPU",
          "model": "A100-SXM4-40GB",
          "sp_gflops": 19500,
          "dp_gflops": 9700,
          "memory": 40
        },
        {
          "global_id": 1,
          "local_id": 1,
          "type": "GPU",
          "model": "A100-SXM4-40GB",
          "sp_gflops": 19500,
          "dp_gflops": 9700,
          "memory": 40
        },
        {
          "global_id": 2,
          "local_id": 2,
          "type": "GPU",
          "model": "A100-SXM4-40GB",
          "sp_gflops": 19500,
          "dp_gflops": 9700,
          "memory": 40
        },
        {
          "global_id": 3,
          "local_id": 3,
          "type": "GPU",
          "model": "A100-SXM4-40GB",
          "sp_gflops": 19500,
          "dp_gflops": 9700,
          "memory": 40
        },
        {
          "global_id": 4,
          "local_id": 0,
          "type": "NIC"
        }
      ],
      "links": [
        {
          "source_global_id": 0,
          "target_global_id": 1,
          "type": "NVL",
          "bandwidth": 42
        },
        {
          "source_global_id": 0,
          "target_global_id": 2,
          "type": "NVL",
          "bandwidth": 42
        },
        {
          "source_global_id": 0,
          "target_global_id": 3,
          "type": "NVL",
          "bandwidth": 42
        },
        {
          "source_global_id": 0,
          "target_global_id": 4,
          "type": "PHB",
125
          "bandwidth": 12
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
        },
        {
          "source_global_id": 1,
          "target_global_id": 0,
          "type": "NVL",
          "bandwidth": 42
        },
        {
          "source_global_id": 1,
          "target_global_id": 2,
          "type": "NVL",
          "bandwidth": 42
        },
        {
          "source_global_id": 1,
          "target_global_id": 3,
          "type": "NVL",
          "bandwidth": 42
        },
        {
          "source_global_id": 1,
          "target_global_id": 4,
          "type": "PHB",
149
          "bandwidth": 12
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 195 196
        },
        {
          "source_global_id": 2,
          "target_global_id": 0,
          "type": "NVL",
          "bandwidth": 42
        },
        {
          "source_global_id": 2,
          "target_global_id": 1,
          "type": "NVL",
          "bandwidth": 42
        },
        {
          "source_global_id": 2,
          "target_global_id": 3,
          "type": "NVL",
          "bandwidth": 42
        },
        {
          "source_global_id": 2,
          "target_global_id": 4,
          "type": "PHB",
          "bandwidth": 12
        },
        {
          "source_global_id": 3,
          "target_global_id": 0,
          "type": "NVL",
          "bandwidth": 42
        },
        {
          "source_global_id": 3,
          "target_global_id": 1,
          "type": "NVL",
          "bandwidth": 42
        },
        {
          "source_global_id": 3,
          "target_global_id": 2,
          "type": "NVL",
          "bandwidth": 42
        },
        {
          "source_global_id": 3,
          "target_global_id": 4,
          "type": "PHB",
197
          "bandwidth": 12
198 199 200 201 202
        },
        {
          "source_global_id": 4,
          "target_global_id": 9,
          "type": "NET",
203
          "bandwidth": 1
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 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 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276
        }
      ]
    },
    {
      "hostname": "machine1",
      "addr": "0.0.0.2",
      "port": "768",
      "devices": [
        {
          "global_id": 5,
          "local_id": 0,
          "type": "GPU",
          "model": "Tesla V100-SXM2-32GB",
          "sp_gflops": 15700,
          "dp_gflops": 7800,
          "memory": 32
        },
        {
          "global_id": 6,
          "local_id": 1,
          "type": "GPU",
          "model": "Tesla V100-SXM2-32GB",
          "sp_gflops": 15700,
          "dp_gflops": 7800,
          "memory": 32
        },
        {
          "global_id": 7,
          "local_id": 2,
          "type": "GPU",
          "model": "Tesla V100-SXM2-32GB",
          "sp_gflops": 15700,
          "dp_gflops": 7800,
          "memory": 32
        },
        {
          "global_id": 8,
          "local_id": 3,
          "type": "GPU",
          "model": "Tesla V100-SXM2-32GB",
          "sp_gflops": 15700,
          "dp_gflops": 7800,
          "memory": 32
        },
        {
          "global_id": 9,
          "local_id": 0,
          "type": "NIC"
        }
      ],
      "links": [
        {
          "source_global_id": 5,
          "target_global_id": 6,
          "type": "NVL",
          "bandwidth": 42
        },
        {
          "source_global_id": 5,
          "target_global_id": 7,
          "type": "NVL",
          "bandwidth": 42
        },
        {
          "source_global_id": 5,
          "target_global_id": 8,
          "type": "NVL",
          "bandwidth": 42
        },
        {
          "source_global_id": 5,
          "target_global_id": 9,
          "type": "PHB",
277
          "bandwidth": 12
278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300
        },
        {
          "source_global_id": 6,
          "target_global_id": 5,
          "type": "NVL",
          "bandwidth": 42
        },
        {
          "source_global_id": 6,
          "target_global_id": 7,
          "type": "NVL",
          "bandwidth": 42
        },
        {
          "source_global_id": 6,
          "target_global_id": 8,
          "type": "NVL",
          "bandwidth": 42
        },
        {
          "source_global_id": 6,
          "target_global_id": 9,
          "type": "PHB",
301
          "bandwidth": 12
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
        },
        {
          "source_global_id": 7,
          "target_global_id": 5,
          "type": "NVL",
          "bandwidth": 42
        },
        {
          "source_global_id": 7,
          "target_global_id": 6,
          "type": "NVL",
          "bandwidth": 42
        },
        {
          "source_global_id": 7,
          "target_global_id": 8,
          "type": "NVL",
          "bandwidth": 42
        },
        {
          "source_global_id": 7,
          "target_global_id": 9,
          "type": "PHB",
325
          "bandwidth": 12
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348
        },
        {
          "source_global_id": 8,
          "target_global_id": 5,
          "type": "NVL",
          "bandwidth": 42
        },
        {
          "source_global_id": 8,
          "target_global_id": 6,
          "type": "NVL",
          "bandwidth": 42
        },
        {
          "source_global_id": 8,
          "target_global_id": 7,
          "type": "NVL",
          "bandwidth": 42
        },
        {
          "source_global_id": 8,
          "target_global_id": 9,
          "type": "PHB",
349
          "bandwidth": 12
350 351 352 353 354
        },
        {
          "source_global_id": 9,
          "target_global_id": 4,
          "type": "NET",
355
          "bandwidth": 1
356 357
        }
      ]
358
    }
359 360 361 362 363 364
  ]
}
"""


class MLPLayer(nn.Layer):
365 366 367
    def __init__(
        self, hidden_size=64, intermediate_size=4 * 64, initializer_range=0.02
    ):
368
        super().__init__()
369 370 371 372 373 374 375 376 377 378 379 380
        d_model = hidden_size
        dim_feedforward = intermediate_size
        np.random.seed(2021)
        arr0 = np.random.normal(0, 0.02, size=(d_model, dim_feedforward))
        arr1 = np.random.normal(0, 0.02, size=(dim_feedforward, d_model))
        arr2 = np.random.normal(0, 0.02, size=(d_model, dim_feedforward))
        arr3 = np.random.normal(0, 0.02, size=(dim_feedforward, d_model))
        weight_attr0 = paddle.ParamAttr(initializer=NumpyArrayInitializer(arr0))
        weight_attr1 = paddle.ParamAttr(initializer=NumpyArrayInitializer(arr1))
        weight_attr2 = paddle.ParamAttr(initializer=NumpyArrayInitializer(arr2))
        weight_attr3 = paddle.ParamAttr(initializer=NumpyArrayInitializer(arr3))
        bias_attr = None
381 382 383 384 385 386
        self.linear0 = nn.Linear(
            d_model, dim_feedforward, weight_attr0, bias_attr=bias_attr
        )
        self.linear1 = nn.Linear(
            dim_feedforward, d_model, weight_attr1, bias_attr=bias_attr
        )
387
        self.norm = nn.LayerNorm(d_model, epsilon=1e-5)
388 389 390 391 392 393
        self.linear2 = nn.Linear(
            d_model, dim_feedforward, weight_attr2, bias_attr=bias_attr
        )
        self.linear3 = nn.Linear(
            dim_feedforward, d_model, weight_attr3, bias_attr=bias_attr
        )
394 395 396

    def forward(self, input):
        if _global_parallel_strategy == "dp_mp_pp":
397 398 399
            auto.shard_tensor(
                self.linear0.weight, _global_process_mesh[0], [None, "y"]
            )
400

401 402 403
            auto.shard_tensor(
                self.linear1.weight, _global_process_mesh[0], ["y", None]
            )
404

405 406 407
            auto.shard_tensor(
                self.linear2.weight, _global_process_mesh[1], [None, "y"]
            )
408

409 410 411
            auto.shard_tensor(
                self.linear3.weight, _global_process_mesh[1], ["y", None]
            )
412 413 414 415 416 417

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

418 419
        auto.shard_tensor(out, _global_process_mesh[1], ["x", None])

420 421 422 423 424 425 426
        out = self.linear2(out)
        out = F.gelu(out, approximate=True)
        out = self.linear3(out)
        return out


def mlp_forward(train_program, start_program):
427 428 429
    with static.program_guard(
        train_program, start_program
    ), utils.unique_name.guard():
430 431
        batch_size = 4
        hidden_size = 64
432 433 434 435 436 437
        input = static.data(
            name="input", shape=[batch_size, hidden_size], dtype='float32'
        )
        label = static.data(
            name="label", shape=[batch_size, 1], dtype='float32'
        )
438 439

        if _global_parallel_strategy == "dp_mp_pp":
440
            auto.shard_tensor(input, _global_process_mesh[0], ["x", None])
441 442 443 444 445
        mlp = MLPLayer(
            hidden_size=hidden_size,
            intermediate_size=4 * hidden_size,
            initializer_range=0.02,
        )
446 447 448 449 450 451 452
        predict = mlp(input)
        error_cost = paddle.nn.functional.square_error_cost(predict, label)
        loss = paddle.mean(error_cost)
    return loss, train_program, start_program


def get_dist_prog(train_program, startup_program, dist_context, rank_id):
453 454 455
    loss, train_program, startup_program = mlp_forward(
        train_program, startup_program
    )
456

457 458 459 460
    fleet._user_defined_strategy = fleet.DistributedStrategy()
    fleet.user_defined_optimizer = paddle.fluid.optimizer.AdamOptimizer()
    parallelizer = AutoParallelizer(fleet)
    parallelizer._dist_context = dist_context
461 462

    # auto completion
463 464
    completer = Completer(dist_context)
    complete_train_program = completer.complete_forward_annotation(
465 466
        train_program
    )
467
    dist_context.block_state.parse_forward_blocks(complete_train_program)
468 469 470 471 472 473 474 475
    params_grads = parallelizer._generate_backward(
        complete_train_program,
        startup_program,
        loss,
        parameter_list=None,
        no_grad_set=None,
        callbacks=None,
    )
476 477

    partitioner = Partitioner(dist_context, rank_id)
478 479 480 481 482 483 484
    (
        dist_train_program,
        dist_startup_prog,
        dist_params_grads,
    ) = partitioner.partition(
        complete_train_program, startup_program, params_grads
    )
485 486

    partitioned_optimize_ops = parallelizer._apply_optimize(
487 488 489 490 491 492 493 494 495 496
        dist_train_program, dist_startup_prog, dist_params_grads
    )

    resharder = Resharder(
        dist_train_program,
        dist_startup_prog,
        rank_id,
        dist_context,
        dist_params_grads,
    )
497
    resharder.reshard()
498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515
    return dist_train_program, dist_startup_prog


def is_in_machine(device_local_id, machine):
    for device in machine.devices.values():
        if device_local_id == device.local_id:
            return True
    return False


def get_device_local_ids(machine):
    local_ids = []
    for device in machine.devices.values():
        local_ids.append[device.local_id]
    return local_ids


class TestAutoParallelMapper(unittest.TestCase):
516 517 518 519 520 521
    def setUp(self):
        self.temp_dir = tempfile.TemporaryDirectory()

    def tearDown(self):
        self.temp_dir.cleanup()

522
    def test_mapper_dp_mp_pp(self):
523 524 525
        cluster_json_path = os.path.join(
            self.temp_dir.name, "auto_parallel_cluster.json"
        )
526
        cluster_json_object = json.loads(cluster_json)
527
        with open(cluster_json_path, "w") as cluster_json_file:
528 529
            json.dump(cluster_json_object, cluster_json_file)
        cluster = Cluster()
530
        cluster.build_from_file(cluster_json_path)
531 532 533 534 535 536

        global _global_parallel_strategy
        _global_parallel_strategy = "dp_mp_pp"
        global _global_num_stages
        _global_num_stages = 2
        global _global_process_mesh
537 538
        _global_process_mesh = [
            auto.ProcessMesh([[0, 1], [2, 3]], dim_names=["x", "y"]),
539
            auto.ProcessMesh([[4, 5], [6, 7]], dim_names=["x", "y"]),
540
        ]
541 542 543 544 545 546 547 548
        processes = [0, 1, 2, 3, 4, 5, 6, 7]

        dist_programs = {}
        for rank_id in processes:
            train_program = static.Program()
            startup_program = static.Program()
            dist_context = DistributedContext()
            dist_train_program, dist_startup_prog = get_dist_prog(
549 550
                train_program, startup_program, dist_context, rank_id
            )
551 552
            # if rank_id == 0:
            #   print_program_with_dist_attr(dist_train_program, dist_context)
553
            dist_programs[rank_id] = [dist_train_program, None]
554 555 556 557 558 559 560 561 562 563 564 565 566 567

        rank_mapping = mapping(dist_programs, cluster)

        all_mapped_ranks = set()
        for machine_id, machine_mapping in rank_mapping.items():
            machine = cluster.machines[machine_id]
            machine_mapped_ranks = set()
            machine_mapped_device_local_ids = set()
            for rank, device_ids in machine_mapping["ranks"].items():
                # Only allow one process to one device mapping
                self.assertEqual(len(device_ids), 1)
                self.assertTrue(is_in_machine(device_ids[0], machine))
                machine_mapped_ranks.add(rank)
                machine_mapped_device_local_ids.add(device_ids[0])
568 569 570
            self.assertEqual(
                len(machine_mapped_ranks), len(machine_mapped_device_local_ids)
            )
571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596
            all_mapped_ranks.update(machine_mapped_ranks)
        self.assertEqual(set(processes), all_mapped_ranks)

    def test_mapper_misc(self):
        self.assertEqual(get_dtype_bytes(paddle.float64), 8)
        self.assertEqual(get_dtype_bytes(paddle.float32), 4)
        self.assertEqual(get_dtype_bytes(paddle.float16), 2)
        self.assertEqual(get_dtype_bytes(paddle.bfloat16), 2)
        self.assertEqual(get_dtype_bytes(paddle.int64), 8)
        self.assertEqual(get_dtype_bytes(paddle.int32), 4)
        self.assertEqual(get_dtype_bytes(paddle.int16), 2)
        self.assertEqual(get_dtype_bytes(paddle.int8), 1)
        self.assertEqual(get_dtype_bytes(paddle.uint8), 1)
        self.assertRaises(ValueError, get_dtype_bytes, "unknown type")
        train_program = static.Program()
        startup_program = static.Program()
        ring_id = 0
        root_id = 0
        nranks = 2
        with fluid.program_guard(train_program, startup_program):
            input = layers.data(name="input", shape=[10, 10], dtype='float32')
            output = train_program.current_block().create_var(
                name="outofbroadcast",
                dtype='float32',
                type=core.VarDesc.VarType.LOD_TENSOR,
                persistable=False,
597 598
                stop_gradient=False,
            )
599 600 601
            broadcast_op = train_program.global_block().append_op(
                type="c_broadcast",
                inputs={'X': input},
602 603 604
                attrs={'ring_id': ring_id, 'root': root_id},
                outputs={'Out': output},
            )
605
            self.assertEqual(get_comm_volume(broadcast_op, 0, 1), 400)
606
            self.assertIsNone(get_comm_volume(broadcast_op, 1, 0))
607 608 609
            allgather_op = train_program.global_block().append_op(
                type="c_allgather",
                inputs={'X': input},
610 611 612
                attrs={'ring_id': ring_id, 'nranks': nranks},
                outputs={'Out': output},
            )
613
            self.assertEqual(get_comm_volume(allgather_op, 0, 1), 400)
614
            self.assertIsNone(get_comm_volume(allgather_op, 0, 0))
615 616 617
            reduce_op = train_program.global_block().append_op(
                type="c_reduce_sum",
                inputs={'X': input},
618 619 620
                attrs={'ring_id': ring_id, 'root_id': root_id},
                outputs={'Out': output},
            )
621
            self.assertIsNone(get_comm_volume(reduce_op, 0, 1))
622 623 624 625 626 627 628
            self.assertEqual(get_comm_volume(reduce_op, 1, 0), 400)
            cast_op = train_program.global_block().append_op(
                type="cast",
                inputs={"X": input},
                outputs={"Out": output},
                attrs={
                    "in_dtype": fluid.core.VarDesc.VarType.FP32,
629 630 631
                    "out_dtype": fluid.core.VarDesc.VarType.FP32,
                },
            )
632 633 634 635 636
            self.assertRaises(ValueError, get_comm_volume, cast_op, 0, 1)


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