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

from __future__ import print_function

import numpy as np

19 20
import paddle
import paddle.fluid as fluid
21
from paddle.fluid.dygraph import Linear
22 23 24 25 26 27 28 29 30 31 32 33 34 35
from paddle.fluid.dygraph.base import to_variable

import unittest


class Test_Detach(unittest.TestCase):
    def generate_Data(self):
        data = np.array(
            [[1, 8, 3, 9], [7, 20, 9, 6], [4, 6, 8, 10]]).astype('float32')
        return data

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

    def detach_multi(self):
        data = self.generate_Data()
        with fluid.dygraph.guard():
104
            linear_w_param_attrs = fluid.ParamAttr(
105
                initializer=fluid.initializer.Constant(5.0))
106
            linear_b_param_attrs = fluid.ParamAttr(
107
                initializer=fluid.initializer.Constant(6.0))
108 109 110 111 112 113
            linear = Linear(
                4,
                10,
                param_attr=linear_w_param_attrs,
                bias_attr=linear_b_param_attrs)
            linear1_w_param_attrs = fluid.ParamAttr(
114
                initializer=fluid.initializer.Constant(7.0))
115
            linear1_b_param_attrs = fluid.ParamAttr(
116
                initializer=fluid.initializer.Constant(8.0))
117 118 119 120 121 122
            linear1 = Linear(
                10,
                1,
                param_attr=linear1_w_param_attrs,
                bias_attr=linear1_b_param_attrs)
            linear2_w_param_attrs = fluid.ParamAttr(
123
                initializer=fluid.initializer.Constant(9.0))
124
            linear2_b_param_attrs = fluid.ParamAttr(
125
                initializer=fluid.initializer.Constant(10.0))
126 127 128 129 130
            linear2 = Linear(
                10,
                1,
                param_attr=linear2_w_param_attrs,
                bias_attr=linear2_b_param_attrs)
131
            data = to_variable(data)
132
            x = linear(data)
133
            x_detach = x.detach()
134 135
            x1 = linear1(x)
            x2 = linear2(x_detach)
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
            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)

    def test_detach_exception(self):
        x = fluid.layers.data(name="a", shape=[3, 4], dtype='float32')
        y = fluid.layers.fc(input=x, size=10, bias_attr=True)
        try:
            y_detach = y.detach()
        except Exception as e:
158 159 160 161
            # Here is to check
            assert type(e) == AssertionError
            assert str(
                e
162
            ) == "'detach' should be called by imperative Varible in imperative mode, please use fluid.dygraph.guard() as context to run it in imperative mode"
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 204 205 206
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)
            with self.assertRaisesRegexp(
                    RuntimeError,
                    "received tensor_version:{} != wrapper_version_snapshot:{}".
                    format(1, 0)):
                loss.backward()


207 208
if __name__ == '__main__':
    unittest.main()