test_detach.py 7.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
# 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.

15 16
import unittest

17 18
import numpy as np

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


class Test_Detach(unittest.TestCase):
    def generate_Data(self):
27 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 36
            linear_w_param_attrs = paddle.ParamAttr(
                initializer=paddle.nn.initializer.Constant(5.0)
37
            )
38 39
            linear_b_param_attrs = paddle.ParamAttr(
                initializer=paddle.nn.initializer.Constant(6.0)
40 41 42 43
            )
            linear = Linear(
                4,
                10,
44
                weight_attr=linear_w_param_attrs,
45 46
                bias_attr=linear_b_param_attrs,
            )
47 48
            linear1_w_param_attrs = paddle.ParamAttr(
                initializer=paddle.nn.initializer.Constant(7.0)
49
            )
50 51
            linear1_b_param_attrs = paddle.ParamAttr(
                initializer=paddle.nn.initializer.Constant(8.0)
52 53 54 55
            )
            linear1 = Linear(
                10,
                1,
56
                weight_attr=linear1_w_param_attrs,
57 58
                bias_attr=linear1_b_param_attrs,
            )
59 60
            linear2_w_param_attrs = paddle.ParamAttr(
                initializer=paddle.nn.initializer.Constant(9.0)
61
            )
62 63
            linear2_b_param_attrs = paddle.ParamAttr(
                initializer=paddle.nn.initializer.Constant(10.0)
64 65 66 67
            )
            linear2 = Linear(
                10,
                1,
68
                weight_attr=linear2_w_param_attrs,
69 70
                bias_attr=linear2_b_param_attrs,
            )
71
            data = to_variable(data)
72 73 74
            x = linear(data)
            x1 = linear1(x)
            x2 = linear2(x)
75 76 77 78 79 80 81 82
            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():
83 84
            linear_w_param_attrs = paddle.ParamAttr(
                initializer=paddle.nn.initializer.Constant(5.0)
85
            )
86 87
            linear_b_param_attrs = paddle.ParamAttr(
                initializer=paddle.nn.initializer.Constant(6.0)
88 89 90 91
            )
            linear = Linear(
                4,
                10,
92
                weight_attr=linear_w_param_attrs,
93 94
                bias_attr=linear_b_param_attrs,
            )
95 96
            linear1_w_param_attrs = paddle.ParamAttr(
                initializer=paddle.nn.initializer.Constant(7.0)
97
            )
98 99
            linear1_b_param_attrs = paddle.ParamAttr(
                initializer=paddle.nn.initializer.Constant(8.0)
100 101 102 103
            )
            linear1 = Linear(
                10,
                1,
104
                weight_attr=linear1_w_param_attrs,
105 106
                bias_attr=linear1_b_param_attrs,
            )
107
            data = to_variable(data)
108
            x = linear(data)
109
            x.retain_grads()
110
            x1 = linear1(x)
111 112 113 114 115 116 117 118
            loss = x1
            # print(loss, loss.shape)
            loss.backward()
            return x.gradient()

    def detach_multi(self):
        data = self.generate_Data()
        with fluid.dygraph.guard():
119 120
            linear_w_param_attrs = paddle.ParamAttr(
                initializer=paddle.nn.initializer.Constant(5.0)
121
            )
122
            linear_b_param_attrs = fluid.ParamAttr(
123 124 125 126 127
                initializer=fluid.initializer.Constant(6.0)
            )
            linear = Linear(
                4,
                10,
128
                weight_attr=linear_w_param_attrs,
129 130
                bias_attr=linear_b_param_attrs,
            )
131 132
            linear1_w_param_attrs = paddle.ParamAttr(
                initializer=paddle.nn.initializer.Constant(7.0)
133
            )
134
            linear1_b_param_attrs = fluid.ParamAttr(
135 136 137 138 139
                initializer=fluid.initializer.Constant(8.0)
            )
            linear1 = Linear(
                10,
                1,
140
                weight_attr=linear1_w_param_attrs,
141 142
                bias_attr=linear1_b_param_attrs,
            )
143 144
            linear2_w_param_attrs = paddle.ParamAttr(
                initializer=paddle.nn.initializer.Constant(9.0)
145
            )
146 147
            linear2_b_param_attrs = paddle.ParamAttr(
                initializer=paddle.nn.initializer.Constant(10.0)
148 149 150 151
            )
            linear2 = Linear(
                10,
                1,
152
                weight_attr=linear2_w_param_attrs,
153 154
                bias_attr=linear2_b_param_attrs,
            )
155
            data = to_variable(data)
156
            x = linear(data)
157
            x.retain_grads()
158
            x_detach = x.detach()
159 160
            x1 = linear1(x)
            x2 = linear2(x_detach)
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177
            loss = x1 + x2
            # print(loss, loss.shape)
            loss.backward()
            return x.gradient()

    def test_NoDetachMulti_DetachMulti(self):
        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)

    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)


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 204 205 206 207 208 209 210 211 212
class TestInplace(unittest.TestCase):
    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)
213
            with self.assertRaisesRegex(
214 215 216 217 218
                RuntimeError,
                "received tensor_version:{} != wrapper_version_snapshot:{}".format(
                    1, 0
                ),
            ):
219 220 221
                loss.backward()


222 223
if __name__ == '__main__':
    unittest.main()