test_var_base.py 69.8 KB
Newer Older
L
Leo Chen 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#   Copyright (c) 2018 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
import copy
L
Leo Chen 已提交
16
import unittest
17

18 19
import numpy as np

20
import paddle
L
Leo Chen 已提交
21 22
import paddle.fluid as fluid
import paddle.fluid.core as core
23
import paddle.nn.functional as F
24
from paddle.fluid.framework import _in_legacy_dygraph, _test_eager_guard
L
Leo Chen 已提交
25 26 27 28 29 30 31 32


class TestVarBase(unittest.TestCase):
    def setUp(self):
        self.shape = [512, 1234]
        self.dtype = np.float32
        self.array = np.random.uniform(0.1, 1, self.shape).astype(self.dtype)

33
    def func_test_to_tensor(self):
34
        def check_with_place(place):
35
            with fluid.dygraph.guard():
36
                paddle.set_default_dtype('float32')
37
                # set_default_dtype should not take effect on int
38
                x = paddle.to_tensor(1, place=place, stop_gradient=False)
39
                np.testing.assert_array_equal(x.numpy(), [1])
40 41
                self.assertNotEqual(x.dtype, core.VarDesc.VarType.FP32)

42 43 44
                y = paddle.to_tensor(2, place=x.place)
                self.assertEqual(str(x.place), str(y.place))

45
                # set_default_dtype should not take effect on numpy
46 47 48 49 50 51 52 53
                x = paddle.to_tensor(
                    np.array([1.2]).astype('float16'),
                    place=place,
                    stop_gradient=False,
                )
                np.testing.assert_array_equal(
                    x.numpy(), np.array([1.2], 'float16')
                )
54 55
                self.assertEqual(x.dtype, core.VarDesc.VarType.FP16)

56 57 58 59
                # set_default_dtype take effect on int
                x = paddle.to_tensor(1, place=place)
                self.assertTrue(x.dtype, core.VarDesc.VarType.INT64)

60
                # set_default_dtype take effect on float
61
                x = paddle.to_tensor(1.2, place=place, stop_gradient=False)
62 63 64
                np.testing.assert_array_equal(
                    x.numpy(), np.array([1.2]).astype('float32')
                )
65
                self.assertEqual(x.dtype, core.VarDesc.VarType.FP32)
Z
Zhou Wei 已提交
66
                clone_x = x.clone()
67 68 69
                np.testing.assert_array_equal(
                    clone_x.numpy(), np.array([1.2]).astype('float32')
                )
Z
Zhou Wei 已提交
70 71 72
                self.assertEqual(clone_x.dtype, core.VarDesc.VarType.FP32)
                y = clone_x**2
                y.backward()
73 74 75
                np.testing.assert_array_equal(
                    x.grad.numpy(), np.array([2.4]).astype('float32')
                )
76
                y = x.cpu()
77
                self.assertEqual(y.place.__repr__(), "Place(cpu)")
78 79
                if core.is_compiled_with_cuda():
                    y = x.pin_memory()
80
                    self.assertEqual(y.place.__repr__(), "Place(gpu_pinned)")
81
                    y = x.cuda()
82
                    self.assertEqual(y.place.__repr__(), "Place(gpu:0)")
83
                    y = x.cuda(None)
84
                    self.assertEqual(y.place.__repr__(), "Place(gpu:0)")
85
                    y = x.cuda(device_id=0)
86
                    self.assertEqual(y.place.__repr__(), "Place(gpu:0)")
87
                    y = x.cuda(blocking=False)
88
                    self.assertEqual(y.place.__repr__(), "Place(gpu:0)")
89
                    y = x.cuda(blocking=True)
90
                    self.assertEqual(y.place.__repr__(), "Place(gpu:0)")
91 92
                    with self.assertRaises(ValueError):
                        y = x.cuda("test")
93

94 95 96 97 98
                # support 'dtype' is core.VarType
                x = paddle.rand((2, 2))
                y = paddle.to_tensor([2, 2], dtype=x.dtype)
                self.assertEqual(y.dtype, core.VarDesc.VarType.FP32)

99
                # set_default_dtype take effect on complex
100
                x = paddle.to_tensor(1 + 2j, place=place, stop_gradient=False)
101
                np.testing.assert_array_equal(x.numpy(), [1 + 2j])
C
chentianyu03 已提交
102
                self.assertEqual(x.dtype, core.VarDesc.VarType.COMPLEX64)
103 104 105

                paddle.set_default_dtype('float64')
                x = paddle.to_tensor(1.2, place=place, stop_gradient=False)
106
                np.testing.assert_array_equal(x.numpy(), [1.2])
107 108 109
                self.assertEqual(x.dtype, core.VarDesc.VarType.FP64)

                x = paddle.to_tensor(1 + 2j, place=place, stop_gradient=False)
110
                np.testing.assert_array_equal(x.numpy(), [1 + 2j])
C
chentianyu03 已提交
111
                self.assertEqual(x.dtype, core.VarDesc.VarType.COMPLEX128)
112

113 114 115
                x = paddle.to_tensor(
                    1, dtype='float32', place=place, stop_gradient=False
                )
116
                np.testing.assert_array_equal(x.numpy(), [1.0])
117 118 119 120 121
                self.assertEqual(x.dtype, core.VarDesc.VarType.FP32)
                self.assertEqual(x.shape, [1])
                self.assertEqual(x.stop_gradient, False)
                self.assertEqual(x.type, core.VarDesc.VarType.LOD_TENSOR)

122 123 124 125 126 127
                x = paddle.to_tensor(
                    (1, 2), dtype='float32', place=place, stop_gradient=False
                )
                x = paddle.to_tensor(
                    [1, 2], dtype='float32', place=place, stop_gradient=False
                )
128
                np.testing.assert_array_equal(x.numpy(), [1.0, 2.0])
129
                self.assertEqual(x.dtype, core.VarDesc.VarType.FP32)
130
                self.assertIsNone(x.grad)
131 132 133 134
                self.assertEqual(x.shape, [2])
                self.assertEqual(x.stop_gradient, False)
                self.assertEqual(x.type, core.VarDesc.VarType.LOD_TENSOR)

135 136 137 138 139 140
                x = paddle.to_tensor(
                    self.array,
                    dtype='float32',
                    place=place,
                    stop_gradient=False,
                )
141
                np.testing.assert_array_equal(x.numpy(), self.array)
142 143 144 145 146 147 148
                self.assertEqual(x.dtype, core.VarDesc.VarType.FP32)
                self.assertEqual(x.shape, self.shape)
                self.assertEqual(x.stop_gradient, False)
                self.assertEqual(x.type, core.VarDesc.VarType.LOD_TENSOR)

                y = paddle.to_tensor(x)
                y = paddle.to_tensor(y, dtype='float64', place=place)
149
                np.testing.assert_array_equal(y.numpy(), self.array)
150 151 152 153 154
                self.assertEqual(y.dtype, core.VarDesc.VarType.FP64)
                self.assertEqual(y.shape, self.shape)
                self.assertEqual(y.stop_gradient, True)
                self.assertEqual(y.type, core.VarDesc.VarType.LOD_TENSOR)
                z = x + y
155
                np.testing.assert_array_equal(z.numpy(), 2 * self.array)
156

157 158 159
                x = paddle.to_tensor(
                    [1 + 2j, 1 - 2j], dtype='complex64', place=place
                )
160
                y = paddle.to_tensor(x)
161
                np.testing.assert_array_equal(x.numpy(), [1 + 2j, 1 - 2j])
C
chentianyu03 已提交
162
                self.assertEqual(y.dtype, core.VarDesc.VarType.COMPLEX64)
163 164
                self.assertEqual(y.shape, [2])

165 166 167 168 169
                paddle.set_default_dtype('float32')
                x = paddle.randn([3, 4])
                x_array = np.array(x)
                self.assertEqual(x_array.shape, x.numpy().shape)
                self.assertEqual(x_array.dtype, x.numpy().dtype)
170
                np.testing.assert_array_equal(x_array, x.numpy())
171 172 173 174 175 176 177 178 179

                x = paddle.to_tensor(1.0)
                self.assertEqual(x.item(), 1.0)
                self.assertTrue(isinstance(x.item(), float))

                x = paddle.randn([3, 2, 2])
                self.assertTrue(isinstance(x.item(5), float))
                self.assertTrue(isinstance(x.item(1, 0, 1), float))
                self.assertEqual(x.item(5), x.item(1, 0, 1))
180 181 182
                np.testing.assert_array_equal(
                    x.item(1, 0, 1), x.numpy().item(1, 0, 1)
                )
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

                x = paddle.to_tensor([[1.111111, 2.222222, 3.333333]])
                self.assertEqual(x.item(0, 2), x.item(2))
                self.assertAlmostEqual(x.item(2), 3.333333)
                self.assertTrue(isinstance(x.item(0, 2), float))

                x = paddle.to_tensor(1.0, dtype='float64')
                self.assertEqual(x.item(), 1.0)
                self.assertTrue(isinstance(x.item(), float))

                x = paddle.to_tensor(1.0, dtype='float16')
                self.assertEqual(x.item(), 1.0)
                self.assertTrue(isinstance(x.item(), float))

                x = paddle.to_tensor(1, dtype='uint8')
                self.assertEqual(x.item(), 1)
                self.assertTrue(isinstance(x.item(), int))

                x = paddle.to_tensor(1, dtype='int8')
                self.assertEqual(x.item(), 1)
                self.assertTrue(isinstance(x.item(), int))

                x = paddle.to_tensor(1, dtype='int16')
                self.assertEqual(x.item(), 1)
                self.assertTrue(isinstance(x.item(), int))

                x = paddle.to_tensor(1, dtype='int32')
                self.assertEqual(x.item(), 1)
                self.assertTrue(isinstance(x.item(), int))

                x = paddle.to_tensor(1, dtype='int64')
                self.assertEqual(x.item(), 1)
T
tianshuo78520a 已提交
215
                self.assertTrue(isinstance(x.item(), int))
216 217 218 219 220 221 222 223 224

                x = paddle.to_tensor(True)
                self.assertEqual(x.item(), True)
                self.assertTrue(isinstance(x.item(), bool))

                x = paddle.to_tensor(1 + 1j)
                self.assertEqual(x.item(), 1 + 1j)
                self.assertTrue(isinstance(x.item(), complex))

225 226 227 228 229
                # empty tensor
                x = paddle.to_tensor([])
                self.assertEqual(x.shape, [0])
                expected_result = np.array([], dtype='float32')
                self.assertEqual(x.numpy().shape, expected_result.shape)
230
                np.testing.assert_array_equal(x.numpy(), expected_result)
231

232 233 234 235 236 237
                numpy_array = np.random.randn(3, 4)
                # covert core.LoDTensor to paddle.Tensor
                lod_tensor = paddle.fluid.core.LoDTensor()
                place = paddle.fluid.framework._current_expected_place()
                lod_tensor.set(numpy_array, place)
                x = paddle.to_tensor(lod_tensor)
238
                np.testing.assert_array_equal(x.numpy(), numpy_array)
239 240 241 242 243 244 245 246
                self.assertEqual(x.type, core.VarDesc.VarType.LOD_TENSOR)
                self.assertEqual(str(x.place), str(place))

                # covert core.Tensor to paddle.Tensor
                x = paddle.to_tensor(numpy_array)
                dlpack = x.value().get_tensor()._to_dlpack()
                tensor_from_dlpack = paddle.fluid.core.from_dlpack(dlpack)
                x = paddle.to_tensor(tensor_from_dlpack)
247
                np.testing.assert_array_equal(x.numpy(), numpy_array)
248 249
                self.assertEqual(x.type, core.VarDesc.VarType.LOD_TENSOR)

250 251 252 253 254 255 256 257
                with self.assertRaises(ValueError):
                    paddle.randn([3, 2, 2]).item()
                with self.assertRaises(ValueError):
                    paddle.randn([3, 2, 2]).item(18)
                with self.assertRaises(ValueError):
                    paddle.randn([3, 2, 2]).item(1, 2)
                with self.assertRaises(ValueError):
                    paddle.randn([3, 2, 2]).item(2, 1, 2)
258 259 260 261 262 263 264 265 266 267 268
                with self.assertRaises(TypeError):
                    paddle.to_tensor('test')
                with self.assertRaises(TypeError):
                    paddle.to_tensor(1, dtype='test')
                with self.assertRaises(ValueError):
                    paddle.to_tensor([[1], [2, 3]])
                with self.assertRaises(ValueError):
                    paddle.to_tensor([[1], [2, 3]], place='test')
                with self.assertRaises(ValueError):
                    paddle.to_tensor([[1], [2, 3]], place=1)

269 270
        check_with_place(core.CPUPlace())
        check_with_place("cpu")
271
        if core.is_compiled_with_cuda():
272 273 274 275
            check_with_place(core.CUDAPinnedPlace())
            check_with_place("gpu_pinned")
            check_with_place(core.CUDAPlace(0))
            check_with_place("gpu:0")
276
        if core.is_compiled_with_npu():
277 278
            check_with_place(core.NPUPlace(0))
            check_with_place("npu:0")
279

280 281 282 283 284 285
    def test_to_tensor(self):
        with _test_eager_guard():
            self.func_test_to_tensor()
        self.func_test_to_tensor()

    def func_test_to_tensor_not_change_input_stop_gradient(self):
286 287 288 289 290 291 292
        with paddle.fluid.dygraph.guard(core.CPUPlace()):
            a = paddle.zeros([1024])
            a.stop_gradient = False
            b = paddle.to_tensor(a)
            self.assertEqual(a.stop_gradient, False)
            self.assertEqual(b.stop_gradient, True)

293 294 295 296 297 298
    def test_to_tensor_not_change_input_stop_gradient(self):
        with _test_eager_guard():
            self.func_test_to_tensor_not_change_input_stop_gradient()
        self.func_test_to_tensor_not_change_input_stop_gradient()

    def func_test_to_tensor_change_place(self):
299 300 301 302 303
        if core.is_compiled_with_cuda():
            a_np = np.random.rand(1024, 1024)
            with paddle.fluid.dygraph.guard(core.CPUPlace()):
                a = paddle.to_tensor(a_np, place=paddle.CUDAPinnedPlace())
                a = paddle.to_tensor(a)
304
                self.assertEqual(a.place.__repr__(), "Place(cpu)")
305 306 307 308

            with paddle.fluid.dygraph.guard(core.CUDAPlace(0)):
                a = paddle.to_tensor(a_np, place=paddle.CUDAPinnedPlace())
                a = paddle.to_tensor(a)
309
                self.assertEqual(a.place.__repr__(), "Place(gpu:0)")
310 311 312 313

            with paddle.fluid.dygraph.guard(core.CUDAPlace(0)):
                a = paddle.to_tensor(a_np, place=paddle.CPUPlace())
                a = paddle.to_tensor(a, place=paddle.CUDAPinnedPlace())
314
                self.assertEqual(a.place.__repr__(), "Place(gpu_pinned)")
315

316 317 318 319 320 321
    def test_to_tensor_change_place(self):
        with _test_eager_guard():
            self.func_test_to_tensor_change_place()
        self.func_test_to_tensor_change_place()

    def func_test_to_tensor_with_lodtensor(self):
322 323 324 325 326 327
        if core.is_compiled_with_cuda():
            a_np = np.random.rand(1024, 1024)
            with paddle.fluid.dygraph.guard(core.CPUPlace()):
                lod_tensor = core.LoDTensor()
                lod_tensor.set(a_np, core.CPUPlace())
                a = paddle.to_tensor(lod_tensor)
328
                np.testing.assert_array_equal(a_np, a.numpy())
329 330 331 332

            with paddle.fluid.dygraph.guard(core.CUDAPlace(0)):
                lod_tensor = core.LoDTensor()
                lod_tensor.set(a_np, core.CUDAPlace(0))
333
                a = paddle.to_tensor(lod_tensor, place=core.CPUPlace())
334
                np.testing.assert_array_equal(a_np, a.numpy())
335
                self.assertTrue(a.place.__repr__(), "Place(cpu)")
336

337 338 339 340 341 342
    def test_to_tensor_with_lodtensor(self):
        with _test_eager_guard():
            self.func_test_to_tensor_with_lodtensor()
        self.func_test_to_tensor_with_lodtensor()

    def func_test_to_variable(self):
L
Leo Chen 已提交
343 344
        with fluid.dygraph.guard():
            var = fluid.dygraph.to_variable(self.array, name="abc")
345
            np.testing.assert_array_equal(var.numpy(), self.array)
L
Leo Chen 已提交
346 347 348 349 350 351 352
            self.assertEqual(var.name, 'abc')
            # default value
            self.assertEqual(var.persistable, False)
            self.assertEqual(var.stop_gradient, True)
            self.assertEqual(var.shape, self.shape)
            self.assertEqual(var.dtype, core.VarDesc.VarType.FP32)
            self.assertEqual(var.type, core.VarDesc.VarType.LOD_TENSOR)
353 354 355 356 357
            # The type of input must be 'ndarray' or 'Variable', it will raise TypeError
            with self.assertRaises(TypeError):
                var = fluid.dygraph.to_variable("test", name="abc")
            # test to_variable of LayerObjectHelper(LayerHelperBase)
            with self.assertRaises(TypeError):
358
                linear = paddle.nn.Linear(32, 64)
359
                var = linear._helper.to_variable("test", name="abc")
L
Leo Chen 已提交
360

361 362 363 364 365 366
    def test_to_variable(self):
        with _test_eager_guard():
            self.func_test_to_variable()
        self.func_test_to_variable()

    def func_test_list_to_variable(self):
367 368 369
        with fluid.dygraph.guard():
            array = [[[1, 2], [1, 2], [1.0, 2]], [[1, 2], [1, 2], [1, 2]]]
            var = fluid.dygraph.to_variable(array, dtype='int32')
370
            np.testing.assert_array_equal(var.numpy(), array)
371 372 373 374
            self.assertEqual(var.shape, [2, 3, 2])
            self.assertEqual(var.dtype, core.VarDesc.VarType.INT32)
            self.assertEqual(var.type, core.VarDesc.VarType.LOD_TENSOR)

375 376 377 378 379 380
    def test_list_to_variable(self):
        with _test_eager_guard():
            self.func_test_list_to_variable()
        self.func_test_list_to_variable()

    def func_test_tuple_to_variable(self):
381 382 383
        with fluid.dygraph.guard():
            array = (((1, 2), (1, 2), (1, 2)), ((1, 2), (1, 2), (1, 2)))
            var = fluid.dygraph.to_variable(array, dtype='float32')
384
            np.testing.assert_array_equal(var.numpy(), array)
385 386 387 388
            self.assertEqual(var.shape, [2, 3, 2])
            self.assertEqual(var.dtype, core.VarDesc.VarType.FP32)
            self.assertEqual(var.type, core.VarDesc.VarType.LOD_TENSOR)

389 390 391 392 393 394
    def test_tuple_to_variable(self):
        with _test_eager_guard():
            self.func_test_tuple_to_variable()
        self.func_test_tuple_to_variable()

    def func_test_tensor_to_variable(self):
395 396
        with fluid.dygraph.guard():
            t = fluid.Tensor()
L
Leo Chen 已提交
397
            t.set(np.random.random((1024, 1024)), fluid.CPUPlace())
398
            var = fluid.dygraph.to_variable(t)
399
            np.testing.assert_array_equal(t, var.numpy())
400

401 402 403 404 405 406
    def test_tensor_to_variable(self):
        with _test_eager_guard():
            self.func_test_tensor_to_variable()
        self.func_test_tensor_to_variable()

    def func_test_leaf_tensor(self):
407 408 409 410 411 412
        with fluid.dygraph.guard():
            x = paddle.to_tensor(np.random.uniform(-1, 1, size=[10, 10]))
            self.assertTrue(x.is_leaf)
            y = x + 1
            self.assertTrue(y.is_leaf)

413 414 415
            x = paddle.to_tensor(
                np.random.uniform(-1, 1, size=[10, 10]), stop_gradient=False
            )
416 417 418 419 420
            self.assertTrue(x.is_leaf)
            y = x + 1
            self.assertFalse(y.is_leaf)

            linear = paddle.nn.Linear(10, 10)
421 422 423 424
            input = paddle.to_tensor(
                np.random.uniform(-1, 1, size=[10, 10]).astype('float32'),
                stop_gradient=False,
            )
425 426 427 428 429 430 431
            self.assertTrue(input.is_leaf)

            out = linear(input)
            self.assertTrue(linear.weight.is_leaf)
            self.assertTrue(linear.bias.is_leaf)
            self.assertFalse(out.is_leaf)

432 433 434 435 436 437
    def test_leaf_tensor(self):
        with _test_eager_guard():
            self.func_test_leaf_tensor()
        self.func_test_leaf_tensor()

    def func_test_detach(self):
Z
Zhou Wei 已提交
438 439 440 441 442
        with fluid.dygraph.guard():
            x = paddle.to_tensor(1.0, dtype="float64", stop_gradient=False)
            detach_x = x.detach()
            self.assertTrue(detach_x.stop_gradient, True)

443 444 445
            cmp_float = (
                np.allclose if core.is_compiled_with_rocm() else np.array_equal
            )
Z
Zhou Wei 已提交
446
            detach_x[:] = 10.0
Z
zhulei 已提交
447
            self.assertTrue(cmp_float(x.numpy(), [10.0]))
Z
Zhou Wei 已提交
448 449 450

            y = x**2
            y.backward()
Z
zhulei 已提交
451
            self.assertTrue(cmp_float(x.grad.numpy(), [20.0]))
452
            self.assertIsNone(detach_x.grad)
Z
Zhou Wei 已提交
453

454 455 456
            detach_x.stop_gradient = (
                False  # Set stop_gradient to be False, supported auto-grad
            )
Z
Zhou Wei 已提交
457 458
            z = 3 * detach_x**2
            z.backward()
Z
zhulei 已提交
459 460
            self.assertTrue(cmp_float(x.grad.numpy(), [20.0]))
            self.assertTrue(cmp_float(detach_x.grad.numpy(), [60.0]))
461

462 463 464 465 466
            with self.assertRaises(ValueError):
                detach_x[:] = 5.0

            detach_x.stop_gradient = True

Z
Zhou Wei 已提交
467
            # Due to sharing of data with origin Tensor, There are some unsafe operations:
468 469 470 471
            with self.assertRaises(RuntimeError):
                y = 2**x
                detach_x[:] = 5.0
                y.backward()
Z
Zhou Wei 已提交
472

473 474 475 476 477 478
    def test_detach(self):
        with _test_eager_guard():
            self.func_test_detach()
        self.func_test_detach()

    def func_test_write_property(self):
L
Leo Chen 已提交
479 480 481
        with fluid.dygraph.guard():
            var = fluid.dygraph.to_variable(self.array)

482
            self.assertEqual(var.name, 'generated_tensor_0')
L
Leo Chen 已提交
483 484 485 486 487 488 489 490 491 492 493
            var.name = 'test'
            self.assertEqual(var.name, 'test')

            self.assertEqual(var.persistable, False)
            var.persistable = True
            self.assertEqual(var.persistable, True)

            self.assertEqual(var.stop_gradient, True)
            var.stop_gradient = False
            self.assertEqual(var.stop_gradient, False)

494 495 496 497 498 499
    def test_write_property(self):
        with _test_eager_guard():
            self.func_test_write_property()
        self.func_test_write_property()

    def func_test_deep_copy(self):
500
        with fluid.dygraph.guard():
501 502 503 504
            if _in_legacy_dygraph():
                empty_var = core.VarBase()
            else:
                empty_var = core.eager.Tensor()
505
            empty_var_copy = copy.deepcopy(empty_var)
506 507 508
            self.assertEqual(
                empty_var.stop_gradient, empty_var_copy.stop_gradient
            )
509 510 511 512
            self.assertEqual(empty_var.persistable, empty_var_copy.persistable)
            self.assertEqual(empty_var.type, empty_var_copy.type)
            self.assertEqual(empty_var.dtype, empty_var_copy.dtype)

513 514
            x = paddle.to_tensor([2.0], stop_gradient=False)
            y = paddle.to_tensor([3.0], stop_gradient=False)
515 516 517 518 519 520 521 522 523
            z = x * y
            memo = {}
            x_copy = copy.deepcopy(x, memo)
            y_copy = copy.deepcopy(y, memo)

            self.assertEqual(x_copy.stop_gradient, y_copy.stop_gradient)
            self.assertEqual(x_copy.persistable, y_copy.persistable)
            self.assertEqual(x_copy.type, y_copy.type)
            self.assertEqual(x_copy.dtype, y_copy.dtype)
524 525
            np.testing.assert_array_equal(x.numpy(), x_copy.numpy())
            np.testing.assert_array_equal(y.numpy(), y_copy.numpy())
526 527

            self.assertNotEqual(id(x), id(x_copy))
528
            np.testing.assert_array_equal(x.numpy(), [2.0])
529

530
            with self.assertRaises(ValueError):
531
                x_copy[:] = 5.0
532

533 534 535 536 537 538 539 540 541
            with self.assertRaises(RuntimeError):
                copy.deepcopy(z)

            x_copy2 = copy.deepcopy(x, memo)
            y_copy2 = copy.deepcopy(y, memo)
            self.assertEqual(id(x_copy), id(x_copy2))
            self.assertEqual(id(y_copy), id(y_copy2))

            # test copy selected rows
542
            if _in_legacy_dygraph():
543 544 545 546 547 548 549
                x = core.VarBase(
                    core.VarDesc.VarType.FP32,
                    [3, 100],
                    "selected_rows",
                    core.VarDesc.VarType.SELECTED_ROWS,
                    True,
                )
550
            else:
551 552 553 554 555 556 557
                x = core.eager.Tensor(
                    core.VarDesc.VarType.FP32,
                    [3, 100],
                    "selected_rows",
                    core.VarDesc.VarType.SELECTED_ROWS,
                    True,
                )
558

559
            selected_rows = x.value().get_selected_rows()
560 561 562
            selected_rows.get_tensor().set(
                np.random.rand(3, 100), core.CPUPlace()
            )
563 564 565 566 567 568 569 570 571 572
            selected_rows.set_height(10)
            selected_rows.set_rows([3, 5, 7])
            x_copy = copy.deepcopy(x)

            self.assertEqual(x_copy.stop_gradient, x.stop_gradient)
            self.assertEqual(x_copy.persistable, x.persistable)
            self.assertEqual(x_copy.type, x.type)
            self.assertEqual(x_copy.dtype, x.dtype)

            copy_selected_rows = x_copy.value().get_selected_rows()
573 574 575
            self.assertEqual(
                copy_selected_rows.height(), selected_rows.height()
            )
576
            self.assertEqual(copy_selected_rows.rows(), selected_rows.rows())
577 578
            np.testing.assert_array_equal(
                np.array(copy_selected_rows.get_tensor()),
579 580
                np.array(selected_rows.get_tensor()),
            )
581

582 583 584 585 586
    def test_deep_copy(self):
        with _test_eager_guard():
            self.func_test_deep_copy()
        self.func_test_deep_copy()

L
Leo Chen 已提交
587
    # test some patched methods
588
    def func_test_set_value(self):
L
Leo Chen 已提交
589 590 591 592 593 594 595
        with fluid.dygraph.guard():
            var = fluid.dygraph.to_variable(self.array)
            tmp1 = np.random.uniform(0.1, 1, [2, 2, 3]).astype(self.dtype)
            self.assertRaises(AssertionError, var.set_value, tmp1)

            tmp2 = np.random.uniform(0.1, 1, self.shape).astype(self.dtype)
            var.set_value(tmp2)
596
            np.testing.assert_array_equal(var.numpy(), tmp2)
L
Leo Chen 已提交
597

598 599 600 601 602 603
    def test_set_value(self):
        with _test_eager_guard():
            self.func_test_set_value()
        self.func_test_set_value()

    def func_test_to_string(self):
L
Leo Chen 已提交
604 605
        with fluid.dygraph.guard():
            var = fluid.dygraph.to_variable(self.array)
606
            self.assertTrue(isinstance(str(var), str))
L
Leo Chen 已提交
607

608 609 610 611 612 613
    def test_to_string(self):
        with _test_eager_guard():
            self.func_test_to_string()
        self.func_test_to_string()

    def func_test_element_size(self):
614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647
        with fluid.dygraph.guard():
            x = paddle.to_tensor(1, dtype='bool')
            self.assertEqual(x.element_size(), 1)

            x = paddle.to_tensor(1, dtype='float16')
            self.assertEqual(x.element_size(), 2)

            x = paddle.to_tensor(1, dtype='float32')
            self.assertEqual(x.element_size(), 4)

            x = paddle.to_tensor(1, dtype='float64')
            self.assertEqual(x.element_size(), 8)

            x = paddle.to_tensor(1, dtype='int8')
            self.assertEqual(x.element_size(), 1)

            x = paddle.to_tensor(1, dtype='int16')
            self.assertEqual(x.element_size(), 2)

            x = paddle.to_tensor(1, dtype='int32')
            self.assertEqual(x.element_size(), 4)

            x = paddle.to_tensor(1, dtype='int64')
            self.assertEqual(x.element_size(), 8)

            x = paddle.to_tensor(1, dtype='uint8')
            self.assertEqual(x.element_size(), 1)

            x = paddle.to_tensor(1, dtype='complex64')
            self.assertEqual(x.element_size(), 8)

            x = paddle.to_tensor(1, dtype='complex128')
            self.assertEqual(x.element_size(), 16)

648 649 650 651 652 653
    def test_element_size(self):
        with _test_eager_guard():
            self.func_test_element_size()
        self.func_test_element_size()

    def func_test_backward(self):
L
Leo Chen 已提交
654 655 656
        with fluid.dygraph.guard():
            var = fluid.dygraph.to_variable(self.array)
            var.stop_gradient = False
657
            loss = F.relu(var)
L
Leo Chen 已提交
658 659 660 661
            loss.backward()
            grad_var = var._grad_ivar()
            self.assertEqual(grad_var.shape, self.shape)

662 663 664 665 666 667
    def test_backward(self):
        with _test_eager_guard():
            self.func_test_backward()
        self.func_test_backward()

    def func_test_gradient(self):
L
Leo Chen 已提交
668 669 670
        with fluid.dygraph.guard():
            var = fluid.dygraph.to_variable(self.array)
            var.stop_gradient = False
671
            loss = F.relu(var)
L
Leo Chen 已提交
672 673 674 675
            loss.backward()
            grad_var = var.gradient()
            self.assertEqual(grad_var.shape, self.array.shape)

676 677 678 679 680 681
    def test_gradient(self):
        with _test_eager_guard():
            self.func_test_gradient()
        self.func_test_gradient()

    def func_test_block(self):
L
Leo Chen 已提交
682 683
        with fluid.dygraph.guard():
            var = fluid.dygraph.to_variable(self.array)
684 685 686
            self.assertEqual(
                var.block, fluid.default_main_program().global_block()
            )
L
Leo Chen 已提交
687

688 689 690 691 692
    def test_block(self):
        with _test_eager_guard():
            self.func_test_block()
        self.func_test_block()

693 694
    def _test_slice(self):
        w = fluid.dygraph.to_variable(
695 696
            np.random.random((784, 100, 100)).astype('float64')
        )
697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718

        for i in range(3):
            nw = w[i]
            self.assertEqual((100, 100), tuple(nw.shape))

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

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

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

        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), tuple(nw.shape))

719 720 721 722 723 724 725
        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')
726 727 728 729 730 731
        var = fluid.dygraph.to_variable(tensor_array)
        var1 = var[0, 1, 1]
        var2 = var[1:]
        var3 = var[0:1]
        var4 = var[::-1]
        var5 = var[1, 1:, 1:]
732
        var_reshape = paddle.reshape(var, [3, -1, 3])
733 734 735 736 737 738 739 740 741 742
        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]
743
        var16 = var[-4:4]
744 745
        var17 = var[:, 0, 0:0]
        var18 = var[:, 1:1:2]
746 747

        vars = [
748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766
            var,
            var1,
            var2,
            var3,
            var4,
            var5,
            var6,
            var7,
            var8,
            var9,
            var10,
            var11,
            var12,
            var13,
            var14,
            var15,
            var16,
            var17,
            var18,
767 768 769
        ]
        local_out = [var.numpy() for var in vars]

770 771 772 773 774 775
        np.testing.assert_array_equal(local_out[1], tensor_array[0, 1, 1:2])
        np.testing.assert_array_equal(local_out[2], tensor_array[1:])
        np.testing.assert_array_equal(local_out[3], tensor_array[0:1])
        np.testing.assert_array_equal(local_out[4], tensor_array[::-1])
        np.testing.assert_array_equal(local_out[5], tensor_array[1, 1:, 1:])
        np.testing.assert_array_equal(
776 777
            local_out[6], tensor_array.reshape((3, -1, 3))[:, :, -1]
        )
778 779 780
        np.testing.assert_array_equal(local_out[7], tensor_array[:, :, :-1])
        np.testing.assert_array_equal(local_out[8], tensor_array[:1, :1, :1])
        np.testing.assert_array_equal(local_out[9], tensor_array[:-1, :-1, :-1])
781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798
        np.testing.assert_array_equal(
            local_out[10], tensor_array[::-1, :1, :-1]
        )
        np.testing.assert_array_equal(
            local_out[11], tensor_array[:-1, ::-1, -1:]
        )
        np.testing.assert_array_equal(
            local_out[12], tensor_array[1:2, 2:, ::-1]
        )
        np.testing.assert_array_equal(
            local_out[13], tensor_array[2:10, 2:, -2:-1]
        )
        np.testing.assert_array_equal(
            local_out[14], tensor_array[1:-1, 0:2, ::-1]
        )
        np.testing.assert_array_equal(
            local_out[15], tensor_array[::-1, ::-1, ::-1]
        )
799 800 801
        np.testing.assert_array_equal(local_out[16], tensor_array[-4:4])
        np.testing.assert_array_equal(local_out[17], tensor_array[:, 0, 0:0])
        np.testing.assert_array_equal(local_out[18], tensor_array[:, 1:1:2])
802

803
    def _test_slice_for_tensor_attr(self):
804 805 806 807 808 809 810
        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')
811 812 813 814 815 816 817 818 819 820 821 822 823 824

        var = paddle.to_tensor(tensor_array)

        one = paddle.ones(shape=[1], dtype="int32")
        two = paddle.full(shape=[1], fill_value=2, dtype="int32")
        negative_one = paddle.full(shape=[1], fill_value=-1, dtype="int32")
        four = paddle.full(shape=[1], fill_value=4, dtype="int32")

        var = fluid.dygraph.to_variable(tensor_array)
        var1 = var[0, one, one]
        var2 = var[one:]
        var3 = var[0:one]
        var4 = var[::negative_one]
        var5 = var[one, one:, one:]
825
        var_reshape = paddle.reshape(var, [3, negative_one, 3])
826 827 828 829 830 831 832 833 834 835 836 837 838
        var6 = var_reshape[:, :, negative_one]
        var7 = var[:, :, :negative_one]
        var8 = var[:one, :one, :1]
        var9 = var[:-1, :negative_one, :negative_one]
        var10 = var[::negative_one, :one, :negative_one]
        var11 = var[:negative_one, ::-1, negative_one:]
        var12 = var[one:2, 2:, ::negative_one]
        var13 = var[two:10, 2:, -2:negative_one]
        var14 = var[1:negative_one, 0:2, ::negative_one]
        var15 = var[::negative_one, ::-1, ::negative_one]
        var16 = var[-4:4]

        vars = [
839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855
            var,
            var1,
            var2,
            var3,
            var4,
            var5,
            var6,
            var7,
            var8,
            var9,
            var10,
            var11,
            var12,
            var13,
            var14,
            var15,
            var16,
856 857 858
        ]
        local_out = [var.numpy() for var in vars]

859 860 861 862 863 864
        np.testing.assert_array_equal(local_out[1], tensor_array[0, 1, 1:2])
        np.testing.assert_array_equal(local_out[2], tensor_array[1:])
        np.testing.assert_array_equal(local_out[3], tensor_array[0:1])
        np.testing.assert_array_equal(local_out[4], tensor_array[::-1])
        np.testing.assert_array_equal(local_out[5], tensor_array[1, 1:, 1:])
        np.testing.assert_array_equal(
865 866
            local_out[6], tensor_array.reshape((3, -1, 3))[:, :, -1]
        )
867 868 869
        np.testing.assert_array_equal(local_out[7], tensor_array[:, :, :-1])
        np.testing.assert_array_equal(local_out[8], tensor_array[:1, :1, :1])
        np.testing.assert_array_equal(local_out[9], tensor_array[:-1, :-1, :-1])
870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887
        np.testing.assert_array_equal(
            local_out[10], tensor_array[::-1, :1, :-1]
        )
        np.testing.assert_array_equal(
            local_out[11], tensor_array[:-1, ::-1, -1:]
        )
        np.testing.assert_array_equal(
            local_out[12], tensor_array[1:2, 2:, ::-1]
        )
        np.testing.assert_array_equal(
            local_out[13], tensor_array[2:10, 2:, -2:-1]
        )
        np.testing.assert_array_equal(
            local_out[14], tensor_array[1:-1, 0:2, ::-1]
        )
        np.testing.assert_array_equal(
            local_out[15], tensor_array[::-1, ::-1, ::-1]
        )
888
        np.testing.assert_array_equal(local_out[16], tensor_array[-4:4])
889

890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910
    def _test_for_getitem_ellipsis_index(self):
        shape = (64, 3, 5, 256)
        np_fp32_value = np.random.random(shape).astype('float32')
        np_int_value = np.random.randint(1, 100, shape)

        var_fp32 = paddle.to_tensor(np_fp32_value)
        var_int = paddle.to_tensor(np_int_value)

        def assert_getitem_ellipsis_index(var_tensor, var_np):
            var = [
                var_tensor[..., 0].numpy(),
                var_tensor[..., 1, 0].numpy(),
                var_tensor[0, ..., 1, 0].numpy(),
                var_tensor[1, ..., 1].numpy(),
                var_tensor[2, ...].numpy(),
                var_tensor[2, 0, ...].numpy(),
                var_tensor[2, 0, 1, ...].numpy(),
                var_tensor[...].numpy(),
                var_tensor[:, ..., 100].numpy(),
            ]

911 912 913 914 915 916 917 918 919
            np.testing.assert_array_equal(var[0], var_np[..., 0])
            np.testing.assert_array_equal(var[1], var_np[..., 1, 0])
            np.testing.assert_array_equal(var[2], var_np[0, ..., 1, 0])
            np.testing.assert_array_equal(var[3], var_np[1, ..., 1])
            np.testing.assert_array_equal(var[4], var_np[2, ...])
            np.testing.assert_array_equal(var[5], var_np[2, 0, ...])
            np.testing.assert_array_equal(var[6], var_np[2, 0, 1, ...])
            np.testing.assert_array_equal(var[7], var_np[...])
            np.testing.assert_array_equal(var[8], var_np[:, ..., 100])
920 921 922 923 924 925 926

        var_fp32 = paddle.to_tensor(np_fp32_value)
        var_int = paddle.to_tensor(np_int_value)

        assert_getitem_ellipsis_index(var_fp32, np_fp32_value)
        assert_getitem_ellipsis_index(var_int, np_int_value)

927 928
        # test 1 dim tensor
        var_one_dim = paddle.to_tensor([1, 2, 3, 4])
929 930 931
        np.testing.assert_array_equal(
            var_one_dim[..., 0].numpy(), np.array([1])
        )
932

933 934 935 936 937 938 939 940 941 942 943 944 945 946 947
    def _test_none_index(self):
        shape = (8, 64, 5, 256)
        np_value = np.random.random(shape).astype('float32')
        var_tensor = paddle.to_tensor(np_value)

        var = [
            var_tensor[1, 0, None].numpy(),
            var_tensor[None, ..., 1, 0].numpy(),
            var_tensor[:, :, :, None].numpy(),
            var_tensor[1, ..., 1, None].numpy(),
            var_tensor[2, ..., None, None].numpy(),
            var_tensor[None, 2, 0, ...].numpy(),
            var_tensor[None, 2, None, 1].numpy(),
            var_tensor[None].numpy(),
            var_tensor[0, 0, None, 0, 0, None].numpy(),
948
            var_tensor[None, None, 0, ..., None].numpy(),
949
            var_tensor[..., None, :, None].numpy(),
950 951 952
            var_tensor[0, 1:10:2, None, None, ...].numpy(),
        ]

953 954 955 956 957 958 959 960 961
        np.testing.assert_array_equal(var[0], np_value[1, 0, None])
        np.testing.assert_array_equal(var[1], np_value[None, ..., 1, 0])
        np.testing.assert_array_equal(var[2], np_value[:, :, :, None])
        np.testing.assert_array_equal(var[3], np_value[1, ..., 1, None])
        np.testing.assert_array_equal(var[4], np_value[2, ..., None, None])
        np.testing.assert_array_equal(var[5], np_value[None, 2, 0, ...])
        np.testing.assert_array_equal(var[6], np_value[None, 2, None, 1])
        np.testing.assert_array_equal(var[7], np_value[None])
        np.testing.assert_array_equal(var[8], np_value[0, 0, None, 0, 0, None])
962 963 964
        np.testing.assert_array_equal(
            var[9], np_value[None, None, 0, ..., None]
        )
965
        np.testing.assert_array_equal(var[10], np_value[..., None, :, None])
966

967 968
        # TODO(zyfncg) there is a bug of dimensions when slice step > 1 and
        #              indexs has int type
969
        # self.assertTrue(
970
        #     np.array_equal(var[11], np_value[0, 1:10:2, None, None, ...]))
971

Z
zyfncg 已提交
972 973 974 975
    def _test_bool_index(self):
        shape = (4, 2, 5, 64)
        np_value = np.random.random(shape).astype('float32')
        var_tensor = paddle.to_tensor(np_value)
976 977 978 979 980 981 982 983 984 985
        index = [
            [True, True, True, True],
            [True, False, True, True],
            [True, False, False, True],
            [False, 0, 1, True, True],
            [False, False, False, False],
        ]
        index2d = np.array(
            [[True, True], [False, False], [True, False], [True, True]]
        )
Z
zyfncg 已提交
986 987
        tensor_index = paddle.to_tensor(index2d)
        var = [
988 989 990 991
            var_tensor[index[0]].numpy(),
            var_tensor[index[1]].numpy(),
            var_tensor[index[2]].numpy(),
            var_tensor[index[3]].numpy(),
Z
zyfncg 已提交
992 993
            var_tensor[paddle.to_tensor(index[0])].numpy(),
            var_tensor[tensor_index].numpy(),
994
            var_tensor[paddle.to_tensor(index[4])].numpy(),
Z
zyfncg 已提交
995
        ]
996 997 998 999 1000 1001 1002
        np.testing.assert_array_equal(var[0], np_value[index[0]])
        np.testing.assert_array_equal(var[1], np_value[index[1]])
        np.testing.assert_array_equal(var[2], np_value[index[2]])
        np.testing.assert_array_equal(var[3], np_value[index[3]])
        np.testing.assert_array_equal(var[4], np_value[index[0]])
        np.testing.assert_array_equal(var[5], np_value[index2d])
        np.testing.assert_array_equal(var[6], np_value[index[4]])
1003 1004 1005 1006 1007 1008
        np.testing.assert_array_equal(
            var_tensor[var_tensor > 0.67], np_value[np_value > 0.67]
        )
        np.testing.assert_array_equal(
            var_tensor[var_tensor < 0.55], np_value[np_value < 0.55]
        )
Z
zyfncg 已提交
1009 1010 1011 1012 1013 1014 1015 1016 1017 1018

        with self.assertRaises(ValueError):
            var_tensor[[False, False, False, False]]
        with self.assertRaises(ValueError):
            var_tensor[[True, False]]
        with self.assertRaises(ValueError):
            var_tensor[[True, False, False, False, False]]
        with self.assertRaises(IndexError):
            var_tensor[paddle.to_tensor([[True, False, False, False]])]

1019 1020 1021 1022 1023 1024
    def _test_scalar_bool_index(self):
        shape = (1, 2, 5, 64)
        np_value = np.random.random(shape).astype('float32')
        var_tensor = paddle.to_tensor(np_value)
        index = [True]
        tensor_index = paddle.to_tensor(index)
1025 1026 1027
        var = [
            var_tensor[tensor_index].numpy(),
        ]
1028
        np.testing.assert_array_equal(var[0], np_value[index])
1029

H
hong 已提交
1030 1031 1032 1033 1034
    def _test_for_var(self):
        np_value = np.random.random((30, 100, 100)).astype('float32')
        w = fluid.dygraph.to_variable(np_value)

        for i, e in enumerate(w):
1035
            np.testing.assert_array_equal(e.numpy(), np_value[i])
H
hong 已提交
1036

1037 1038 1039
    def _test_numpy_index(self):
        array = np.arange(120).reshape([4, 5, 6])
        t = paddle.to_tensor(array)
1040 1041
        np.testing.assert_array_equal(t[np.longlong(0)].numpy(), array[0])
        np.testing.assert_array_equal(
1042 1043 1044
            t[np.longlong(0) : np.longlong(4) : np.longlong(2)].numpy(),
            array[0:4:2],
        )
1045 1046
        np.testing.assert_array_equal(t[np.int64(0)].numpy(), array[0])
        np.testing.assert_array_equal(
1047 1048
            t[np.int32(1) : np.int32(4) : np.int32(2)].numpy(), array[1:4:2]
        )
1049
        np.testing.assert_array_equal(
1050 1051
            t[np.int16(0) : np.int16(4) : np.int16(2)].numpy(), array[0:4:2]
        )
1052 1053 1054 1055 1056 1057 1058

    def _test_list_index(self):
        # case1:
        array = np.arange(120).reshape([6, 5, 4])
        x = paddle.to_tensor(array)
        py_idx = [[0, 2, 0, 1, 3], [0, 0, 1, 2, 0]]
        idx = [paddle.to_tensor(py_idx[0]), paddle.to_tensor(py_idx[1])]
1059 1060
        np.testing.assert_array_equal(x[idx].numpy(), array[py_idx])
        np.testing.assert_array_equal(x[py_idx].numpy(), array[py_idx])
1061 1062
        # case2:
        tensor_x = paddle.to_tensor(
1063 1064
            np.zeros(12).reshape(2, 6).astype(np.float32)
        )
1065 1066
        tensor_y1 = paddle.zeros([1], dtype='int32') + 2
        tensor_y2 = paddle.zeros([1], dtype='int32') + 5
1067 1068
        tensor_x[:, tensor_y1:tensor_y2] = 42
        res = tensor_x.numpy()
1069 1070 1071 1072 1073 1074
        exp = np.array(
            [
                [0.0, 0.0, 42.0, 42.0, 42.0, 0.0],
                [0.0, 0.0, 42.0, 42.0, 42.0, 0.0],
            ]
        )
1075
        np.testing.assert_array_equal(res, exp)
1076

W
WeiXin 已提交
1077 1078 1079
        # case3:
        row = np.array([0, 1, 2])
        col = np.array([2, 1, 3])
1080
        np.testing.assert_array_equal(array[row, col], x[row, col].numpy())
W
WeiXin 已提交
1081

W
wanghuancoder 已提交
1082
    def func_test_slice(self):
L
Leo Chen 已提交
1083
        with fluid.dygraph.guard():
1084
            self._test_slice()
1085
            self._test_slice_for_tensor_attr()
H
hong 已提交
1086
            self._test_for_var()
1087
            self._test_for_getitem_ellipsis_index()
1088
            self._test_none_index()
Z
zyfncg 已提交
1089
            self._test_bool_index()
1090
            self._test_scalar_bool_index()
1091 1092
            self._test_numpy_index()
            self._test_list_index()
1093

L
Leo Chen 已提交
1094
            var = fluid.dygraph.to_variable(self.array)
1095 1096
            np.testing.assert_array_equal(var[1, :].numpy(), self.array[1, :])
            np.testing.assert_array_equal(var[::-1].numpy(), self.array[::-1])
L
Leo Chen 已提交
1097

H
hong 已提交
1098 1099 1100
            with self.assertRaises(IndexError):
                y = var[self.shape[0]]

1101 1102 1103
            with self.assertRaises(IndexError):
                y = var[0 - self.shape[0] - 1]

W
WeiXin 已提交
1104 1105 1106 1107
            with self.assertRaises(IndexError):
                mask = np.array([1, 0, 1, 0], dtype=bool)
                var[paddle.to_tensor([0, 1]), mask]

W
wanghuancoder 已提交
1108 1109 1110 1111 1112
    def test_slice(self):
        with _test_eager_guard():
            self.func_test_slice()
        self.func_test_slice()

1113
    def func_test_var_base_to_np(self):
L
Leo Chen 已提交
1114 1115
        with fluid.dygraph.guard():
            var = fluid.dygraph.to_variable(self.array)
1116 1117 1118
            np.testing.assert_array_equal(
                var.numpy(), fluid.framework._var_base_to_np(var)
            )
L
Leo Chen 已提交
1119

1120 1121 1122 1123 1124 1125
    def test_var_base_to_np(self):
        with _test_eager_guard():
            self.func_test_var_base_to_np()
        self.func_test_var_base_to_np()

    def func_test_var_base_as_np(self):
1126 1127
        with fluid.dygraph.guard():
            var = fluid.dygraph.to_variable(self.array)
1128
            np.testing.assert_array_equal(var.numpy(), np.array(var))
1129 1130 1131
            np.testing.assert_array_equal(
                var.numpy(), np.array(var, dtype=np.float32)
            )
1132

1133 1134 1135 1136 1137 1138
    def test_var_base_as_np(self):
        with _test_eager_guard():
            self.func_test_var_base_as_np()
        self.func_test_var_base_as_np()

    def func_test_if(self):
1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151
        with fluid.dygraph.guard():
            var1 = fluid.dygraph.to_variable(np.array([[[0]]]))
            var2 = fluid.dygraph.to_variable(np.array([[[1]]]))

            var1_bool = False
            var2_bool = False

            if var1:
                var1_bool = True

            if var2:
                var2_bool = True

1152 1153 1154 1155
            assert not var1_bool, "if var1 should be false"
            assert var2_bool, "if var2 should be true"
            assert not bool(var1), "bool(var1) is False"
            assert bool(var2), "bool(var2) is True"
1156

1157 1158 1159 1160 1161 1162
    def test_if(self):
        with _test_eager_guard():
            self.func_test_if()
        self.func_test_if()

    def func_test_to_static_var(self):
1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173
        with fluid.dygraph.guard():
            # Convert VarBase into Variable or Parameter
            var_base = fluid.dygraph.to_variable(self.array, name="var_base_1")
            static_var = var_base._to_static_var()
            self._assert_to_static(var_base, static_var)

            var_base = fluid.dygraph.to_variable(self.array, name="var_base_2")
            static_param = var_base._to_static_var(to_parameter=True)
            self._assert_to_static(var_base, static_param, True)

            # Convert ParamBase into Parameter
1174
            fc = paddle.nn.Linear(
1175 1176
                10,
                20,
1177
                weight_attr=paddle.ParamAttr(
1178 1179
                    learning_rate=0.001,
                    do_model_average=True,
1180
                    regularizer=paddle.regularizer.L1Decay(),
1181 1182
                ),
            )
1183 1184 1185 1186
            weight = fc.parameters()[0]
            static_param = weight._to_static_var()
            self._assert_to_static(weight, static_param, True)

1187 1188 1189 1190 1191
    def test_to_static_var(self):
        with _test_eager_guard():
            self.func_test_to_static_var()
        self.func_test_to_static_var()

1192 1193 1194 1195 1196 1197
    def _assert_to_static(self, var_base, static_var, is_param=False):
        if is_param:
            self.assertTrue(isinstance(static_var, fluid.framework.Parameter))
            self.assertTrue(static_var.persistable, True)
            if isinstance(var_base, fluid.framework.ParamBase):
                for attr in ['trainable', 'is_distributed', 'do_model_average']:
1198 1199 1200
                    self.assertEqual(
                        getattr(var_base, attr), getattr(static_var, attr)
                    )
1201

1202 1203 1204
                self.assertEqual(
                    static_var.optimize_attr['learning_rate'], 0.001
                )
1205
                self.assertTrue(
1206 1207 1208 1209
                    isinstance(
                        static_var.regularizer, fluid.regularizer.L1Decay
                    )
                )
1210 1211 1212 1213 1214 1215 1216 1217 1218
        else:
            self.assertTrue(isinstance(static_var, fluid.framework.Variable))

        attr_keys = ['block', 'dtype', 'type', 'name']
        for attr in attr_keys:
            self.assertEqual(getattr(var_base, attr), getattr(static_var, attr))

        self.assertListEqual(list(var_base.shape), list(static_var.shape))

1219
    def func_test_tensor_str(self):
Z
Zhou Wei 已提交
1220
        paddle.enable_static()
1221
        paddle.disable_static(paddle.CPUPlace())
C
cnn 已提交
1222
        paddle.seed(10)
1223 1224 1225 1226
        a = paddle.rand([10, 20])
        paddle.set_printoptions(4, 100, 3)
        a_str = str(a)

1227
        expected = '''Tensor(shape=[10, 20], dtype=float32, place=Place(cpu), stop_gradient=True,
1228 1229 1230 1231 1232 1233 1234 1235 1236 1237
       [[0.2727, 0.5489, 0.8655, ..., 0.2916, 0.8525, 0.9000],
        [0.3806, 0.8996, 0.0928, ..., 0.9535, 0.8378, 0.6409],
        [0.1484, 0.4038, 0.8294, ..., 0.0148, 0.6520, 0.4250],
        ...,
        [0.3426, 0.1909, 0.7240, ..., 0.4218, 0.2676, 0.5679],
        [0.5561, 0.2081, 0.0676, ..., 0.9778, 0.3302, 0.9559],
        [0.2665, 0.8483, 0.5389, ..., 0.4956, 0.6862, 0.9178]])'''

        self.assertEqual(a_str, expected)

1238 1239 1240 1241 1242 1243
    def test_tensor_str(self):
        with _test_eager_guard():
            self.func_test_tensor_str()
        self.func_test_tensor_str()

    def func_test_tensor_str2(self):
1244 1245 1246 1247
        paddle.disable_static(paddle.CPUPlace())
        a = paddle.to_tensor([[1.5111111, 1.0], [0, 0]])
        a_str = str(a)

1248
        expected = '''Tensor(shape=[2, 2], dtype=float32, place=Place(cpu), stop_gradient=True,
1249 1250 1251 1252 1253
       [[1.5111, 1.    ],
        [0.    , 0.    ]])'''

        self.assertEqual(a_str, expected)

1254 1255 1256 1257 1258 1259
    def test_tensor_str2(self):
        with _test_eager_guard():
            self.func_test_tensor_str2()
        self.func_test_tensor_str2()

    def func_test_tensor_str3(self):
1260 1261 1262 1263
        paddle.disable_static(paddle.CPUPlace())
        a = paddle.to_tensor([[-1.5111111, 1.0], [0, -0.5]])
        a_str = str(a)

1264
        expected = '''Tensor(shape=[2, 2], dtype=float32, place=Place(cpu), stop_gradient=True,
1265 1266 1267 1268 1269
       [[-1.5111,  1.    ],
        [ 0.    , -0.5000]])'''

        self.assertEqual(a_str, expected)

1270 1271 1272 1273 1274 1275
    def test_tensor_str3(self):
        with _test_eager_guard():
            self.func_test_tensor_str3()
        self.func_test_tensor_str3()

    def func_test_tensor_str_scaler(self):
1276 1277 1278 1279
        paddle.disable_static(paddle.CPUPlace())
        a = paddle.to_tensor(np.array(False))
        a_str = str(a)

1280
        expected = '''Tensor(shape=[], dtype=bool, place=Place(cpu), stop_gradient=True,
1281 1282 1283 1284
       False)'''

        self.assertEqual(a_str, expected)

1285 1286 1287 1288 1289 1290
    def test_tensor_str_scaler(self):
        with _test_eager_guard():
            self.func_test_tensor_str_scaler()
        self.func_test_tensor_str_scaler()

    def func_test_tensor_str_shape_with_zero(self):
1291 1292
        paddle.disable_static(paddle.CPUPlace())
        x = paddle.ones((10, 10))
1293
        y = paddle.nonzero(x == 0)
1294 1295
        a_str = str(y)

1296
        expected = '''Tensor(shape=[0, 2], dtype=int64, place=Place(cpu), stop_gradient=True,
1297 1298 1299 1300
       [])'''

        self.assertEqual(a_str, expected)

1301 1302 1303 1304 1305 1306
    def test_tensor_str_shape_with_zero(self):
        with _test_eager_guard():
            self.func_test_tensor_str_shape_with_zero()
        self.func_test_tensor_str_shape_with_zero()

    def func_test_tensor_str_linewidth(self):
1307 1308 1309
        paddle.disable_static(paddle.CPUPlace())
        paddle.seed(2021)
        x = paddle.rand([128])
1310 1311 1312
        paddle.set_printoptions(
            precision=4, threshold=1000, edgeitems=3, linewidth=80
        )
1313 1314
        a_str = str(x)

1315
        expected = '''Tensor(shape=[128], dtype=float32, place=Place(cpu), stop_gradient=True,
1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333
       [0.3759, 0.0278, 0.2489, 0.3110, 0.9105, 0.7381, 0.1905, 0.4726, 0.2435,
        0.9142, 0.3367, 0.7243, 0.7664, 0.9915, 0.2921, 0.1363, 0.8096, 0.2915,
        0.9564, 0.9972, 0.2573, 0.2597, 0.3429, 0.2484, 0.9579, 0.7003, 0.4126,
        0.4274, 0.0074, 0.9686, 0.9910, 0.0144, 0.6564, 0.2932, 0.7114, 0.9301,
        0.6421, 0.0538, 0.1273, 0.5771, 0.9336, 0.6416, 0.1832, 0.9311, 0.7702,
        0.7474, 0.4479, 0.3382, 0.5579, 0.0444, 0.9802, 0.9874, 0.3038, 0.5640,
        0.2408, 0.5489, 0.8866, 0.1006, 0.5881, 0.7560, 0.7928, 0.8604, 0.4670,
        0.9285, 0.1482, 0.4541, 0.1307, 0.6221, 0.4902, 0.1147, 0.4415, 0.2987,
        0.7276, 0.2077, 0.7551, 0.9652, 0.4369, 0.2282, 0.0047, 0.2934, 0.4308,
        0.4190, 0.1442, 0.3650, 0.3056, 0.6535, 0.1211, 0.8721, 0.7408, 0.4220,
        0.5937, 0.3123, 0.9198, 0.0275, 0.5338, 0.4622, 0.7521, 0.3609, 0.4703,
        0.1736, 0.8976, 0.7616, 0.3756, 0.2416, 0.2907, 0.3246, 0.4305, 0.5717,
        0.0735, 0.0361, 0.5534, 0.4399, 0.9260, 0.6525, 0.3064, 0.4573, 0.9210,
        0.8269, 0.2424, 0.7494, 0.8945, 0.7098, 0.8078, 0.4707, 0.5715, 0.7232,
        0.4678, 0.5047])'''

        self.assertEqual(a_str, expected)

1334 1335 1336 1337 1338 1339
    def test_tensor_str_linewidth(self):
        with _test_eager_guard():
            self.func_test_tensor_str_linewidth()
        self.func_test_tensor_str_linewidth()

    def func_test_tensor_str_linewidth2(self):
1340 1341 1342 1343 1344 1345
        paddle.disable_static(paddle.CPUPlace())
        paddle.seed(2021)
        x = paddle.rand([128])
        paddle.set_printoptions(precision=4, linewidth=160, sci_mode=True)
        a_str = str(x)

1346
        expected = '''Tensor(shape=[128], dtype=float32, place=Place(cpu), stop_gradient=True,
1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360
       [3.7587e-01, 2.7798e-02, 2.4891e-01, 3.1097e-01, 9.1053e-01, 7.3811e-01, 1.9045e-01, 4.7258e-01, 2.4354e-01, 9.1415e-01, 3.3666e-01, 7.2428e-01,
        7.6640e-01, 9.9146e-01, 2.9215e-01, 1.3625e-01, 8.0957e-01, 2.9153e-01, 9.5642e-01, 9.9718e-01, 2.5732e-01, 2.5973e-01, 3.4292e-01, 2.4841e-01,
        9.5794e-01, 7.0029e-01, 4.1260e-01, 4.2737e-01, 7.3788e-03, 9.6863e-01, 9.9102e-01, 1.4416e-02, 6.5640e-01, 2.9318e-01, 7.1136e-01, 9.3008e-01,
        6.4209e-01, 5.3849e-02, 1.2730e-01, 5.7712e-01, 9.3359e-01, 6.4155e-01, 1.8320e-01, 9.3110e-01, 7.7021e-01, 7.4736e-01, 4.4793e-01, 3.3817e-01,
        5.5794e-01, 4.4412e-02, 9.8023e-01, 9.8735e-01, 3.0376e-01, 5.6397e-01, 2.4082e-01, 5.4893e-01, 8.8659e-01, 1.0065e-01, 5.8812e-01, 7.5600e-01,
        7.9280e-01, 8.6041e-01, 4.6701e-01, 9.2852e-01, 1.4821e-01, 4.5410e-01, 1.3074e-01, 6.2210e-01, 4.9024e-01, 1.1466e-01, 4.4154e-01, 2.9868e-01,
        7.2758e-01, 2.0766e-01, 7.5508e-01, 9.6522e-01, 4.3688e-01, 2.2823e-01, 4.7394e-03, 2.9342e-01, 4.3083e-01, 4.1902e-01, 1.4416e-01, 3.6500e-01,
        3.0560e-01, 6.5350e-01, 1.2115e-01, 8.7206e-01, 7.4081e-01, 4.2203e-01, 5.9372e-01, 3.1230e-01, 9.1979e-01, 2.7486e-02, 5.3383e-01, 4.6224e-01,
        7.5211e-01, 3.6094e-01, 4.7034e-01, 1.7355e-01, 8.9763e-01, 7.6165e-01, 3.7557e-01, 2.4157e-01, 2.9074e-01, 3.2458e-01, 4.3049e-01, 5.7171e-01,
        7.3509e-02, 3.6087e-02, 5.5341e-01, 4.3993e-01, 9.2601e-01, 6.5248e-01, 3.0640e-01, 4.5727e-01, 9.2104e-01, 8.2688e-01, 2.4243e-01, 7.4937e-01,
        8.9448e-01, 7.0981e-01, 8.0783e-01, 4.7065e-01, 5.7154e-01, 7.2319e-01, 4.6777e-01, 5.0465e-01])'''

        self.assertEqual(a_str, expected)

1361 1362 1363 1364 1365 1366
    def test_tensor_str_linewidth2(self):
        with _test_eager_guard():
            self.func_test_tensor_str_linewidth2()
        self.func_test_tensor_str_linewidth2()

    def func_tensor_str_bf16(self):
1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378
        paddle.disable_static(paddle.CPUPlace())
        a = paddle.to_tensor([[1.5, 1.0], [0, 0]])
        a = paddle.cast(a, dtype=core.VarDesc.VarType.BF16)
        paddle.set_printoptions(precision=4)
        a_str = str(a)

        expected = '''Tensor(shape=[2, 2], dtype=bfloat16, place=Place(cpu), stop_gradient=True,
       [[1.5000, 1.    ],
        [0.    , 0.    ]])'''

        self.assertEqual(a_str, expected)

1379 1380 1381 1382 1383
    def test_tensor_str_bf16(self):
        with _test_eager_guard():
            self.func_tensor_str_bf16()
        self.func_tensor_str_bf16()

1384
    def func_test_print_tensor_dtype(self):
L
Leo Chen 已提交
1385 1386 1387 1388 1389 1390 1391
        paddle.disable_static(paddle.CPUPlace())
        a = paddle.rand([1])
        a_str = str(a.dtype)

        expected = 'paddle.float32'

        self.assertEqual(a_str, expected)
1392 1393 1394 1395 1396

    def test_print_tensor_dtype(self):
        with _test_eager_guard():
            self.func_test_print_tensor_dtype()
        self.func_test_print_tensor_dtype()
L
Leo Chen 已提交
1397

L
Leo Chen 已提交
1398

1399
class TestVarBaseSetitem(unittest.TestCase):
1400
    def func_setUp(self):
1401 1402 1403
        self.set_dtype()
        self.tensor_x = paddle.to_tensor(np.ones((4, 2, 3)).astype(self.dtype))
        self.np_value = np.random.random((2, 3)).astype(self.dtype)
1404 1405
        self.tensor_value = paddle.to_tensor(self.np_value)

1406 1407 1408
    def set_dtype(self):
        self.dtype = "int32"

1409
    def _test(self, value):
J
Jiabin Yang 已提交
1410
        if _in_legacy_dygraph():
W
wanghuancoder 已提交
1411
            self.assertEqual(self.tensor_x.inplace_version, 0)
1412

1413
        id_origin = id(self.tensor_x)
1414
        self.tensor_x[0] = value
J
Jiabin Yang 已提交
1415
        if _in_legacy_dygraph():
W
wanghuancoder 已提交
1416
            self.assertEqual(self.tensor_x.inplace_version, 1)
1417

1418
        if isinstance(value, (int, float)):
1419
            result = np.zeros((2, 3)).astype(self.dtype) + value
1420 1421 1422 1423

        else:
            result = self.np_value

1424
        np.testing.assert_array_equal(self.tensor_x[0].numpy(), result)
1425 1426 1427
        self.assertEqual(id_origin, id(self.tensor_x))

        self.tensor_x[1:2] = value
J
Jiabin Yang 已提交
1428
        if _in_legacy_dygraph():
W
wanghuancoder 已提交
1429
            self.assertEqual(self.tensor_x.inplace_version, 2)
1430
        np.testing.assert_array_equal(self.tensor_x[1].numpy(), result)
1431 1432 1433
        self.assertEqual(id_origin, id(self.tensor_x))

        self.tensor_x[...] = value
J
Jiabin Yang 已提交
1434
        if _in_legacy_dygraph():
W
wanghuancoder 已提交
1435
            self.assertEqual(self.tensor_x.inplace_version, 3)
1436
        np.testing.assert_array_equal(self.tensor_x[3].numpy(), result)
1437 1438
        self.assertEqual(id_origin, id(self.tensor_x))

W
wanghuancoder 已提交
1439
    def func_test_value_tensor(self):
1440 1441
        self._test(self.tensor_value)

W
wanghuancoder 已提交
1442 1443
    def test_value_tensor(self):
        with _test_eager_guard():
1444
            self.func_setUp()
W
wanghuancoder 已提交
1445
            self.func_test_value_tensor()
1446
        self.func_setUp()
W
wanghuancoder 已提交
1447 1448 1449
        self.func_test_value_tensor()

    def func_test_value_numpy(self):
1450 1451
        self._test(self.np_value)

W
wanghuancoder 已提交
1452 1453
    def test_value_numpy(self):
        with _test_eager_guard():
1454
            self.func_setUp()
W
wanghuancoder 已提交
1455
            self.func_test_value_numpy()
1456
        self.func_setUp()
W
wanghuancoder 已提交
1457 1458 1459
        self.func_test_value_numpy()

    def func_test_value_int(self):
1460 1461
        self._test(10)

W
wanghuancoder 已提交
1462 1463
    def test_value_int(self):
        with _test_eager_guard():
1464
            self.func_setUp()
W
wanghuancoder 已提交
1465
            self.func_test_value_int()
1466
        self.func_setUp()
W
wanghuancoder 已提交
1467 1468
        self.func_test_value_int()

1469 1470 1471 1472 1473 1474 1475 1476 1477 1478

class TestVarBaseSetitemInt64(TestVarBaseSetitem):
    def set_dtype(self):
        self.dtype = "int64"


class TestVarBaseSetitemFp32(TestVarBaseSetitem):
    def set_dtype(self):
        self.dtype = "float32"

1479
    def func_test_value_float(self):
1480 1481 1482
        paddle.disable_static()
        self._test(3.3)

1483 1484 1485 1486 1487 1488 1489
    def test_value_float(self):
        with _test_eager_guard():
            self.func_setUp()
            self.func_test_value_float()
        self.func_setUp()
        self.func_test_value_float()

1490

1491 1492 1493 1494 1495
class TestVarBaseSetitemFp64(TestVarBaseSetitem):
    def set_dtype(self):
        self.dtype = "float64"


1496
class TestVarBaseSetitemBoolIndex(unittest.TestCase):
1497
    def func_setUp(self):
1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518
        paddle.disable_static()
        self.set_dtype()
        self.set_input()

    def set_input(self):
        self.tensor_x = paddle.to_tensor(np.ones((4, 2, 3)).astype(self.dtype))
        self.np_value = np.random.random((2, 3)).astype(self.dtype)
        self.tensor_value = paddle.to_tensor(self.np_value)

    def set_dtype(self):
        self.dtype = "int32"

    def _test(self, value):
        paddle.disable_static()
        self.assertEqual(self.tensor_x.inplace_version, 0)

        id_origin = id(self.tensor_x)
        index_1 = paddle.to_tensor(np.array([True, False, False, False]))
        self.tensor_x[index_1] = value
        self.assertEqual(self.tensor_x.inplace_version, 1)

1519
        if isinstance(value, (int, float)):
1520 1521 1522 1523 1524
            result = np.zeros((2, 3)).astype(self.dtype) + value

        else:
            result = self.np_value

1525
        np.testing.assert_array_equal(self.tensor_x[0].numpy(), result)
1526 1527 1528 1529 1530
        self.assertEqual(id_origin, id(self.tensor_x))

        index_2 = paddle.to_tensor(np.array([False, True, False, False]))
        self.tensor_x[index_2] = value
        self.assertEqual(self.tensor_x.inplace_version, 2)
1531
        np.testing.assert_array_equal(self.tensor_x[1].numpy(), result)
1532 1533 1534 1535 1536
        self.assertEqual(id_origin, id(self.tensor_x))

        index_3 = paddle.to_tensor(np.array([True, True, True, True]))
        self.tensor_x[index_3] = value
        self.assertEqual(self.tensor_x.inplace_version, 3)
1537
        np.testing.assert_array_equal(self.tensor_x[3].numpy(), result)
1538 1539
        self.assertEqual(id_origin, id(self.tensor_x))

1540
    def func_test_value_tensor(self):
1541 1542 1543
        paddle.disable_static()
        self._test(self.tensor_value)

1544 1545 1546 1547 1548 1549 1550 1551
    def test_value_tensor(self):
        with _test_eager_guard():
            self.func_setUp()
            self.func_test_value_tensor()
        self.func_setUp()
        self.func_test_value_tensor()

    def func_test_value_numpy(self):
1552 1553 1554
        paddle.disable_static()
        self._test(self.np_value)

1555 1556 1557 1558 1559 1560 1561 1562
    def test_value_numpy(self):
        with _test_eager_guard():
            self.func_setUp()
            self.func_test_value_numpy()
        self.func_setUp()
        self.func_test_value_numpy()

    def func_test_value_int(self):
1563 1564 1565
        paddle.disable_static()
        self._test(10)

1566 1567 1568 1569 1570 1571 1572
    def test_value_int(self):
        with _test_eager_guard():
            self.func_setUp()
            self.func_test_value_int()
        self.func_setUp()
        self.func_test_value_int()

1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588

class TestVarBaseSetitemBoolScalarIndex(unittest.TestCase):
    def set_input(self):
        self.tensor_x = paddle.to_tensor(np.ones((1, 2, 3)).astype(self.dtype))
        self.np_value = np.random.random((2, 3)).astype(self.dtype)
        self.tensor_value = paddle.to_tensor(self.np_value)

    def _test(self, value):
        paddle.disable_static()
        self.assertEqual(self.tensor_x.inplace_version, 0)

        id_origin = id(self.tensor_x)
        index = paddle.to_tensor(np.array([True]))
        self.tensor_x[index] = value
        self.assertEqual(self.tensor_x.inplace_version, 1)

1589
        if isinstance(value, (int, float)):
1590 1591 1592 1593 1594
            result = np.zeros((2, 3)).astype(self.dtype) + value

        else:
            result = self.np_value

1595
        np.testing.assert_array_equal(self.tensor_x[0].numpy(), result)
1596 1597 1598
        self.assertEqual(id_origin, id(self.tensor_x))


1599
class TestVarBaseInplaceVersion(unittest.TestCase):
1600
    def func_test_setitem(self):
1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611
        paddle.disable_static()

        var = paddle.ones(shape=[4, 2, 3], dtype="float32")
        self.assertEqual(var.inplace_version, 0)

        var[1] = 1
        self.assertEqual(var.inplace_version, 1)

        var[1:2] = 1
        self.assertEqual(var.inplace_version, 2)

1612 1613 1614 1615 1616 1617
    def test_setitem(self):
        with _test_eager_guard():
            self.func_test_setitem()
        self.func_test_setitem()

    def func_test_bump_inplace_version(self):
1618 1619 1620 1621 1622 1623 1624 1625 1626 1627
        paddle.disable_static()
        var = paddle.ones(shape=[4, 2, 3], dtype="float32")
        self.assertEqual(var.inplace_version, 0)

        var._bump_inplace_version()
        self.assertEqual(var.inplace_version, 1)

        var._bump_inplace_version()
        self.assertEqual(var.inplace_version, 2)

1628 1629 1630 1631 1632
    def test_bump_inplace_version(self):
        with _test_eager_guard():
            self.func_test_bump_inplace_version()
        self.func_test_bump_inplace_version()

1633

1634
class TestVarBaseSlice(unittest.TestCase):
1635
    def func_test_slice(self):
1636 1637 1638 1639 1640 1641 1642
        paddle.disable_static()
        np_x = np.random.random((3, 8, 8))
        x = paddle.to_tensor(np_x, dtype="float64")
        actual_x = x._slice(0, 1)
        actual_x = paddle.to_tensor(actual_x)
        self.assertEqual(actual_x.numpy().all(), np_x[0:1].all())

1643 1644 1645 1646 1647
    def test_slice(self):
        with _test_eager_guard():
            self.func_test_slice()
        self.func_test_slice()

1648 1649

class TestVarBaseClear(unittest.TestCase):
1650
    def func_test_clear(self):
1651 1652 1653 1654 1655 1656
        paddle.disable_static()
        np_x = np.random.random((3, 8, 8))
        x = paddle.to_tensor(np_x, dtype="float64")
        x._clear()
        self.assertEqual(str(x), "Tensor(Not initialized)")

1657 1658 1659 1660 1661
    def test_clear(self):
        with _test_eager_guard():
            self.func_test_clear()
        self.func_test_clear()

1662 1663

class TestVarBaseOffset(unittest.TestCase):
1664
    def func_offset(self):
1665 1666 1667 1668 1669 1670 1671 1672
        paddle.disable_static()
        np_x = np.random.random((3, 8, 8))
        x = paddle.to_tensor(np_x, dtype="float64")
        expected_offset = 0
        actual_x = x._slice(expected_offset, 1)
        actual_x = paddle.to_tensor(actual_x)
        self.assertEqual(actual_x._offset(), expected_offset)

1673 1674 1675 1676 1677
    def test_offset(self):
        with _test_eager_guard():
            self.func_offset()
        self.func_offset()

1678

1679
class TestVarBaseShareBufferTo(unittest.TestCase):
1680
    def func_test_share_buffer_To(self):
1681
        paddle.disable_static()
1682 1683 1684
        np_src = np.random.random((3, 8, 8))
        src = paddle.to_tensor(np_src, dtype="float64")
        # empty_var
1685 1686 1687 1688
        if _in_legacy_dygraph():
            dst = core.VarBase()
        else:
            dst = core.eager.Tensor()
1689 1690
        src._share_buffer_to(dst)
        self.assertEqual(src._is_shared_buffer_with(dst), True)
1691

1692 1693 1694 1695 1696
    def test_share_buffer_To(self):
        with _test_eager_guard():
            self.func_test_share_buffer_To()
        self.func_test_share_buffer_To()

1697 1698

class TestVarBaseTo(unittest.TestCase):
1699
    def func_setUp(self):
1700 1701 1702 1703
        paddle.disable_static()
        self.np_x = np.random.random((3, 8, 8))
        self.x = paddle.to_tensor(self.np_x, dtype="float32")

1704
    def func_test_to_api(self):
1705 1706
        x_double = self.x._to(dtype='double')
        self.assertEqual(x_double.dtype, paddle.fluid.core.VarDesc.VarType.FP64)
1707
        np.testing.assert_allclose(self.np_x, x_double, rtol=1e-05)
1708 1709 1710

        x_ = self.x._to()
        self.assertEqual(self.x.dtype, paddle.fluid.core.VarDesc.VarType.FP64)
1711
        np.testing.assert_allclose(self.np_x, x_, rtol=1e-05)
1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724

        if paddle.fluid.is_compiled_with_cuda():
            x_gpu = self.x._to(device=paddle.CUDAPlace(0))
            self.assertTrue(x_gpu.place.is_gpu_place())
            self.assertEqual(x_gpu.place.gpu_device_id(), 0)

            x_gpu0 = self.x._to(device='gpu:0')
            self.assertTrue(x_gpu0.place.is_gpu_place())
            self.assertEqual(x_gpu0.place.gpu_device_id(), 0)

            x_gpu1 = self.x._to(device='gpu:0', dtype="float64")
            self.assertTrue(x_gpu1.place.is_gpu_place())
            self.assertEqual(x_gpu1.place.gpu_device_id(), 0)
1725 1726 1727
            self.assertEqual(
                x_gpu1.dtype, paddle.fluid.core.VarDesc.VarType.FP64
            )
1728 1729 1730 1731

            x_gpu2 = self.x._to(device='gpu:0', dtype="float16")
            self.assertTrue(x_gpu2.place.is_gpu_place())
            self.assertEqual(x_gpu2.place.gpu_device_id(), 0)
1732 1733 1734
            self.assertEqual(
                x_gpu2.dtype, paddle.fluid.core.VarDesc.VarType.FP16
            )
1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752

        x_cpu = self.x._to(device=paddle.CPUPlace())
        self.assertTrue(x_cpu.place.is_cpu_place())

        x_cpu0 = self.x._to(device='cpu')
        self.assertTrue(x_cpu0.place.is_cpu_place())

        x_cpu1 = self.x._to(device=paddle.CPUPlace(), dtype="float64")
        self.assertTrue(x_cpu1.place.is_cpu_place())
        self.assertEqual(x_cpu1.dtype, paddle.fluid.core.VarDesc.VarType.FP64)

        x_cpu2 = self.x._to(device='cpu', dtype="float16")
        self.assertTrue(x_cpu2.place.is_cpu_place())
        self.assertEqual(x_cpu2.dtype, paddle.fluid.core.VarDesc.VarType.FP16)

        self.assertRaises(ValueError, self.x._to, device=1)
        self.assertRaises(AssertionError, self.x._to, blocking=1)

1753 1754 1755 1756 1757 1758 1759
    def test_to_api(self):
        with _test_eager_guard():
            self.func_setUp()
            self.func_test_to_api()
        self.func_setUp()
        self.func_test_to_api()

1760 1761

class TestVarBaseInitVarBaseFromTensorWithDevice(unittest.TestCase):
1762
    def func_test_varbase_init(self):
1763 1764 1765 1766 1767 1768 1769
        paddle.disable_static()
        t = fluid.Tensor()
        np_x = np.random.random((3, 8, 8))
        t.set(np_x, fluid.CPUPlace())

        if paddle.fluid.is_compiled_with_cuda():
            device = paddle.CUDAPlace(0)
1770 1771 1772 1773
            if _in_legacy_dygraph():
                tmp = fluid.core.VarBase(t, device)
            else:
                tmp = fluid.core.eager.Tensor(t, device)
1774 1775 1776 1777
            self.assertTrue(tmp.place.is_gpu_place())
            self.assertEqual(tmp.numpy().all(), np_x.all())

        device = paddle.CPUPlace()
1778 1779 1780 1781
        if _in_legacy_dygraph():
            tmp = fluid.core.VarBase(t, device)
        else:
            tmp = fluid.core.eager.Tensor(t, device)
1782 1783
        self.assertEqual(tmp.numpy().all(), np_x.all())

1784 1785 1786 1787 1788
    def test_varbase_init(self):
        with _test_eager_guard():
            self.func_test_varbase_init()
        self.func_test_varbase_init()

1789 1790

class TestVarBaseNumel(unittest.TestCase):
1791
    def func_test_numel_normal(self):
1792 1793 1794 1795 1796 1797 1798
        paddle.disable_static()
        np_x = np.random.random((3, 8, 8))
        x = paddle.to_tensor(np_x, dtype="float64")
        x_actual_numel = x._numel()
        x_expected_numel = np.product((3, 8, 8))
        self.assertEqual(x_actual_numel, x_expected_numel)

1799 1800 1801 1802 1803 1804
    def test_numel_normal(self):
        with _test_eager_guard():
            self.func_test_numel_normal()
        self.func_test_numel_normal()

    def func_test_numel_without_holder(self):
1805
        paddle.disable_static()
1806 1807 1808 1809
        if _in_legacy_dygraph():
            x_without_holder = core.VarBase()
        else:
            x_without_holder = core.eager.Tensor()
1810 1811 1812
        x_actual_numel = x_without_holder._numel()
        self.assertEqual(x_actual_numel, 0)

1813 1814 1815 1816 1817
    def ttest_numel_without_holder(self):
        with _test_eager_guard():
            self.func_test_numel_without_holder()
        self.func_test_numel_without_holder()

1818 1819

class TestVarBaseCopyGradientFrom(unittest.TestCase):
1820
    def func_test_copy_gradient_from(self):
1821 1822 1823 1824 1825 1826 1827 1828 1829 1830
        paddle.disable_static()
        np_x = np.random.random((2, 2))
        np_y = np.random.random((2, 2))
        x = paddle.to_tensor(np_x, dtype="float64", stop_gradient=False)
        y = paddle.to_tensor(np_y, dtype="float64")
        out = x + x
        out.backward()
        x._copy_gradient_from(y)
        self.assertEqual(x.grad.numpy().all(), np_y.all())

1831 1832 1833 1834 1835
    def test_copy_gradient_from(self):
        with _test_eager_guard():
            self.func_test_copy_gradient_from()
        self.func_test_copy_gradient_from()

1836

1837 1838 1839 1840 1841 1842 1843
class TestEagerTensorGradNameValue(unittest.TestCase):
    def test_eager_tensor_grad_name_value(self):
        with _test_eager_guard():
            a_np = np.array([2, 3]).astype('float32')
            a = paddle.to_tensor(a_np)
            a.stop_gradient = False
            b = a**2
1844
            self.assertIsNone(a._grad_value())
1845
            b.backward()
1846
            # Note, for new dygraph, there are no generated grad name, so we skip the name check.
1847
            self.assertIsNotNone(a._grad_value())
1848 1849


L
Leo Chen 已提交
1850 1851
if __name__ == '__main__':
    unittest.main()