test_vjp_prim.py 6.4 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
        paddle.framework.set_flags({"FLAGS_enable_new_ir_api": True})
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
        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.full",
            "pd.scale",
89
            "pd.multiply",
90 91 92 93 94 95 96 97 98 99 100 101 102 103
            "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 已提交
104
        paddle.framework.core._set_prim_backward_enabled(False)
105
        paddle.framework.set_flags({"FLAGS_enable_new_ir_api": False})
106 107

    def test_divide_grad_no_prim(self):
C
Charles-hit 已提交
108 109
        newir_program = get_ir_divide_program()
        paddle.framework.core._set_prim_backward_enabled(False)
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
        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 已提交
126 127
        newir_program = get_ir_sum_program()
        paddle.framework.core._set_prim_backward_enabled(True)
128
        paddle.framework.set_flags({"FLAGS_enable_new_ir_api": True})
129
        dout = newir_program.block().ops[-3].result(0)
130
        out_grads = [[dout]]
131
        stop_gradients = [[False], [True]]
132 133 134 135
        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]
136
        self.assertEqual(len(grad_outs), 2)
137 138
        self.assertEqual(len(newir_program.block().ops), 8)
        self.assertEqual(expand_op.result(0), grad_outs[0][0])
139
        self.assertEqual(grad_outs[1][0], None)
140 141 142 143 144 145 146 147 148 149 150 151
        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 已提交
152
        paddle.framework.core._set_prim_backward_enabled(False)
153
        paddle.framework.set_flags({"FLAGS_enable_new_ir_api": False})
154 155

    def test_sum_grad_no_prim(self):
C
Charles-hit 已提交
156 157
        newir_program = get_ir_sum_program()
        paddle.framework.core._set_prim_backward_enabled(False)
158 159
        dout = newir_program.block().ops[-2].result(0)
        out_grads = [[dout]]
160
        stop_gradients = [[False], [True]]
161 162 163
        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)
164
        self.assertEqual(len(grad_outs), 2)
165 166 167
        self.assertEqual(
            grad_outs[0][0].get_defining_op().name(), "pd.sum_grad"
        )
168
        self.assertEqual(grad_outs[1][0], None)
169
        self.assertEqual(len(newir_program.block().ops), 5)
170 171 172 173


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