test_detach.py 7.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
# Copyright (c) 2019 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 numpy as np

17 18
import paddle
import paddle.fluid as fluid
19
from paddle.fluid.dygraph import Linear
20 21 22 23 24 25
from paddle.fluid.dygraph.base import to_variable

import unittest


class Test_Detach(unittest.TestCase):
26

27
    def generate_Data(self):
28 29
        data = np.array([[1, 8, 3, 9], [7, 20, 9, 6], [4, 6, 8,
                                                       10]]).astype('float32')
30 31 32 33 34
        return data

    def no_detach_multi(self):
        data = self.generate_Data()
        with fluid.dygraph.guard():
35
            linear_w_param_attrs = fluid.ParamAttr(
36
                initializer=fluid.initializer.Constant(5.0))
37
            linear_b_param_attrs = fluid.ParamAttr(
38
                initializer=fluid.initializer.Constant(6.0))
39 40 41 42
            linear = Linear(4,
                            10,
                            param_attr=linear_w_param_attrs,
                            bias_attr=linear_b_param_attrs)
43
            linear1_w_param_attrs = fluid.ParamAttr(
44
                initializer=fluid.initializer.Constant(7.0))
45
            linear1_b_param_attrs = fluid.ParamAttr(
46
                initializer=fluid.initializer.Constant(8.0))
47 48 49 50
            linear1 = Linear(10,
                             1,
                             param_attr=linear1_w_param_attrs,
                             bias_attr=linear1_b_param_attrs)
51
            linear2_w_param_attrs = fluid.ParamAttr(
52
                initializer=fluid.initializer.Constant(9.0))
53
            linear2_b_param_attrs = fluid.ParamAttr(
54
                initializer=fluid.initializer.Constant(10.0))
55 56 57 58
            linear2 = Linear(10,
                             1,
                             param_attr=linear2_w_param_attrs,
                             bias_attr=linear2_b_param_attrs)
59
            data = to_variable(data)
60 61 62
            x = linear(data)
            x1 = linear1(x)
            x2 = linear2(x)
63 64 65 66 67 68 69 70
            loss = x1 + x2
            # print(loss, loss.shape)
            loss.backward()
            return x.gradient()

    def no_detach_single(self):
        data = self.generate_Data()
        with fluid.dygraph.guard():
71
            linear_w_param_attrs = fluid.ParamAttr(
72
                initializer=fluid.initializer.Constant(5.0))
73
            linear_b_param_attrs = fluid.ParamAttr(
74
                initializer=fluid.initializer.Constant(6.0))
75 76 77 78
            linear = Linear(4,
                            10,
                            param_attr=linear_w_param_attrs,
                            bias_attr=linear_b_param_attrs)
79
            linear1_w_param_attrs = fluid.ParamAttr(
80
                initializer=fluid.initializer.Constant(7.0))
81
            linear1_b_param_attrs = fluid.ParamAttr(
82
                initializer=fluid.initializer.Constant(8.0))
83 84 85 86
            linear1 = Linear(10,
                             1,
                             param_attr=linear1_w_param_attrs,
                             bias_attr=linear1_b_param_attrs)
87
            data = to_variable(data)
88 89
            x = linear(data)
            x1 = linear1(x)
90 91 92 93 94 95 96 97
            loss = x1
            # print(loss, loss.shape)
            loss.backward()
            return x.gradient()

    def detach_multi(self):
        data = self.generate_Data()
        with fluid.dygraph.guard():
98
            linear_w_param_attrs = fluid.ParamAttr(
99
                initializer=fluid.initializer.Constant(5.0))
100
            linear_b_param_attrs = fluid.ParamAttr(
101
                initializer=fluid.initializer.Constant(6.0))
102 103 104 105
            linear = Linear(4,
                            10,
                            param_attr=linear_w_param_attrs,
                            bias_attr=linear_b_param_attrs)
106
            linear1_w_param_attrs = fluid.ParamAttr(
107
                initializer=fluid.initializer.Constant(7.0))
108
            linear1_b_param_attrs = fluid.ParamAttr(
109
                initializer=fluid.initializer.Constant(8.0))
110 111 112 113
            linear1 = Linear(10,
                             1,
                             param_attr=linear1_w_param_attrs,
                             bias_attr=linear1_b_param_attrs)
114
            linear2_w_param_attrs = fluid.ParamAttr(
115
                initializer=fluid.initializer.Constant(9.0))
116
            linear2_b_param_attrs = fluid.ParamAttr(
117
                initializer=fluid.initializer.Constant(10.0))
118 119 120 121
            linear2 = Linear(10,
                             1,
                             param_attr=linear2_w_param_attrs,
                             bias_attr=linear2_b_param_attrs)
122
            data = to_variable(data)
123
            x = linear(data)
124
            x_detach = x.detach()
125 126
            x1 = linear1(x)
            x2 = linear2(x_detach)
127 128 129 130 131 132
            loss = x1 + x2
            # print(loss, loss.shape)
            loss.backward()
            return x.gradient()

    def test_NoDetachMulti_DetachMulti(self):
133
        fluid.set_flags({"FLAGS_retain_grad_for_all_tensor": True})
134 135 136 137
        array_no_detach_multi = self.no_detach_multi()
        array_detach_multi = self.detach_multi()

        assert not np.array_equal(array_no_detach_multi, array_detach_multi)
138
        fluid.set_flags({"FLAGS_retain_grad_for_all_tensor": False})
139 140 141 142 143 144 145

    def test_NoDetachSingle_DetachMulti(self):
        array_no_detach_single = self.no_detach_single()
        array_detach_multi = self.detach_multi()
        assert np.array_equal(array_no_detach_single, array_detach_multi)


146
class TestInplace(unittest.TestCase):
147

148 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
    def test_forward_version(self):
        with paddle.fluid.dygraph.guard():
            var = paddle.to_tensor(np.ones((4, 2, 3)).astype(np.float32))
            self.assertEqual(var.inplace_version, 0)
            detach_var_1 = var.detach()
            self.assertEqual(detach_var_1.inplace_version, 0)

            var[0] = 1.1
            self.assertEqual(var.inplace_version, 1)

            detach_var_2 = var.detach()
            self.assertEqual(detach_var_2.inplace_version, 1)

            var[0] = 3
            self.assertEqual(detach_var_1.inplace_version, 2)
            self.assertEqual(detach_var_2.inplace_version, 2)

    def test_backward_error(self):
        # It raises an error because the inplace operator will result
        # in incorrect gradient computation.
        with paddle.fluid.dygraph.guard():
            var_a = paddle.ones(shape=[4, 2, 3], dtype="float32")
            var_a.stop_gradient = False

            var_b = var_a**2

            # Here, the gradient computation will use the value of var_b
            var_c = var_b**2
            detach_var_b = var_b.detach()
            detach_var_b[1:2] = 3.3  # var_b is modified inplace

            var_d = var_b**2

            loss = paddle.nn.functional.relu(var_c + var_d)
            with self.assertRaisesRegexp(
                    RuntimeError,
                    "received tensor_version:{} != wrapper_version_snapshot:{}".
                    format(1, 0)):
                loss.backward()


189 190
if __name__ == '__main__':
    unittest.main()