planner.py 44.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
# 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 copy
import random
17 18
import time
from collections import OrderedDict
19 20 21 22 23 24
from functools import reduce
from itertools import chain, product

import numpy as np

import paddle
25
from paddle.distributed.fleet import auto
26

27
from .cost_model import estimate_cost
28 29 30 31
from .dist_attribute import (
    OperatorDistributedAttribute,
    TensorDistributedAttribute,
)
32 33 34 35 36 37 38 39 40 41 42 43
from .dist_context import DistributedContext, DistributedOperatorContext
from .dist_op import DistributedOperator
from .operators.common import (
    get_distributed_operator_impl_container,
    is_elementwise_op,
)
from .process_group import get_process_group
from .utils import (
    get_all_distributed_main_program,
    update_op_dims_mapping_by_default_dist_impl,
    update_op_dims_mapping_by_elementwise_like_dist_impl,
)
44 45 46 47 48 49 50 51

paddle.seed(123)
random.seed(123)
np.random.seed(123)


class PlanFilter:
    @staticmethod
52 53 54
    def check_dims_mapping_for_tensor(
        process_mesh_topology, tensor_shape, dims_mapping
    ):
55 56 57 58 59
        valid = True
        assert len(tensor_shape) == len(dims_mapping)

        for idx, dim_mapping in enumerate(dims_mapping):
            if dim_mapping != -1:
60 61 62 63
                if (
                    tensor_shape[idx] % process_mesh_topology[dim_mapping] != 0
                    or dims_mapping.count(dim_mapping) > 1
                ):
64 65 66 67 68 69 70 71 72 73 74 75 76
                    valid = False
            if dim_mapping != -1 and process_mesh_topology[0] == 1:
                valid = False

        return valid

    @staticmethod
    def check_dims_mapping_for_op(op, op_dist_attr, vars):
        process_mesh = op_dist_attr.process_mesh
        assert process_mesh is not None, "The process mesh should not be None."
        for var_name in op.input_arg_names:
            dims_mapping = op_dist_attr.get_input_dims_mapping(var_name)
            if not PlanFilter.check_dims_mapping_for_tensor(
77
                process_mesh.shape, vars[var_name].shape, dims_mapping
78
            ):
79 80 81 82 83 84 85 86 87
                return False
            if vars[var_name].is_data and len(dims_mapping) > 1:
                for dim in dims_mapping[1:]:
                    if dim != -1:
                        return False

        for var_name in op.output_arg_names:
            dims_mapping = op_dist_attr.get_output_dims_mapping(var_name)
            if not PlanFilter.check_dims_mapping_for_tensor(
88
                process_mesh.shape, vars[var_name].shape, dims_mapping
89
            ):
90 91 92 93 94 95
                return False

        return True

    @staticmethod
    def check_dims_mapping_for_special_op(op, op_dist_attr, vars):
96
        # NOTE: Those ops has some partition limits, and will be solved when corresponding dist op implemented in the future.
97 98 99 100 101
        if (
            op.type == "elementwise_add"
            or op.type == 'layer_norm'
            or op.type == "softmax_with_cross_entropy"
        ):
102 103 104 105 106 107 108 109 110 111 112 113 114 115
            for name in op.input_arg_names:
                for item in op_dist_attr.get_input_dims_mapping(name):
                    if item != -1:
                        return False
            for name in op.output_arg_names:
                for item in op_dist_attr.get_output_dims_mapping(name):
                    if item != -1:
                        return False
        if op.type == "lookup_table_v2":
            for name in op.input_arg_names:
                if name == 'pos_embeddings':
                    for item in op_dist_attr.get_input_dims_mapping(name):
                        if item != -1:
                            return False
116 117 118 119 120 121
        return True


class PlanSpace:
    not_enum_ops = ["create_py_reader", "create_double_buffer_reader", "read"]
    special_vars = [
122 123 124
        "lod_tensor_blocking_queue_0",
        "create_py_reader_0",
        "double_buffer_0",
125 126 127
    ]

    @staticmethod
128 129 130
    def _enum_dims_mapping(
        process_mesh_topology, visited, path, depth, res, tensor_shape
    ):
131 132 133 134 135 136
        """Enumerate dims mapping of tensor by the given process_mesh_topology"""
        nums = list(range(-1, len(process_mesh_topology)))
        if depth == len(tensor_shape):
            valid = True
            for idx, item in enumerate(path):
                if item != -1:
137 138 139 140
                    if (
                        tensor_shape[idx] % process_mesh_topology[item] != 0
                        or path.count(item) > 1
                    ):
141 142 143 144 145 146 147 148 149 150
                        valid = False
            if valid:
                res.append(copy.deepcopy(path))
            return

        for i in range(len(nums)):
            if not visited[i]:
                if i != 0:
                    visited[i] = True
                path.append(nums[i])
151 152 153 154 155 156 157 158
                PlanSpace._enum_dims_mapping(
                    process_mesh_topology,
                    visited,
                    path,
                    depth + 1,
                    res,
                    tensor_shape,
                )
159 160 161 162 163 164
                visited[i] = False
                path.pop()

    @staticmethod
    def enum_process_mesh_topology(processes):
        """Enumerate all process meshes with the given processes."""
165 166 167
        assert (
            processes >= 1
        ), "The processes must be number and greater than 0."
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 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
        # compute divisors
        divisors = []
        for i in range(1, processes + 1):
            if processes % i == 0:
                divisors.append(i)

        # compute valid process mesh
        results = []
        for i in range(len(divisors) - 1, 0, -1):
            result = []
            result.append(divisors[i])
            if i == len(divisors) - 1:
                results.append(copy.deepcopy(result))
                continue

            j = 1
            while j < len(divisors):
                if len(result) == 1:
                    result.append(divisors[j])
                elif len(result) == 2:
                    if processes % (result[0] * result[1]) == 0:
                        if processes // (result[0] * result[1]) == 1:
                            results.append(copy.deepcopy(result))
                            break
                        else:
                            result.append(processes // (result[0] * result[1]))
                            results.append(copy.deepcopy(result))
                            result.pop(-1)
                            result.pop(-1)
                            j += 1
                    else:
                        if result[0] * result[1] < processes:
                            result.pop(-1)
                            j += 1
                        else:
                            break
        return results

    @staticmethod
    def _enum_valid_dist_attr_for_op(program, op, process_mesh):
        """Enumerate the valid distributed attribute for op based on the given process mesh."""
        vars = program.global_block().vars
        dims_mapping_dict = OrderedDict()
        op_valid_dist_attrs = []
        dist_op_impl_container = get_distributed_operator_impl_container(
213 214
            op.type
        )
215 216 217 218 219

        # enumerate all valid dims mapping of tensor when process mesh given
        for var_name in chain(op.input_arg_names, op.output_arg_names):
            visited = [
                False
220
                for _ in range(len(list(range(-1, len(process_mesh.shape)))))
221 222 223 224
            ]
            depth = 0
            path = []
            dims_mapping_list = []
225
            PlanSpace._enum_dims_mapping(
226
                process_mesh.shape,
227 228 229 230 231 232
                visited,
                path,
                depth,
                dims_mapping_list,
                vars[var_name].shape,
            )
233 234 235 236 237
            dims_mapping_dict[var_name] = copy.deepcopy(dims_mapping_list)

        # compose dims mapping
        composed_dims_mapping_list = list(
            product(
238 239 240
                *[dims_mapping_dict[key] for key in dims_mapping_dict.keys()]
            )
        )
241 242 243 244 245 246 247
        for composed_dims_mapping in composed_dims_mapping_list:
            op_dist_attr = OperatorDistributedAttribute()
            op_dist_attr.process_mesh = process_mesh
            var_names = list(dims_mapping_dict.keys())

            for idx, dims_mapping in enumerate(composed_dims_mapping):
                if var_names[idx] in op.input_arg_names:
248 249 250
                    op_dist_attr.set_input_dims_mapping(
                        var_names[idx], dims_mapping
                    )
251
                elif var_names[idx] in op.output_arg_names:
252
                    op_dist_attr.set_output_dims_mapping(
253 254
                        var_names[idx], dims_mapping
                    )
255 256
                else:
                    raise ValueError(
257 258 259 260
                        "The {varname} is not input or output of op {op}.".format(
                            varname='var_names[idx]', op='op'
                        )
                    )
261 262 263

            dist_op = DistributedOperator(op, op_dist_attr)
            if dist_op_impl_container is None:
264
                if is_elementwise_op(op.type):
265 266 267 268
                    changed = True
                    valid = True
                    try:
                        changed = update_op_dims_mapping_by_elementwise_like_dist_impl(
269 270
                            dist_op
                        )
271 272 273 274
                    except Exception as e:
                        valid = False
                    if valid and not changed:
                        if PlanFilter.check_dims_mapping_for_op(
275
                            op, dist_op.dist_attr, vars
276
                        ) and PlanFilter.check_dims_mapping_for_special_op(
277 278
                            op, dist_op.dist_attr, vars
                        ):
279 280
                            dist_op.dist_attr.impl_type = "elementwise"
                            dist_op.dist_attr.impl_idx = 0
281 282 283 284 285 286 287
                            op_valid_dist_attrs.append(dist_op.dist_attr)
                    continue
                else:
                    changed = True
                    valid = True
                    try:
                        changed = update_op_dims_mapping_by_default_dist_impl(
288 289
                            dist_op
                        )
290 291 292 293
                    except Exception as e:
                        valid = False
                    if valid and not changed:
                        if PlanFilter.check_dims_mapping_for_op(
294
                            op, dist_op.dist_attr, vars
295
                        ) and PlanFilter.check_dims_mapping_for_special_op(
296 297
                            op, dist_op.dist_attr, vars
                        ):
298 299
                            dist_op.dist_attr.impl_type = "default"
                            dist_op.dist_attr.impl_idx = 0
300 301 302 303
                            op_valid_dist_attrs.append(dist_op.dist_attr)
                    continue

            # if op has distributed implements, find all valid dist attr of this op
304
            impls = dist_op_impl_container.impls
305 306 307
            for idx, impl in enumerate(impls):
                if impl.is_auto_compatible(dist_op):
                    if PlanFilter.check_dims_mapping_for_op(
308 309
                        op, dist_op.dist_attr, vars
                    ):
310
                        dist_op.dist_attr.impl_type = dist_op.serial_op.type
311 312 313 314 315 316 317 318 319 320
                        dist_op.dist_attr.impl_idx = idx
                        op_valid_dist_attrs.append(dist_op.dist_attr)

        # set default dist attr for some special ops whose distributed attributes can not be enumerated
        if not op_valid_dist_attrs:
            op_dist_attr = OperatorDistributedAttribute()
            op_dist_attr.process_mesh = process_mesh
            dist_op = DistributedOperator(op, op_dist_attr)
            for var_name in op.input_arg_names:
                op_dist_attr.set_input_dims_mapping(
321 322
                    vars[var_name], [-1 for i in vars[var_name].shape]
                )
323 324
            for var_name in op.output_arg_names:
                op_dist_attr.set_output_dims_mapping(
325 326
                    vars[var_name], [-1 for i in vars[var_name].shape]
                )
327 328
            dist_op.dist_attr.impl_type = "default"
            dist_op.dist_attr.impl_idx = 0
329 330 331 332 333
            op_valid_dist_attrs.append(dist_op.dist_attr)

        return op_valid_dist_attrs

    @staticmethod
334 335 336
    def enum_valid_dist_attr_for_program(
        program, process_mesh_topology, is_pipeline=False
    ):
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353
        """Enumerate valid distributed attributes for all ops in program."""
        valid_dist_attr_dict = OrderedDict()
        ops = program.global_block().ops
        vars = program.global_block().vars

        processes = reduce(lambda x, y: x * y, process_mesh_topology)
        global_group = [i for i in range(processes)]
        global_process_mesh = None
        pipeline_process_meshes = None

        # in the pipeline mode, there are some process meshes
        if is_pipeline:
            pipeline_stages = process_mesh_topology[-1]
            op_count_per_stage = len(ops) // pipeline_stages
            if len(process_mesh_topology) > 1:
                process_mesh_shape = process_mesh_topology[:-1]
                per_process_mesh_group = processes // pipeline_stages
354 355 356 357 358 359 360 361 362 363 364 365 366 367
                pipeline_process_meshes = [
                    auto.ProcessMesh(
                        mesh=np.array(
                            global_group[
                                i
                                * per_process_mesh_group : (i + 1)
                                * per_process_mesh_group
                            ]
                        )
                        .reshape(process_mesh_shape)
                        .tolist()
                    )
                    for i in range(pipeline_stages)
                ]
368 369 370 371 372 373
            elif len(process_mesh_topology) == 1:
                pipeline_process_meshes = [
                    auto.ProcessMesh(mesh=[i]) for i in range(pipeline_stages)
                ]
        else:
            if len(process_mesh_topology) > 1:
374 375 376 377 378
                global_process_mesh = auto.ProcessMesh(
                    mesh=np.array(global_group)
                    .reshape(process_mesh_topology)
                    .tolist()
                )
379 380 381 382 383 384 385 386 387
            else:
                global_process_mesh = auto.ProcessMesh(mesh=global_group)

        # enumerate valid distributed attribute for each op in the program
        for idx, op in enumerate(ops):
            op_valid_dist_attrs = None
            op_process_mesh = global_process_mesh
            pipeline_stage = -1
            if pipeline_process_meshes is not None:
388 389 390 391 392
                pipeline_stage = (
                    idx // op_count_per_stage
                    if idx // op_count_per_stage < len(pipeline_process_meshes)
                    else idx // op_count_per_stage - 1
                )
393 394 395 396 397 398 399 400 401 402 403 404
                if pipeline_stage >= len(pipeline_process_meshes):
                    pipeline_stage = len(pipeline_process_meshes) - 1
                op_process_mesh = pipeline_process_meshes[pipeline_stage]

            if op.type in PlanSpace.not_enum_ops:
                op_dist_attr = OperatorDistributedAttribute()
                op_dist_attr.process_mesh = op_process_mesh
                for var_name in op.input_arg_names:
                    if var_name in PlanSpace.special_vars:
                        op_dist_attr.set_input_dims_mapping(var_name, [])
                    else:
                        dims_mapping = [-1 for i in vars[var_name].shape]
405
                        op_dist_attr.set_input_dims_mapping(
406 407
                            var_name, dims_mapping
                        )
408 409 410 411 412 413

                for var_name in op.output_arg_names:
                    if var_name in PlanSpace.special_vars:
                        op_dist_attr.set_output_dims_mapping(var_name, [])
                    else:
                        dims_mapping = [-1 for i in vars[var_name].shape]
414
                        op_dist_attr.set_output_dims_mapping(
415 416
                            var_name, dims_mapping
                        )
417 418 419 420
                op_valid_dist_attrs = [op_dist_attr]
                pipeline_stage = 0 if pipeline_stage != -1 else pipeline_stage
            else:
                op_valid_dist_attrs = PlanSpace._enum_valid_dist_attr_for_op(
421 422
                    program, op, op_process_mesh
                )
423

424 425 426
            assert (
                op_valid_dist_attrs is not None
            ), "Enumerate {} valid distributed attribute failed.".format(op)
427
            valid_dist_attr_dict[op.desc.id()] = [
428 429
                op_valid_dist_attrs,
                pipeline_stage,
430
            ]
431

432 433 434 435 436
        return (
            valid_dist_attr_dict,
            pipeline_process_meshes,
            global_process_mesh,
        )
437 438 439 440 441 442 443 444


class SearchAlgorithm:
    def __init__(self, name):
        self._name = name

    @property
    def name(self):
445
        self.name = self._name
446 447 448 449 450 451

    def search(self):
        raise NotImplementedError("Please Implement this method in subclass.")


class MCMC(SearchAlgorithm):
452
    def __init__(self, serial_program_info, parallelizer, max_search_times=5):
453
        super().__init__("mcmc")
454 455
        self._serial_program_info = serial_program_info
        self._max_search_times = max_search_times
456
        self._parallelizer = parallelizer
457 458 459 460 461

    @property
    def serial_program_info(self):
        return self._serial_program_info

462 463 464 465
    @property
    def parallelizer(self):
        return self._parallelizer

466 467 468 469
    @property
    def max_search_times(self):
        return self._max_search_times

470 471 472
    def make_special_op_unshard(
        self, op, ops, vars, dist_context, valid_dist_attr_dict
    ):
473 474 475
        if op.type == "softmax_with_cross_entropy":
            for var_name in op.input_arg_names:
                dims_mapping = dist_context.get_op_dist_attr_for_program(
476 477 478 479 480 481 482 483
                    op
                ).get_input_dims_mapping(var_name)
                if (
                    dims_mapping
                    != dist_context.get_tensor_dist_attr_for_program(
                        vars[var_name]
                    ).dims_mapping
                ):
484 485 486 487
                    has_changed = False
                    for search_op in ops:
                        if var_name in search_op.output_arg_names:
                            op_dist_attr_list = valid_dist_attr_dict[
488 489
                                search_op.desc.id()
                            ][0]
490
                            for op_dist_attr in op_dist_attr_list:
491 492 493 494 495 496
                                if (
                                    op_dist_attr.get_output_dims_mapping(
                                        var_name
                                    )
                                    == dims_mapping
                                ):
497
                                    dist_context.set_op_dist_attr_for_program(
498 499
                                        search_op, op_dist_attr
                                    )
500
                                    for name in search_op.output_arg_names:
501 502 503 504 505
                                        tensor_dist_attr = (
                                            TensorDistributedAttribute()
                                        )
                                        tensor_dist_attr.process_mesh = (
                                            op_dist_attr.process_mesh
506 507
                                        )
                                        tensor_dist_attr.dims_mapping = op_dist_attr.get_output_dims_mapping(
508 509
                                            name
                                        )
510
                                        dist_context.set_tensor_dist_attr_for_program(
511 512
                                            vars[name], tensor_dist_attr
                                        )
513 514 515 516 517 518
                                    has_changed = True
                                    break
                        if has_changed:
                            break
                    if not has_changed:
                        raise ValueError(
519 520
                            "Change softmax_with_cross_entropy dist attr failed"
                        )
521

522 523 524 525 526 527 528
    def init_program(
        self,
        valid_dist_attr_dict,
        program,
        pipeline_process_meshes,
        global_process_mesh,
    ):
529 530 531 532 533 534 535
        ops = program.global_block().ops
        vars = program.global_block().vars
        new_dist_context = DistributedContext()

        for op in ops:
            op_valid_dist_attr_list = valid_dist_attr_dict[op.desc.id()][0]
            random_op_dist_attr = np.random.randint(
536 537
                len(op_valid_dist_attr_list)
            )
538 539 540 541 542
            init_op_dist_attr = op_valid_dist_attr_list[random_op_dist_attr]
            new_dist_context.set_op_dist_attr_for_program(op, init_op_dist_attr)
            for var_name in op.input_arg_names:
                if var_name == "lod_tensor_blocking_queue_0":
                    continue
543 544 545 546 547 548
                if (
                    new_dist_context.get_tensor_dist_attr_for_program(
                        vars[var_name]
                    )
                    is None
                ):
549
                    tensor_dist_attr = TensorDistributedAttribute()
550 551 552 553 554 555
                    tensor_dist_attr.process_mesh = (
                        init_op_dist_attr.process_mesh
                    )
                    tensor_dist_attr.dims_mapping = (
                        init_op_dist_attr.get_input_dims_mapping(var_name)
                    )
556
                    new_dist_context.set_tensor_dist_attr_for_program(
557 558
                        vars[var_name], tensor_dist_attr
                    )
559 560 561 562

            for var_name in op.output_arg_names:
                tensor_dist_attr = TensorDistributedAttribute()
                tensor_dist_attr.process_mesh = init_op_dist_attr.process_mesh
563 564 565
                tensor_dist_attr.dims_mapping = (
                    init_op_dist_attr.get_output_dims_mapping(var_name)
                )
566
                new_dist_context.set_tensor_dist_attr_for_program(
567 568
                    vars[var_name], tensor_dist_attr
                )
569 570

            # NOTE: this is a temporary solution to make softmax_with_cross_entropy unshard
571 572 573
            self.make_special_op_unshard(
                op, ops, vars, new_dist_context, valid_dist_attr_dict
            )
574 575 576 577 578 579 580 581 582 583

        # add process meshes to distributed context
        if global_process_mesh is not None:
            new_dist_context.add_process_mesh(global_process_mesh)
        elif pipeline_process_meshes is not None:
            for process_mesh in pipeline_process_meshes:
                new_dist_context.add_process_mesh(process_mesh)

        return new_dist_context

584 585 586
    def estimate_searched_strategy_cost(
        self, dist_context, pipeline_process_meshes=None
    ):
587 588 589
        cost = None
        # get all distributed programs
        all_dist_main_program = get_all_distributed_main_program(
590 591 592
            self.serial_program_info, dist_context, self.parallelizer
        )
        pipeline_config = (
593 594 595 596
            [
                process_mesh.process_ids
                for process_mesh in pipeline_process_meshes
            ]
597 598 599
            if pipeline_process_meshes is not None
            else None
        )
600 601 602 603 604 605 606 607 608 609 610 611
        microbatch_size = 1
        for program in all_dist_main_program:
            searched_batch_size = False
            for var in program.list_vars():
                if var.is_data and "@RESHARD" in var.name:
                    microbatch_size = var.shape[0]
                    searched_batch_size = True
                    break
            if searched_batch_size:
                break

        from .utils import get_standalone_cost_data
612

613 614 615
        standalone_cost_data = get_standalone_cost_data(all_dist_main_program)

        # cost model does not support cluster argument
616 617 618 619 620 621 622
        cost = estimate_cost(
            all_dist_main_program,
            cluster=None,
            pipeline_config=pipeline_config,
            standalone_cost_data=standalone_cost_data,
            batch_size=microbatch_size,
        )
623 624 625 626 627 628 629 630 631

        return cost

    def set_tensor_dist_attr(self, op, op_dist_attr, vars, dist_context):
        # set output tensor distributed attribute
        for var_name in op.output_arg_names:
            process_mesh = op_dist_attr.process_mesh
            tensor_dist_attr = TensorDistributedAttribute()
            tensor_dist_attr.process_mesh = process_mesh
632 633 634
            tensor_dist_attr.dims_mapping = (
                op_dist_attr.get_output_dims_mapping(var_name)
            )
635
            dist_context.set_tensor_dist_attr_for_program(
636 637
                vars[var_name], tensor_dist_attr
            )
638 639 640 641 642 643 644

        # set input tensor distributed attribute if input is data or parameter
        for var_name in op.input_arg_names:
            if vars[var_name].is_parameter or vars[var_name].is_data:
                process_mesh = op_dist_attr.process_mesh
                tensor_dist_attr = TensorDistributedAttribute()
                tensor_dist_attr.process_mesh = process_mesh
645 646 647
                tensor_dist_attr.dims_mapping = (
                    op_dist_attr.get_input_dims_mapping(var_name)
                )
648
                dist_context.set_tensor_dist_attr_for_program(
649 650
                    vars[var_name], tensor_dist_attr
                )
651 652 653

    def change_process_mesh(self, op, changed_process_mesh, vars, dist_context):
        dist_context.get_op_dist_attr_for_program(
654 655
            op
        ).process_mesh = changed_process_mesh
656
        for var_name in op.output_arg_names:
657
            dist_context.get_tensor_dist_attr_for_program(
658 659
                vars[var_name]
            ).process_mesh = changed_process_mesh
660 661
        for var_name in op.input_arg_names:
            if vars[var_name].is_parameter or vars[var_name].is_data:
662
                dist_context.get_tensor_dist_attr_for_program(
663 664 665 666 667 668 669 670 671 672
                    vars[var_name]
                ).process_mesh = changed_process_mesh

    def search_once(
        self,
        program,
        valid_dist_attr_dict,
        dist_context,
        pipeline_process_meshes=None,
    ):
673 674 675 676 677 678 679 680 681 682 683 684 685 686 687
        raw_ops = program.global_block().ops
        ops = []
        for op in raw_ops:
            if op.type not in PlanSpace.not_enum_ops:
                ops.append(op)
        assert ops, "The ops of program have no distributed attributes."
        vars = program.global_block().vars
        new_dist_context = copy.deepcopy(dist_context)
        new_dist_context._dist_op_context = DistributedOperatorContext()
        new_valid_dist_attr_dict = None
        random_selected_op_idx = np.random.randint(len(ops))
        selected_op = ops[random_selected_op_idx]
        op_valid_dist_attr_list = valid_dist_attr_dict[selected_op.desc.id()][0]
        pipeline_stage = valid_dist_attr_dict[selected_op.desc.id()][1]
        random_selected_dist_attr_idx = np.random.randint(
688 689
            len(op_valid_dist_attr_list)
        )
690
        selected_op_dist_attr = copy.deepcopy(
691 692
            op_valid_dist_attr_list[random_selected_dist_attr_idx]
        )
693 694 695 696 697 698 699 700 701 702

        start_idx = ops[0].desc.id()
        if pipeline_stage > -1:
            # in pipeline mode, the above phase just select a dims mapping
            # 0 represents not changed, 1 represents to be the same with before stage, 2 represents to be the same with the latter stage
            new_valid_dist_attr_dict = copy.deepcopy(valid_dist_attr_dict)
            changed_mode = np.random.randint(3)
            if changed_mode == 0:
                # not change the process mesh, just change dims mapping
                new_dist_context.set_op_dist_attr_for_program(
703 704 705 706 707
                    selected_op, selected_op_dist_attr
                )
                self.set_tensor_dist_attr(
                    selected_op, selected_op_dist_attr, vars, new_dist_context
                )
708 709 710

            elif changed_mode == 1:
                changed_stage = pipeline_stage - 1
711 712 713 714 715 716 717 718 719 720 721
                if (
                    changed_stage == -1
                    or random_selected_op_idx == len(ops) - 1
                    or (
                        random_selected_op_idx + 1 == len(ops) - 1
                        and new_valid_dist_attr_dict[
                            ops[random_selected_op_idx + 1].desc.id()
                        ][1]
                        == pipeline_stage + 1
                    )
                ):
722
                    new_dist_context.set_op_dist_attr_for_program(
723 724 725 726 727 728 729 730
                        selected_op, selected_op_dist_attr
                    )
                    self.set_tensor_dist_attr(
                        selected_op,
                        selected_op_dist_attr,
                        vars,
                        new_dist_context,
                    )
731 732 733

                else:
                    selected_op_process_mesh = pipeline_process_meshes[
734 735
                        pipeline_stage
                    ]
736
                    next_op_id = ops[random_selected_op_idx + 1].desc.id()
737 738 739 740 741
                    if (
                        new_valid_dist_attr_dict[next_op_id][1]
                        == pipeline_stage + 1
                        and random_selected_op_idx + 1 != len(ops) - 1
                    ):
742 743
                        new_valid_dist_attr_dict[next_op_id][1] = pipeline_stage
                        for op_dist_attr in new_valid_dist_attr_dict[
744 745
                            next_op_id
                        ][0]:
746 747 748 749
                            op_dist_attr.process_mesh = selected_op_process_mesh
                        # set next op dist attr in the discontext and output/input tensor process mesh
                        self.change_process_mesh(
                            ops[random_selected_op_idx + 1],
750 751 752 753
                            selected_op_process_mesh,
                            vars,
                            new_dist_context,
                        )
754 755

                    # change the selected op stage and output dist attr
756 757 758
                    new_valid_dist_attr_dict[selected_op.desc.id()][
                        1
                    ] = changed_stage
759 760 761
                    new_process_mesh = pipeline_process_meshes[changed_stage]
                    selected_op_dist_attr.process_mesh = new_process_mesh
                    for op_dist_attr in new_valid_dist_attr_dict[
762 763
                        selected_op.desc.id()
                    ][0]:
764 765
                        op_dist_attr.process_mesh = new_process_mesh
                    new_dist_context.set_op_dist_attr_for_program(
766 767
                        selected_op, selected_op_dist_attr
                    )
768

769 770 771 772 773 774
                    self.set_tensor_dist_attr(
                        selected_op,
                        selected_op_dist_attr,
                        vars,
                        new_dist_context,
                    )
775 776 777 778

                    # change the pre op stage
                    for idx in range(random_selected_op_idx - 1, -1, -1):
                        stage = new_valid_dist_attr_dict[ops[idx].desc.id()][1]
779
                        valid_dist_attr_list = new_valid_dist_attr_dict[
780 781
                            ops[idx].desc.id()
                        ][0]
782
                        new_process_mesh = pipeline_process_meshes[
783 784
                            changed_stage
                        ]
785
                        if stage == changed_stage + 1:
786 787 788
                            new_valid_dist_attr_dict[ops[idx].desc.id()][
                                1
                            ] = changed_stage
789 790
                            for op_dist_attr in valid_dist_attr_list:
                                op_dist_attr.process_mesh = new_process_mesh
791
                            new_dist_context.get_op_dist_attr_for_program(
792 793
                                ops[idx]
                            ).process_mesh = new_process_mesh
794
                            # change process mesh of the output and input tensor
795 796 797 798 799 800
                            self.change_process_mesh(
                                ops[idx],
                                new_process_mesh,
                                vars,
                                new_dist_context,
                            )
801 802 803 804 805
                        else:
                            break

            else:
                changed_stage = pipeline_stage + 1
806 807 808 809 810 811 812 813 814 815 816
                if (
                    changed_stage == len(pipeline_process_meshes)
                    or random_selected_op_idx == 0
                    or (
                        new_valid_dist_attr_dict[
                            ops[random_selected_op_idx - 1].desc.id()
                        ][1]
                        == pipeline_stage - 1
                        and (random_selected_op_idx == 1)
                    )
                ):
817
                    new_dist_context.set_op_dist_attr_for_program(
818 819 820 821 822 823 824 825
                        selected_op, selected_op_dist_attr
                    )
                    self.set_tensor_dist_attr(
                        selected_op,
                        selected_op_dist_attr,
                        vars,
                        new_dist_context,
                    )
826 827 828

                else:
                    selected_op_process_mesh = pipeline_process_meshes[
829 830
                        pipeline_stage
                    ]
831
                    pre_op_id = ops[random_selected_op_idx - 1].desc.id()
832 833 834 835 836
                    if (
                        new_valid_dist_attr_dict[pre_op_id][1]
                        == pipeline_stage - 1
                        and random_selected_op_idx != 1
                    ):
837 838
                        new_valid_dist_attr_dict[pre_op_id][1] = pipeline_stage
                        for op_dist_attr in new_valid_dist_attr_dict[pre_op_id][
839 840
                            0
                        ]:
841 842 843 844
                            op_dist_attr.process_mesh = selected_op_process_mesh
                        # set pre op dist attr in the discontext and output tensor process mesh
                        self.change_process_mesh(
                            ops[random_selected_op_idx - 1],
845 846 847 848
                            selected_op_process_mesh,
                            vars,
                            new_dist_context,
                        )
849 850

                    # change the selected op stage and output tensor dist attr
851 852 853
                    new_valid_dist_attr_dict[selected_op.desc.id()][
                        1
                    ] = changed_stage
854 855 856
                    new_process_mesh = pipeline_process_meshes[changed_stage]
                    selected_op_dist_attr.process_mesh = new_process_mesh
                    for op_dist_attr in new_valid_dist_attr_dict[
857 858
                        selected_op.desc.id()
                    ][0]:
859 860
                        op_dist_attr.process_mesh = new_process_mesh
                    new_dist_context.set_op_dist_attr_for_program(
861 862 863 864 865 866 867 868
                        selected_op, selected_op_dist_attr
                    )
                    self.set_tensor_dist_attr(
                        selected_op,
                        selected_op_dist_attr,
                        vars,
                        new_dist_context,
                    )
869 870 871 872

                    # change the next op stage
                    for idx in range(random_selected_op_idx + 1, len(ops)):
                        stage = new_valid_dist_attr_dict[ops[idx].desc.id()][1]
873
                        valid_dist_attr_list = new_valid_dist_attr_dict[
874 875
                            ops[idx].desc.id()
                        ][0]
876
                        new_process_mesh = pipeline_process_meshes[
877 878
                            changed_stage
                        ]
879
                        if stage == changed_stage - 1:
880 881 882
                            new_valid_dist_attr_dict[ops[idx].desc.id()][
                                1
                            ] = changed_stage
883 884 885
                            for op_dist_attr in valid_dist_attr_list:
                                op_dist_attr.process_mesh = new_process_mesh

886
                            new_dist_context.get_op_dist_attr_for_program(
887 888
                                ops[idx]
                            ).process_mesh = new_process_mesh
889
                            # change the output tensor dist attr
890 891 892 893 894 895
                            self.change_process_mesh(
                                ops[idx],
                                new_process_mesh,
                                vars,
                                new_dist_context,
                            )
896 897 898
                        else:
                            break
        else:
899
            new_dist_context.set_op_dist_attr_for_program(
900 901 902 903 904
                selected_op, selected_op_dist_attr
            )
            self.set_tensor_dist_attr(
                selected_op, selected_op_dist_attr, vars, new_dist_context
            )
905 906 907 908

        for op in ops:
            # make softmax_with_cross_entropy unshard
            if op.type == "softmax_with_cross_entropy":
909 910 911
                self.make_special_op_unshard(
                    op, ops, vars, new_dist_context, valid_dist_attr_dict
                )
912 913 914 915 916 917 918
                break

        if new_valid_dist_attr_dict is None:
            return valid_dist_attr_dict, new_dist_context
        else:
            return new_valid_dist_attr_dict, new_dist_context

919 920 921 922 923 924
    def _search_core(
        self,
        valid_dist_attr_dict,
        init_dist_context,
        pipeline_process_meshes=None,
    ):
925 926 927
        times = 0
        best_dist_context = init_dist_context
        cost = self.estimate_searched_strategy_cost(
928 929
            init_dist_context, pipeline_process_meshes
        ).runtime
930 931 932 933
        min_cost = cost
        while times < self.max_search_times:
            times += 1
            new_dist_context = self.search_once(
934 935 936 937 938
                self.serial_program_info.train_program,
                valid_dist_attr_dict,
                best_dist_context,
                pipeline_process_meshes,
            )[1]
939
            cur_cost = self.estimate_searched_strategy_cost(
940 941
                new_dist_context, pipeline_process_meshes
            ).runtime
942 943 944 945 946 947 948
            if (min_cost - cur_cost) > 0:
                best_dist_context = copy.deepcopy(new_dist_context)
                min_cost = cur_cost
                times = 0
        return best_dist_context, min_cost

    def search(self):
C
caozhou 已提交
949
        print("Start MCMC searching.")
950 951 952
        start_time = time.time()
        train_program = self.serial_program_info.train_program
        cluster = self.serial_program_info.cluster
953 954 955 956 957
        processes = (
            paddle.distributed.get_world_size()
            if cluster is None
            else len(cluster.get_all_devices("GPU"))
        )
958 959 960
        assert processes > 0, "Get process failed."

        process_mesh_topology_list = PlanSpace.enum_process_mesh_topology(
961 962
            processes
        )
963 964 965 966 967 968
        searched_dist_context = None
        min_cost = None

        searched_pipeline_dist_context = None
        pipeline_min_cost = None
        for process_mesh_topology in process_mesh_topology_list:
969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986
            print(
                "MCMC search: search process mesh {} with pipeline mode.".format(
                    process_mesh_topology
                )
            )
            (
                valid_dist_attr_dict,
                pipeline_process_meshes,
                global_process_mesh,
            ) = PlanSpace.enum_valid_dist_attr_for_program(
                train_program, process_mesh_topology, True
            )
            init_dist_context = self.init_program(
                valid_dist_attr_dict,
                train_program,
                pipeline_process_meshes,
                global_process_mesh,
            )
987
            best_dist_context, cost = self._search_core(
988 989
                valid_dist_attr_dict, init_dist_context, pipeline_process_meshes
            )
C
caozhou 已提交
990
            print(
991 992 993 994
                "MCMC search: the min cost is {} in the process mesh {} with pipeline mode.".format(
                    cost, process_mesh_topology
                )
            )
995
            best_dist_context._dist_op_context = DistributedOperatorContext()
996 997 998 999 1000 1001 1002 1003
            pipeline_min_cost = (
                cost if pipeline_min_cost is None else pipeline_min_cost
            )
            searched_pipeline_dist_context = (
                best_dist_context
                if searched_pipeline_dist_context is None
                else searched_pipeline_dist_context
            )
1004 1005 1006 1007 1008 1009 1010 1011 1012 1013
            if pipeline_min_cost > cost:
                searched_pipeline_dist_context = best_dist_context
                pipeline_min_cost = cost

        searched_non_pipeline_dist_context = None
        non_pipeline_min_cost = None
        for process_mesh_topology in process_mesh_topology_list:
            # if process_mesh_topology shape is 3, include pipeline mode by default
            if len(process_mesh_topology) == 3:
                continue
1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031
            print(
                "MCMC search: search process mesh {} without pipeline mode.".format(
                    process_mesh_topology
                )
            )
            (
                valid_dist_attr_dict,
                pipeline_process_meshes,
                global_process_mesh,
            ) = PlanSpace.enum_valid_dist_attr_for_program(
                train_program, process_mesh_topology, False
            )
            init_dist_context = self.init_program(
                valid_dist_attr_dict,
                train_program,
                pipeline_process_meshes,
                global_process_mesh,
            )
1032
            best_dist_context, cost = self._search_core(
1033 1034
                valid_dist_attr_dict, init_dist_context, pipeline_process_meshes
            )
C
caozhou 已提交
1035
            print(
1036 1037 1038 1039
                "MCMC search: the min cost is {} in the process mesh {} without pipeline mode.".format(
                    cost, process_mesh_topology
                )
            )
1040
            best_dist_context._dist_op_context = DistributedOperatorContext()
1041 1042 1043 1044 1045 1046 1047 1048
            non_pipeline_min_cost = (
                cost if non_pipeline_min_cost is None else non_pipeline_min_cost
            )
            searched_non_pipeline_dist_context = (
                best_dist_context
                if searched_non_pipeline_dist_context is None
                else searched_non_pipeline_dist_context
            )
1049 1050 1051 1052 1053 1054 1055
            if non_pipeline_min_cost > cost:
                searched_non_pipeline_dist_context = best_dist_context
                non_pipeline_min_cost = cost

        if non_pipeline_min_cost > pipeline_min_cost:
            searched_dist_context = searched_pipeline_dist_context
            min_cost = pipeline_min_cost
C
caozhou 已提交
1056
            print(
1057 1058 1059 1060 1061 1062 1063 1064 1065
                "Better set FLAGS_benchmark=1 to avoid hang problem in the pipeline mode."
            )
        else:
            searched_dist_context = searched_non_pipeline_dist_context
            min_cost = non_pipeline_min_cost

        # rebuild g_process_group
        pg0 = get_process_group(0)
        for process_mesh in searched_dist_context._process_meshes:
1066
            pg0.add_ranks(process_mesh.process_ids)
1067
        end_time = time.time()
C
caozhou 已提交
1068
        print(
1069 1070 1071 1072
            "End MCMC searching: the min cost is {} and the search time is {}s.".format(
                min_cost, end_time - start_time
            )
        )
1073 1074 1075 1076
        return searched_dist_context, min_cost


class Planner:
1077 1078 1079
    def __init__(
        self, serial_program_info, parallelizer, algorithm_config=None
    ):
1080
        self._serial_program_info = serial_program_info
1081
        self._parallelizer = parallelizer
1082 1083
        self._algorithm_config = algorithm_config
        self._algorithm_searcher = self.create_algorithm_searcher(
1084 1085
            algorithm_config
        )
1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098

    @property
    def serial_program_info(self):
        return self._serial_program_info

    @property
    def algorithm_config(self):
        return self._algorithm_config

    @property
    def algorithm_searcher(self):
        return self._algorithm_searcher

1099 1100 1101 1102
    @property
    def parallelizer(self):
        return self._parallelizer

1103 1104 1105 1106 1107 1108 1109 1110
    def create_algorithm_searcher(self, algorithm_config):
        name = algorithm_config.get("name", None)
        assert name is not None, "Invalid algorithm config."

        algorithm_searcher = None
        if name == "mcmc":
            # NOTE: Only GPU clusters are supported now.
            max_search_times = algorithm_config.get("max_search_times", None)
1111 1112 1113 1114 1115 1116 1117 1118 1119
            algorithm_searcher = (
                MCMC(
                    self.serial_program_info,
                    self.parallelizer,
                    max_search_times,
                )
                if max_search_times is not None
                else MCMC(self.serial_program_info, self.parallelizer)
            )
1120 1121
        else:
            raise NotImplementedError(
1122 1123
                "Other search algorithms have not been supported now."
            )
1124 1125 1126 1127 1128

        return algorithm_searcher

    def search(self):
        return self.algorithm_searcher.search()