test_vjp_prim.py 6.2 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
# 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 unittest

import paddle
from paddle import ir
from paddle.fluid.core import call_vjp

paddle.enable_static()


C
Charles-hit 已提交
24
def get_ir_divide_program():
25 26 27 28 29 30 31 32 33 34
    main_program, start_program = (
        paddle.static.Program(),
        paddle.static.Program(),
    )
    with paddle.static.program_guard(main_program, start_program):
        x = paddle.tensor.fill_constant(
            shape=[1, 4], dtype='float32', value=2.0
        )
        x.stop_gradient = False
        y = paddle.tensor.fill_constant(shape=[4], dtype='float32', value=1.0)
35
        y.stop_gradient = False
36 37 38
        dout = paddle.tensor.fill_constant(
            shape=[1, 4], dtype='float32', value=1.0
        )
39
        dout.stop_gradient = False
40 41 42 43 44
        out = paddle.divide(x, y)
    newir_program = ir.translate_to_new_ir(main_program.desc)
    return newir_program


C
Charles-hit 已提交
45
def get_ir_sum_program():
46 47 48 49 50 51 52 53 54
    main_program, start_program = (
        paddle.static.Program(),
        paddle.static.Program(),
    )
    with paddle.static.program_guard(main_program, start_program):
        x = paddle.tensor.fill_constant(
            shape=[4, 5], dtype='float32', value=2.0
        )
        x.stop_gradient = False
55 56
        dout = paddle.tensor.fill_constant(shape=[], dtype='float32', value=1.0)
        dout.stop_gradient = False
57 58 59 60 61 62 63
        out = paddle.sum(x)
    newir_program = ir.translate_to_new_ir(main_program.desc)
    return newir_program


class TestVjpPrim(unittest.TestCase):
    def test_divide_grad_prim_case1(self):
C
Charles-hit 已提交
64 65
        newir_program = get_ir_divide_program()
        paddle.framework.core._set_prim_backward_enabled(True)
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
        dout = newir_program.block().ops[-2].result(0)
        out_grads = [[dout]]
        stop_gradients = [[False], [False]]
        divide_op = newir_program.block().ops[-1]
        with paddle.ir.core.program_guard(newir_program):
            grad_outs = call_vjp(divide_op, out_grads, stop_gradients)
        reshape_op2 = newir_program.block().ops[-1]
        reshape_op1 = newir_program.block().ops[-8]
        self.assertEqual(len(grad_outs), 2)
        self.assertEqual(len(newir_program.block().ops), 21)
        self.assertEqual(reshape_op2.result(0), grad_outs[0][0])
        self.assertEqual(reshape_op1.result(0), grad_outs[1][0])
        all_op_names = [
            "pd.full",
            "pd.full",
            "pd.full",
            "pd.divide",
            "pd.full",
            "pd.elementwise_pow",
            "pd.divide",
            "pd.multiply",
            "pd.full",
            "pd.scale",
            "pd.full_int_array",
            "pd.sum",
            "pd.full_int_array",
            "pd.reshape",
            "pd.full",
            "pd.divide",
            "pd.multiply",
            "pd.full_int_array",
            "pd.sum",
            "pd.full_int_array",
            "pd.reshape",
        ]
        for idx, op in enumerate(newir_program.block().ops):
            self.assertEqual(op.name(), all_op_names[idx])
C
Charles-hit 已提交
103
        paddle.framework.core._set_prim_backward_enabled(False)
104 105

    def test_divide_grad_no_prim(self):
C
Charles-hit 已提交
106 107
        newir_program = get_ir_divide_program()
        paddle.framework.core._set_prim_backward_enabled(False)
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
        dout = newir_program.block().ops[-2].result(0)
        out_grads = [[dout]]
        stop_gradients = [[False], [False]]
        divide_op = newir_program.block().ops[-1]
        with paddle.ir.core.program_guard(newir_program):
            grad_outs = call_vjp(divide_op, out_grads, stop_gradients)
        self.assertEqual(len(grad_outs), 2)
        self.assertEqual(
            grad_outs[0][0].get_defining_op().name(), "pd.divide_grad"
        )
        self.assertEqual(
            grad_outs[1][0].get_defining_op().name(), "pd.divide_grad"
        )
        self.assertEqual(len(newir_program.block().ops), 5)

    def test_sum_grad_prim(self):
C
Charles-hit 已提交
124 125
        newir_program = get_ir_sum_program()
        paddle.framework.core._set_prim_backward_enabled(True)
126
        dout = newir_program.block().ops[-3].result(0)
127
        out_grads = [[dout]]
128
        stop_gradients = [[False], [True]]
129 130 131 132
        sum_op = newir_program.block().ops[-1]
        with paddle.ir.core.program_guard(newir_program):
            grad_outs = call_vjp(sum_op, out_grads, stop_gradients)
        expand_op = newir_program.block().ops[-1]
133
        self.assertEqual(len(grad_outs), 2)
134 135
        self.assertEqual(len(newir_program.block().ops), 8)
        self.assertEqual(expand_op.result(0), grad_outs[0][0])
136
        self.assertEqual(grad_outs[1][0], None)
137 138 139 140 141 142 143 144 145 146 147 148
        all_op_names = [
            "pd.full",
            "pd.full",
            "pd.full_int_array",
            "pd.sum",
            "pd.full_int_array",
            "pd.reshape",
            "pd.full_int_array",
            "pd.expand",
        ]
        for idx, op in enumerate(newir_program.block().ops):
            self.assertEqual(op.name(), all_op_names[idx])
C
Charles-hit 已提交
149
        paddle.framework.core._set_prim_backward_enabled(False)
150 151

    def test_sum_grad_no_prim(self):
C
Charles-hit 已提交
152 153
        newir_program = get_ir_sum_program()
        paddle.framework.core._set_prim_backward_enabled(False)
154 155
        dout = newir_program.block().ops[-2].result(0)
        out_grads = [[dout]]
156
        stop_gradients = [[False], [True]]
157 158 159
        sum_op = newir_program.block().ops[-1]
        with paddle.ir.core.program_guard(newir_program):
            grad_outs = call_vjp(sum_op, out_grads, stop_gradients)
160
        self.assertEqual(len(grad_outs), 2)
161 162 163
        self.assertEqual(
            grad_outs[0][0].get_defining_op().name(), "pd.sum_grad"
        )
164
        self.assertEqual(grad_outs[1][0], None)
165
        self.assertEqual(len(newir_program.block().ops), 5)
166 167 168 169


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