test_assign_op.py 9.7 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.

15 16
from __future__ import print_function

17
import op_test
18
import numpy as np
Y
Yu Yang 已提交
19
import unittest
20
import paddle
21 22 23 24
import paddle.fluid.core as core
from paddle.fluid.op import Operator
import paddle.fluid as fluid
from paddle.fluid import compiler, Program, program_guard
25
from paddle.fluid.backward import append_backward
Y
Yu Yang 已提交
26 27 28


class TestAssignOp(op_test.OpTest):
29

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

    def test_forward(self):
38
        fluid.set_flags({"FLAGS_retain_grad_for_all_tensor": True})
C
chentianyu03 已提交
39
        self.check_output(check_eager=True)
40
        fluid.set_flags({"FLAGS_retain_grad_for_all_tensor": False})
Y
Yu Yang 已提交
41 42

    def test_backward(self):
43
        fluid.set_flags({"FLAGS_retain_grad_for_all_tensor": True})
C
chentianyu03 已提交
44
        self.check_grad(['X'], 'Out', check_eager=True)
45
        fluid.set_flags({"FLAGS_retain_grad_for_all_tensor": False})
Y
Yu Yang 已提交
46 47


48
class TestAssignFP16Op(op_test.OpTest):
49

50
    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
        fluid.set_flags({"FLAGS_retain_grad_for_all_tensor": True})
C
chentianyu03 已提交
59
        self.check_output(check_eager=True)
60
        fluid.set_flags({"FLAGS_retain_grad_for_all_tensor": False})
61 62

    def test_backward(self):
63
        fluid.set_flags({"FLAGS_retain_grad_for_all_tensor": True})
C
chentianyu03 已提交
64
        self.check_grad(['X'], 'Out', check_eager=True)
65
        fluid.set_flags({"FLAGS_retain_grad_for_all_tensor": False})
66 67


68
class TestAssignOpWithLoDTensorArray(unittest.TestCase):
69

70
    def test_assign_LoDTensorArray(self):
71
        fluid.set_flags({"FLAGS_retain_grad_for_all_tensor": True})
72 73 74 75 76
        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
77 78 79
            y = fluid.layers.fill_constant(shape=[100, 10],
                                           dtype='float32',
                                           value=1)
80 81 82 83 84 85 86
            z = fluid.layers.elementwise_add(x=x, y=y)
            i = fluid.layers.fill_constant(shape=[1], dtype='int64', value=0)
            init_array = fluid.layers.array_write(x=z, i=i)
            array = fluid.layers.assign(init_array)
            sums = fluid.layers.array_read(array=init_array, i=i)
            mean = fluid.layers.mean(sums)
            append_backward(mean)
87
        fluid.set_flags({"FLAGS_retain_grad_for_all_tensor": False})
88

89 90
        place = fluid.CUDAPlace(
            0) if core.is_compiled_with_cuda() else fluid.CPUPlace()
91 92 93 94 95 96 97 98 99 100 101
        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
        res = exe.run(main_program,
                      feed={'x': feed_x},
                      fetch_list=[sums.name, x.grad_name])
        self.assertTrue(np.allclose(res[0], feed_add))
        self.assertTrue(np.allclose(res[1], ones / 1000.0))


102
class TestAssignOpError(unittest.TestCase):
103

104 105 106
    def test_errors(self):
        with program_guard(Program(), Program()):
            # The type of input must be Variable or numpy.ndarray.
107 108
            x1 = fluid.create_lod_tensor(np.array([[-1]]), [[1]],
                                         fluid.CPUPlace())
109 110
            self.assertRaises(TypeError, fluid.layers.assign, x1)
            # When the type of input is numpy.ndarray, the dtype of input must be float32, int32.
111 112
            x2 = np.array([[2.5, 2.5]], dtype='uint8')
            self.assertRaises(TypeError, fluid.layers.assign, x2)
113 114


115
class TestAssignOApi(unittest.TestCase):
116

117 118 119 120 121 122
    def test_assign_LoDTensorArray(self):
        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
123 124 125
            y = fluid.layers.fill_constant(shape=[100, 10],
                                           dtype='float32',
                                           value=1)
126 127 128 129 130 131 132 133
            z = fluid.layers.elementwise_add(x=x, y=y)
            i = fluid.layers.fill_constant(shape=[1], dtype='int64', value=0)
            init_array = fluid.layers.array_write(x=z, i=i)
            array = paddle.assign(init_array)
            sums = fluid.layers.array_read(array=init_array, i=i)
            mean = fluid.layers.mean(sums)
            append_backward(mean)

134 135
        place = fluid.CUDAPlace(
            0) if core.is_compiled_with_cuda() else fluid.CPUPlace()
136 137 138 139 140 141 142 143 144 145 146 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
        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
        res = exe.run(main_program,
                      feed={'x': feed_x},
                      fetch_list=[sums.name, x.grad_name])
        self.assertTrue(np.allclose(res[0], feed_add))
        self.assertTrue(np.allclose(res[1], ones / 1000.0))

    def test_assign_NumpyArray(self):
        with fluid.dygraph.guard():
            array = np.random.random(size=(100, 10)).astype(np.bool)
            result1 = paddle.zeros(shape=[3, 3], dtype='float32')
            paddle.assign(array, result1)
        self.assertTrue(np.allclose(result1.numpy(), array))

    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)
        self.assertTrue(np.allclose(result1.numpy(), array))

    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)
        self.assertTrue(np.allclose(result1.numpy(), array))

    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)
        self.assertTrue(np.allclose(result1.numpy(), array))

174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
    def test_assign_List(self):
        paddle.disable_static()
        l = [1, 2, 3]
        result = paddle.assign(l)
        self.assertTrue(np.allclose(result.numpy(), np.array(l)))
        paddle.enable_static()

    def test_assign_BasicTypes(self):
        paddle.disable_static()
        result1 = paddle.assign(2)
        result2 = paddle.assign(3.0)
        result3 = paddle.assign(True)
        self.assertTrue(np.allclose(result1.numpy(), np.array([2])))
        self.assertTrue(np.allclose(result2.numpy(), np.array([3.0])))
        self.assertTrue(np.allclose(result3.numpy(), np.array([1])))
        paddle.enable_static()

191 192
    def test_clone(self):
        paddle.disable_static()
193
        fluid.set_flags({"FLAGS_retain_grad_for_all_tensor": True})
C
chentianyu03 已提交
194 195
        self.python_api = paddle.clone

196 197 198 199 200 201 202 203 204 205
        x = paddle.ones([2])
        x.stop_gradient = False
        clone_x = paddle.clone(x)

        y = clone_x**3
        y.backward()

        self.assertTrue(np.array_equal(x, [1, 1]), True)
        self.assertTrue(np.array_equal(clone_x.grad.numpy(), [3, 3]), True)
        self.assertTrue(np.array_equal(x.grad.numpy(), [3, 3]), True)
206
        fluid.set_flags({"FLAGS_retain_grad_for_all_tensor": False})
207 208 209 210 211 212 213 214 215 216 217 218 219
        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()
            y_np = exe.run(paddle.static.default_main_program(),
                           feed={'X': x_np},
                           fetch_list=[clone_x])[0]

        self.assertTrue(np.array_equal(y_np, x_np), True)

220 221

class TestAssignOpErrorApi(unittest.TestCase):
222

223
    def test_errors(self):
224
        fluid.set_flags({"FLAGS_retain_grad_for_all_tensor": True})
225 226
        with program_guard(Program(), Program()):
            # The type of input must be Variable or numpy.ndarray.
227 228
            x1 = fluid.create_lod_tensor(np.array([[-1]]), [[1]],
                                         fluid.CPUPlace())
229 230
            self.assertRaises(TypeError, paddle.assign, x1)
            # When the type of input is numpy.ndarray, the dtype of input must be float32, int32.
231 232
            x2 = np.array([[2.5, 2.5]], dtype='uint8')
            self.assertRaises(TypeError, paddle.assign, x2)
233
        fluid.set_flags({"FLAGS_retain_grad_for_all_tensor": False})
234

235 236 237 238 239 240 241
    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)

242

Y
Yu Yang 已提交
243
if __name__ == '__main__':
244
    paddle.enable_static()
Y
Yu Yang 已提交
245
    unittest.main()