backward.py 27.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
# Copyright (c) 2023 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import collections
from collections.abc import Sequence

import paddle.ir
from paddle.autograd.backward_utils import State

"""
    grad: for templete test, will combine in paddle.grad .
    calc_gradient: for internal use, optest, parallel etc .
    calc_gradient_helper: for dygraph to static .
"""
__all__ = ['grad', 'calc_gradient', 'calc_gradient_helper']


def check_type(input, input_name, expected_type, op_name, extra_message=''):
    if not isinstance(input, expected_type):
        raise TypeError(
            f"The type of '{input_name}' in {op_name} must be {expected_type}, but received {type(input)}. {extra_message}"
        )


def _as_list(x):
    if x is None:
        return []
    return list(x) if isinstance(x, Sequence) else [x]


def check_all_puts(block, inputs, outputs):
    for output in outputs:
        if output.get_defining_op().get_parent_block() != block:
            raise ValueError("all outputs must be in the same block")
    for input in inputs:
        if input.get_defining_op().get_parent_block() != block:
            raise ValueError(
                "all inputs must be in the same block with outputs"
            )


def update_no_grad_set_by_stopgradient(block, no_grad_set):
    for op in block.ops:
55
        for value in op.results():
56 57 58 59 60 61 62 63 64
            if value.stop_gradient and value not in no_grad_set:
                no_grad_set.add(value)


def update_bwdop_structure(backward_ops, op_to_opgrad_list, grad_op):
    backward_ops.append(grad_op)
    op_to_opgrad_list.append(grad_op)


65
def prepare_grad_outputs(grad_outputs, outputs, state):
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
    """
    if grad_outputs is none, add fill_1 op to create grad_outputs,
    else check whether outputs shape and dtype is same to grad_outputs, otherwise raise error.

    if only part of op's outputs in outputs, add fill_0 op to create other grad_outputs.
    eg: split.

    update value_to_valuegrad and op_to_opgrad.

    return complete_outputs and complete_gradoutputs, backward_ops.

    """
    if not grad_outputs:
        grad_outputs = [None] * len(outputs)

    if len(grad_outputs) != len(outputs):
        raise ValueError(
            "grad_outputs should have the same length of as outputs."
        )
    backward_ops = []
    for i, grad in enumerate(grad_outputs):
        output = outputs[i]
        # fwd : op1 -> op2 -> op3 -> output
        # bwd : op1G <- op2G <- op3G <- outputG <- fillop/feedop
        if grad is None:
            output_grad = paddle.full(
                output.shape,
                1.0,
                dtype=output.dtype,
            )
            fillop = output_grad.get_defining_op()

            update_bwdop_structure(
                backward_ops,
100
                state.op_to_opgrad[output.get_defining_op()],
101 102
                fillop,
            )
103
            state.value_to_valuegrad[output] = [[output_grad]]
104 105 106 107 108 109 110 111 112 113 114 115 116
        else:
            if output.shape != grad.shape:
                raise ValueError(
                    "The shape of grad_output[%d] should be the same as the shape of output[%d]"
                    % (i, i)
                )
            if output.dtype != grad.dtype:
                raise ValueError(
                    "The dtype of grad_output[%d] should be the same as the dtype of output[%d]"
                    % (i, i)
                )
            feedop = grad.get_defining_op()
            update_bwdop_structure(
117 118 119
                backward_ops,
                state.op_to_opgrad[output.get_defining_op()],
                feedop,
120
            )
121
            state.value_to_valuegrad[output] = [[grad]]
122 123 124 125 126 127 128 129 130 131

    # add input for bwd first op
    complete_outputs = outputs
    complete_gradoutputs = grad_outputs

    visited_output = set()
    for output in outputs:
        if output in visited_output:
            continue
        for opresult in output.get_defining_op().results():
132
            if opresult in state.value_to_valuegrad:
133 134 135 136 137 138 139 140 141 142 143 144
                visited_output.add(opresult)
                continue
            else:
                grad_value = paddle.full(
                    opresult.shape,
                    0.0,
                    opresult.dtype,
                )
                fillop = grad.get_defining_op()

                update_bwdop_structure(
                    backward_ops,
145
                    state.op_to_opgrad[opresult.get_defining_op()],
146 147
                    fillop,
                )
148
                state.value_to_valuegrad[opresult] = [grad_value]
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203

                visited_output.add(opresult)

                complete_outputs.append(opresult)
                complete_gradoutputs.append(grad_value)

    return complete_outputs, complete_gradoutputs, backward_ops


def some_in_set(value_list, value_set):
    def operand2value(values):
        value_set = set()
        for item in values:
            if isinstance(item, paddle.ir.OpOperand):
                value_set.add(item.source())
            else:
                value_set.add(item)
        return value_set

    if operand2value(value_list) & operand2value(value_set):
        return True
    else:
        return False


def prune_ops(total_ops, inputs_set, outputs_set, no_grad_set):
    '''
    prune ops which do not in the path from inputs_set to outputs_set,
    prune ops which do not in the path from outputs_set to inputs_set,

    pruned op in total_ops is uneffective_ops, else is effective_ops

    '''
    relevant_op_flags = [True] * len(total_ops)
    # from input to output
    if inputs_set:
        for i, op in enumerate(total_ops):
            if some_in_set(op.results(), inputs_set):
                continue

            if some_in_set(op.operands_source(), inputs_set):
                for value in op.results():
                    if value not in no_grad_set:
                        inputs_set.add(value)
            else:
                relevant_op_flags[i] = False

    # from output to input
    for i, op in reversed(list(enumerate(total_ops))):
        if some_in_set(op.results(), outputs_set):
            for operand in op.operands_source():
                if operand not in no_grad_set:
                    outputs_set.add(operand)
        else:
            relevant_op_flags[i] = False
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
    # recover full op or full_Intarray op created by mutable attribute.
    total_ops_list = list(total_ops)
    for i, op in enumerate(total_ops_list):
        if relevant_op_flags[i] is False:
            for result in op.results():
                if result.has_one_use():
                    next_op = result.first_use().owner()
                    if (
                        next_op in total_ops
                        and relevant_op_flags[total_ops_list.index(next_op)]
                        is True
                    ):
                        relevant_op_flags[i] = True
                else:
                    continue

220 221 222 223 224 225 226 227 228 229 230 231
    effective_ops = [
        total_ops[i] for i in range(len(total_ops)) if relevant_op_flags[i]
    ]
    uneffective_ops = [
        total_ops[i]
        for i in reversed(range(len(total_ops)))
        if not relevant_op_flags[i]
    ]

    return effective_ops, uneffective_ops


232
def update_no_grad_set_after_prune(
233
    block, effective_forward_ops, no_grad_set, inputs, outputs
234 235
):
    '''
236
    update no_grad_set after forward prune
237 238 239 240 241 242 243 244 245 246 247 248

    from inputs to outputs add value not in the path to no_grad_set,
    from outputs to inputs add value not in the path to no_grad_set,
    '''
    inputs_set = set(inputs)
    if inputs_set:
        for op in block.ops:
            if some_in_set(op.operands_source(), inputs_set):
                for value in op.results():
                    if value not in no_grad_set:
                        inputs_set.add(value)

249
        for op in effective_forward_ops:
250
            for value in op.operands_source():
251
                if value not in inputs_set:
252 253 254 255
                    no_grad_set.add(value)

    outputs_set = set(outputs)
    no_grad_set_tmp = set()
256
    for op in reversed(effective_forward_ops):
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
        for output in op.results():
            if output not in outputs_set and not some_in_set(
                [output], set(op.operands_source())
            ):
                no_grad_set_tmp.add(output)

        for input in op.operands_source():
            if input not in no_grad_set:
                outputs_set.add(input)

    no_grad_set.update(no_grad_set_tmp)


def inverse_sort_op(ops):
    '''
    if topo graph is op1 -> op2 -> op3
    return [op3, op2, op1]

    '''

    # init pending_count[op] which descibes number of
    # pending edges for its grad_op

    pending_count = collections.defaultdict(int)
    ops_set = set(ops)
    sorted_list = []
    for op in ops:
        for x in op.operands():
            if x.source().get_defining_op() in ops_set:
                pending_count[x.source().get_defining_op()] += 1

    queue = collections.deque()

    for op in ops:
        if pending_count[op] == 0:
            queue.append(op)

    while queue:
        op = queue.popleft()
        sorted_list.append(op)

        for x in op.operands():
            x_op = x.source().get_defining_op()
            pending_count[x_op] -= 1
            if pending_count[x_op] == 0:
                queue.append(x_op)

    if len(sorted_list) != len(ops):
        raise ValueError(
            "inverse_sort_op wrong, sorted_list size is not equal to origin_list size"
        )

    return sorted_list


def append_backward_ops(
313
    block, effective_forward_ops, no_grad_set, backward_ops, state
314 315 316 317 318 319 320 321 322 323 324 325 326
):
    '''
    add grad_op in order of topological inverse sort
        eg:
        from :op1 -> v1 -> op2 -> v2 -> op3 -> v3
        to: og1_g <- v1_g <- op2_g <- v2_g <- op3_g <- v3_g

    if op has grad_op, prepare its grad_op's inputs by value_to_valuegrad,
        eg:
        value_to_valuegrad[v3] = [[v3_g]];
        v2_g = call_vjp(op3, [v3_g], [v2_stopgradient])


327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
    special pattern 1:
        v11 -> combine_op -> v1 -> op -> v3
        v12 ->
                             v2 ->
        value_to_valuegrad[v3] = [[v3_g]]

        v1 is inside python api, we don't describe it in backward process(state)
        so v1_grad is inside vjp, we don't describe it in backward process(state)
        [[v11_g, v12_g], v2_g] = call_vjp(combine_op, [v3_g], [[v11_stopgradient, v12_stopgradient], v2_stop_gradient)


        op_vjp is:
        v11_g <- split_op <- v1_g <- op_g <- v3_g
        v12_g <-
                             v2_g <-

        value_to_valuegrad[v11] = [[v11_g]]
        value_to_valuegrad[v12] = [[v12_g]]
        value_to_valuegrad[v2] = [[v2_g]]

347 348 349 350 351 352
    if op don't has grad_op, if it don't has input and it's output has more than
    one output_grad, add sumop for grad aggregation.
        (eg: full op and get_parameter op etc.)

    else continue to next op.
    '''
353

354
    def make_output_grad(op):
355
        zero_flag = [False] * op.num_results()
356
        output_grads = []
357 358 359 360 361
        for i, value in enumerate(op.results()):
            if (
                value not in state.value_to_valuegrad
                or state.value_to_valuegrad[value] is None
            ):
362 363 364 365
                if (
                    not value.use_empty()
                    and value.first_use().owner().name() == "builtin.split"
                ):
366 367 368 369
                    # pattern case:
                    # this fwd_op's output is vectorType, it will split to
                    # Type by builtin.split op, so need get from split op's ouput
                    split_zero_flag, split_output_grad = make_output_grad(
370
                        value.first_use().owner()
371 372
                    )
                    zero_flag[i] = all(split_zero_flag)
373
                    state.value_to_valuegrad[value] = [split_output_grad]
374
                else:
375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393
                    # first case:
                    # this fwd_op's output didn't used by other fwd_op,
                    # so no output_grad created.

                    # second case:
                    # last bwd_op return None because input in no_grad_set,
                    # but this bwd_op need a input.
                    grad_value = paddle.full(
                        value.shape,
                        0.0,
                        dtype=value.dtype,
                    )
                    fillop = grad_value.get_defining_op()

                    update_bwdop_structure(
                        backward_ops, state.op_to_opgrad[op], fillop
                    )
                    zero_flag[i] = True

394
                    state.value_to_valuegrad[value] = [[grad_value]]
395

396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416
            if len(state.value_to_valuegrad[value]) > 1:
                # one value is input of more than one fwd_op,
                # so more than one bwd_op create input_grad,
                # need add sum op to accumulate gradient

                paddle.add_n(
                    [item[0] for item in state.value_to_valuegrad[value]]
                )
                combineop = block.ops[len(block.ops) - 2]
                sumop = block.ops[len(block.ops) - 1]
                update_bwdop_structure(
                    backward_ops, state.op_to_opgrad[op], combineop
                )
                update_bwdop_structure(
                    backward_ops, state.op_to_opgrad[op], sumop
                )
                state.value_to_valuegrad[value] = [[sumop.result(0)]]
                state.value_to_sumvaluegrad[value] = state.value_to_valuegrad[
                    value
                ]

417 418
            output_grads.append(state.value_to_valuegrad[value][0][0])
        return zero_flag, output_grads
419

420
    def make_input_stopgradient(op):
421
        input_grad_stopgradients = []
422
        for input in op.operands_source():
423 424
            if input.get_defining_op().name() == "builtin.combine":
                stop_gradient = make_input_stopgradient(input.get_defining_op())
425
                input_grad_stopgradients.append(
426 427 428 429
                    [info[0] for info in stop_gradient]
                )
            else:
                if input in no_grad_set:
430
                    input_grad_stopgradients.append([True])
431
                else:
432 433
                    input_grad_stopgradients.append([False])
        return input_grad_stopgradients
434

435
    def update_input_grad_map(op, input_grads):
436
        for i, input in enumerate(op.operands_source()):
437
            if input.get_defining_op().name() == "builtin.combine":
438
                update_input_grad_map(input.get_defining_op(), input_grads[i])
439
            else:
440
                input_grad = input_grads[i]
441 442 443 444 445
                if isinstance(input_grad, list):
                    state.value_to_valuegrad[input].append(input_grad)
                else:
                    state.value_to_valuegrad[input].append([input_grad])

446
    # there are four patterns:
447 448 449 450 451 452
    # [builtin.combine , op1] (op1's one input is vectorType, outputs are not vectorType)
    # [op2 , builtin.split] (op2's inputs are not vectorType, one output is vectorType)
    # [builtin.combine , op3 , buitin.split] (op3's one input and one output are vectorType)
    # [op4] (op4's inputs and outputs are not vectorType)
    # einsum has twp vectorType outputs, special pattern

453
    clear_effective_forward_ops = []
454

455
    for op in effective_forward_ops:
456
        if op.name() != "builtin.combine" and op.name() != "builtin.split":
457
            clear_effective_forward_ops.append(op)
458

459
    for op in clear_effective_forward_ops:
460 461
        if paddle.framework.core.has_vjp(op):
            # prepare output_grad
462
            output_grads = []  # (opresult)
463
            zero_flag, output_grad = make_output_grad(op)
464
            output_grads.append(output_grad)
465 466 467

            # all(zero_flag) support this op has no contribution for grad
            # should be delete (prune sub_graph)
468
            if len(output_grads) == 0 or all(zero_flag):
469 470 471
                continue

            # prepare input_grad stop_gradient info.
472
            input_grad_stopgradients = make_input_stopgradient(op)
473

474
            # create grad_op
475
            before_ops_num = len(block.ops)
476 477
            input_grads = paddle.framework.core.call_vjp(
                op, output_grads, input_grad_stopgradients
478 479 480
            )
            after_ops_num = len(block.ops)

481
            # update grad_op structure
482 483
            for i in range(before_ops_num, after_ops_num):
                update_bwdop_structure(
484
                    backward_ops, state.op_to_opgrad[op], block.ops[i]
485 486
                )

487
            # update input_grad map
488
            update_input_grad_map(op, input_grads)
489

490 491 492 493 494
        else:
            if op.num_operands() == 0 and op.num_results() != 0:
                for value in op.results():
                    if len(state.value_to_valuegrad[value]) > 1:
                        # need add sum op
495 496 497 498 499 500 501
                        paddle.add_n(
                            [
                                item[0]
                                for item in state.value_to_valuegrad[value]
                            ]
                        )
                        combineop = block.ops[len(block.ops) - 2]
502
                        sumop = block.ops[len(block.ops) - 1]
503 504 505
                        update_bwdop_structure(
                            backward_ops, state.op_to_opgrad[op], combineop
                        )
506 507 508 509 510 511 512 513 514 515 516 517 518
                        update_bwdop_structure(
                            backward_ops, state.op_to_opgrad[op], sumop
                        )
                        state.value_to_valuegrad[value] = [[sumop.result(0)]]
                        state.value_to_sumvaluegrad[
                            value
                        ] = state.value_to_valuegrad[value]
                    else:
                        state.op_to_opgrad[op] = []
                else:
                    state.op_to_opgrad[op] = []


519
def create_backward_prune_set(inputs, outputs, no_grad_set, state):
520
    outputs_set = set()
521 522 523 524 525 526 527 528
    for input_ in inputs:
        if not input_.use_empty():
            for item in input_.first_use().owner().operands_source():
                if state.value_to_valuegrad[item] != []:
                    outputs_set.add(state.value_to_valuegrad[item][0][0])
        else:
            raise ValueError("input privided by inputs has no use")

529 530 531 532
    inputs_set = set()
    for output in outputs:
        if state.value_to_valuegrad[output] != []:
            inputs_set.add(state.value_to_valuegrad[output][0][0])
533 534
    inputs_set_tmp = set()
    for out_grad in inputs_set:
535 536 537
        if not out_grad.use_empty():
            for item in out_grad.first_use().owner().operands_source():
                inputs_set_tmp.add(item)
538 539
    inputs_set.update(inputs_set_tmp)

540 541 542 543 544 545
    no_gradvar_set = set()  # grad_value of value in no_grad_set
    for key in state.value_to_valuegrad:
        if key in no_grad_set:
            no_gradvar_set.add(state.value_to_valuegrad[key][0][0])
    for key in state.value_to_sumvaluegrad:
        if key in no_grad_set:
546
            for item in state.value_to_sumvaluegrad[key][0]:
547 548 549 550 551 552 553 554 555 556 557 558 559 560 561
                no_gradvar_set.add(item)

    return outputs_set, inputs_set, no_gradvar_set


def remove_op(block, op, state):
    '''
    remove op from block
    '''
    block.remove_op(op)
    if state.opgrad_to_op[op] != []:
        fwd_op = state.opgrad_to_op[op][0]
        state.op_to_opgrad[fwd_op].remove(op)

    for valuegrad in op.results():
562 563 564 565 566 567 568 569
        if state.valuegrad_to_value[valuegrad] != []:
            value = state.valuegrad_to_value[valuegrad][0]
            state.value_to_valuegrad[value] = []

            if value in state.sumvaluegrad_to_value:
                raise ValueError(
                    'input_grad in [%s] is value which need to sum ', op.name()
                )
570 571 572 573 574 575 576 577 578 579


def calc_gradient_helper(outputs, inputs, grad_outputs, no_grad_set):
    block = outputs[0].get_defining_op().get_parent_block()
    state = State(block.get_parent_program())
    # check all inputs and outputs in the same block
    check_all_puts(block, inputs, outputs)
    # update no_grad_set if some value stop_gradient=True
    update_no_grad_set_by_stopgradient(block, no_grad_set)
    complete_outputs, _, backward_ops = prepare_grad_outputs(
580
        grad_outputs, outputs, state
581 582 583 584
    )

    inputs_set = set(inputs)
    outputs_set = set(complete_outputs)
585
    effective_forward_ops, _ = prune_ops(
586 587
        block.ops, inputs_set, outputs_set, no_grad_set
    )
588
    update_no_grad_set_after_prune(
589
        block, effective_forward_ops, no_grad_set, inputs, complete_outputs
590 591
    )

592
    inverse_effective_forward_ops = inverse_sort_op(effective_forward_ops)
593 594

    append_backward_ops(
595
        block, inverse_effective_forward_ops, no_grad_set, backward_ops, state
596 597 598
    )
    # now value_to_valuegrad should be value <-> value (add sum op for the same values's gradvalue)

599
    outputs_set, inputs_set, no_gradvar_set = create_backward_prune_set(
600 601 602 603 604 605
        inputs, complete_outputs, no_grad_set, state
    )
    _, remove_ops = prune_ops(
        backward_ops, inputs_set, outputs_set, no_gradvar_set
    )

606
    state.turn_map()
607 608
    for bwd_op in inverse_sort_op(remove_ops):
        remove_op(block, bwd_op, state)
609
    state.turn_map()
610 611

    input_grad_map = state.value_to_valuegrad
612

613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719
    return input_grad_map


def calc_gradient(outputs, inputs, grad_outputs, no_grad_set):
    """
    caclulate gradient of input

    Args:
        outputs (Value|list(Value)|tuple(Value)): the output Value or
            Value list/tuple of the graph to compute gradients.
        inputs (Value|list(Value)|tuple(Value)): the input Value or
            Value list/tuple of the graph to compute gradients. The returned
            values of this API are the gradients of `inputs` .
        grad_outputs (Value|list(Value|None)|tuple(Value|None), optional):
            initial gradient values of `outputs` . If `grad_outputs` is None,
            the initial gradient values of `outputs` would be Values filled with 1;
            if `grad_outputs` is not None, it must have the same length as `outputs` ,
            and in this case, the initial gradient value of the i-th `outputs` would
            be: (1) a Value filled with 1 when the i-th element of `grad_outputs`
            is None; (2) the i-th element of `grad_outputs` when the i-th element of
            `grad_outputs` is a Value. Default None.
        no_grad_set (set(Value), optional):
            the Values whose gradients are not needed to compute. Default None.

    Return:
        list[Value]:A list of gradients for inputs
        If an input does not affect targets, the corresponding gradient Tensor
        will be None
        TODO if allow_unused=False raise TypeError() if input_grad has None
    """
    # record input value and its gradient (Value to Value)
    input_to_inputgrad_map = calc_gradient_helper(
        outputs, inputs, grad_outputs=grad_outputs, no_grad_set=no_grad_set
    )

    inputgrad = []
    for input in inputs:
        inputgrad.append(
            input_to_inputgrad_map[input][0][0]
            if input_to_inputgrad_map[input] != []
            else None
        )
    return inputgrad


def grad(
    outputs,
    inputs,
    grad_outputs=None,
    retain_graph=None,
    create_graph=False,
    only_inputs=True,
    allow_unused=False,
    no_grad_vars=None,
):
    '''
    .. note::
        **This API is ONLY available in imperative mode.**

    This API computes the sum of gradients of `outputs` with respect to each `inputs` .

    Parameters:
        outputs (Value|list(Value)|tuple(Value)): the output Value or
            Value list/tuple of the graph to compute gradients.
        inputs (Value|list(Value)|tuple(Value)): the input Value or
            Value list/tuple of the graph to compute gradients. The returned
            values of this API are the gradients of `inputs` .
        grad_outputs (Value|list(Value|None)|tuple(Value|None), optional):
            initial gradient values of `outputs` . If `grad_outputs` is None,
            the initial gradient values of `outputs` would be Values filled with 1;
            if `grad_outputs` is not None, it must have the same length as `outputs` ,
            and in this case, the initial gradient value of the i-th `outputs` would
            be: (1) a Value filled with 1 when the i-th element of `grad_outputs`
            is None; (2) the i-th element of `grad_outputs` when the i-th element of
            `grad_outputs` is a Value. Default None.
        retain_graph (bool, optional): whether to retain the forward graph which
            is used to calculate the gradient. When it is True, the graph would
            be retained, in which way users can calculate backward twice for the
            same graph. When it is False, the graph would be freed. Default None,
            which means it is equal to `create_graph` .
        create_graph (bool, optional): whether to create the gradient graphs of
            the computing process. When it is True, higher order derivatives are
            supported to compute; when it is False, the gradient graphs of the
            computing process would be discarded. Default False.
        only_inputs (bool, optional): whether to only compute the gradients of
            `inputs` . If it is False, the gradients of all remaining leaf
            Values in the graph would be also computed and accumulated.
            If it is True, only the gradients of `inputs` would be computed.
            Default True. only_inputs=False is under development, and it is
            not supported yet.
        allow_unused (bool, optional): whether to raise error or return None if some
            Values of `inputs` are unreachable in the graph. If some Values of
            `inputs` are unreachable in the graph (i.e., their gradients are None),
            error would be raised if allow_unused=False, or None would be returned as
            their gradients if allow_unused=True. Default False.
        no_grad_vars (Value|list(Value)|tuple(Value)|set(Value), optional):
            the Values whose gradients are not needed to compute. Default None.

    Returns:
        list: a list of Values, whose length is the same as the Value number
        inside `inputs`, and the i-th returned Value is the sum of gradients of
        `outputs` with respect to the i-th `inputs`.
    '''
    check_type(
        outputs,
        'outputs',
        ((paddle.ir.Value, paddle.ir.OpResult), list, tuple),
720
        'paddle.autograd.backward.grad',
721 722 723 724 725
    )
    check_type(
        inputs,
        'inputs',
        ((paddle.ir.Value, paddle.ir.OpResult), list, tuple),
726
        'paddle.autograd.backward.grad',
727 728 729 730 731
    )
    check_type(
        grad_outputs,
        'grad_outputs',
        ((paddle.ir.Value, paddle.ir.OpResult), list, tuple, type(None)),
732
        'paddle.autograd.backward.grad',
733 734 735 736 737 738
    )

    check_type(
        no_grad_vars,
        'no_grad_vars',
        ((paddle.ir.Value, paddle.ir.OpResult), list, tuple, set, type(None)),
739
        'paddle.autograd.backward.grad',
740 741 742 743 744 745 746 747 748 749 750 751 752 753
    )
    outputs = _as_list(outputs)
    inputs = _as_list(inputs)
    grad_outputs = _as_list(grad_outputs)
    if no_grad_vars is None:
        no_grad_set = set()
    elif no_grad_vars is not set:
        no_grad_set = set(no_grad_vars)
    else:
        no_grad_set = no_grad_vars

    input_grad = calc_gradient(outputs, inputs, grad_outputs, no_grad_set)

    return input_grad