utils.py 80.8 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
import copy
16 17
import logging
import os
18
import threading
19
import warnings
20
from functools import reduce
21

22 23 24
import numpy as np

import paddle
25
from paddle.fluid.wrapped_decorator import wrap_decorator
26
from paddle.framework import core
27
from paddle.framework.io_utils import is_belong_to_optimizer, is_parameter
28
from paddle.static import Variable
29

30
from ..process_mesh import ProcessMesh
31
from .dist_attribute import OperatorDistAttr, TensorDistAttr
32

33
OpRole = core.op_proto_and_checker_maker.OpRole
34 35
OP_ROLE_KEY = core.op_proto_and_checker_maker.kOpRoleAttrName()

Z
zhaoyingli 已提交
36
__no_shape_var_type__ = [
37 38
    core.VarDesc.VarType.READER,
    core.VarDesc.VarType.STEP_SCOPES,
Z
zhaoyingli 已提交
39 40 41
    core.VarDesc.VarType.LOD_TENSOR_ARRAY,
    core.VarDesc.VarType.FEED_MINIBATCH,
    core.VarDesc.VarType.FETCH_LIST,
42 43
]

44 45
__not_naive_data_parallel_op__ = ["expand_v2"]

46

47 48 49 50 51 52 53
def get_logger(log_level, name="auto_parallel"):
    logger = logging.getLogger(name)
    logger.propagate = False
    if not logger.handlers:
        logger.setLevel(log_level)
        log_handler = logging.StreamHandler()
        log_format = logging.Formatter(
54 55
            '%(levelname)s %(asctime)s %(filename)s:%(lineno)d] %(message)s'
        )
56 57
        log_handler.setFormatter(log_format)
        logger.addHandler(log_handler)
58 59
    else:
        logger.setLevel(log_level)
60 61 62
    return logger


63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
def is_valid_list_index(list, index):
    if index >= -len(list) and index < len(list):
        return True
    else:
        return False


def is_dim_shard(mapping):
    if mapping != -1:
        return True
    else:
        return False


def is_dim_replicate(mapping):
    if mapping == -1:
        return True
    else:
        return False


84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
def verify_dims_mapping(dims_mapping, process_mesh):
    if dims_mapping is None:
        return False
    if not all(isinstance(d, int) for d in dims_mapping):
        return False
    for i in range(len(dims_mapping)):
        if dims_mapping[i] < -1 or dims_mapping[i] >= len(process_mesh.shape):
            return False
    for i in range(len(process_mesh.shape)):
        if dims_mapping.count(i) > 1:
            return False
    return True


def convert_to_dims_mapping(shard_spec, process_mesh):
    dims_mapping = []
    for shard in shard_spec:
        if shard is None:
            dims_mapping.append(-1)
103
        elif process_mesh.shape[process_mesh.dim_names.index(shard)] == 1:
Z
zhaoyingli 已提交
104
            dims_mapping.append(-1)
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
        else:
            dims_mapping.append(process_mesh.dim_names.index(shard))
    return dims_mapping


def convert_to_shard_spec(dims_mapping, process_mesh):
    shard_spec = []
    for dim_mapping in dims_mapping:
        if dim_mapping == -1:
            shard_spec.append(None)
        else:
            shard_spec.append(process_mesh.dim_names[dim_mapping])
    return shard_spec


def verify_shard_spec(shard_spec, tensor_shape, process_mesh):
    if len(shard_spec) != len(tensor_shape):
        return False
    for shard in shard_spec:
        if shard is not None and not isinstance(shard, str):
            return False
        if shard is not None and shard not in process_mesh.dim_names:
            return False
    dims_mapping = convert_to_dims_mapping(shard_spec, process_mesh)
    if not verify_dims_mapping(dims_mapping, process_mesh):
        return False
    for i in range(len(tensor_shape)):
132 133 134 135 136
        if (
            dims_mapping[i] != -1
            and tensor_shape[i] > 0
            and tensor_shape[i] % process_mesh.shape[dims_mapping[i]] != 0
        ):
137 138 139 140
            return False
    return True


141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
def compute_compatible_dim_mapping(dim_mappings):
    if not dim_mappings:
        return None
    compatible_mapping = dim_mappings[0]
    for mapping in dim_mappings:
        if compatible_mapping == -1:
            compatible_mapping = mapping
        elif mapping == -1:
            continue
        elif compatible_mapping == mapping:
            continue
        else:
            return None
    return compatible_mapping


def compute_compatible_dims_mapping(dims_mapping_list):
    if not dims_mapping_list:
        return None
    length = len(dims_mapping_list[0])
    for dims_mapping in dims_mapping_list:
162 163 164 165 166 167
        assert (
            dims_mapping is not None
        ), "Dims mapping must not be None for compatible computation"
        assert (
            len(dims_mapping) == length
        ), "The length of dims_mapping in list must be same for compatible computation."
168 169 170
    compatible_result = []
    for dim_mappings in zip(*dims_mapping_list):
        compatible_dim_mapping = compute_compatible_dim_mapping(
171 172
            list(dim_mappings)
        )
173 174 175 176 177 178 179 180 181 182 183 184
        if compatible_dim_mapping is None:
            return None
        compatible_result.append(compatible_dim_mapping)
    return compatible_result


def compute_compatible_process_mesh(process_mesh_list):
    compatible_process_mesh = None
    if not process_mesh_list:
        return compatible_process_mesh
    for process_mesh in process_mesh_list:
        if process_mesh is not None:
185 186 187 188
            if (
                compatible_process_mesh is None
                or compatible_process_mesh == process_mesh
            ):
189 190
                compatible_process_mesh = process_mesh
            else:
191
                return None
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
    return compatible_process_mesh


def compute_compatible_and_update_dim_mapping(dims_mapping_list, index_list):
    assert len(dims_mapping_list) == len(index_list)
    changed = False
    dim_mappings = []
    for i in range(len(dims_mapping_list)):
        assert is_valid_list_index(dims_mapping_list[i], index_list[i])
        dim_mappings.append(dims_mapping_list[i][index_list[i]])
    compatible_dim_mapping = compute_compatible_dim_mapping(dim_mappings)
    if compatible_dim_mapping is None:
        return False
    for i in range(len(dims_mapping_list)):
        if compatible_dim_mapping != dims_mapping_list[i][index_list[i]]:
            dims_mapping_list[i][index_list[i]] = compatible_dim_mapping
            changed = True
    return changed


def append_distributed_attr_suffix(name):
    """
    Append auto parallel suffix for distributed attribute name.
    """
    return name + core.kAutoParallelSuffix()


def remove_distributed_attr_suffix(name):
    """
    Remove auto parallel suffix from distributed attribute name.
    """
    return name.strip(core.kAutoParallelSuffix())


def check_distributed_attr_for_program(program, dist_context=None):
227
    from .dist_context import get_default_distributed_context
228

229 230
    if dist_context is None:
        dist_context = get_default_distributed_context()
231 232 233
    assert (
        dist_context.is_initialized_for_program()
    ), "Distributed attributes must be initialized before check."
234 235
    for block in program.blocks:
        for tensor in block.vars.values():
236 237
            dist_tensor = dist_context.get_dist_tensor_for_graph(tensor)
            tensor_dist_attr = dist_context.get_tensor_dist_attr_for_program(
238 239
                tensor
            )
240
            if (tensor_dist_attr is not None) and (not dist_tensor.is_valid()):
241 242
                return False
        for op in block.ops:
243 244 245
            dist_op = dist_context.get_dist_op_for_graph(tensor)
            op_dist_attr = dist_context.get_op_dist_attr_for_program(op)
            if (op_dist_attr is not None) and (not dist_op.is_valid()):
246 247 248 249
                return False
    return True


250
def print_program_with_dist_attr(program, dist_context=None):
251 252 253 254 255 256
    """
    This function reuses the original program output ability with a distributed context.
    Using lock can avoid multiple threads change the default distributed context simultaneously.
    """
    lock = threading.Lock()
    lock.acquire()
257 258 259 260
    from .dist_context import (
        get_default_distributed_context,
        set_default_distributed_context,
    )
261

262 263
    if dist_context is None:
        dist_context = get_default_distributed_context()
264
        print(program, flush=True)
265 266 267
    else:
        original_default_context = get_default_distributed_context()
        set_default_distributed_context(dist_context)
268
        print(program, flush=True)
269 270
        set_default_distributed_context(original_default_context)
    lock.release()
271 272 273 274


def _get_comm_group(processes, shape, axis, rank):
    """
275
    Given a rank and the processes mesh the rank belongs to,
276 277
    compute the communication peers of the rank based on the give axis in the mesh.

C
chenxujun 已提交
278
    Example: 16 processes managed in a 4-Dimensional mesh with shape of [2, 2, 2, 2].
279 280 281 282 283 284 285 286
    the rank communication peers of rank 0 (included) are following:
    in axis 0: [0, 1]
    in axis 1: [0, 2]
    in axis 2: [0, 4]
    in axis 3: [0, 8]
    """

    # NOTE _linear_idx2coordinate assume processes mesh start with 0 and continuous
287 288
    # tricks to support processes mesh when it is not start with 0 or continuous
    assert rank in processes, "rank [{}] is NOT in processes group {}".format(
289 290
        rank, processes
    )
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307
    rank_relatvie = processes.index(rank)
    coordinate = _linear_idx2coordinate(shape, rank_relatvie)
    coordinates_in_group = [coordinate[:] for i in range(shape[axis])]

    # select comm group
    for i in range(shape[axis]):
        coordinates_in_group[i][axis] = i

    ranks_in_group_relative = [
        _coordinate2linear_idx(shape, coordinate)
        for coordinate in coordinates_in_group
    ]
    ranks_in_group = [processes[idx] for idx in ranks_in_group_relative]

    return sorted(ranks_in_group)


308 309
def _get_idx_in_axis(processes, shape, axis, rank):
    """
310
    Given a rank and the processes mesh the rank belongs to,
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326
    compute the index of the rank in given axis.

    Example: 27 processes managed in a 3-Dimensinal mesh with shape of [3, 3, 3].
    the index of rank 22 are:
    in axis 0: 1
    in axis 1: 1
    in axis 2: 2
    """

    # NOTE _linear_idx2coordinate assume processes mesh start with 0 and continuous
    #  tricks to support processes mesh when it is not start with 0 or continuous
    rank_relatvie = processes.index(rank)
    coordinate = _linear_idx2coordinate(shape, rank_relatvie)
    return coordinate[axis]


327 328 329 330
def _coordinate2linear_idx(mesh_shape, coordinate):
    """
    convert a coordinate in multidimensional mesh space into a scala idx in linear space.

331
    it use Row-major order for dimension conversion.
332
    so it has:  [most_significant_dim, ..., least_significant_dim]
333
    assume:
334 335 336 337

        the size of i-th dimension to be:  S[i]
        the index of j-th dimension is: I[j]

338
    linear_idx of a n dimensional coordinate is:
339 340

        I[n-1] * (S[n-2] * S[n-3] * S[n-4] *     ....    S[0]) +
341 342
        I[n-2] * (         S[n-3] * S[n-4] *     ....    S[0]) +
        I[n-3] * (                  S[n-4] *     ....    S[0]) +
343
        ...
344
        I[1]   * (                                       S[0]) +
345 346 347 348
        I[0]

    """
    # NOTE the following function work based on a strong an assumption
349
    # that the processes in mesh are
350
    #    1. starts from 0
351
    #    2. continuous
C
chenxujun 已提交
352
    # it will be wrong if ths above condition does not meet,
353
    # e.g. process_mesh = { process_groups = [7, 8, 9,10, 12, 13, 14, 15], mesh = [2, 4]}
354
    # if you want a more general mapping, you should use cartesian product
355 356 357 358

    assert len(mesh_shape) == len(
        coordinate
    ), "coordinate should have the same size as mesh shape, but got shape: {}, coordinate: {}".format(
359 360
        mesh_shape, coordinate
    )
361
    for i in range(len(mesh_shape)):
362 363 364 365 366 367 368 369 370 371
        assert (
            coordinate[i] >= 0
        ), "index in dimension [{}] is least than zero. coordinate: {}".format(
            i, coordinate
        )
        assert (
            coordinate[i] < mesh_shape[i]
        ), "index beyond extent in dimension [{}]. shape: {}, coordinate: {}".format(
            i, mesh_shape, coordinate
        )
372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388

    base = mesh_shape[-1]
    linear_idx = coordinate[-1]

    # row major order
    for i in range(len(mesh_shape) - 2, -1, -1):
        linear_idx += base * coordinate[i]
        base *= mesh_shape[i]

    return linear_idx


def _linear_idx2coordinate(mesh_shape, linear_idx):
    """
    mapping a linear scala into multidimensional mesh space, return it coordinate in that space.

    it is the inverse function of _coordinate2linear_idx.
389
    assume:
390 391 392 393 394 395 396 397 398 399 400 401 402 403

        the size of i-th dimension to be:  S[i]
        the index of j-th dimension is: I[j]

    the coordinate given linear_idx is:

        I[0] = linear_idx                                  % S[0]
        I[0] = (linear_idx / S[0])                         % S[1]
        I[0] = (linear_idx / (S[0] * S[1]))                % S[2]
        ....

    """

    assert linear_idx >= 0, "linear index [{}] is least than zero".format(
404 405
        linear_idx
    )
406 407 408
    assert linear_idx < np.prod(
        mesh_shape
    ), "linear index beyond the extent of mesh shape. shape: {}, linear index: {}".format(
409 410
        mesh_shape, linear_idx
    )
411 412 413 414 415 416 417 418 419 420 421

    base = 1
    coordinate = [-1] * len(mesh_shape)

    for i in reversed(range(len(mesh_shape))):
        offset = linear_idx / base
        coordinate[i] = int(offset % mesh_shape[i])
        base *= mesh_shape[i]

    # row major order
    return coordinate
422 423


424
def _get_corresponding_rank(dist_context, target_mesh, rank):
425 426 427 428 429
    # TODO(JZ-LIANG) a hack method to support varying mesh in Pipeline parallelism case.
    # we assume that all mesh are evenly divide from a parent mesh and should have same size.
    # to revise this in future.

    coordinate = None
430
    for mesh in dist_context.process_meshes:
431
        if rank in mesh.process_ids and mesh.shape == target_mesh.shape:
432
            coordinate = _linear_idx2coordinate(
433
                mesh.shape, mesh.process_ids.index(rank)
434
            )
435 436
            break

437 438 439
    # assert coordinate is not None, "could NOT found rank [{}] in any registered mesh".format(
    #     rank)
    if coordinate is not None:
440 441
        return target_mesh.process_ids[
            _coordinate2linear_idx(mesh.shape, coordinate)
442
        ]
443
    else:
444
        return target_mesh.process_ids[0]
445 446


447 448
def _get_unshard_dist_shape(var, dist_attr):
    var_shape = var.shape
449
    mapping = dist_attr.dims_mapping
450
    mesh = dist_attr.process_mesh.shape
451 452 453
    assert len(var_shape) == len(
        mapping
    ), "variable shape [{}] and dim_mapping [{}] is NOT match !".format(
454 455
        var_shape, mapping
    )
456 457 458 459 460 461 462 463 464 465
    new_shape = []
    for idx in range(len(var_shape)):
        if var_shape[idx] == -1 or mapping[idx] == -1:
            new_shape.append(var_shape[idx])
        else:
            new_shape.append(var_shape[idx] * mesh[mapping[idx]])

    return new_shape


466
def make_data_unshard(dist_main_prog, dist_startup_prog, dist_context=None):
467
    from .dist_context import get_default_distributed_context
468

469 470
    if dist_context is None:
        dist_context = get_default_distributed_context()
471 472 473

    for var in dist_main_prog.list_vars():
        if var.is_data:
474
            tensor_dist_attr = dist_context.get_tensor_dist_attr_for_program(
475 476
                var
            )
477 478
            inverse_shape = _get_unshard_dist_shape(var, tensor_dist_attr)
            var.desc.set_shape(inverse_shape)
479
            dim_mapping = tensor_dist_attr.dims_mapping
480
            dim_mapping = [-1] * len(dim_mapping)
481 482
            tensor_dist_attr.dims_mapping = dim_mapping
            dist_context.set_tensor_dist_attr_for_program(var, tensor_dist_attr)
483 484


485
def _update_addition_info(addition_info):
486
    """Update default addition_info with inputs"""
487
    add_info = {"epoch": 0, "batch": 0, "batch_size": 0}
488
    if not addition_info:
489
        return add_info
490
    elif not isinstance(addition_info, dict):
491 492 493 494
        raise TypeError(
            "The type of 'addition_info' should be 'dict', "
            "but got '{}'.".format(str(type(addition_info)))
        )
495
    else:
496 497 498 499
        for item, value in addition_info.items():
            if item not in ["epoch", "batch", "batch_size"]:
                raise ValueError(
                    "The key of 'addition_info' should be one of the "
500
                    "['epoch', 'batch', 'batch_size'], but got '{}'.".format(
501 502 503
                        str(item)
                    )
                )
504 505 506
            if not isinstance(value, int):
                raise ValueError(
                    "The value of 'addition_info' should be 'int', "
507 508
                    "but got '{}'.".format(str(type(value)))
                )
509 510
            add_info[item] = value
        return add_info
511 512 513


def _check_valid_path(file_path):
514
    """Validity check of input file path"""
515 516 517
    if not file_path:
        return file_path
    elif isinstance(file_path, list):
518 519
        for file in file_path:
            if not isinstance(file, str):
520 521 522 523
                raise TypeError(
                    "The type of file path should be 'str', "
                    "but got '{}'.".format(str(type(file)))
                )
524
            if not os.path.exists(file):
525
                raise ValueError(f"The file path '{file}' does not exist.")
526 527
        return file_path
    else:
528 529 530 531
        raise TypeError(
            "The type of file path should be 'list', "
            "but got '{}'.".format(str(type(file_path)))
        )
532 533 534 535 536 537


def _check_param_dict(param_dict):
    if not param_dict:
        raise ValueError("'param_dict' cannot be None.")
    elif not isinstance(param_dict, dict):
538 539 540 541
        raise TypeError(
            "The type of 'param_dict' should be 'dict', "
            "but got '{}'.".format(str(type(param_dict)))
        )
542 543 544 545 546
    else:
        for name, value in param_dict.items():
            if not isinstance(name, str):
                raise TypeError(
                    "The type of key of 'param_dict' should be 'str', "
547 548
                    "but got '{}'.".format(str(type(name)))
                )
549 550 551
            if not isinstance(value, paddle.fluid.LoDTensor):
                raise TypeError(
                    "The type of value of 'param_dict' should be 'LoDTensor', "
552 553
                    "but got '{}'.".format(str(type(value)))
                )
554 555 556 557 558 559 560
        return param_dict


def _check_dist_attr(dist_attr):
    if not dist_attr:
        return dist_attr
    elif not isinstance(dist_attr, dict):
561 562 563 564
        raise TypeError(
            "The type of 'dist_attr' should be 'dict', "
            "but got '{}'.".format(str(type(dist_attr)))
        )
565 566 567 568 569
    else:
        for name, value in dist_attr.items():
            if not isinstance(name, str):
                raise TypeError(
                    "The type of param name of 'dist_attr' should be 'str', "
570 571
                    "but got '{}'.".format(str(type(name)))
                )
572 573 574
            if not isinstance(value, dict):
                raise TypeError(
                    "The type of distributed attribute should be 'dict', "
575 576
                    "but got '{}'".format(str(type(value)))
                )
577 578 579 580 581
            attr = ['process_shape', 'process_group', 'dims_mapping']
            if list(value.keys()) != attr:
                raise ValueError(
                    "The key of distributed attribute should be "
                    "'['process_shape', 'process_group', 'dims_mapping']', "
582 583
                    "but got {}.".format(str(value.keys()))
                )
584
        return dist_attr
585 586


587 588 589 590 591 592 593 594
def save_distributed_checkpoint(
    program,
    checkpoint_path,
    dist_attr_path,
    addition_info=None,
    is_integrated=False,
    dist_context=None,
):
595
    """
C
chenxujun 已提交
596
    Save model parameter state, optimizer state, distributed attribute and
597 598 599 600 601
    additional information of each rank.

    Args:
        program(Program): The program to be saved.
        checkpoint_path(str): The path of the checkpoint file to be saved.
602 603 604
        dist_attr_path(str): The path of distributed attribute file to be saved.
        addition_info(dict, optional): Additional information, key should be selected in ['epoch', 'batch', 'batch_size'].
            Default values are 0, when 'addition_info' is None. Default: None.
605
        is_integrated(bool, optional): Whether to integrate param before save. Default: False.
606
        dist_context(DistributedContext ,optional): collect related distributed information for program
607 608 609 610 611 612 613

    Returns:
        None

    Examples:
        .. code-block:: python

614 615 616 617
            path = os.path.join("./output", "step_%d" % step)
            os.makedirs(path, exist_ok=True)
            add_info = {'batch': step, "batch_size": global_batch_size}
            save_distributed_checkpoint(program, path, path, add_info)
618
    """
619 620
    from .dist_context import get_default_distributed_context

621
    assert isinstance(program, paddle.static.Program)
622 623 624 625 626
    assert isinstance(is_integrated, bool)
    if dist_context is None:
        dist_context = get_default_distributed_context()
    addition_info = _update_addition_info(addition_info)

627
    if not is_integrated:
628 629
        _save_distributed_state_dict(program, addition_info, checkpoint_path)
        _save_distributed_attribute(program, dist_attr_path, dist_context)
630 631 632
    else:
        # TODO: integrate param before save
        raise NotImplementedError(
633 634
            "Integrating parameter has not been implemented."
        )
635 636


637
def load_distributed_checkpoint(checkpoint_path, dist_attr_path):
638
    """
639
    Load parameter, optimizer, distributed attribute and addition_info.
640 641

    Args:
642 643
        checkpoint_path(list[str]): model parameter file path, must be in order of rank id.
        dist_attr_path(list[str]): distributed attribute file path, must be in order of rank id.
644 645

    Returns:
646 647
        param_dict(dict): parameters' value of all ranks.
        dist_attr(dict): parameters' distributed attribute.
648
        addition_info(dict): additional information user saved in last training.
649 650 651 652 653 654 655

    Notes:
        The return, 'addition_info', is belonging to the first file of checkpoint_path by default.

    Examples:
        .. code-block:: python

656
            ckpt_path = ['./model_state_rank0.pdmodel',
657
                         './model_state_rank1.pdmodel']
658
            dist_attr_path = ['./dist_attr_rank0.pdattr',
659 660 661
                              './dist_attr_rank1.pdattr']
            param_dict, dist_attr, add_info = load_distributed_checkpoint(ckpt_path, dist_attr_path)
    """
662 663 664 665
    assert _check_valid_path(
        checkpoint_path
    ), "'checkpoint_path' cannot be None."
    assert _check_valid_path(dist_attr_path), "'dist_attr_path' cannot be None."
666 667 668 669 670 671 672 673

    state_dict_info = _load_distributed_state_dict(checkpoint_path)
    dist_attr = _load_distributed_attribute(dist_attr_path)
    param_dict = state_dict_info["model"]
    addition_info = state_dict_info["addition_info"]
    return param_dict, dist_attr, addition_info


674 675 676
def load_checkpoint_into_program(
    checkpoint_path, dist_attr_path, program, dist_context=None
):
677
    """
678 679 680 681 682 683 684 685 686 687
    Load parameter, optimizer, distributed attribute and addition_info into model.

    Args:
        checkpoint_path(list[str]): model parameter file path, must be in order of rank id.
        dist_attr_path(list[str]): distributed attribute file path, must be in order of rank id.
        program(Program): the program to be updated with checkpoint_path.
        dist_context(DistributedContext ,optional): collect related distributed information for program

    Returns:
        addition_info(dict): user saved in last train.
688

689 690
    Notes:
        The return, 'addition_info', is belonging to the first file of checkpoint_path by default.
691 692 693 694 695

    Examples:
        .. code-block:: python

            exe.run(startup_program)
696
            ckpt_path = ['./model_state_rank0.pdmodel',
697
                         './model_state_rank1.pdmodel']
698
            dist_attr_path = ['./dist_attr_rank0.pdattr',
699 700
                              './dist_attr_rank1.pdattr']
            load_checkpoint_into_program(ckpt_path, dist_attr_path, main_program)
701
    """
702
    from .dist_context import get_default_distributed_context
703

704
    assert isinstance(program, paddle.static.Program)
705 706 707 708
    assert _check_valid_path(
        checkpoint_path
    ), "'checkpoint_path' cannot be None."
    assert _check_valid_path(dist_attr_path), "'dist_attr_path' cannot be None."
709 710 711 712 713 714 715
    if dist_context is None:
        dist_context = get_default_distributed_context()
    all_state_dict_info = _load_distributed_state_dict(checkpoint_path)
    all_pre_dist_attr = _load_distributed_attribute(dist_attr_path)
    all_cur_dist_attr = get_dist_attr(program, dist_context)
    all_param_dict = all_state_dict_info["model"]
    addition_info = all_state_dict_info["addition_info"]
716 717 718
    sliced_param_dict = merge_and_slice_parameter(
        all_param_dict, all_pre_dist_attr, all_cur_dist_attr
    )
719 720 721 722 723 724
    load_parameter_into_program(sliced_param_dict, program)

    return addition_info


def load_parameter_into_program(param_dict, program):
725
    """
726 727 728 729 730 731
    Load parameters into program.

    Args:
        param_dict(dict): parameters' name and value.
        program(Program): the program to be updated
    """
732
    assert isinstance(param_dict, dict)
733
    assert program and isinstance(program, paddle.static.Program)
734 735
    if not param_dict:
        return
736 737 738 739
    program.set_state_dict(param_dict)


def _save_distributed_attribute(program, dist_attr_path, dist_context):
740
    """Save distributed attribute of all parameters"""
741 742
    # TODO: just save a complete distributed attribute file
    rank_id = paddle.distributed.get_rank()
743
    dist_attr_name = os.path.join(
744
        dist_attr_path, f"dist_attr_rank{rank_id}.pdattr"
745
    )
746 747
    dist_attr_dict = {
        "model": get_dist_attr(program, dist_context),
748
        "world_size": paddle.distributed.get_world_size(),
749 750
    }
    paddle.save(dist_attr_dict, dist_attr_name)
751
    logging.info(f"Already saved distributed attribute to '{dist_attr_path}'.")
752 753 754


def _load_distributed_attribute(dist_attr_path):
755
    """Load parameters' distributed attribute from dist_attr_path"""
756 757 758 759
    total_dist_attr = {}
    for dist_attr_file in dist_attr_path:
        dist_attr = paddle.load(dist_attr_file)
        pre_world_size = dist_attr["world_size"]
760 761 762
        assert pre_world_size == len(
            dist_attr_path
        ), "The number of 'dist_attr_path' must be equal to the last training world size."
763 764 765 766 767 768 769 770
        for name, attr in dist_attr["model"].items():
            if name not in total_dist_attr:
                total_dist_attr[name] = attr

    return total_dist_attr


def _save_distributed_state_dict(program, addition_info, checkpoint_path):
771
    """Save parameters' state_dict"""
772
    rank = paddle.distributed.get_rank()
773
    ckpt_file_name = os.path.join(
774
        checkpoint_path, f"model_state_rank{rank}.pdmodel"
775
    )
776 777 778
    state_dict = {
        "model": program.state_dict(),
        "world_size": paddle.distributed.get_world_size(),
779
        "addition_info": addition_info,
780 781
    }
    paddle.save(state_dict, ckpt_file_name)
782
    logging.info(f"Already saved model to '{checkpoint_path}'.")
783 784 785


def _load_distributed_state_dict(checkpoint_path):
786
    """Load parameters' state_dict from checkpoint_path"""
787 788
    all_state_dict = {}
    for idx, ckpt_file in enumerate(checkpoint_path):
Z
zhaoyingli 已提交
789
        state_dict_info = paddle.load(ckpt_file, return_numpy=True)
790
        pre_world_size = state_dict_info["world_size"]
791 792 793
        assert pre_world_size == len(
            checkpoint_path
        ), "The number of 'checkpoint_path' must be equal to the last training world size."
794 795 796 797 798 799 800 801 802 803
        if idx == 0:
            addition_info = state_dict_info["addition_info"]
        for name, value in state_dict_info["model"].items():
            if name in all_state_dict:
                all_state_dict[name].append(np.array(value))
            else:
                all_state_dict[name] = [np.array(value)]

    all_state_dict_info = {
        "model": all_state_dict,
804
        "addition_info": addition_info,
805 806 807 808 809
    }
    return all_state_dict_info


def get_dist_attr(program, dist_context=None):
810
    """
811 812 813 814 815 816 817
    Get distributed attribute of current rank.

    Args:
        program(Program): main program for training
    """
    from .dist_context import get_default_distributed_context

818
    assert isinstance(program, paddle.static.Program)
819 820 821 822 823 824
    if dist_context is None:
        dist_context = get_default_distributed_context()
    dist_attr = {}
    for var in program.list_vars():
        if is_parameter(var) or is_belong_to_optimizer(var):
            tensor_dist_attr = dist_context.get_tensor_dist_attr_for_program(
825 826
                var
            )
827 828 829
            process_mesh = tensor_dist_attr.process_mesh
            dims_mapping = tensor_dist_attr.dims_mapping
            dist_attr[var.name] = {
830 831
                "process_shape": process_mesh.shape,
                "process_group": process_mesh.process_ids,
832
                "dims_mapping": dims_mapping,
833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849
            }
    return dist_attr


def merge_and_slice_parameter(dist_param_dict, pre_dist_attr, cur_dist_attr):
    """
    Merge parameters with previous dist_attr and slice parameters with current dist_attr

    Arags:
        dist_param_dict(dict): parameters' value of all ranks.
        pre_dist_attr(dict): parameters' dist_attr of last training process.
        cur_dist_attr(dict): parameters' dist_attr of current training process.

    Returns:
        dist_param_dict(dict): parameters' value of current rank.
    """
    assert _check_dist_attr(pre_dist_attr), "'pre_dist_attr' cannot be None."
850 851 852 853 854
    assert isinstance(
        dist_param_dict, dict
    ), "The type of 'dist_param_dict' should be 'dict', but got {}.".format(
        str(type(dist_param_dict))
    )
855 856
    for name, value in dist_param_dict.items():
        if not isinstance(name, str):
857 858 859 860 861 862
            raise TypeError(
                "The key of 'dist_param_dict' is parameter's name, "
                "and its type should be 'str', but got {}.".format(
                    str(type(name))
                )
            )
863
        if not isinstance(value, list) or not all(
864 865
            isinstance(v, np.ndarray) for v in value
        ):
866 867
            raise TypeError(
                "The value of 'dist_param_dict' is parameter's value of all ranks, "
868 869
                "and its type should be 'list(numpy.ndarray)'."
            )
870

871 872 873
    if cur_dist_attr is None:
        return {}

874 875 876 877 878 879 880 881 882 883 884 885 886 887 888
    param_not_in_pre = []
    param_not_in_cur = []
    logging.info("Start to merge and slice parameters.")
    for var_name in cur_dist_attr.keys():
        if var_name not in pre_dist_attr:
            param_not_in_pre.append(var_name)
            continue

        pre_attr = pre_dist_attr[var_name]
        cur_attr = cur_dist_attr[var_name]
        if pre_attr == cur_attr:
            # skip merge and slice
            rank_id = paddle.distributed.get_rank()
            index = cur_attr["process_group"].index(rank_id)
            param = dist_param_dict[var_name][index]
889
            dist_param_dict[var_name] = param
890 891 892 893 894 895
            continue

        pre_param = dist_param_dict[var_name]
        pre_dims_mapping = pre_attr["dims_mapping"]
        cur_dims_mapping = cur_attr["dims_mapping"]
        if len(set(pre_dims_mapping)) > 1 or -1 not in pre_dims_mapping:
896
            complete_param = _merge_parameter_with_dist_attr(
897 898
                pre_param, pre_attr
            )
899 900 901
            dist_param_dict[var_name] = complete_param
        else:
            complete_param = pre_param[0]
902
            dist_param_dict[var_name] = complete_param
903 904

        if len(set(cur_dims_mapping)) > 1 or -1 not in cur_dims_mapping:
905
            sliced_param = _slice_parameter_with_dist_attr(
906 907
                complete_param, cur_attr
            )
908 909 910 911 912 913 914 915
            dist_param_dict[var_name] = sliced_param

    for var_name in pre_dist_attr:
        if var_name not in cur_dist_attr:
            param_not_in_cur.append(var_name)
            dist_param_dict.pop(var_name)

    if param_not_in_pre:
916 917
        warnings.warn(
            "Parameters '{}' are not found in last training process.".format(
918 919 920
                str(param_not_in_pre)
            )
        )
921 922
    if param_not_in_cur:
        warnings.warn(
923
            "Parameters '{}' are not found in current training process.".format(
924 925 926
                str(param_not_in_cur)
            )
        )
927 928 929 930 931

    return dist_param_dict


def _merge_parameter_with_dist_attr(param_list, dist_attr):
932
    """Merge parameter with distributed attribute"""
933
    from .reshard import Resharder
934 935 936 937 938

    dims_mapping = dist_attr["dims_mapping"]
    process_shape = dist_attr["process_shape"]
    process_group = dist_attr["process_group"]
    # get the complete shape of the parameter
939 940 941
    complete_shape = Resharder.compute_complete_shape(
        param_list[0].shape, process_shape, dims_mapping
    )
942 943
    # merge the parameter with dist_attr
    partition_param_list = []
Z
zhaoyingli 已提交
944
    merged_partiton = []
945
    for process in process_group:
946
        partition_index = Resharder.compute_partition_index(
947 948
            process, complete_shape, dims_mapping, process_shape, process_group
        )
949
        index = process_group.index(process)
Z
zhaoyingli 已提交
950 951
        if partition_index not in merged_partiton:
            merged_partiton.append(partition_index)
952 953 954 955 956 957
            _merge_parameter(
                partition_param_list,
                param_list[index],
                partition_index,
                complete_shape,
            )
Z
zhaoyingli 已提交
958

959 960 961
    assert (
        len(partition_param_list) == 1 or not partition_param_list
    ), "Fail to merge parameter"
962
    complete_param = partition_param_list[0][0]
963 964 965 966
    return complete_param


def _slice_parameter_with_dist_attr(param, dist_attr):
967 968 969 970
    """Slice parameter with distributed attribute"""
    param = (
        np.array(param) if isinstance(param, paddle.fluid.LoDTensor) else param
    )
971 972 973 974
    dims_mapping = dist_attr["dims_mapping"]
    process_shape = dist_attr["process_shape"]
    process_group = dist_attr["process_group"]
    # slice the parameter with dist_attr
975 976 977 978 979 980
    partition_index_list = _get_split_indices(
        param.shape, dims_mapping, process_shape, process_group
    )
    sliced_param_list = _slice_parameter(
        param, partition_index_list, len(partition_index_list)
    )
981 982
    # get the current parameter's index in sliced_param_list
    rank_id = paddle.distributed.get_rank()
983 984 985
    sliced_param_index = _get_sliced_param_index(
        rank_id, param.shape, dims_mapping, process_shape, process_group
    )
986
    sliced_param = sliced_param_list[sliced_param_index]
987 988 989
    return sliced_param


990 991 992
def _merge_parameter(
    partition_param_list, param, partition_index, complete_shape
):
993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009
    """
    Merge partitial parameters to a complete one.

    Returns:
        None

    Examples:
        .. code-block:: python

            import numpy as np
            partition_param_list = [(np.array([[[1.11, 1.12]]]), [[0,1],[0,1],[0,2]])]
            param = np.array([[[1.13, 1.14]]])
            partition_index = [[0,1],[0,1],[2,4]]

            _merge_parameter(partition_param_list, param, partition_index)
            # partition_param_list: [(np.array([[[1.11, 1.12, 1.13, 1.14]]]), [[0,1],[0,1],[0,4]])]
    """
1010
    from .reshard import Resharder
1011

Z
zhaoyingli 已提交
1012 1013 1014 1015 1016 1017 1018 1019 1020
    if len(partition_param_list) == 1:
        is_complete_data = True
        for idx, item in enumerate(partition_param_list[0][1]):
            if item[0] != 0 or item[1] != complete_shape[idx]:
                is_complete_data = False
                break
        if is_complete_data:
            return

1021 1022
    if not partition_param_list:
        partition_param_list.append((param, partition_index))
1023
    else:
1024 1025
        i = 0
        while i < len(partition_param_list):
1026 1027 1028 1029 1030 1031 1032
            (
                concat_axis,
                first_order,
                new_partition,
            ) = Resharder.compute_concat_info(
                partition_param_list[i][1], partition_index
            )
1033 1034 1035
            if concat_axis != -1:
                if first_order == 0:
                    new_param = np.concatenate(
1036 1037
                        (partition_param_list[i][0], param), axis=concat_axis
                    )
1038 1039
                else:
                    new_param = np.concatenate(
1040 1041
                        (param, partition_param_list[i][0]), axis=concat_axis
                    )
1042 1043

                partition_param_list.pop(i)
1044 1045 1046 1047 1048 1049
                _merge_parameter(
                    partition_param_list,
                    new_param,
                    new_partition,
                    complete_shape,
                )
1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076
                break
            i += 1


def _slice_parameter(complete_param, partition_index_list, length):
    """
    Slice a complete parameter.

    Returns:
        sliced_param_list(list): sliced parameters with 'partition_index_list'

    Examples:
        .. code-block:: python

            import numpy as np
            complete_param = np.array([[[1.11, 1.12, 1.13, 1.14, 1.15, 1.16]]])
            rank = 2
            complete_shape = [1, 1, 6]
            dims_mapping = [-1, -1, 0]
            process_shape = [3]
            process_group = [0, 1, 2]

            sliced_param_list = _slice_parameter(complete_param, [[], [], [2, 4]], 3)
            # [array([[[1.11, 1.12]]]), array([[[1.13, 1.14]]]), array([[[1.15, 1.16]]])]
    """
    sliced_param_list = []
    axis = len(complete_param.shape) - length
1077 1078 1079
    sliced_param = np.split(
        complete_param, partition_index_list[axis], axis=axis
    )
1080 1081 1082 1083
    if length == 1:
        return sliced_param
    for param in sliced_param:
        sliced_param_list.extend(
1084 1085
            _slice_parameter(param, partition_index_list, length - 1)
        )
1086 1087 1088
    return sliced_param_list


1089 1090 1091
def _get_sliced_param_index(
    rank, complete_shape, dims_mapping, process_shape, process_group
):
1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109
    """
    Get sliced_param's index of current rank in all sliced parameters list.

    Returns:
        sliced_param_index(int): the index of sliced param in sliced_param_list

    Examples:
        .. code-block:: python

            import numpy as np
            complete_param = np.array([[[1.11, 1.12, 1.13, 1.14, 1.15, 1.16]]])
            rank = 2
            complete_shape = [1, 1, 6]
            dims_mapping = [-1, -1, 0]
            process_shape = [3]
            process_group = [0, 1, 2]

            slice_param = _slice_parameter(complete_param, [[], [], [2, 4]], 3)
1110
            # slice_param:
1111 1112 1113 1114 1115 1116
            # [array([[[1.11, 1.12]]]), array([[[1.13, 1.14]]]), array([[[1.15, 1.16]]])]

            index = _get_sliced_param_index(rank, complete_shape, dims_mapping
                                            process_shape, process_group)
            # index: 2
    """
1117
    from .reshard import Resharder
1118

1119 1120 1121
    partition_index = Resharder.compute_partition_index(
        rank, complete_shape, dims_mapping, process_shape, process_group
    )
1122 1123 1124 1125 1126 1127
    sliced_param_index = 0
    for i, shape in enumerate(complete_shape):
        if dims_mapping[i] == -1:
            slice_shape = shape
        else:
            slice_shape = shape // process_shape[dims_mapping[i]]
1128 1129
        if slice_shape == 1:
            index = partition_index[i][0]
1130 1131 1132 1133
        else:
            index = (partition_index[i][0] + 1) // slice_shape
        sliced_param_index = sliced_param_index * (shape // slice_shape) + index
    return sliced_param_index
1134 1135


1136 1137 1138
def _get_split_indices(
    complete_shape, dims_mapping, process_shape, process_group
):
1139 1140 1141 1142 1143
    """
    Get split indices of every dimension.

    Returns:
        split_indices_list(list): the split indices of every dimension of the parameter
1144

1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157
    Examples:
        .. code-block:: python

            import numpy as np
            complete_param = np.array([[[1.11, 1.12, 1.13, 1.14, 1.15, 1.16]]])
            complete_shape = [1, 1, 6]
            dims_mapping = [-1, -1, 0]
            process_shape = [3]
            process_group = [0, 1, 2]

            index = _get_split_indices(complete_shape, dims_mapping, process_shape, process_group)
            # index: [[], [], [2, 4]]
    """
1158
    from .reshard import Resharder
1159 1160 1161

    split_indices_list = []
    for process in process_group:
1162
        partition_index = Resharder.compute_partition_index(
1163 1164
            process, complete_shape, dims_mapping, process_shape, process_group
        )
1165 1166 1167 1168 1169 1170
        if split_indices_list:
            for dim in range(len(partition_index)):
                split_indices_list[dim].extend(partition_index[dim])
        else:
            split_indices_list = partition_index
    split_indices_list = list(
1171
        map(
1172
            lambda x, y: list(set(x) - {y} - {0}),
1173 1174 1175 1176
            split_indices_list,
            complete_shape,
        )
    )
1177 1178
    split_indices_list = [sorted(x) for x in split_indices_list]
    return split_indices_list
Z
zhaoyingli 已提交
1179 1180 1181


def set_grad_var_shape(program, dist_context):
1182 1183
    from paddle.distributed.fleet.meta_optimizers.common import OpRole

Z
zhaoyingli 已提交
1184 1185 1186 1187
    from .operators.common import infer_shape

    block = program.global_block()
    vars = block.vars
1188 1189 1190 1191 1192 1193 1194
    appended_grad_times = 0
    grad_var_to_var = dist_context.dist_op_context.grad_var_to_var

    for idx, op in enumerate(block.ops):
        if int(op.attr('op_role')) != int(OpRole.Backward):
            continue

1195 1196 1197 1198
        if (
            int(block.ops[idx - 1].attr('op_role')) == int(OpRole.Forward)
            or int(block.ops[idx - 1].attr('op_role')) == 257
        ):
1199
            appended_grad_times += 1
J
JZ-LIANG 已提交
1200 1201 1202 1203

        if op.type in ["check_finite_and_unscale", "update_loss_scaling"]:
            break

1204
        if op.type in ["sum", "concat", "shape"]:
Z
zhaoyingli 已提交
1205 1206
            continue

1207 1208 1209 1210 1211 1212 1213 1214
        op_dist_attr = dist_context.get_op_dist_attr_for_program(op)
        assert op_dist_attr is not None

        for var_name in op.output_arg_names:
            if "@GRAD" not in var_name:
                continue
            if var_name in grad_var_to_var[appended_grad_times]:
                forward_var_name = grad_var_to_var[appended_grad_times][
1215 1216
                    var_name
                ]
1217
            else:
1218
                forward_var_name = var_name[: var_name.find("@GRAD")]
1219 1220

            if op.type in [
1221 1222 1223 1224 1225
                "c_allreduce_sum",
                "c_identity",
                "scale",
                "cast",
                "fill_any_like",
1226 1227
            ]:
                forward_var_name = op.input_arg_names[0]
1228 1229 1230 1231 1232
            elif (
                op.type == "matmul_v2_grad"
                or op.type == "matmul_grad"
                or op.type == "mul_grad"
            ):
1233 1234 1235 1236
                forward_var_name = None
                for output_name in op.output_names:
                    if var_name in op.output(output_name):
                        assert "@GRAD" in output_name
1237
                        input_name = output_name[: output_name.find("@GRAD")]
1238 1239 1240 1241 1242
                        assert len(op.input(input_name)) == 1
                        forward_var_name = op.input(input_name)[0]
                assert forward_var_name is not None

            need_set_shape_list = [
1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255
                "reshape2_grad",
                "softmax_with_cross_entropy_grad",
                "transpose2_grad",
                "softmax_grad",
                "cross_entropy_grad2",
                "dropout_grad",
                "tanh_grad",
                "slice",
                "assign",
                "matmul_v2_triple_grad",
                "elementwise_add_triple_grad",
                "fill_constant",
                "sqrt_grad",
Z
zhaoyingli 已提交
1256
                "fused_softmax_mask_upper_triangle_grad",
1257 1258
                "flatten_contiguous_range_grad",
                "relu_grad",
1259 1260
                "exp_grad",
                "sigmoid_grad",
1261
                "unsqueeze2_grad",
1262
                "fused_dropout_add_grad",
1263 1264
            ]
            forward_list = [
1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280
                "reshape2",
                "softmax_with_cross_entropy",
                "transpose2",
                "softmax",
                "cross_entropy2",
                "dropout",
                "tanh",
                ["slice_grad", "c_allgather"],
                "assign",
                "matmul_v2_grad_grad",
                "elementwise_add_grad_grad",
                "shape",
                "sqrt",
                "fused_softmax_mask_upper_triangle",
                "flatten_contiguous_range",
                "relu",
1281 1282
                "exp",
                "sigmoid",
1283
                "unsqueeze2",
1284
                "fused_dropout_add",
1285 1286 1287 1288 1289
            ]
            if op.type in need_set_shape_list:
                for forward_op in block.ops:
                    idx = need_set_shape_list.index(op.type)
                    forward_op_name = forward_list[idx]
1290 1291 1292 1293 1294 1295 1296 1297 1298
                    if (
                        forward_op.type in forward_op_name
                        and forward_var_name in forward_op.input_arg_names
                    ):
                        op_dist_attr = (
                            dist_context.get_op_dist_attr_for_program(
                                forward_op
                            )
                        )
1299 1300 1301
                        break

            forward_input_dist_attr = op_dist_attr.get_input_dist_attr(
1302 1303 1304 1305 1306
                forward_var_name
            )
            assert (
                forward_input_dist_attr is not None
            ), f"{forward_var_name, str(op)}"
1307
            forward_var = vars[forward_var_name]
1308 1309 1310
            forward_var_dist_attr = (
                dist_context.get_tensor_dist_attr_for_program(forward_var)
            )
1311 1312
            assert forward_var_dist_attr is not None
            grad_var = vars[var_name]
1313 1314 1315 1316 1317 1318
            ref_shape = infer_shape(
                block,
                forward_var,
                forward_var_dist_attr,
                forward_input_dist_attr,
            )
1319 1320 1321

            if list(grad_var.shape) != ref_shape:
                grad_var.desc.set_shape(ref_shape)
C
caozhou 已提交
1322 1323


1324 1325
def is_forward_op(op):
    op_role = int(op.attr('op_role'))
1326 1327 1328
    return OP_ROLE_KEY in op.attr_names and (
        op_role == int(OpRole.Forward) or op_role == int(OpRole.Loss)
    )
1329 1330 1331


def is_backward_op(op):
1332 1333 1334
    return OP_ROLE_KEY in op.attr_names and int(
        op.all_attrs()[OP_ROLE_KEY]
    ) & int(OpRole.Backward)
1335 1336


1337
def is_optimize_op(op):
1338 1339 1340
    return OP_ROLE_KEY in op.attr_names and int(
        op.all_attrs()[OP_ROLE_KEY]
    ) & int(OpRole.Optimize)
1341 1342


1343
def is_lr_sched_op(op):
1344 1345 1346
    return OP_ROLE_KEY in op.attr_names and int(
        op.all_attrs()[OP_ROLE_KEY]
    ) & int(OpRole.Optimize.LRSched)
1347 1348


J
JZ-LIANG 已提交
1349
def is_loss_op(op):
1350 1351 1352
    return OP_ROLE_KEY in op.attr_names and int(
        op.all_attrs()[OP_ROLE_KEY]
    ) == (int(OpRole.Forward) | int(OpRole.Loss))
J
JZ-LIANG 已提交
1353 1354


1355 1356 1357 1358 1359 1360 1361
def is_loss_grad_op(op):
    if OP_ROLE_KEY not in op.attr_names:
        return False
    op_role = int(op.all_attrs()[OP_ROLE_KEY])
    return op_role & int(OpRole.Backward) and op_role & int(OpRole.Loss)


1362
def is_gradient_clip_op(op):
1363 1364 1365
    return op.desc.has_attr("op_namescope") and op.desc.attr(
        "op_namescope"
    ).startswith("/gradient_clip")
1366 1367


1368 1369 1370 1371
def is_prim_op(op):
    return op.type.endswith("_p")


J
JZ-LIANG 已提交
1372 1373 1374 1375
def get_loss_op(block):
    loss_ops = []
    for op in block.ops:
        if is_loss_op(op):
1376 1377 1378
            assert (
                len(op.desc.output_arg_names()) == 1
            ), "loss op should only output loss var"
J
JZ-LIANG 已提交
1379 1380 1381 1382 1383 1384 1385
            loss_ops.append(op)

    assert len(loss_ops) == 1, "num of loss op is not equal to one"
    return loss_ops[0]


def set_var_dist_attr(dist_context, var, dims_mapping, process_mesh, **kwargs):
1386
    tensor_dist_attr = TensorDistAttr()
J
JZ-LIANG 已提交
1387 1388
    tensor_dist_attr.dims_mapping = dims_mapping
    # TODO get global mesh group
1389 1390 1391 1392 1393 1394 1395 1396 1397 1398
    if isinstance(process_mesh, (list, np.ndarray)):
        tensor_dist_attr.process_mesh = ProcessMesh(process_mesh)
    elif isinstance(process_mesh, core.ProcessMesh):
        tensor_dist_attr.process_mesh = process_mesh
    else:
        raise ValueError(
            "{} must be a instance of ProcessMesh or list, but receive {}".format(
                process_mesh, type(process_mesh)
            )
        )
1399 1400 1401
    if "mark_annotated" in kwargs and kwargs["mark_annotated"]:
        tensor_dist_attr.mark_annotated("dims_mapping")
        tensor_dist_attr.mark_annotated("process_mesh")
J
JZ-LIANG 已提交
1402 1403 1404 1405
    dist_context.set_tensor_dist_attr_for_program(var, tensor_dist_attr)
    return tensor_dist_attr


1406
def naive_set_dist_op_attr_for_program_by_mesh_and_mapping(
1407 1408
    new_op, process_mesh, ref_mapping, ctx
):
J
JZ-LIANG 已提交
1409 1410 1411
    assert process_mesh is not None
    assert ref_mapping is not None

1412
    new_op_dist_attr = OperatorDistAttr()
J
JZ-LIANG 已提交
1413 1414 1415 1416 1417 1418 1419 1420 1421 1422

    for input_varname in new_op.desc.input_arg_names():
        new_op_dist_attr.set_input_dims_mapping(input_varname, ref_mapping)
    for output_varname in new_op.desc.output_arg_names():
        new_op_dist_attr.set_output_dims_mapping(output_varname, ref_mapping)

    new_op_dist_attr.process_mesh = process_mesh
    ctx.set_op_dist_attr_for_program(new_op, new_op_dist_attr)


1423 1424 1425 1426 1427
def naive_set_dist_op_attr_for_program_by_mesh(
    new_op, process_mesh, ctx, is_recompute=False
):
    assert process_mesh is not None

1428
    new_op_dist_attr = OperatorDistAttr()
1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443

    for input_varname in new_op.desc.input_arg_names():
        var = ctx.serial_main_program.global_block().var(input_varname)
        mapping = ctx.get_tensor_dist_attr_for_program(var).dims_mapping
        new_op_dist_attr.set_input_dims_mapping(input_varname, mapping)
    for output_varname in new_op.desc.output_arg_names():
        var = ctx.serial_main_program.global_block().var(output_varname)
        mapping = ctx.get_tensor_dist_attr_for_program(var).dims_mapping
        new_op_dist_attr.set_output_dims_mapping(output_varname, mapping)

    new_op_dist_attr.process_mesh = process_mesh
    new_op_dist_attr.is_recompute = is_recompute
    ctx.set_op_dist_attr_for_program(new_op, new_op_dist_attr)


C
caozhou 已提交
1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462
def update_op_dims_mapping_by_default_dist_impl(dist_op):
    changed = False
    op_dist_attr = dist_op.dist_attr
    op_desc = dist_op.serial_op.desc
    # The following statement will be replaced by a more elegent way
    if op_desc.type() == "shape" or op_desc.type() == "slice":
        return False
    output_names = op_desc.output_names()
    xshape_arg_names = []
    if "XShape" in output_names:
        xshape_arg_names = op_desc.output("XShape")
    batch_dim_mappings = []
    for arg_name in op_desc.input_arg_names():
        serial_tensor = dist_op.get_serial_input(arg_name)
        if serial_tensor.is_parameter:
            continue
        dims_mapping = op_dist_attr.get_input_dims_mapping(arg_name)
        if len(dims_mapping) > 1:
            for idx, mapping in enumerate(dims_mapping[1:]):
1463 1464 1465 1466 1467
                assert (
                    mapping == -1
                ), "{} only the batch dimension (0-dim) can be sharded, but the dimension {} is sharded by {} part.".format(
                    op_desc.type(), idx, mapping
                )
1468 1469
        if len(dims_mapping) >= 1:
            batch_dim_mappings.append(dims_mapping[0])
C
caozhou 已提交
1470 1471 1472 1473 1474 1475 1476 1477
    for arg_name in op_desc.output_arg_names():
        serial_tensor = dist_op.get_serial_output(arg_name)
        if serial_tensor.is_parameter:
            continue
        dims_mapping = op_dist_attr.get_output_dims_mapping(arg_name)
        if arg_name not in xshape_arg_names:
            if len(dims_mapping) > 1:
                for idx, mapping in enumerate(dims_mapping[1:]):
1478 1479 1480 1481 1482
                    assert (
                        mapping == -1
                    ), "{} only the batch dimension (0-dim) can be sharded, but the dimension {} is sharded by {} part.".format(
                        op_desc.type(), idx, mapping
                    )
1483 1484
            if len(dims_mapping) >= 1:
                batch_dim_mappings.append(dims_mapping[0])
C
caozhou 已提交
1485
        else:
1486 1487 1488 1489 1490
            assert (
                dims_mapping[0] == -1
            ), "{} only the batch dimension (1-dim) of XShape can be sharded, but the dimension 0 is sharded by {} part.".format(
                op_desc.type(), mapping
            )
C
caozhou 已提交
1491 1492
            if len(dims_mapping) > 2:
                for idx, mapping in enumerate(dims_mapping[2:]):
1493 1494 1495 1496 1497
                    assert (
                        mapping == -1
                    ), "{} only the batch dimension (1-dim) of XShape can be sharded, but the dimension {} is sharded by {} part.".format(
                        op_desc.type(), idx, mapping
                    )
C
caozhou 已提交
1498 1499 1500
            batch_dim_mappings.append(dims_mapping[1])

    compatible_dim_mapping = compute_compatible_dim_mapping(batch_dim_mappings)
1501 1502 1503
    assert (
        compatible_dim_mapping is not None
    ), "There is no compatible dim mapping."
C
caozhou 已提交
1504 1505 1506 1507 1508
    for arg_name in op_desc.input_arg_names():
        serial_tensor = dist_op.get_serial_input(arg_name)
        if serial_tensor.is_parameter:
            continue
        dims_mapping = op_dist_attr.get_input_dims_mapping(arg_name)
1509
        if len(dims_mapping) >= 1 and compatible_dim_mapping != dims_mapping[0]:
C
caozhou 已提交
1510 1511 1512 1513 1514 1515 1516 1517
            dims_mapping[0] = compatible_dim_mapping
            changed = True
    for arg_name in op_desc.output_arg_names():
        serial_tensor = dist_op.get_serial_output(arg_name)
        if serial_tensor.is_parameter:
            continue
        dims_mapping = op_dist_attr.get_output_dims_mapping(arg_name)
        if arg_name not in xshape_arg_names:
1518 1519 1520 1521
            if (
                len(dims_mapping) >= 1
                and compatible_dim_mapping != dims_mapping[0]
            ):
C
caozhou 已提交
1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551
                dims_mapping[0] = compatible_dim_mapping
                changed = True
        else:
            if compatible_dim_mapping != dims_mapping[1]:
                dims_mapping[1] = compatible_dim_mapping
                changed = True

    return changed


def update_op_dims_mapping_by_elementwise_like_dist_impl(dist_op):
    changed = False
    op_dist_attr = dist_op.dist_attr
    op_desc = dist_op.serial_op.desc
    input_arg_names = op_desc.input_arg_names()
    input_dims_mapping_dict = {}
    input_dims_mapping_lens = {}
    max_dims_mapping_len = -1
    for arg_name in input_arg_names:
        dims_mapping = op_dist_attr.get_input_dims_mapping(arg_name)
        if max_dims_mapping_len < len(dims_mapping):
            max_dims_mapping_len = len(dims_mapping)
        input_dims_mapping_dict[arg_name] = dims_mapping
        input_dims_mapping_lens[arg_name] = len(dims_mapping)

    dims_mapping_list = []
    for arg_name in input_arg_names:
        if input_dims_mapping_lens[arg_name] < max_dims_mapping_len:
            new_dims_mapping = [-1 for _ in range(max_dims_mapping_len)]
            for i in range(input_dims_mapping_lens[arg_name]):
1552 1553 1554
                new_idx = (
                    max_dims_mapping_len - input_dims_mapping_lens[arg_name]
                ) + i
C
caozhou 已提交
1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565
                new_dims_mapping[new_idx] = input_dims_mapping_dict[arg_name][i]
            dims_mapping_list.append(new_dims_mapping)
        else:
            dims_mapping_list.append(input_dims_mapping_dict[arg_name])
    output_arg_names = op_desc.output_arg_names()
    for arg_name in output_arg_names:
        dims_mapping = op_dist_attr.get_output_dims_mapping(arg_name)
        assert len(dims_mapping) == max_dims_mapping_len
        dims_mapping_list.append(dims_mapping)

    compatible_dims_mapping = compute_compatible_dims_mapping(dims_mapping_list)
1566 1567 1568
    assert (
        compatible_dims_mapping is not None
    ), "There is no compatible dim mapping."
C
caozhou 已提交
1569 1570 1571 1572 1573 1574 1575

    for arg_name in input_arg_names:
        if input_dims_mapping_lens[arg_name] < max_dims_mapping_len:
            new_dims_mapping = [
                -1 for _ in range(input_dims_mapping_lens[arg_name])
            ]
            for i in range(input_dims_mapping_lens[arg_name]):
1576 1577 1578
                new_idx = (
                    max_dims_mapping_len - input_dims_mapping_lens[arg_name]
                ) + i
C
caozhou 已提交
1579 1580 1581 1582 1583 1584
                new_dims_mapping[i] = compatible_dims_mapping[new_idx]
            if new_dims_mapping != input_dims_mapping_dict[arg_name]:
                op_dist_attr.set_input_dims_mapping(arg_name, new_dims_mapping)
                changed = True
        else:
            if compatible_dims_mapping != input_dims_mapping_dict[arg_name]:
1585 1586 1587
                op_dist_attr.set_input_dims_mapping(
                    arg_name, compatible_dims_mapping
                )
C
caozhou 已提交
1588 1589 1590 1591 1592
                changed = True

    for arg_name in output_arg_names:
        dims_mapping = op_dist_attr.get_output_dims_mapping(arg_name)
        if compatible_dims_mapping != dims_mapping:
1593 1594 1595
            op_dist_attr.set_output_dims_mapping(
                arg_name, compatible_dims_mapping
            )
C
caozhou 已提交
1596 1597 1598
            changed = True

    return changed
1599 1600


1601 1602 1603
def get_all_distributed_main_program(
    serial_program_info, dist_context, parallelizer
):
1604
    "Get all distributed main programs by dist_context."
1605
    from .dist_context import DistributedOperatorContext
1606

1607
    cluster = serial_program_info.cluster
1608
    copied_parallelizer = copy.deepcopy(parallelizer)
1609
    all_dist_main_program = []
1610 1611 1612 1613 1614
    ranks = (
        paddle.distributed.get_world_size()
        if cluster is None
        else len(cluster.get_all_devices("GPU"))
    )
1615 1616 1617
    for rank_id in range(ranks):
        used_dist_context = copy.deepcopy(dist_context)
        used_dist_context._dist_op_context = DistributedOperatorContext()
1618 1619 1620 1621 1622 1623 1624
        (
            _,
            _,
            dist_startup_program,
            dist_main_program,
            _,
        ) = copied_parallelizer._get_dist_program(rank_id, used_dist_context)
1625 1626 1627 1628 1629 1630
        all_dist_main_program.append(dist_main_program)

    return all_dist_main_program


class SerialProgramInfo:
1631 1632 1633
    def __init__(
        self, train_program, satrtup_program, loss, optimizer, cluster=None
    ):
1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658
        self._train_program = train_program
        self._startup_program = satrtup_program
        self._loss = loss
        self._optimizer = optimizer
        self._cluster = cluster

    @property
    def train_program(self):
        return self._train_program

    @property
    def startup_program(self):
        return self._startup_program

    @property
    def loss(self):
        return self._loss

    @property
    def optimizer(self):
        return self._optimizer

    @property
    def cluster(self):
        return self._cluster
1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673


def get_standalone_cost_data(distributed_programs):
    def _compute_runtime(op_cost, op, vars):
        runtime = 0
        try:
            runtime = float(op_cost["op_time"])
        except:
            return runtime
        op_config = op_cost["config"]
        total_static_input_size = 0
        total_actual_input_size = 0
        parsed_info = op_config.split("\n")
        variable = "(Variable)"
        for info in parsed_info:
1674 1675 1676
            variable = (
                "(Variable)" if "(Variable)" in info else "(list<Variable>"
            )
1677
            if variable in info:
1678
                arg_name_lower = info[: info.find(variable) - 1]
1679 1680
                shape_left_boundary = info.find("[")
                shape_right_boundary = info.find("]")
1681 1682 1683 1684 1685 1686 1687 1688
                assert (
                    shape_left_boundary > 0
                    and shape_right_boundary > 0
                    and shape_right_boundary > shape_left_boundary
                ), "Get shape failed."
                shape = info[
                    shape_left_boundary + 1 : shape_right_boundary
                ].split(",")
1689
                shape = [int(x.strip()) for x in shape]
1690
                dtype_factor = 1
1691
                total_static_input_size += reduce(lambda x, y: x * y, shape, 1)
1692
                if op.type == "c_embedding":
1693 1694 1695
                    arg_name_lower = (
                        "w" if arg_name_lower == "weight" else "ids"
                    )
1696 1697 1698 1699 1700
                for arg_name in op.input_names:
                    if arg_name.lower() == arg_name_lower:
                        for var_name in op.input(arg_name):
                            var = vars[var_name]
                            total_actual_input_size += reduce(
1701 1702
                                lambda x, y: x * y, var.shape
                            )
1703
                        break
1704 1705 1706
        assert (
            total_static_input_size > 0 and total_actual_input_size > 0
        ), "Get input size failed."
1707

1708 1709 1710
        actual_runtime = (
            total_actual_input_size / total_static_input_size * runtime
        )
1711 1712
        return actual_runtime

1713
    import paddle.cost_model as cm
1714

1715
    cost_model = cm.CostModel()
1716 1717 1718 1719 1720 1721 1722 1723 1724
    cost_model.static_cost_data()
    DEFAULT_MULTIPLE = 2
    OP_NAME_MAPPING = {
        "c_embedding": "embedding",
        "matmul_v2": "matmul",
        "transpose2": "transpose",
        "reshape2": "reshape",
        "unsqueeze2": "unsqueeze",
        "reduce_sum": "sum",
1725
        "elementwise_div": "divide",
1726 1727 1728
    }

    standalone_cost_data = []
1729 1730
    # skip ops
    not_enum_ops = [
1731 1732 1733 1734
        "create_py_reader",
        "create_double_buffer_reader",
        "read",
        "assign",
1735
    ]
1736 1737 1738 1739 1740 1741 1742 1743
    for distributed_program in distributed_programs:
        cost_data = {}
        vars = distributed_program.global_block().vars
        for op in distributed_program.global_block().ops:
            runtime = 0
            if op.type in not_enum_ops:
                cost_data[op.desc.id()] = runtime
                continue
1744 1745 1746 1747 1748
            dtype = (
                str(vars[op.input_arg_names[0]].dtype)
                if op.input_arg_names
                else "float32"
            )
1749 1750 1751 1752 1753
            if int(op.attr('op_role')) == int(OpRole.Backward):
                if "_grad" in op.type:
                    forward_op_name = op.type[:-5]
                    if forward_op_name in OP_NAME_MAPPING.keys():
                        forward_op_name = OP_NAME_MAPPING[forward_op_name]
1754 1755 1756
                    op_cost = cost_model.get_static_op_time(
                        forward_op_name, forward=False, dtype=dtype
                    )
1757 1758 1759
                    if op_cost:
                        runtime = _compute_runtime(op_cost, op, vars)
                    else:
1760 1761 1762
                        op_cost = cost_model.get_static_op_time(
                            forward_op_name, dtype=dtype
                        )
1763 1764 1765
                        if op_cost:
                            runtime = 2 * _compute_runtime(op_cost, op, vars)
            elif int(op.attr('op_role')) == int(OpRole.Forward):
1766 1767 1768 1769 1770
                op_name = (
                    OP_NAME_MAPPING[op.type]
                    if op.type in OP_NAME_MAPPING.keys()
                    else op.type
                )
1771 1772 1773 1774 1775 1776 1777 1778 1779
                op_cost = cost_model.get_static_op_time(op_name)
                if op_cost:
                    runtime = _compute_runtime(op_cost, op, vars)

            cost_data[op.desc.id()] = runtime

        standalone_cost_data.append(cost_data)

    return standalone_cost_data
1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794


def set_dist_op_desc_original_id(dist_op_desc, op_desc, dist_context):
    op_id = op_desc.id()
    op_original_id = op_desc.original_id()
    # First, try to set the original id to the id of the op_desc
    if op_id in dist_context._dist_ops_for_program:
        dist_op_desc.set_original_id(op_id)
        return
    # Second, try to set the original id to the original_id of the op_desc
    elif op_original_id in dist_context._dist_ops_for_program:
        dist_op_desc.set_original_id(op_original_id)
        return
    # Third, print error infomation if we cannot find the original id
    else:
1795 1796 1797
        raise AssertionError(
            "Cannot find the original id in the distributed context"
        )
1798 1799 1800 1801 1802 1803 1804 1805


def to_list(value):
    if value is None:
        return value
    if isinstance(value, (list, tuple)):
        return list(value)
    return [value]
1806 1807 1808 1809


def debug_program(program, path, name):
    filename = os.path.join(
1810 1811
        path, name + '_program' + ".%d" % (paddle.distributed.get_rank())
    )
1812 1813
    with open(filename, 'w') as f:
        f.write(str(program))
1814 1815 1816


def ring_id_to_process_group(ring_id):
1817 1818
    from .process_group import get_all_process_groups

1819 1820 1821 1822
    for g in get_all_process_groups():
        if g.id == ring_id:
            return g
    return None
1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833


def find_higher_order_backward_op(program):
    higher_order_op_suffix = ['_grad_grad', 'triple_grad']
    for block in program.blocks:
        for op in block.ops:
            for suffix in higher_order_op_suffix:
                if suffix in op.type:
                    return True

    return False
Z
zhaoyingli 已提交
1834 1835


1836 1837 1838 1839 1840 1841 1842 1843 1844
def get_var_numel(var):
    """
    input:
        - var: variable
    return:
        number of elemnet in var
    """
    assert isinstance(var, Variable)
    assert -1 not in var.shape
1845
    return reduce(lambda x, y: x * y, var.shape, 1)
1846 1847


Z
zhaoyingli 已提交
1848 1849 1850
def get_lr(optimizer):
    if isinstance(optimizer, paddle.optimizer.Optimizer):
        return optimizer.get_lr()
1851
    elif isinstance(optimizer, paddle.static.Optimizer):
Z
zhaoyingli 已提交
1852 1853 1854 1855 1856 1857
        if isinstance(optimizer._learning_rate, float):
            return optimizer._learning_rate
        else:
            return optimizer._learning_rate()
    else:
        raise TypeError(
1858
            "'optimizer' must be object of class `paddle.optimizer.Optimizer`"
1859
            " or `paddle.static.Optimizer`, but got {}.".format(type(optimizer))
1860
        )
1861 1862 1863 1864


def initialize_pg_in_full_mode(all_process_groups, cur_rank):
    import socket
1865

1866
    from ...collective import _get_global_env
1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890

    has_recv_by_socket = []
    # This is a magic number
    magic_num = 500
    genv = _get_global_env()
    cur_rank_ip, cur_rank_port = genv.current_endpoint.split(":")
    cur_rank_recv_port = int(cur_rank_port) + magic_num
    server_socket = None
    # Large enough for recv rank
    buff_size = 1024
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_socket.bind((cur_rank_ip, cur_rank_recv_port))
    # The 10 is an empirical value
    server_socket.listen(10)
    client_sockets = {}
    for process_group in all_process_groups:
        if cur_rank not in process_group.ranks:
            continue
        if len(process_group.ranks) == 2:
            index = process_group.ranks.index(cur_rank)
            is_send = True if index == 0 else False
            if is_send:
                recv_rank = process_group.ranks[1]
                recv_rank_ip, recv_rank_port = genv.trainer_endpoints[
1891 1892
                    recv_rank
                ].split(":")
1893
                connect_port = int(recv_rank_port) + magic_num
1894 1895 1896
                client_socket = socket.socket(
                    socket.AF_INET, socket.SOCK_STREAM
                )
1897 1898 1899 1900 1901 1902
                client_socket.connect((recv_rank_ip, connect_port))
                client_socket.send(str(cur_rank).encode('utf-8'))
                rank = client_socket.recv(buff_size).decode('utf-8')
                rank = int(rank)
                if rank != recv_rank:
                    raise ValueError(
1903 1904 1905 1906
                        "Please check comm pair, the recv rank should be {} but got {}.".format(
                            recv_rank, rank
                        )
                    )
1907
                else:
1908 1909 1910 1911 1912
                    print(
                        "It is able to instantiate {} as sender now.".format(
                            process_group.ranks
                        )
                    )
1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923
                client_socket.close()
            else:
                send_rank = process_group.ranks[0]
                while True:
                    if send_rank not in has_recv_by_socket:
                        client_socket, recv_addr = server_socket.accept()
                        rank = int(client_socket.recv(buff_size).decode())
                        client_sockets[rank] = client_socket
                        has_recv_by_socket.append(rank)
                    else:
                        client_sockets[send_rank].send(
1924 1925
                            str(cur_rank).encode("utf-8")
                        )
1926
                        client_sockets[send_rank].close()
1927 1928 1929 1930 1931
                        print(
                            "It is able to instantiate {} as recver now.".format(
                                process_group.ranks
                            )
                        )
1932 1933 1934
                        break
        process_group.instantiate()
    server_socket.close()
1935 1936


1937 1938 1939 1940
def is_recompute_op(op):
    return op.has_attr('op_namescope') and "/auto_parallel/rc" in op.attr(
        'op_namescope'
    )
1941

1942 1943

def set_recompute_segments(model, losses, strategy, program):
1944
    from ...passes.auto_parallel_recompute import RecomputeState
1945 1946

    if not losses:
1947 1948 1949 1950 1951 1952 1953 1954 1955
        return

    recompute = strategy.recompute
    if not recompute.enable:
        return

    # NOTE: hack to enable recompute in engine api for GPT-3
    # TODO support more PaddleNLP/CV models here
    # extract ckpts by specific model
1956
    ckpts = []
1957
    if isinstance(model, paddle.nn.Layer):
1958 1959 1960 1961 1962 1963 1964 1965 1966 1967
        if (
            hasattr(model, "gpt")
            and model.__class__.__name__
            in [
                'GPTForPretraining',
                'GPTForPretrainingAuto',
            ]
            and hasattr(model.gpt, "checkpoints")
        ):
            ckpts = model.gpt.checkpoints
1968 1969 1970
            # last recompute segment is not need to recompute
            if len(ckpts) > 2:
                ckpts.pop()
1971
        else:
1972
            ckpts = recompute.checkpoints
1973
    else:
1974
        ckpts = recompute.checkpoints
1975

1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017
    if not ckpts:
        return

    block = program.global_block()
    rc_state = RecomputeState(block, block.ops)
    rc_state.build_stats()
    checkpoints = rc_state.sort_checkpoints(ckpts)

    segments = []
    start_idx = -1
    pre_segment_end_idx = -1
    while start_idx + 1 < len(checkpoints):
        if start_idx == -1:
            ckpt_name = checkpoints[start_idx + 1]
            if ckpt_name not in rc_state.var_op_deps:
                start_idx += 1
                continue
            op_idx_list = rc_state.var_op_deps[ckpt_name]["var_as_output_ops"]
            if op_idx_list and max(op_idx_list) > 0:
                segments.append([0, max(op_idx_list) + 1])
        else:
            flag, min_idx, max_idx = rc_state.is_subgraph(
                [checkpoints[start_idx]], [checkpoints[start_idx + 1]]
            )
            if flag:
                min_idx = rc_state._update_segment_start(
                    min_idx, pre_segment_end_idx
                )
                segments.append([min_idx, max_idx + 1])
            else:
                logging.debug(
                    "Could not recompute op range [{}] - [{}] ".format(
                        min_idx, max_idx + 1
                    )
                )
        start_idx += 1

    for i, segment in enumerate(segments):
        for j in range(segment[0], segment[1]):
            block.ops[j]._set_attr(
                'op_namescope', "/auto_parallel/rc_" + str(i)
            )
2018 2019


2020 2021 2022 2023 2024 2025
def get_input_split_info(cur_rank, var, dist_context):
    # deduce how the input data is split among the cluster
    tensor_dist_attr = dist_context.get_tensor_dist_attr_for_program(var)
    process_mesh = tensor_dist_attr.process_mesh
    dims_mapping = tensor_dist_attr.dims_mapping

2026
    if cur_rank not in process_mesh.process_ids:
2027 2028 2029 2030 2031
        rank_id = _get_corresponding_rank(dist_context, process_mesh, cur_rank)
    else:
        rank_id = cur_rank

    batch_size_axis = dims_mapping[0]
2032
    if batch_size_axis > -1 and process_mesh.shape[batch_size_axis] > 1:
2033
        group_ranks = _get_comm_group(
2034 2035
            process_mesh.process_ids,
            process_mesh.shape,
2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048
            batch_size_axis,
            rank_id,
        )
        return len(group_ranks), group_ranks.index(rank_id)

    return 1, 0


def validate_opt(optimizer):
    if optimizer is not None:
        optimizer._parameter_list = None
        optimizer._param_groups = None
    return optimizer
2049 2050


2051
def set_data_parallel(x):
2052
    from ..interface import ProcessMesh, shard_tensor
2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079
    from .process_group import get_world_process_group

    world_ranks = get_world_process_group().ranks
    process_mesh = ProcessMesh(world_ranks, ['dp'])
    shard_spec = ['dp' if len(world_ranks) > 1 else None] + [
        None for _ in range(len(x.shape) - 1)
    ]

    return shard_tensor(x, process_mesh, shard_spec)


def is_naive_data_parallel(dist_context):
    # Navie data parallel only completes dist_attr once from the front to back.
    if not dist_context.data_parallel:
        return False

    ops_type = [
        op.type
        for op in dist_context._original_serial_main_program.global_block().ops
    ]
    if (
        not set(ops_type) & set(__not_naive_data_parallel_op__)
    ) and dist_context.data_parallel:
        return True
    return False


2080 2081 2082 2083 2084 2085 2086 2087 2088
def _copy_tensor_dist_attr_to_cpp(cpp_dist_attr, py_dist_attr):
    py_process_mesh = py_dist_attr.process_mesh
    if py_process_mesh is not None:
        cpp_dist_attr.process_mesh = core.ProcessMesh(
            py_process_mesh.shape,
            py_process_mesh.process_ids,
            ["d" + str(i) for i in range(len(py_process_mesh.shape))],
        )
    cpp_dist_attr.dims_mapping = py_dist_attr.dims_mapping
2089
    cpp_dist_attr.annotated = py_dist_attr.annotated
2090 2091 2092


def _copy_tensor_dist_attr_from_cpp(cpp_dist_attr, py_dist_attr):
2093
    from ..process_mesh import ProcessMesh
2094 2095

    cpp_process_mesh = cpp_dist_attr.process_mesh
2096
    if cpp_process_mesh is not None:
2097 2098 2099 2100 2101
        py_dist_attr.process_mesh = ProcessMesh(
            shape=cpp_process_mesh.shape,
            process_ids=cpp_process_mesh.process_ids,
        )
    py_dist_attr.dims_mapping = cpp_dist_attr.dims_mapping
2102
    py_dist_attr.annotated = cpp_dist_attr.annotated
2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114


def _copy_op_dist_attr_to_cpp(cpp_dist_attr, py_dist_attr):
    py_process_mesh = py_dist_attr.process_mesh
    if py_process_mesh is not None:
        cpp_dist_attr.process_mesh = core.ProcessMesh(
            py_process_mesh.shape,
            py_process_mesh.process_ids,
            ["d" + str(i) for i in range(len(py_process_mesh.shape))],
        )
    cpp_dist_attr.impl_type = py_dist_attr.impl_type
    cpp_dist_attr.impl_idx = py_dist_attr.impl_idx
2115 2116
    cpp_dist_attr.is_recompute = py_dist_attr.is_recompute
    cpp_dist_attr.annotated = py_dist_attr.annotated
2117 2118 2119 2120 2121 2122 2123 2124 2125
    for name, py_tensor_dist_attr in py_dist_attr.inputs_dist_attrs.items():
        cpp_tensor_dist_attr = cpp_dist_attr.get_input_dist_attr(name)
        _copy_tensor_dist_attr_to_cpp(cpp_tensor_dist_attr, py_tensor_dist_attr)
    for name, py_tensor_dist_attr in py_dist_attr.outputs_dist_attrs.items():
        cpp_tensor_dist_attr = cpp_dist_attr.get_output_dist_attr(name)
        _copy_tensor_dist_attr_to_cpp(cpp_tensor_dist_attr, py_tensor_dist_attr)


def _copy_op_dist_attr_from_cpp(cpp_dist_attr, py_dist_attr):
2126
    from ..process_mesh import ProcessMesh
2127 2128

    cpp_process_mesh = cpp_dist_attr.process_mesh
2129
    if cpp_process_mesh is not None:
2130 2131 2132 2133 2134 2135
        py_dist_attr.process_mesh = ProcessMesh(
            shape=cpp_process_mesh.shape,
            process_ids=cpp_process_mesh.process_ids,
        )
    py_dist_attr.impl_type = cpp_dist_attr.impl_type
    py_dist_attr.impl_idx = cpp_dist_attr.impl_idx
2136 2137
    py_dist_attr.is_recompute = cpp_dist_attr.is_recompute
    py_dist_attr.annotated = cpp_dist_attr.annotated
2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195
    for name, cpp_tensor_dist_attr in cpp_dist_attr.inputs_dist_attrs.items():
        py_tensor_dist_attr = py_dist_attr.get_input_dist_attr(name)
        _copy_tensor_dist_attr_from_cpp(
            cpp_tensor_dist_attr, py_tensor_dist_attr
        )
    for name, cpp_tensor_dist_attr in cpp_dist_attr.outputs_dist_attrs.items():
        py_tensor_dist_attr = py_dist_attr.get_output_dist_attr(name)
        _copy_tensor_dist_attr_from_cpp(
            cpp_tensor_dist_attr, py_tensor_dist_attr
        )


def _copy_dist_attr_to_cpp(dist_context):
    for dist_tensor in dist_context._dist_tensors_for_program.values():
        _copy_tensor_dist_attr_to_cpp(
            dist_tensor.serial_tensor.dist_attr, dist_tensor.dist_attr
        )

    for dist_op in dist_context._dist_ops_for_program.values():
        _copy_op_dist_attr_to_cpp(
            dist_op.serial_op.dist_attr, dist_op.dist_attr
        )


def _copy_dist_attr_from_cpp(dist_context):
    for dist_tensor in dist_context._dist_tensors_for_program.values():
        _copy_tensor_dist_attr_from_cpp(
            dist_tensor.serial_tensor.dist_attr, dist_tensor.dist_attr
        )

    for dist_op in dist_context._dist_ops_for_program.values():
        _copy_op_dist_attr_from_cpp(
            dist_op.serial_op.dist_attr, dist_op.dist_attr
        )


def _copy_dist_attr_to_cpp_for_graph(dist_context):
    for node in dist_context.serial_ordered_nodes:
        if node.is_var() and node.var() is not None:
            py_dist_attr = dist_context.get_tensor_dist_attr_for_graph(node)
            cpp_dist_attr = node.var().dist_attr
            _copy_tensor_dist_attr_to_cpp(cpp_dist_attr, py_dist_attr)
        if node.is_op() and node.op() is not None:
            py_dist_attr = dist_context.get_op_dist_attr_for_graph(node)
            cpp_dist_attr = node.op().dist_attr
            _copy_op_dist_attr_to_cpp(cpp_dist_attr, py_dist_attr)


def _copy_dist_attr_from_cpp_for_graph(dist_context):
    for node in dist_context.serial_ordered_nodes:
        if node.is_var() and node.var() is not None:
            py_dist_attr = dist_context.get_tensor_dist_attr_for_graph(node)
            cpp_dist_attr = node.var().dist_attr
            _copy_tensor_dist_attr_from_cpp(cpp_dist_attr, py_dist_attr)
        if node.is_op() and node.op() is not None:
            py_dist_attr = dist_context.get_op_dist_attr_for_graph(node)
            cpp_dist_attr = node.op().dist_attr
            _copy_op_dist_attr_from_cpp(cpp_dist_attr, py_dist_attr)
2196 2197 2198 2199 2200 2201


def insert_dependencies_for_two_ops(
    block,
    idx,
    prior_op,
2202
    posterior_op,
2203 2204 2205
    dist_context,
    is_recompute=False,
    sync=False,
2206
    op_namescope=None,
2207 2208
):
    """
2209
    dependency: prior_op should be run before posterior_op
2210 2211 2212 2213 2214 2215 2216 2217
    """

    assert (
        len(prior_op.output_arg_names) >= 1
    ), "first op of dependency should at least have one output. [{}]".format(
        str(prior_op)
    )
    assert (
2218
        len(posterior_op.input_arg_names) >= 1
2219
    ), "second op of dependency should at least have one input. [{}]".format(
2220
        str(posterior_op)
2221 2222 2223 2224 2225
    )
    prior_op_mesh = dist_context.get_op_dist_attr_for_program(
        prior_op
    ).process_mesh
    posterior_mesh = dist_context.get_op_dist_attr_for_program(
2226
        posterior_op
2227 2228 2229 2230 2231 2232 2233 2234
    ).process_mesh
    assert (
        prior_op_mesh == posterior_mesh
    ), "two ops of dependency should have same mesh but got [{}] and [{}]".format(
        str(prior_op_mesh), str(posterior_mesh)
    )

    def _select_best_depend_var(vars):
2235 2236 2237
        # parameter should not be dep var since it maybe partition in sharding pass
        vars = [var for var in vars if not var.is_parameter]
        assert len(vars) > 0
2238 2239 2240 2241 2242 2243 2244 2245 2246
        vars_with_numels = [(var, get_var_numel(var)) for var in vars]
        vars_with_numels.sort(key=lambda x: x[1])

        return vars_with_numels[-1][0]

    first_var = _select_best_depend_var(
        [block.var(name) for name in prior_op.output_arg_names]
    )
    second_var = _select_best_depend_var(
2247
        [block.var(name) for name in posterior_op.input_arg_names]
2248 2249
    )

2250
    return insert_dependencies_for_vars(
2251 2252 2253 2254 2255 2256
        block,
        idx,
        first_var,
        second_var,
        dist_context,
        OpRole.Backward,
2257 2258 2259 2260 2261
        process_mesh=prior_op_mesh,
        is_recompute=is_recompute,
        sync=sync,
        op_namescope=op_namescope,
        use_nop=False,
2262 2263 2264
    )


2265
def insert_dependencies_for_vars(
2266 2267
    block,
    idx,
2268 2269
    prior_vars,
    post_vars,
2270 2271 2272 2273 2274
    dist_context,
    oprole,
    process_mesh=None,
    is_recompute=False,
    sync=False,
2275 2276
    op_namescope=None,
    use_nop=False,
2277 2278
):
    """
2279
    dependency: op that generates prior_vars should be run before op that generates post_vars
2280
    """
2281 2282 2283 2284 2285 2286 2287 2288 2289 2290

    if isinstance(prior_vars, Variable):
        prior_vars = [prior_vars]
    if isinstance(post_vars, Variable):
        post_vars = [post_vars]
    for prior_var in prior_vars:
        assert block.has_var(prior_var.name)
    for post_var in post_vars:
        assert block.has_var(post_var.name)

2291 2292
    if process_mesh is None:
        process_mesh = dist_context.get_tensor_dist_attr_for_program(
2293
            post_vars[0]
2294 2295 2296
        ).process_mesh
    assert process_mesh is not None

2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316
    use_nop = True
    if use_nop:
        depend_op = block._insert_op_without_sync(
            idx,
            type='nop',
            inputs={
                "X": prior_vars,
            },
            outputs={"Out": post_vars},
        )
    else:
        depend_op = block._insert_op_without_sync(
            idx,
            type='depend',
            inputs={
                "X": post_vars,
                "Dep": prior_vars,
            },
            outputs={"Out": post_vars},
        )
2317
    depend_op._set_attr(OP_ROLE_KEY, oprole)
2318

2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341
    # TODO: condition can be removed when add correct dist_attr for coalesce vars and ops in sharding_pass
    if is_recompute or process_mesh != [-1]:
        depend_op_dist_attr = OperatorDistAttr()
        depend_op_dist_attr.impl_idx = 0
        depend_op_dist_attr.impl_type = "default"
        depend_op_dist_attr.process_mesh = process_mesh
        depend_op_dist_attr.is_recompute = is_recompute
        for input_varname in depend_op.desc.input_arg_names():
            var = block.var(input_varname)
            mapping = dist_context.get_tensor_dist_attr_for_program(
                var
            ).dims_mapping
            depend_op_dist_attr.set_input_dims_mapping(input_varname, mapping)
        for output_varname in depend_op.desc.output_arg_names():
            var = block.var(output_varname)
            mapping = dist_context.get_tensor_dist_attr_for_program(
                var
            ).dims_mapping
            depend_op_dist_attr.set_output_dims_mapping(output_varname, mapping)
        dist_context.set_op_dist_attr_for_program(
            depend_op, depend_op_dist_attr
        )

2342
    if op_namescope is not None:
2343
        depend_op._set_attr('op_namescope', f"/{op_namescope}")
2344 2345 2346

    if sync:
        block._sync_with_cpp()
2347 2348 2349 2350

    return depend_op


2351 2352 2353 2354 2355
def is_dep_skip_op(op):
    if "c_" in op.type:
        return True

    return False
2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369


def _dygraph_guard_(func):
    def __impl__(*args, **kwargs):
        if paddle.framework.in_dynamic_mode():
            return func(*args, **kwargs)
        else:
            with paddle.fluid.dygraph.guard():
                return func(*args, **kwargs)

    return __impl__


dygraph_guard = wrap_decorator(_dygraph_guard_)