test_assign_op.py 11.2 KB
Newer Older
1
#   Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
D
dzhwinter 已提交
2
#
D
dzhwinter 已提交
3 4 5
# 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
D
dzhwinter 已提交
6
#
D
dzhwinter 已提交
7
#     http://www.apache.org/licenses/LICENSE-2.0
D
dzhwinter 已提交
8
#
D
dzhwinter 已提交
9 10 11 12 13 14
# 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.

Y
Yu Yang 已提交
15
import unittest
16 17 18 19 20 21

import gradient_checker
import numpy as np
import op_test
from decorator_helper import prog_scope

22
import paddle
23
import paddle.fluid as fluid
24
import paddle.fluid.core as core
25
import paddle.fluid.layers as layers
26 27
from paddle.fluid import Program, program_guard
from paddle.fluid.backward import append_backward
Y
Yu Yang 已提交
28 29 30 31


class TestAssignOp(op_test.OpTest):
    def setUp(self):
C
chentianyu03 已提交
32
        self.python_api = paddle.assign
Y
Yu Yang 已提交
33
        self.op_type = "assign"
34
        x = np.random.random(size=(100, 10)).astype('float64')
Y
Yu Yang 已提交
35 36 37 38
        self.inputs = {'X': x}
        self.outputs = {'Out': x}

    def test_forward(self):
39
        paddle.enable_static()
C
chentianyu03 已提交
40
        self.check_output(check_eager=True)
41
        paddle.disable_static()
Y
Yu Yang 已提交
42 43

    def test_backward(self):
44
        paddle.enable_static()
C
chentianyu03 已提交
45
        self.check_grad(['X'], 'Out', check_eager=True)
46
        paddle.disable_static()
Y
Yu Yang 已提交
47 48


49 50
class TestAssignFP16Op(op_test.OpTest):
    def setUp(self):
C
chentianyu03 已提交
51
        self.python_api = paddle.assign
52 53 54 55 56 57
        self.op_type = "assign"
        x = np.random.random(size=(100, 10)).astype('float16')
        self.inputs = {'X': x}
        self.outputs = {'Out': x}

    def test_forward(self):
58
        paddle.enable_static()
C
chentianyu03 已提交
59
        self.check_output(check_eager=True)
60
        paddle.disable_static()
61 62

    def test_backward(self):
63
        paddle.enable_static()
C
chentianyu03 已提交
64
        self.check_grad(['X'], 'Out', check_eager=True)
65
        paddle.disable_static()
66 67


68 69
class TestAssignOpWithLoDTensorArray(unittest.TestCase):
    def test_assign_LoDTensorArray(self):
70
        paddle.enable_static()
71 72 73 74 75
        main_program = Program()
        startup_program = Program()
        with program_guard(main_program):
            x = fluid.data(name='x', shape=[100, 10], dtype='float32')
            x.stop_gradient = False
76 77 78
            y = fluid.layers.fill_constant(
                shape=[100, 10], dtype='float32', value=1
            )
79
            z = paddle.add(x=x, y=y)
80
            i = fluid.layers.fill_constant(shape=[1], dtype='int64', value=0)
81
            init_array = paddle.tensor.array_write(x=z, i=i)
82
            array = fluid.layers.assign(init_array)
83
            sums = paddle.tensor.array_read(array=init_array, i=i)
84
            mean = paddle.mean(sums)
85 86
            append_backward(mean)

87 88 89 90 91
        place = (
            fluid.CUDAPlace(0)
            if core.is_compiled_with_cuda()
            else fluid.CPUPlace()
        )
92 93 94 95
        exe = fluid.Executor(place)
        feed_x = np.random.random(size=(100, 10)).astype('float32')
        ones = np.ones((100, 10)).astype('float32')
        feed_add = feed_x + ones
96 97 98 99 100
        res = exe.run(
            main_program,
            feed={'x': feed_x},
            fetch_list=[sums.name, x.grad_name],
        )
101 102
        np.testing.assert_allclose(res[0], feed_add, rtol=1e-05)
        np.testing.assert_allclose(res[1], ones / 1000.0, rtol=1e-05)
103
        paddle.disable_static()
104 105


106
class TestAssignOpError(unittest.TestCase):
107
    def test_errors(self):
108
        paddle.enable_static()
109 110
        with program_guard(Program(), Program()):
            # The type of input must be Variable or numpy.ndarray.
111 112 113
            x1 = fluid.create_lod_tensor(
                np.array([[-1]]), [[1]], fluid.CPUPlace()
            )
114 115
            self.assertRaises(TypeError, fluid.layers.assign, x1)
            # When the type of input is numpy.ndarray, the dtype of input must be float32, int32.
116 117
            x2 = np.array([[2.5, 2.5]], dtype='uint8')
            self.assertRaises(TypeError, fluid.layers.assign, x2)
118
        paddle.disable_static()
119 120


121 122
class TestAssignOApi(unittest.TestCase):
    def test_assign_LoDTensorArray(self):
123
        paddle.enable_static()
124 125 126 127 128
        main_program = Program()
        startup_program = Program()
        with program_guard(main_program):
            x = fluid.data(name='x', shape=[100, 10], dtype='float32')
            x.stop_gradient = False
129 130 131
            y = fluid.layers.fill_constant(
                shape=[100, 10], dtype='float32', value=1
            )
132
            z = paddle.add(x=x, y=y)
133
            i = fluid.layers.fill_constant(shape=[1], dtype='int64', value=0)
134
            init_array = paddle.tensor.array_write(x=z, i=i)
135
            array = paddle.assign(init_array)
136
            sums = paddle.tensor.array_read(array=init_array, i=i)
137
            mean = paddle.mean(sums)
138 139
            append_backward(mean)

140 141 142 143 144
        place = (
            fluid.CUDAPlace(0)
            if core.is_compiled_with_cuda()
            else fluid.CPUPlace()
        )
145 146 147 148
        exe = fluid.Executor(place)
        feed_x = np.random.random(size=(100, 10)).astype('float32')
        ones = np.ones((100, 10)).astype('float32')
        feed_add = feed_x + ones
149 150 151 152 153
        res = exe.run(
            main_program,
            feed={'x': feed_x},
            fetch_list=[sums.name, x.grad_name],
        )
154 155
        np.testing.assert_allclose(res[0], feed_add, rtol=1e-05)
        np.testing.assert_allclose(res[1], ones / 1000.0, rtol=1e-05)
156
        paddle.disable_static()
157 158 159

    def test_assign_NumpyArray(self):
        with fluid.dygraph.guard():
160
            array = np.random.random(size=(100, 10)).astype(np.bool_)
161 162
            result1 = paddle.zeros(shape=[3, 3], dtype='float32')
            paddle.assign(array, result1)
163
        np.testing.assert_allclose(result1.numpy(), array, rtol=1e-05)
164 165 166 167 168 169

    def test_assign_NumpyArray1(self):
        with fluid.dygraph.guard():
            array = np.random.random(size=(100, 10)).astype(np.float32)
            result1 = paddle.zeros(shape=[3, 3], dtype='float32')
            paddle.assign(array, result1)
170
        np.testing.assert_allclose(result1.numpy(), array, rtol=1e-05)
171 172 173 174 175 176

    def test_assign_NumpyArray2(self):
        with fluid.dygraph.guard():
            array = np.random.random(size=(100, 10)).astype(np.int32)
            result1 = paddle.zeros(shape=[3, 3], dtype='float32')
            paddle.assign(array, result1)
177
        np.testing.assert_allclose(result1.numpy(), array, rtol=1e-05)
178 179 180 181 182 183

    def test_assign_NumpyArray3(self):
        with fluid.dygraph.guard():
            array = np.random.random(size=(100, 10)).astype(np.int64)
            result1 = paddle.zeros(shape=[3, 3], dtype='float32')
            paddle.assign(array, result1)
184
        np.testing.assert_allclose(result1.numpy(), array, rtol=1e-05)
185

186 187 188
    def test_assign_List(self):
        l = [1, 2, 3]
        result = paddle.assign(l)
189
        np.testing.assert_allclose(result.numpy(), np.array(l), rtol=1e-05)
190 191 192 193 194

    def test_assign_BasicTypes(self):
        result1 = paddle.assign(2)
        result2 = paddle.assign(3.0)
        result3 = paddle.assign(True)
195 196 197
        np.testing.assert_allclose(result1.numpy(), np.array([2]), rtol=1e-05)
        np.testing.assert_allclose(result2.numpy(), np.array([3.0]), rtol=1e-05)
        np.testing.assert_allclose(result3.numpy(), np.array([1]), rtol=1e-05)
198

199
    def test_clone(self):
C
chentianyu03 已提交
200 201
        self.python_api = paddle.clone

202 203
        x = paddle.ones([2])
        x.stop_gradient = False
姜永久 已提交
204
        x.retain_grads()
205
        clone_x = paddle.clone(x)
姜永久 已提交
206
        clone_x.retain_grads()
207 208 209 210

        y = clone_x**3
        y.backward()

211 212 213
        np.testing.assert_array_equal(x, [1, 1])
        np.testing.assert_array_equal(clone_x.grad.numpy(), [3, 3])
        np.testing.assert_array_equal(x.grad.numpy(), [3, 3])
214 215 216 217 218 219 220
        paddle.enable_static()

        with program_guard(Program(), Program()):
            x_np = np.random.randn(2, 3).astype('float32')
            x = paddle.static.data("X", shape=[2, 3])
            clone_x = paddle.clone(x)
            exe = paddle.static.Executor()
221 222 223 224 225
            y_np = exe.run(
                paddle.static.default_main_program(),
                feed={'X': x_np},
                fetch_list=[clone_x],
            )[0]
226

227
        np.testing.assert_array_equal(y_np, x_np)
228
        paddle.disable_static()
229

230 231 232

class TestAssignOpErrorApi(unittest.TestCase):
    def test_errors(self):
233
        paddle.enable_static()
234 235
        with program_guard(Program(), Program()):
            # The type of input must be Variable or numpy.ndarray.
236 237 238
            x1 = fluid.create_lod_tensor(
                np.array([[-1]]), [[1]], fluid.CPUPlace()
            )
239 240
            self.assertRaises(TypeError, paddle.assign, x1)
            # When the type of input is numpy.ndarray, the dtype of input must be float32, int32.
241 242
            x2 = np.array([[2.5, 2.5]], dtype='uint8')
            self.assertRaises(TypeError, paddle.assign, x2)
243
        paddle.disable_static()
244

245 246 247 248 249 250
    def test_type_error(self):
        paddle.enable_static()
        with program_guard(Program(), Program()):
            x = [paddle.randn([3, 3]), paddle.randn([3, 3])]
            # not support to assign list(var)
            self.assertRaises(TypeError, paddle.assign, x)
251
        paddle.disable_static()
252

253

254 255 256 257 258 259 260 261 262 263 264 265 266 267 268
class TestAssignDoubleGradCheck(unittest.TestCase):
    def assign_wrapper(self, x):
        return paddle.fluid.layers.assign(x[0])

    @prog_scope()
    def func(self, place):
        # the shape of input variable should be clearly specified, not inlcude -1.
        eps = 0.005
        dtype = np.float32

        data = layers.data('data', [3, 4, 5], False, dtype)
        data.persistable = True
        out = paddle.fluid.layers.assign(data)
        data_arr = np.random.uniform(-1, 1, data.shape).astype(dtype)

269 270 271 272 273 274
        gradient_checker.double_grad_check(
            [data], out, x_init=[data_arr], place=place, eps=eps
        )
        gradient_checker.double_grad_check_for_dygraph(
            self.assign_wrapper, [data], out, x_init=[data_arr], place=place
        )
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299

    def test_grad(self):
        paddle.enable_static()
        places = [fluid.CPUPlace()]
        if core.is_compiled_with_cuda():
            places.append(fluid.CUDAPlace(0))
        for p in places:
            self.func(p)


class TestAssignTripleGradCheck(unittest.TestCase):
    def assign_wrapper(self, x):
        return paddle.fluid.layers.assign(x[0])

    @prog_scope()
    def func(self, place):
        # the shape of input variable should be clearly specified, not inlcude -1.
        eps = 0.005
        dtype = np.float32

        data = layers.data('data', [3, 4, 5], False, dtype)
        data.persistable = True
        out = paddle.fluid.layers.assign(data)
        data_arr = np.random.uniform(-1, 1, data.shape).astype(dtype)

300 301 302 303 304 305
        gradient_checker.triple_grad_check(
            [data], out, x_init=[data_arr], place=place, eps=eps
        )
        gradient_checker.triple_grad_check_for_dygraph(
            self.assign_wrapper, [data], out, x_init=[data_arr], place=place
        )
306 307 308 309 310 311 312 313 314 315

    def test_grad(self):
        paddle.enable_static()
        places = [fluid.CPUPlace()]
        if core.is_compiled_with_cuda():
            places.append(fluid.CUDAPlace(0))
        for p in places:
            self.func(p)


Y
Yu Yang 已提交
316 317
if __name__ == '__main__':
    unittest.main()