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

import copy
import logging

from .pass_base import PassBase, register_pass
from paddle.fluid import core, unique_name
from paddle.fluid import framework as framework
from paddle.fluid.framework import Variable, Operator
from paddle.fluid.backward import _append_grad_suffix_, _get_no_grad_set_name
from paddle.fluid.backward import ProgramStats, _rename_arg_, _find_op_path_
from paddle.distributed.auto_parallel.process_mesh import ProcessMesh
J
JZ-LIANG 已提交
25 26 27 28 29 30 31 32 33 34 35
from paddle.distributed.auto_parallel.dist_attribute import (
    OperatorDistributedAttribute,
)
from paddle.distributed.auto_parallel.utils import (
    get_loss_op,
    set_var_dist_attr,
    set_dist_op_desc_original_id,
)
from paddle.distributed.auto_parallel.utils import (
    naive_set_dist_op_attr_for_program_by_mesh_and_mapping,
)
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63


class RecomputeState(ProgramStats):
    def __init__(self, block, ops):
        super(RecomputeState, self).__init__(block=block, ops=ops)
        self._block = block
        self._ops = ops
        self.var_op_deps = {}

    def build_stats(self):
        for i, op in enumerate(self._ops):
            for name in op.desc.input_arg_names():
                if name in self.var_op_deps:
                    self.var_op_deps[name]["var_as_input_ops"].extend([i])
                else:
                    self.var_op_deps[name] = {}
                    self.var_op_deps[name]["var_as_input_ops"] = [i]
                    self.var_op_deps[name]["var_as_output_ops"] = []

            for name in op.desc.output_arg_names():
                if name in self.var_op_deps:
                    self.var_op_deps[name]["var_as_output_ops"].extend([i])
                else:
                    self.var_op_deps[name] = {}
                    self.var_op_deps[name]["var_as_input_ops"] = []
                    self.var_op_deps[name]["var_as_output_ops"] = [i]

    def get_recompute_segments(self, checkpoints):
J
JZ-LIANG 已提交
64
        """get recompute segments from checkpoints"""
65 66 67 68 69 70 71 72 73 74 75 76 77 78
        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 self.var_op_deps:
                    start_idx += 1
                    continue
                op_idx_list = self.var_op_deps[ckpt_name]["var_as_output_ops"]
                if op_idx_list:
                    segments.append([0, max(op_idx_list) + 1])
            else:
                flag, min_idx, max_idx = self.is_subgraph(
J
JZ-LIANG 已提交
79 80
                    [checkpoints[start_idx]], [checkpoints[start_idx + 1]]
                )
81
                if flag:
82
                    min_idx = self._update_segment_start(
J
JZ-LIANG 已提交
83 84
                        min_idx, pre_segment_end_idx
                    )
85 86
                    segments.append([min_idx, max_idx + 1])
                else:
87 88
                    logging.info(
                        "Could not recompute op range [{}] - [{}] ".format(
J
JZ-LIANG 已提交
89 90 91
                            min_idx, max_idx + 1
                        )
                    )
92 93 94 95
            start_idx += 1

        for i, (idx1, idx2) in enumerate(segments):
            logging.info("recompute segment[{}]".format(i))
J
JZ-LIANG 已提交
96 97 98 99 100 101 102 103 104 105 106 107 108 109
            logging.info(
                "segment start op: [{}]: [{}] [{}]".format(
                    self._ops[idx1].desc.type(),
                    self._ops[idx1].desc.input_arg_names(),
                    self._ops[idx1].desc.output_arg_names(),
                )
            )
            logging.info(
                "segment end op: [{}]: [{}] [{}]".format(
                    self._ops[idx2 - 1].desc.type(),
                    self._ops[idx2 - 1].desc.input_arg_names(),
                    self._ops[idx2 - 1].desc.output_arg_names(),
                )
            )
110 111 112 113 114

        return segments

    def modify_forward_desc_for_recompute(self, dist_context):
        """
J
JZ-LIANG 已提交
115
        If program's foward part has 'dropout' op, this function will insert
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
        a seed op before it to guarantee that two dropout op have the same outputs.
        """
        op_types = [op.desc.type() for op in self._ops]
        if "dropout" not in op_types:
            return

        op_idx = 0
        while op_idx < len(self._ops):
            cur_op = self._ops[op_idx]
            if "grad" in cur_op.type:
                break
            if cur_op.type != "dropout":
                op_idx += 1
                continue
            if cur_op.input("Seed") is not None and len(cur_op.input("Seed")):
                op_idx += 1
                continue

            cur_op_dist_attr = dist_context.get_op_dist_attr_for_program(cur_op)
            # insert seed op to guarantee that two dropout op have the same outputs
J
JZ-LIANG 已提交
136 137 138 139 140 141
            # NOTE Hack for adopt recompute for random control, for more info see dist_dropout.py
            # new seed added by recompute should have a prefix to distinguish with seed added by user or other moudule.
            op_unique_name = unique_name.generate("rc_seed")
            var_unique_name = unique_name.generate_with_ignorable_key(
                ".".join([op_unique_name, 'tmp'])
            )
142 143 144 145 146
            seed_var = self._block.create_var(
                name=var_unique_name,
                dtype='int32',
                type=core.VarDesc.VarType.LOD_TENSOR,
                persistable=False,
J
JZ-LIANG 已提交
147 148
                stop_gradient=False,
            )
149 150 151 152

            # set new seed_var's dist_attr
            ref_dims_mapping = [-1]
            ref_process_mesh = cur_op_dist_attr.process_mesh
J
JZ-LIANG 已提交
153 154 155 156 157 158 159 160 161
            seed_var_dist_attr = set_var_dist_attr(
                dist_context, seed_var, ref_dims_mapping, ref_process_mesh
            )

            seed = (
                0
                if cur_op.attr("fix_seed") is False
                else int(cur_op.attr("seed"))
            )
162 163 164 165 166
            seed_op = self._block._insert_op_without_sync(
                index=cur_op.idx,
                type="seed",
                inputs={},
                outputs={"Out": seed_var},
J
JZ-LIANG 已提交
167 168
                attrs={"seed": seed, "force_cpu": True},
            )
169 170
            # set new seed op's dist_attr
            naive_set_dist_op_attr_for_program_by_mesh_and_mapping(
J
JZ-LIANG 已提交
171 172
                seed_op, ref_process_mesh, ref_dims_mapping, dist_context
            )
173 174 175 176

            # modify dropout op's desc
            self._ops.insert(op_idx, seed_op)
            cur_op.desc.set_input("Seed", [var_unique_name])
177 178
            cur_op._remove_attr("fix_seed")
            cur_op._remove_attr("seed")
J
JZ-LIANG 已提交
179 180 181
            cur_op_dist_attr.set_input_dist_attr(
                seed_var.name, seed_var_dist_attr
            )
182 183
            op_idx += 2

184 185
        self._block._sync_with_cpp()

186 187 188 189 190 191 192 193 194

def _find_op_index(block, cur_op):
    for idx in range(block.desc.op_size()):
        if cur_op.desc == block.desc.op(idx):
            return idx
    return -1


def _get_stop_gradients(program, no_grad_set):
J
JZ-LIANG 已提交
195
    """get no grad var"""
196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211
    if no_grad_set is None:
        no_grad_set = set()
    else:
        no_grad_set = _get_no_grad_set_name(no_grad_set)

    no_grad_set_name = set()
    for var in program.list_vars():
        assert isinstance(var, Variable)
        if "@GRAD" in var.name:
            break
        if var.stop_gradient:
            no_grad_set_name.add(_append_grad_suffix_(var.name))
    no_grad_set_name.update(list(map(_append_grad_suffix_, no_grad_set)))
    return no_grad_set_name


J
JZ-LIANG 已提交
212 213 214
def _add_needed_descs_to_block(
    descs, block, main_block, in_memory_vars, dist_context
):
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
    """
    Get the recomputed ops which will insert the backward part
    """
    if len(descs) == 0:
        return []
    result_descs = []
    op_role_attr_name = core.op_proto_and_checker_maker.kOpRoleAttrName()
    backward = core.op_proto_and_checker_maker.OpRole.Backward
    for desc in descs:
        if isinstance(desc, framework.Operator):
            desc = desc.desc
        if isinstance(desc, tuple):
            desc = desc[0]
        is_needed = False
        for name in desc.output_arg_names():
            if main_block.has_var(name) and main_block.var(name).persistable:
                continue
            if name not in in_memory_vars:
                is_needed = True
        if is_needed:
            new_op_desc = block.desc.append_op()
            new_op_desc.copy_from(desc)
            set_dist_op_desc_original_id(new_op_desc, desc, dist_context)
            new_op_desc._set_attr(op_role_attr_name, backward)
            result_descs.append(new_op_desc)
    return result_descs


@register_pass("auto_parallel_recompute")
class RecomputePass(PassBase):
    def __init__(self):
        super(RecomputePass, self).__init__()
        self.set_attr("checkpoints", None)
        self.set_attr("loss", None)
        self.set_attr("dist_context", None)
        self.set_attr("no_grad_set", None)

    def _check_self(self):
        if self.get_attr("dist_context") is None:
            return False
        if self.get_attr("loss") is None:
            return False
        if self.get_attr("checkpoints") is None:
            return False
        return True

    def _check_conflict(self, other_pass):
        return True

264
    def _apply_single_impl(self, main_program, startup_program, context):
265 266 267 268 269
        checkpoints = self.get_attr("checkpoints")
        loss = self.get_attr("loss")
        no_grad_set = self.get_attr("no_grad_set")
        self._dist_context = self.get_attr("dist_context")

270 271
        main_block = main_program.global_block()
        no_grad_set_name = _get_stop_gradients(main_program, no_grad_set)
272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
        # get op_path which is related to loss
        op_path = _find_op_path_(main_block, [loss], [], no_grad_set_name)

        # step 1: build recompute state
        rc_state = RecomputeState(main_block, op_path)
        rc_state.modify_forward_desc_for_recompute(self._dist_context)
        rc_state.build_stats()
        checkpoints = rc_state.sort_checkpoints(checkpoints)
        segments = rc_state.get_recompute_segments(checkpoints)
        if segments == []:
            return

        # step 2: get vars_should_be_hold
        vars_should_be_hold = []
        for segment in segments:
            vars_should_be_hold.extend(
J
JZ-LIANG 已提交
288 289
                rc_state.get_out_of_subgraph_vars(segment[0], segment[1])
            )
290
        cross_vars = set(vars_should_be_hold) - set(checkpoints)
291 292 293
        logging.info(
            "found [{}] vars which cross recompute segment: [{}],"
            "better checkpoints might be set to reduce those vars".format(
J
JZ-LIANG 已提交
294 295 296
                len(cross_vars), cross_vars
            )
        )
297 298 299 300 301 302 303 304 305 306
        vars_should_be_hold.extend(rc_state.get_reserved_vars())
        vars_should_be_hold.extend(rc_state.get_input_nodes())
        vars_should_be_hold = list(set(vars_should_be_hold))
        vars_in_memory = vars_should_be_hold + checkpoints

        # step 3: get recomputed fwd ops desc
        var_name_dict = {}
        ckpt_ops_dict = {}
        buffer_block = main_block.program._create_block()
        for i, segment in enumerate(segments[::-1]):
J
JZ-LIANG 已提交
307
            fwd_ops = op_path[segment[0] : segment[1]]
308 309 310 311 312
            var_suffix = ".subprog_%d" % i
            for op in fwd_ops:
                input_and_output_names = []
                input_and_output_names.extend(op.desc.input_arg_names())
                input_and_output_names.extend(op.desc.output_arg_names())
J
JZ-LIANG 已提交
313 314 315
                cur_op_dist_attr = (
                    self._dist_context.get_op_dist_attr_for_program(op)
                )
316 317 318 319 320 321 322 323 324
                assert cur_op_dist_attr is not None
                for name in input_and_output_names:
                    if main_block.var(name).persistable or name in checkpoints:
                        continue
                    if name in vars_should_be_hold:
                        continue
                    if name not in var_name_dict:
                        ref_process_mesh = cur_op_dist_attr.process_mesh
                        if name in op.desc.input_arg_names():
J
JZ-LIANG 已提交
325 326 327
                            ref_dims_mapping = (
                                cur_op_dist_attr.get_input_dims_mapping(name)
                            )
328
                        else:
J
JZ-LIANG 已提交
329 330 331
                            ref_dims_mapping = (
                                cur_op_dist_attr.get_output_dims_mapping(name)
                            )
332 333 334 335 336 337 338 339 340 341
                        # record recomputed var's old_name and new_name (old_name.subprog_XXX)
                        # create new var with new name
                        var_name_dict[name] = name + var_suffix
                        ref_var = main_block.var(name)
                        rc_var = main_block.create_var(
                            name=var_name_dict[name],
                            shape=ref_var.shape,
                            dtype=ref_var.dtype,
                            type=ref_var.type,
                            persistable=ref_var.persistable,
J
JZ-LIANG 已提交
342 343
                            stop_gradient=ref_var.stop_gradient,
                        )
344
                        # set new recomputed var's dist attr
J
JZ-LIANG 已提交
345 346 347 348 349 350
                        set_var_dist_attr(
                            self._dist_context,
                            rc_var,
                            ref_dims_mapping,
                            ref_process_mesh,
                        )
351
            # get recomputed segment's descs
J
JZ-LIANG 已提交
352 353 354 355 356 357 358
            segment_descs = _add_needed_descs_to_block(
                fwd_ops,
                buffer_block,
                main_block,
                vars_in_memory,
                self._dist_context,
            )
359 360 361 362 363
            # rename recomputed ops' input and output var name
            for key in var_name_dict:
                _rename_arg_(segment_descs, key, var_name_dict[key])

            # NOTE: one forward op could be correspond to multiple xxx_grad op.
364
            # When traversing all grad_ops in reverse, need to set a flag to indicate
365 366
            # whether the ckpt and its segment_descs can be used.
            ckpt_op = op_path[segment[1] - 1]
367
            ckpt_ops_dict[ckpt_op.desc.original_id()] = [True, segment_descs]
368 369 370 371 372 373 374 375 376 377 378 379 380

        # step 4: insert recomputed fwd ops
        ops = main_block.ops
        loss_op = get_loss_op(main_block)
        loss_op_idx = _find_op_index(main_block, loss_op)
        dist_op_context = self._dist_context.dist_op_context
        assert loss_op_idx != -1
        # Traversing all grad_ops in reverse, and if the fwd op corresponding to reverse op is checkpoints,
        # segments ops should be inserted.
        for i in range(len(ops) - 1, loss_op_idx, -1):
            grad_op = ops[i]
            # remove some attrs of dropout_grad op's desc
            if grad_op.type == "dropout_grad":
381 382
                grad_op._remove_attr("fix_seed")
                grad_op._remove_attr("seed")
383 384 385

            # rename grad op's var_name which is not in 'vars_in_memory'
            for key in var_name_dict:
J
JZ-LIANG 已提交
386 387 388 389
                if (
                    key
                    not in grad_op.input_arg_names + grad_op.output_arg_names
                ):
390
                    continue
391 392 393 394
                self.reset_op_dist_attr(grad_op, var_name_dict)
                _rename_arg_([grad_op.desc], key, var_name_dict[key])

            # insert recomputed ops
395 396 397
            original_id = grad_op.desc.original_id()
            if original_id in dist_op_context.grad_op_id_to_op_id:
                fwd_op_id = dist_op_context.grad_op_id_to_op_id[original_id]
398 399 400 401 402 403
                if fwd_op_id in ckpt_ops_dict and ckpt_ops_dict[fwd_op_id][0]:
                    idx = grad_op.idx
                    while idx - 1 >= 0 and ops[idx - 1].type == "sum":
                        idx -= 1
                    segment_descs = ckpt_ops_dict[fwd_op_id][1]
                    for _, op_desc in reversed(list(enumerate(segment_descs))):
J
JZ-LIANG 已提交
404 405 406
                        rc_op = main_block._insert_op_without_sync(
                            idx, type='nop'
                        )
407
                        rc_desc = rc_op.desc
408
                        rc_desc.copy_from(op_desc)
409
                        rc_desc.set_original_id(rc_desc.id())
410 411
                        # set recomputed ops' dist attr
                        fwd_op_dist_attr = self._dist_context.get_op_dist_attr_for_program_with_id(
J
JZ-LIANG 已提交
412 413
                            op_desc.original_id()
                        )
414
                        assert fwd_op_dist_attr is not None
J
JZ-LIANG 已提交
415 416 417
                        self.set_op_dist_attr(
                            rc_op, fwd_op_dist_attr, var_name_dict
                        )
418 419 420

                    ckpt_ops_dict[fwd_op_id][0] = False

421
        main_program._sync_with_cpp()
422 423 424 425 426 427 428

    def reset_op_dist_attr(self, op, var_name_dict):
        op_dist_attr = self._dist_context.get_op_dist_attr_for_program(op)
        assert op_dist_attr is not None
        for input in op.desc.input_arg_names():
            if input in var_name_dict.keys():
                in_dist_attr = op_dist_attr.get_input_dist_attr(input)
J
JZ-LIANG 已提交
429 430 431
                op_dist_attr.set_input_dist_attr(
                    var_name_dict[input], in_dist_attr
                )
432 433 434
        for output in op.desc.output_arg_names():
            if output in var_name_dict.keys():
                out_dist_attr = op_dist_attr.get_output_dist_attr(output)
J
JZ-LIANG 已提交
435 436 437
                op_dist_attr.set_output_dist_attr(
                    var_name_dict[output], out_dist_attr
                )
438 439 440 441 442

    def set_op_dist_attr(self, op, old_dist_attr, var_name_dict):
        new_dist_attr = OperatorDistributedAttribute()
        new_dist_attr.is_recompute = True
        new_dist_attr.impl_idx = old_dist_attr.impl_idx
Z
zhaoyingli 已提交
443
        new_dist_attr.impl_type = old_dist_attr.impl_type
444 445 446 447
        new_dist_attr.process_mesh = old_dist_attr.process_mesh
        for input in old_dist_attr.inputs_dist_attrs.keys():
            if input in var_name_dict.keys():
                in_dist_attr = old_dist_attr.inputs_dist_attrs[input]
J
JZ-LIANG 已提交
448 449 450
                new_dist_attr.set_input_dist_attr(
                    var_name_dict[input], in_dist_attr
                )
451 452 453 454 455 456
            else:
                in_dist_attr = old_dist_attr.inputs_dist_attrs[input]
                new_dist_attr.set_input_dist_attr(input, in_dist_attr)
        for output in old_dist_attr.outputs_dist_attrs.keys():
            if output in var_name_dict.keys():
                out_dist_attr = old_dist_attr.outputs_dist_attrs[output]
J
JZ-LIANG 已提交
457 458 459
                new_dist_attr.set_output_dist_attr(
                    var_name_dict[output], out_dist_attr
                )
460 461 462 463
            else:
                out_dist_attr = old_dist_attr.outputs_dist_attrs[output]
                new_dist_attr.set_output_dist_attr(output, out_dist_attr)
        self._dist_context.set_op_dist_attr_for_program(op, new_dist_attr)