test_variable.py 11.0 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

Y
Yu Yang 已提交
17
import unittest
18
import paddle
19
from paddle.fluid.framework import default_main_program, Program, convert_np_dtype_to_dtype_, in_dygraph_mode
W
wopeizl 已提交
20
import paddle.fluid as fluid
H
Hongyu Liu 已提交
21
import paddle.fluid.layers as layers
22
import paddle.fluid.core as core
Y
Yu Yang 已提交
23 24
import numpy as np

25 26
paddle.enable_static()

Y
Yu Yang 已提交
27 28 29

class TestVariable(unittest.TestCase):
    def test_np_dtype_convert(self):
30
        DT = core.VarDesc.VarType
31
        convert = convert_np_dtype_to_dtype_
Y
Yu Yang 已提交
32 33 34 35 36 37 38
        self.assertEqual(DT.FP32, convert(np.float32))
        self.assertEqual(DT.FP16, convert("float16"))
        self.assertEqual(DT.FP64, convert("float64"))
        self.assertEqual(DT.INT32, convert("int32"))
        self.assertEqual(DT.INT16, convert("int16"))
        self.assertEqual(DT.INT64, convert("int64"))
        self.assertEqual(DT.BOOL, convert("bool"))
Q
qingqing01 已提交
39 40
        self.assertEqual(DT.INT8, convert("int8"))
        self.assertEqual(DT.UINT8, convert("uint8"))
Y
Yu Yang 已提交
41

Y
Yu Yang 已提交
42
    def test_var(self):
Y
Yu Yang 已提交
43
        b = default_main_program().current_block()
Y
Yu Yang 已提交
44 45
        w = b.create_var(
            dtype="float64", shape=[784, 100], lod_level=0, name="fc.w")
46
        self.assertNotEqual(str(w), "")
47
        self.assertEqual(core.VarDesc.VarType.FP64, w.dtype)
Y
Yu Yang 已提交
48 49
        self.assertEqual((784, 100), w.shape)
        self.assertEqual("fc.w", w.name)
50
        self.assertEqual("fc.w@GRAD", w.grad_name)
Y
Yu Yang 已提交
51 52 53
        self.assertEqual(0, w.lod_level)

        w = b.create_var(name='fc.w')
54
        self.assertEqual(core.VarDesc.VarType.FP64, w.dtype)
Y
Yu Yang 已提交
55 56
        self.assertEqual((784, 100), w.shape)
        self.assertEqual("fc.w", w.name)
57
        self.assertEqual("fc.w@GRAD", w.grad_name)
Y
Yu Yang 已提交
58 59 60 61 62
        self.assertEqual(0, w.lod_level)

        self.assertRaises(ValueError,
                          lambda: b.create_var(name="fc.w", shape=(24, 100)))

Y
Yu Yang 已提交
63 64 65 66 67 68 69
    def test_step_scopes(self):
        prog = Program()
        b = prog.current_block()
        var = b.create_var(
            name='step_scopes', type=core.VarDesc.VarType.STEP_SCOPES)
        self.assertEqual(core.VarDesc.VarType.STEP_SCOPES, var.type)

W
wopeizl 已提交
70
    def _test_slice(self, place):
W
wopeizl 已提交
71 72 73 74 75
        b = default_main_program().current_block()
        w = b.create_var(dtype="float64", shape=[784, 100, 100], lod_level=0)

        for i in range(3):
            nw = w[i]
H
Hongyu Liu 已提交
76
            self.assertEqual((100, 100), nw.shape)
W
wopeizl 已提交
77 78 79 80

        nw = w[:]
        self.assertEqual((784, 100, 100), nw.shape)

H
Hongyu Liu 已提交
81
        nw = w[:, :]
W
wopeizl 已提交
82 83
        self.assertEqual((784, 100, 100), nw.shape)

H
Hongyu Liu 已提交
84 85
        nw = w[:, :, -1]
        self.assertEqual((784, 100), nw.shape)
W
wopeizl 已提交
86

H
Hongyu Liu 已提交
87 88 89 90 91 92 93
        nw = w[1, 1, 1]

        self.assertEqual(len(nw.shape), 1)
        self.assertEqual(nw.shape[0], 1)

        nw = w[:, :, :-1]
        self.assertEqual((784, 100, 99), nw.shape)
W
wopeizl 已提交
94 95 96 97 98 99 100 101 102 103 104 105 106 107

        self.assertEqual(0, nw.lod_level)

        main = fluid.Program()
        with fluid.program_guard(main):
            exe = fluid.Executor(place)
            tensor_array = np.array(
                [[[1, 2, 3], [4, 5, 6], [7, 8, 9]],
                 [[10, 11, 12], [13, 14, 15], [16, 17, 18]],
                 [[19, 20, 21], [22, 23, 24], [25, 26, 27]]]).astype('float32')
            var = fluid.layers.assign(tensor_array)
            var1 = var[0, 1, 1]
            var2 = var[1:]
            var3 = var[0:1]
H
Hongyu Liu 已提交
108 109
            var4 = var[::-1]
            var5 = var[1, 1:, 1:]
W
wopeizl 已提交
110
            var_reshape = fluid.layers.reshape(var, [3, -1, 3])
H
Hongyu Liu 已提交
111 112 113 114 115 116 117 118 119 120
            var6 = var_reshape[:, :, -1]
            var7 = var[:, :, :-1]
            var8 = var[:1, :1, :1]
            var9 = var[:-1, :-1, :-1]
            var10 = var[::-1, :1, :-1]
            var11 = var[:-1, ::-1, -1:]
            var12 = var[1:2, 2:, ::-1]
            var13 = var[2:10, 2:, -2:-1]
            var14 = var[1:-1, 0:2, ::-1]
            var15 = var[::-1, ::-1, ::-1]
W
wopeizl 已提交
121 122 123

            x = fluid.layers.data(name='x', shape=[13], dtype='float32')
            y = fluid.layers.fc(input=x, size=1, act=None)
H
Hongyu Liu 已提交
124
            y_1 = y[:, 0]
W
wopeizl 已提交
125 126 127 128 129
            feeder = fluid.DataFeeder(place=place, feed_list=[x])
            data = []
            data.append((np.random.randint(10, size=[13]).astype('float32')))
            exe.run(fluid.default_startup_program())

W
wopeizl 已提交
130
            local_out = exe.run(main,
W
wopeizl 已提交
131
                                feed=feeder.feed([data]),
W
wopeizl 已提交
132 133
                                fetch_list=[
                                    var, var1, var2, var3, var4, var5, var6,
H
Hongyu Liu 已提交
134 135
                                    var7, var8, var9, var10, var11, var12,
                                    var13, var14, var15
W
wopeizl 已提交
136 137
                                ])

H
Hongyu Liu 已提交
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
            self.assertTrue(
                np.array_equal(local_out[1], tensor_array[0, 1, 1:2]))
            self.assertTrue(np.array_equal(local_out[2], tensor_array[1:]))
            self.assertTrue(np.array_equal(local_out[3], tensor_array[0:1]))
            self.assertTrue(np.array_equal(local_out[4], tensor_array[::-1]))
            self.assertTrue(
                np.array_equal(local_out[5], tensor_array[1, 1:, 1:]))
            self.assertTrue(
                np.array_equal(local_out[6],
                               tensor_array.reshape((3, -1, 3))[:, :, -1]))
            self.assertTrue(
                np.array_equal(local_out[7], tensor_array[:, :, :-1]))
            self.assertTrue(
                np.array_equal(local_out[8], tensor_array[:1, :1, :1]))
            self.assertTrue(
                np.array_equal(local_out[9], tensor_array[:-1, :-1, :-1]))
            self.assertTrue(
                np.array_equal(local_out[10], tensor_array[::-1, :1, :-1]))
            self.assertTrue(
                np.array_equal(local_out[11], tensor_array[:-1, ::-1, -1:]))
            self.assertTrue(
                np.array_equal(local_out[12], tensor_array[1:2, 2:, ::-1]))
            self.assertTrue(
                np.array_equal(local_out[13], tensor_array[2:10, 2:, -2:-1]))
            self.assertTrue(
                np.array_equal(local_out[14], tensor_array[1:-1, 0:2, ::-1]))
            self.assertTrue(
                np.array_equal(local_out[15], tensor_array[::-1, ::-1, ::-1]))
W
wopeizl 已提交
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 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
    def _test_slice_index_tensor(self, place):
        data = np.random.rand(2, 3).astype("float32")
        prog = paddle.static.Program()
        with paddle.static.program_guard(prog):
            x = paddle.assign(data)
            idx0 = [1, 0]
            idx1 = [0, 1]
            idx2 = [0, 0]
            idx3 = [1, 1]

            out0 = x[paddle.assign(np.array(idx0))]
            out1 = x[paddle.assign(np.array(idx1))]
            out2 = x[paddle.assign(np.array(idx2))]
            out3 = x[paddle.assign(np.array(idx3))]

        exe = paddle.static.Executor(place)
        result = exe.run(prog, fetch_list=[out0, out1, out2, out3])

        expected = [data[idx0], data[idx1], data[idx2], data[idx3]]

        self.assertTrue((result[0] == expected[0]).all())
        self.assertTrue((result[1] == expected[1]).all())
        self.assertTrue((result[2] == expected[2]).all())
        self.assertTrue((result[3] == expected[3]).all())

        with self.assertRaises(IndexError):
            one = paddle.ones(shape=[1])
            res = x[one, [0, 0]]

    def _test_slice_index_list(self, place):
        data = np.random.rand(2, 3).astype("float32")
        prog = paddle.static.Program()
        with paddle.static.program_guard(prog):
            x = paddle.assign(data)
            idx0 = [1, 0]
            idx1 = [0, 1]
            idx2 = [0, 0]
            idx3 = [1, 1]

            out0 = x[idx0]
            out1 = x[idx1]
            out2 = x[idx2]
            out3 = x[idx3]

        exe = paddle.static.Executor(place)
        result = exe.run(prog, fetch_list=[out0, out1, out2, out3])

        expected = [data[idx0], data[idx1], data[idx2], data[idx3]]

        self.assertTrue((result[0] == expected[0]).all())
        self.assertTrue((result[1] == expected[1]).all())
        self.assertTrue((result[2] == expected[2]).all())
        self.assertTrue((result[3] == expected[3]).all())

        with self.assertRaises(IndexError):
            res = x[[1, 0], [0, 0]]

        with self.assertRaises(TypeError):
            res = x[[1.2, 0]]
W
wopeizl 已提交
226

227 228
    def test_slice(self):
        places = [fluid.CPUPlace()]
W
wopeizl 已提交
229
        if core.is_compiled_with_cuda():
230 231 232 233 234 235
            places.append(core.CUDAPlace(0))

        for place in places:
            self._test_slice(place)
            self._test_slice_index_tensor(place)
            self._test_slice_index_list(place)
W
wopeizl 已提交
236

237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252
    def _tostring(self):
        b = default_main_program().current_block()
        w = b.create_var(dtype="float64", lod_level=0)
        self.assertTrue(isinstance(str(w), str))

        if core.is_compiled_with_cuda():
            wc = b.create_var(dtype="int", lod_level=0)
            self.assertTrue(isinstance(str(wc), str))

    def test_tostring(self):
        with fluid.dygraph.guard():
            self._tostring()

        with fluid.program_guard(default_main_program()):
            self._tostring()

253
    def test_fake_interface_only_api(self):
254 255 256
        b = default_main_program().current_block()
        var = b.create_var(dtype="float64", lod_level=0)
        with fluid.dygraph.guard():
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
            self.assertRaises(AssertionError, var.detach)
            self.assertRaises(AssertionError, var.numpy)
            self.assertRaises(AssertionError, var.backward)
            self.assertRaises(AssertionError, var.gradient)
            self.assertRaises(AssertionError, var.clear_gradient)

    def test_variable_in_dygraph_mode(self):
        b = default_main_program().current_block()
        var = b.create_var(dtype="float64", shape=[1, 1])
        with fluid.dygraph.guard():
            self.assertTrue(var.to_string(True).startswith('name:'))

            self.assertFalse(var.persistable)
            var.persistable = True
            self.assertTrue(var.persistable)

            self.assertFalse(var.stop_gradient)
274
            var.stop_gradient = True
275 276 277 278 279 280
            self.assertTrue(var.stop_gradient)

            self.assertTrue(var.name.startswith('_generated_var_'))
            self.assertEqual(var.shape, (1, 1))
            self.assertEqual(var.dtype, fluid.core.VarDesc.VarType.FP64)
            self.assertEqual(var.type, fluid.core.VarDesc.VarType.LOD_TENSOR)
281

282 283 284 285 286 287 288 289 290 291 292 293 294 295 296
    def test_create_selected_rows(self):
        b = default_main_program().current_block()

        var = b.create_var(
            name="var",
            shape=[1, 1],
            dtype="float32",
            type=fluid.core.VarDesc.VarType.SELECTED_ROWS,
            persistable=True)

        def _test():
            var.lod_level()

        self.assertRaises(Exception, _test)

Y
Yu Yang 已提交
297 298 299

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