test_egr_python_api.py 44.5 KB
Newer Older
1
# Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
2
#
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
6
#
7
#     http://www.apache.org/licenses/LICENSE-2.0
8
#
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 17
import copy
import unittest

18
import numpy as np
19 20 21

import paddle
import paddle.fluid.core as core
22 23 24 25 26 27 28
from paddle.fluid.framework import (
    EagerParamBase,
    _current_expected_place,
    _disable_legacy_dygraph,
    _test_eager_guard,
    in_dygraph_mode,
)
29 30 31 32


class EagerScaleTestCase(unittest.TestCase):
    def test_scale_base(self):
J
Jiabin Yang 已提交
33
        with _test_eager_guard():
34 35 36 37 38 39 40 41 42 43 44 45
            paddle.set_device("cpu")
            arr = np.ones([4, 16, 16, 32]).astype('float32')
            tensor = paddle.to_tensor(arr, 'float32', core.CPUPlace())
            print(tensor)
            tensor = core.eager.scale(tensor, 2.0, 0.9, True, False)
            for i in range(0, 100):
                tensor = core.eager.scale(tensor, 2.0, 0.9, True, False)
            print(tensor)
            self.assertEqual(tensor.shape, [4, 16, 16, 32])
            self.assertEqual(tensor.stop_gradient, True)

    def test_retain_grad_and_run_backward(self):
J
Jiabin Yang 已提交
46
        with _test_eager_guard():
47 48 49
            paddle.set_device("cpu")

            input_data = np.ones([4, 16, 16, 32]).astype('float32')
50 51 52
            data_eager = paddle.to_tensor(
                input_data, 'float32', core.CPUPlace(), False
            )
53 54 55 56

            grad_data = np.ones([4, 16, 16, 32]).astype('float32')
            grad_eager = paddle.to_tensor(grad_data, 'float32', core.CPUPlace())

57
            data_eager.retain_grads()
58 59

            out_eager = core.eager.scale(data_eager, 1.0, 0.9, True, True)
60
            self.assertIsNone(data_eager.grad)
61
            out_eager.backward(grad_eager, False)
62
            self.assertIsNotNone(data_eager.grad)
63
            np.testing.assert_array_equal(data_eager.grad.numpy(), input_data)
64

65 66 67 68 69
    def test_retain_grad_and_run_backward_raises(self):
        with _test_eager_guard():
            paddle.set_device("cpu")

            input_data = np.ones([4, 16, 16, 32]).astype('float32')
70 71 72
            data_eager = paddle.to_tensor(
                input_data, 'float32', core.CPUPlace(), False
            )
73 74 75 76

            grad_data = np.ones([4, 16, 16, 32]).astype('float32')
            grad_data2 = np.ones([4, 16]).astype('float32')
            grad_eager = paddle.to_tensor(grad_data, 'float32', core.CPUPlace())
77 78 79
            grad_eager2 = paddle.to_tensor(
                grad_data2, 'float32', core.CPUPlace()
            )
80 81 82 83

            data_eager.retain_grads()

            out_eager = core.eager.scale(data_eager, 1.0, 0.9, True, True)
84
            self.assertIsNone(data_eager.grad)
85
            with self.assertRaisesRegexp(
86 87
                AssertionError, "The type of grad_tensor must be paddle.Tensor"
            ):
88 89 90
                out_eager.backward(grad_data, False)

            with self.assertRaisesRegexp(
91 92 93
                AssertionError,
                "Tensor shape not match, Tensor of grad_tensor /*",
            ):
94 95
                out_eager.backward(grad_eager2, False)

96 97

class EagerDtypeTestCase(unittest.TestCase):
J
Jiabin Yang 已提交
98 99
    def check_to_tesnsor_and_numpy(self, dtype, proto_dtype):
        with _test_eager_guard():
100 101
            arr = np.random.random([4, 16, 16, 32]).astype(dtype)
            tensor = paddle.to_tensor(arr, dtype)
J
Jiabin Yang 已提交
102
            self.assertEqual(tensor.dtype, proto_dtype)
103
            np.testing.assert_array_equal(arr, tensor.numpy())
104 105

    def test_dtype_base(self):
J
Jiabin Yang 已提交
106 107 108 109 110 111 112 113 114 115
        print("Test_dtype")
        self.check_to_tesnsor_and_numpy('bool', core.VarDesc.VarType.BOOL)
        self.check_to_tesnsor_and_numpy('int8', core.VarDesc.VarType.INT8)
        self.check_to_tesnsor_and_numpy('uint8', core.VarDesc.VarType.UINT8)
        self.check_to_tesnsor_and_numpy('int16', core.VarDesc.VarType.INT16)
        self.check_to_tesnsor_and_numpy('int32', core.VarDesc.VarType.INT32)
        self.check_to_tesnsor_and_numpy('int64', core.VarDesc.VarType.INT64)
        self.check_to_tesnsor_and_numpy('float16', core.VarDesc.VarType.FP16)
        self.check_to_tesnsor_and_numpy('float32', core.VarDesc.VarType.FP32)
        self.check_to_tesnsor_and_numpy('float64', core.VarDesc.VarType.FP64)
116 117 118 119 120 121
        self.check_to_tesnsor_and_numpy(
            'complex64', core.VarDesc.VarType.COMPLEX64
        )
        self.check_to_tesnsor_and_numpy(
            'complex128', core.VarDesc.VarType.COMPLEX128
        )
122 123


124
class EagerVariablePropertiesAndMethodsTestCase(unittest.TestCase):
125
    def constructor(self, place):
126
        egr_tensor = core.eager.Tensor()
127 128
        self.assertEqual(egr_tensor.persistable, False)
        self.assertTrue("generated" in egr_tensor.name)
129
        self.assertEqual(egr_tensor.shape, [0])
130 131 132
        self.assertEqual(egr_tensor.dtype, core.VarDesc.VarType.FP32)
        self.assertEqual(egr_tensor.stop_gradient, True)

133 134 135 136 137 138 139
        egr_tensor0 = core.eager.Tensor(
            core.VarDesc.VarType.FP32,
            [4, 16, 16, 32],
            "test_eager_tensor",
            core.VarDesc.VarType.LOD_TENSOR,
            True,
        )
140 141 142 143 144 145
        self.assertEqual(egr_tensor0.persistable, True)
        self.assertEqual(egr_tensor0.name, "test_eager_tensor")
        self.assertEqual(egr_tensor0.shape, [4, 16, 16, 32])
        self.assertEqual(egr_tensor0.dtype, core.VarDesc.VarType.FP32)

        arr0 = np.random.rand(4, 16, 16, 32).astype('float32')
146 147 148
        egr_tensor1 = core.eager.Tensor(
            arr0, place, True, False, "numpy_tensor1", False
        )
149 150 151 152 153 154
        self.assertEqual(egr_tensor1.persistable, True)
        self.assertEqual(egr_tensor1.name, "numpy_tensor1")
        self.assertEqual(egr_tensor1.shape, [4, 16, 16, 32])
        self.assertEqual(egr_tensor1.dtype, core.VarDesc.VarType.FP32)
        self.assertEqual(egr_tensor1.stop_gradient, False)
        self.assertTrue(egr_tensor1.place._equals(place))
155
        np.testing.assert_array_equal(egr_tensor1.numpy(), arr0)
156 157

        arr1 = np.random.randint(100, size=(4, 16, 16, 32), dtype=np.int64)
158 159 160
        egr_tensor2 = core.eager.Tensor(
            arr1, place, False, True, "numpy_tensor2", True
        )
161 162 163 164 165 166
        self.assertEqual(egr_tensor2.persistable, False)
        self.assertEqual(egr_tensor2.name, "numpy_tensor2")
        self.assertEqual(egr_tensor2.shape, [4, 16, 16, 32])
        self.assertEqual(egr_tensor2.dtype, core.VarDesc.VarType.INT64)
        self.assertEqual(egr_tensor2.stop_gradient, True)
        self.assertTrue(egr_tensor2.place._equals(place))
167
        np.testing.assert_array_equal(egr_tensor2.numpy(), arr1)
168 169

        arr2 = np.random.rand(4, 16, 16, 32, 64).astype('float32')
170
        egr_tensor3 = core.eager.Tensor(arr2)
171 172 173 174 175 176 177
        self.assertEqual(egr_tensor3.persistable, False)
        self.assertTrue("generated_tensor" in egr_tensor3.name)
        self.assertEqual(egr_tensor3.shape, [4, 16, 16, 32, 64])
        self.assertEqual(egr_tensor3.dtype, core.VarDesc.VarType.FP32)
        self.assertEqual(egr_tensor3.stop_gradient, True)
        self.assertTrue(
            egr_tensor3.place._equals(
178 179 180
                paddle.fluid.framework._current_expected_place()
            )
        )
181
        np.testing.assert_array_equal(egr_tensor3.numpy(), arr2)
182 183

        egr_tensor3.stop_gradient = False
184
        egr_tensor4 = core.eager.Tensor(egr_tensor3)
185 186 187 188 189 190 191
        self.assertEqual(egr_tensor4.persistable, False)
        self.assertTrue("generated_tensor" in egr_tensor4.name)
        self.assertEqual(egr_tensor4.shape, egr_tensor3.shape)
        self.assertEqual(egr_tensor4.dtype, egr_tensor3.dtype)
        self.assertEqual(egr_tensor4.stop_gradient, True)
        self.assertTrue(
            egr_tensor4.place._equals(
192 193 194
                paddle.fluid.framework._current_expected_place()
            )
        )
195
        np.testing.assert_array_equal(egr_tensor4.numpy(), egr_tensor3.numpy())
196 197

        arr4 = np.random.rand(4, 16, 16, 32).astype('float32')
198
        egr_tensor5 = core.eager.Tensor(arr4, place)
199 200 201 202 203 204
        self.assertEqual(egr_tensor5.persistable, False)
        self.assertTrue("generated_tensor" in egr_tensor5.name)
        self.assertEqual(egr_tensor5.shape, [4, 16, 16, 32])
        self.assertEqual(egr_tensor5.dtype, core.VarDesc.VarType.FP32)
        self.assertEqual(egr_tensor5.stop_gradient, True)
        self.assertTrue(egr_tensor5.place._equals(place))
205
        np.testing.assert_array_equal(egr_tensor5.numpy(), arr4)
206

207
        egr_tensor6 = core.eager.Tensor(egr_tensor5, core.CPUPlace())
208 209 210 211 212 213
        self.assertEqual(egr_tensor6.persistable, False)
        self.assertTrue("generated_tensor" in egr_tensor6.name)
        self.assertEqual(egr_tensor6.shape, [4, 16, 16, 32])
        self.assertEqual(egr_tensor6.dtype, core.VarDesc.VarType.FP32)
        self.assertEqual(egr_tensor6.stop_gradient, True)
        self.assertEqual(egr_tensor6.place.is_cpu_place(), True)
214
        np.testing.assert_array_equal(egr_tensor6.numpy(), egr_tensor5.numpy())
215

216
        egr_tensor7 = core.eager.Tensor(arr4, place, True)
217 218 219 220 221 222
        self.assertEqual(egr_tensor7.persistable, True)
        self.assertTrue("generated_tensor" in egr_tensor7.name)
        self.assertEqual(egr_tensor7.shape, [4, 16, 16, 32])
        self.assertEqual(egr_tensor7.dtype, core.VarDesc.VarType.FP32)
        self.assertEqual(egr_tensor7.stop_gradient, True)
        self.assertTrue(egr_tensor7.place._equals(place))
223
        np.testing.assert_array_equal(egr_tensor7.numpy(), arr4)
224

225
        egr_tensor8 = core.eager.Tensor(egr_tensor6, place, "egr_tensor8")
226 227 228 229 230 231
        self.assertEqual(egr_tensor8.persistable, False)
        self.assertEqual(egr_tensor8.name, "egr_tensor8")
        self.assertEqual(egr_tensor8.shape, [4, 16, 16, 32])
        self.assertEqual(egr_tensor8.dtype, core.VarDesc.VarType.FP32)
        self.assertEqual(egr_tensor8.stop_gradient, True)
        self.assertTrue(egr_tensor8.place._equals(place))
232
        np.testing.assert_array_equal(egr_tensor8.numpy(), egr_tensor5.numpy())
233

234
        egr_tensor9 = core.eager.Tensor(arr4, place, True, True)
235 236 237 238 239 240
        self.assertEqual(egr_tensor9.persistable, True)
        self.assertTrue("generated_tensor" in egr_tensor9.name)
        self.assertEqual(egr_tensor9.shape, [4, 16, 16, 32])
        self.assertEqual(egr_tensor9.dtype, core.VarDesc.VarType.FP32)
        self.assertEqual(egr_tensor9.stop_gradient, True)
        self.assertTrue(egr_tensor9.place._equals(place))
241
        np.testing.assert_array_equal(egr_tensor9.numpy(), arr4)
242

243 244 245
        x = np.random.rand(3, 3).astype('float32')
        t = paddle.fluid.Tensor()
        t.set(x, paddle.fluid.CPUPlace())
246
        egr_tensor10 = core.eager.Tensor(t, place)
247 248 249 250 251 252
        self.assertEqual(egr_tensor10.persistable, False)
        self.assertTrue("generated_tensor" in egr_tensor10.name)
        self.assertEqual(egr_tensor10.shape, [3, 3])
        self.assertEqual(egr_tensor10.dtype, core.VarDesc.VarType.FP32)
        self.assertEqual(egr_tensor10.stop_gradient, True)
        self.assertTrue(egr_tensor10.place._equals(place))
253
        np.testing.assert_array_equal(egr_tensor10.numpy(), x)
254

255
        egr_tensor11 = core.eager.Tensor(t, place, "framework_constructed")
256 257 258 259 260 261
        self.assertEqual(egr_tensor11.persistable, False)
        self.assertTrue("framework_constructed" in egr_tensor11.name)
        self.assertEqual(egr_tensor11.shape, [3, 3])
        self.assertEqual(egr_tensor11.dtype, core.VarDesc.VarType.FP32)
        self.assertEqual(egr_tensor11.stop_gradient, True)
        self.assertTrue(egr_tensor11.place._equals(place))
262
        np.testing.assert_array_equal(egr_tensor11.numpy(), x)
263

264
        egr_tensor12 = core.eager.Tensor(t)
265 266 267 268 269 270
        self.assertEqual(egr_tensor12.persistable, False)
        self.assertTrue("generated_tensor" in egr_tensor12.name)
        self.assertEqual(egr_tensor12.shape, [3, 3])
        self.assertEqual(egr_tensor12.dtype, core.VarDesc.VarType.FP32)
        self.assertEqual(egr_tensor12.stop_gradient, True)
        self.assertTrue(egr_tensor12.place._equals(paddle.fluid.CPUPlace()))
271
        np.testing.assert_array_equal(egr_tensor12.numpy(), x)
272

273 274 275
        zero_dim_param = EagerParamBase(shape=[], dtype="float32")
        self.assertEqual(zero_dim_param.shape, [])

276
        with self.assertRaisesRegexp(
277 278
            ValueError, "The shape of Parameter should not be None"
        ):
279 280 281
            eager_param = EagerParamBase(shape=None, dtype="float32")

        with self.assertRaisesRegexp(
282 283
            ValueError, "The dtype of Parameter should not be None"
        ):
284 285 286
            eager_param = EagerParamBase(shape=[1, 1], dtype=None)

        with self.assertRaisesRegexp(
287 288
            ValueError,
            "Each dimension of shape for Parameter must be greater than 0, but received /*",
289 290 291 292 293 294 295 296
        ):
            eager_param = EagerParamBase(shape=[-1], dtype="float32")

        eager_param = EagerParamBase(shape=[1, 1], dtype="float32")
        self.assertTrue(eager_param.trainable)
        eager_param.trainable = False
        self.assertFalse(eager_param.trainable)
        with self.assertRaisesRegexp(
297 298
            ValueError, "The type of trainable MUST be bool, but the type is /*"
        ):
299 300
            eager_param.trainable = "False"

301 302 303
        eager_param_2 = EagerParamBase(
            shape=paddle.shape(paddle.to_tensor([1, 2, 3, 4])), dtype="float32"
        )
304 305 306 307
        self.assertTrue(eager_param_2.trainable)
        eager_param_2.trainable = False
        self.assertFalse(eager_param_2.trainable)
        with self.assertRaisesRegexp(
308 309
            ValueError, "The type of trainable MUST be bool, but the type is /*"
        ):
310 311
            eager_param_2.trainable = "False"

312 313 314 315 316 317 318 319 320 321
    def test_constructor(self):
        print("Test_constructor")
        paddle.set_device("cpu")
        place_list = [core.CPUPlace()]
        if core.is_compiled_with_cuda():
            place_list.append(core.CUDAPlace(0))
        with _test_eager_guard():
            for p in place_list:
                self.constructor(p)

322
    def constructor_with_kwargs(self, place):
323
        # init Tensor by Python array
324 325
        arr = np.random.rand(4, 16, 16, 32).astype('float32')

326
        egr_tensor0 = core.eager.Tensor(value=arr)
327 328 329 330 331
        self.assertEqual(egr_tensor0.persistable, False)
        self.assertTrue("generated" in egr_tensor0.name)
        self.assertEqual(egr_tensor0.shape, [4, 16, 16, 32])
        self.assertTrue(
            egr_tensor0.place._equals(
332 333 334
                paddle.fluid.framework._current_expected_place()
            )
        )
335 336 337
        self.assertEqual(egr_tensor0.dtype, core.VarDesc.VarType.FP32)
        self.assertEqual(egr_tensor0.stop_gradient, True)

338
        egr_tensor1 = core.eager.Tensor(value=arr, place=place)
339 340 341 342 343 344 345
        self.assertEqual(egr_tensor1.persistable, False)
        self.assertTrue("generated" in egr_tensor1.name)
        self.assertEqual(egr_tensor1.shape, [4, 16, 16, 32])
        self.assertTrue(egr_tensor1.place._equals(place))
        self.assertEqual(egr_tensor1.dtype, core.VarDesc.VarType.FP32)
        self.assertEqual(egr_tensor1.stop_gradient, True)

346
        egr_tensor2 = core.eager.Tensor(arr, place=place)
347 348 349 350 351 352 353
        self.assertEqual(egr_tensor2.persistable, False)
        self.assertTrue("generated" in egr_tensor2.name)
        self.assertEqual(egr_tensor2.shape, [4, 16, 16, 32])
        self.assertTrue(egr_tensor2.place._equals(place))
        self.assertEqual(egr_tensor2.dtype, core.VarDesc.VarType.FP32)
        self.assertEqual(egr_tensor2.stop_gradient, True)

354 355 356
        egr_tensor3 = core.eager.Tensor(
            arr, place=place, name="new_eager_tensor"
        )
357 358 359 360 361 362 363
        self.assertEqual(egr_tensor3.persistable, False)
        self.assertTrue("new_eager_tensor" in egr_tensor3.name)
        self.assertEqual(egr_tensor3.shape, [4, 16, 16, 32])
        self.assertTrue(egr_tensor3.place._equals(place))
        self.assertEqual(egr_tensor3.dtype, core.VarDesc.VarType.FP32)
        self.assertEqual(egr_tensor3.stop_gradient, True)

364 365 366
        egr_tensor4 = core.eager.Tensor(
            arr, place=place, persistable=True, name="new_eager_tensor"
        )
367 368 369 370 371 372 373
        self.assertEqual(egr_tensor4.persistable, True)
        self.assertTrue("new_eager_tensor" in egr_tensor4.name)
        self.assertEqual(egr_tensor4.shape, [4, 16, 16, 32])
        self.assertTrue(egr_tensor4.place._equals(place))
        self.assertEqual(egr_tensor4.dtype, core.VarDesc.VarType.FP32)
        self.assertEqual(egr_tensor4.stop_gradient, True)

374 375 376 377 378 379 380
        egr_tensor5 = core.eager.Tensor(
            arr,
            core.CPUPlace(),
            persistable=True,
            name="new_eager_tensor",
            zero_copy=True,
        )
381 382 383 384 385 386 387
        self.assertEqual(egr_tensor5.persistable, True)
        self.assertTrue("new_eager_tensor" in egr_tensor5.name)
        self.assertEqual(egr_tensor5.shape, [4, 16, 16, 32])
        self.assertTrue(egr_tensor5.place.is_cpu_place())
        self.assertEqual(egr_tensor5.dtype, core.VarDesc.VarType.FP32)
        self.assertEqual(egr_tensor5.stop_gradient, True)

388 389 390 391 392 393 394
        egr_tensor6 = core.eager.Tensor(
            arr,
            place=core.CPUPlace(),
            persistable=True,
            name="new_eager_tensor",
            zero_copy=True,
        )
395 396 397 398 399 400 401
        self.assertEqual(egr_tensor6.persistable, True)
        self.assertTrue("new_eager_tensor" in egr_tensor6.name)
        self.assertEqual(egr_tensor6.shape, [4, 16, 16, 32])
        self.assertTrue(egr_tensor6.place.is_cpu_place())
        self.assertEqual(egr_tensor6.dtype, core.VarDesc.VarType.FP32)
        self.assertEqual(egr_tensor6.stop_gradient, True)

402 403 404 405 406 407 408
        egr_tensor7 = core.eager.Tensor(
            arr,
            place=place,
            persistable=True,
            name="new_eager_tensor",
            zero_copy=True,
        )
409 410 411 412 413 414 415
        self.assertEqual(egr_tensor7.persistable, True)
        self.assertTrue("new_eager_tensor" in egr_tensor7.name)
        self.assertEqual(egr_tensor7.shape, [4, 16, 16, 32])
        self.assertTrue(egr_tensor7.place._equals(place))
        self.assertEqual(egr_tensor7.dtype, core.VarDesc.VarType.FP32)
        self.assertEqual(egr_tensor7.stop_gradient, True)

416 417 418 419 420 421 422 423
        egr_tensor8 = core.eager.Tensor(
            arr,
            place=place,
            persistable=True,
            name="new_eager_tensor",
            zero_copy=True,
            stop_gradient=False,
        )
424 425 426 427 428 429 430
        self.assertEqual(egr_tensor8.persistable, True)
        self.assertTrue("new_eager_tensor" in egr_tensor8.name)
        self.assertEqual(egr_tensor8.shape, [4, 16, 16, 32])
        self.assertTrue(egr_tensor8.place._equals(place))
        self.assertEqual(egr_tensor8.dtype, core.VarDesc.VarType.FP32)
        self.assertEqual(egr_tensor8.stop_gradient, False)

431 432 433
        egr_tensor9 = core.eager.Tensor(
            arr, place, True, True, "new_eager_tensor", stop_gradient=False
        )
434 435 436 437 438 439 440
        self.assertEqual(egr_tensor9.persistable, True)
        self.assertTrue("new_eager_tensor" in egr_tensor9.name)
        self.assertEqual(egr_tensor9.shape, [4, 16, 16, 32])
        self.assertTrue(egr_tensor9.place._equals(place))
        self.assertEqual(egr_tensor9.dtype, core.VarDesc.VarType.FP32)
        self.assertEqual(egr_tensor9.stop_gradient, False)

441 442 443
        egr_tensor10 = core.eager.Tensor(
            arr, place, True, True, name="new_eager_tensor", stop_gradient=False
        )
444 445 446 447 448 449 450
        self.assertEqual(egr_tensor10.persistable, True)
        self.assertTrue("new_eager_tensor" in egr_tensor10.name)
        self.assertEqual(egr_tensor10.shape, [4, 16, 16, 32])
        self.assertTrue(egr_tensor10.place._equals(place))
        self.assertEqual(egr_tensor10.dtype, core.VarDesc.VarType.FP32)
        self.assertEqual(egr_tensor10.stop_gradient, False)

451 452 453 454 455 456 457 458
        egr_tensor11 = core.eager.Tensor(
            arr,
            place,
            True,
            zero_copy=True,
            name="new_eager_tensor",
            stop_gradient=False,
        )
459 460 461 462 463 464 465
        self.assertEqual(egr_tensor11.persistable, True)
        self.assertTrue("new_eager_tensor" in egr_tensor11.name)
        self.assertEqual(egr_tensor11.shape, [4, 16, 16, 32])
        self.assertTrue(egr_tensor11.place._equals(place))
        self.assertEqual(egr_tensor11.dtype, core.VarDesc.VarType.FP32)
        self.assertEqual(egr_tensor11.stop_gradient, False)

466 467 468 469 470 471 472 473
        egr_tensor12 = core.eager.Tensor(
            arr,
            place,
            persistable=True,
            zero_copy=True,
            name="new_eager_tensor",
            stop_gradient=False,
        )
474 475 476 477 478 479 480
        self.assertEqual(egr_tensor12.persistable, True)
        self.assertTrue("new_eager_tensor" in egr_tensor12.name)
        self.assertEqual(egr_tensor12.shape, [4, 16, 16, 32])
        self.assertTrue(egr_tensor12.place._equals(place))
        self.assertEqual(egr_tensor12.dtype, core.VarDesc.VarType.FP32)
        self.assertEqual(egr_tensor12.stop_gradient, False)

481 482 483 484 485 486 487 488
        egr_tensor13 = core.eager.Tensor(
            value=arr,
            place=place,
            persistable=True,
            zero_copy=True,
            name="new_eager_tensor",
            stop_gradient=False,
        )
489 490 491 492 493 494 495 496
        self.assertEqual(egr_tensor13.persistable, True)
        self.assertTrue("new_eager_tensor" in egr_tensor13.name)
        self.assertEqual(egr_tensor13.shape, [4, 16, 16, 32])
        self.assertTrue(egr_tensor13.place._equals(place))
        self.assertEqual(egr_tensor13.dtype, core.VarDesc.VarType.FP32)
        self.assertEqual(egr_tensor13.stop_gradient, False)

        # special case
497 498 499 500 501 502 503
        egr_tensor14 = core.eager.Tensor(
            dtype=core.VarDesc.VarType.FP32,
            dims=[4, 16, 16, 32],
            name="special_eager_tensor",
            type=core.VarDesc.VarType.LOD_TENSOR,
            persistable=True,
        )
504 505 506 507 508
        self.assertEqual(egr_tensor14.persistable, True)
        self.assertEqual(egr_tensor14.name, "special_eager_tensor")
        self.assertEqual(egr_tensor14.shape, [4, 16, 16, 32])
        self.assertEqual(egr_tensor14.dtype, core.VarDesc.VarType.FP32)

509 510
        # init Tensor by Tensor
        egr_tensor15 = core.eager.Tensor(value=egr_tensor4)
511 512 513 514 515 516 517
        self.assertEqual(egr_tensor15.persistable, True)
        self.assertTrue("generated" in egr_tensor15.name)
        self.assertEqual(egr_tensor15.shape, egr_tensor4.shape)
        self.assertEqual(egr_tensor15.dtype, egr_tensor4.dtype)
        self.assertEqual(egr_tensor15.stop_gradient, True)
        self.assertTrue(
            egr_tensor15.place._equals(
518 519 520
                paddle.fluid.framework._current_expected_place()
            )
        )
521
        np.testing.assert_array_equal(egr_tensor15.numpy(), egr_tensor4.numpy())
522

523 524 525
        egr_tensor16 = core.eager.Tensor(
            value=egr_tensor4, name="new_eager_tensor"
        )
526 527 528 529 530 531 532
        self.assertEqual(egr_tensor16.persistable, True)
        self.assertTrue("new_eager_tensor" in egr_tensor16.name)
        self.assertEqual(egr_tensor16.shape, egr_tensor4.shape)
        self.assertEqual(egr_tensor16.dtype, egr_tensor4.dtype)
        self.assertEqual(egr_tensor16.stop_gradient, True)
        self.assertTrue(
            egr_tensor16.place._equals(
533 534 535
                paddle.fluid.framework._current_expected_place()
            )
        )
536
        np.testing.assert_array_equal(egr_tensor16.numpy(), egr_tensor4.numpy())
537

538
        egr_tensor17 = core.eager.Tensor(
539 540
            value=egr_tensor4,
            place=place,
541 542
            name="new_eager_tensor",
        )
543 544 545 546 547 548
        self.assertEqual(egr_tensor17.persistable, True)
        self.assertTrue("new_eager_tensor" in egr_tensor17.name)
        self.assertEqual(egr_tensor17.shape, egr_tensor4.shape)
        self.assertEqual(egr_tensor17.dtype, egr_tensor4.dtype)
        self.assertEqual(egr_tensor17.stop_gradient, True)
        self.assertTrue(egr_tensor17.place._equals(place))
549
        np.testing.assert_array_equal(egr_tensor17.numpy(), egr_tensor4.numpy())
550

551
        egr_tensor18 = core.eager.Tensor(
552 553
            egr_tensor4,
            place=place,
554 555
            name="new_eager_tensor",
        )
556 557 558 559 560 561
        self.assertEqual(egr_tensor18.persistable, True)
        self.assertTrue("new_eager_tensor" in egr_tensor18.name)
        self.assertEqual(egr_tensor18.shape, egr_tensor4.shape)
        self.assertEqual(egr_tensor18.dtype, egr_tensor4.dtype)
        self.assertEqual(egr_tensor18.stop_gradient, True)
        self.assertTrue(egr_tensor18.place._equals(place))
562
        np.testing.assert_array_equal(egr_tensor18.numpy(), egr_tensor4.numpy())
563

564
        egr_tensor19 = core.eager.Tensor(
565 566
            egr_tensor4,
            place,
567 568
            name="new_eager_tensor",
        )
569 570 571 572 573 574
        self.assertEqual(egr_tensor19.persistable, True)
        self.assertTrue("new_eager_tensor" in egr_tensor19.name)
        self.assertEqual(egr_tensor19.shape, egr_tensor4.shape)
        self.assertEqual(egr_tensor19.dtype, egr_tensor4.dtype)
        self.assertEqual(egr_tensor19.stop_gradient, True)
        self.assertTrue(egr_tensor19.place._equals(place))
575
        np.testing.assert_array_equal(egr_tensor19.numpy(), egr_tensor4.numpy())
576 577 578 579 580

        # init eager tensor by framework tensor
        x = np.random.rand(3, 3).astype('float32')
        t = paddle.fluid.Tensor()
        t.set(x, paddle.fluid.CPUPlace())
581
        egr_tensor20 = core.eager.Tensor(value=t)
582 583 584 585 586 587 588
        self.assertEqual(egr_tensor20.persistable, False)
        self.assertTrue("generated_tensor" in egr_tensor20.name)
        self.assertEqual(egr_tensor20.shape, [3, 3])
        self.assertEqual(egr_tensor20.dtype, core.VarDesc.VarType.FP32)
        self.assertEqual(egr_tensor20.stop_gradient, True)
        self.assertTrue(
            egr_tensor20.place._equals(
589 590 591
                paddle.fluid.framework._current_expected_place()
            )
        )
592
        np.testing.assert_array_equal(egr_tensor20.numpy(), x)
593

594
        egr_tensor21 = core.eager.Tensor(value=t, place=place)
595 596 597 598 599 600
        self.assertEqual(egr_tensor21.persistable, False)
        self.assertTrue("generated_tensor" in egr_tensor21.name)
        self.assertEqual(egr_tensor21.shape, [3, 3])
        self.assertEqual(egr_tensor21.dtype, core.VarDesc.VarType.FP32)
        self.assertEqual(egr_tensor21.stop_gradient, True)
        self.assertTrue(egr_tensor21.place._equals(place))
601
        np.testing.assert_array_equal(egr_tensor21.numpy(), x)
602

603
        egr_tensor22 = core.eager.Tensor(t, place=place)
604 605 606 607 608 609
        self.assertEqual(egr_tensor22.persistable, False)
        self.assertTrue("generated_tensor" in egr_tensor22.name)
        self.assertEqual(egr_tensor22.shape, [3, 3])
        self.assertEqual(egr_tensor22.dtype, core.VarDesc.VarType.FP32)
        self.assertEqual(egr_tensor22.stop_gradient, True)
        self.assertTrue(egr_tensor22.place._equals(place))
610
        np.testing.assert_array_equal(egr_tensor22.numpy(), x)
611

612
        egr_tensor23 = core.eager.Tensor(t, place, name="from_framework_tensor")
613 614 615 616 617 618
        self.assertEqual(egr_tensor23.persistable, False)
        self.assertTrue("from_framework_tensor" in egr_tensor23.name)
        self.assertEqual(egr_tensor23.shape, [3, 3])
        self.assertEqual(egr_tensor23.dtype, core.VarDesc.VarType.FP32)
        self.assertEqual(egr_tensor23.stop_gradient, True)
        self.assertTrue(egr_tensor23.place._equals(place))
619
        np.testing.assert_array_equal(egr_tensor23.numpy(), x)
620

621 622 623
        egr_tensor24 = core.eager.Tensor(
            value=t, place=place, name="from_framework_tensor"
        )
624 625 626 627 628 629
        self.assertEqual(egr_tensor24.persistable, False)
        self.assertTrue("from_framework_tensor" in egr_tensor24.name)
        self.assertEqual(egr_tensor24.shape, [3, 3])
        self.assertEqual(egr_tensor24.dtype, core.VarDesc.VarType.FP32)
        self.assertEqual(egr_tensor24.stop_gradient, True)
        self.assertTrue(egr_tensor24.place._equals(place))
630
        np.testing.assert_array_equal(egr_tensor24.numpy(), x)
631 632 633

        # Bad usage
        # SyntaxError: positional argument follows keyword argument
634
        # egr_tensor25 = core.eager.Tensor(value=t, place)
635 636 637 638 639 640 641 642 643 644 645

    def test_constructor_with_kwargs(self):
        print("Test_constructor_with_kwargs")
        paddle.set_device("cpu")
        place_list = [core.CPUPlace()]
        if core.is_compiled_with_cuda():
            place_list.append(core.CUDAPlace(0))
        with _test_eager_guard():
            for p in place_list:
                self.constructor_with_kwargs(p)

646 647 648 649 650 651 652
    def test_copy_and_copy_to(self):
        print("Test_copy_and_copy_to")
        with _test_eager_guard():
            paddle.set_device("cpu")
            arr = np.ones([4, 16, 16, 32]).astype('float32')
            arr1 = np.zeros([4, 16]).astype('float32')
            arr2 = np.ones([4, 16, 16, 32]).astype('float32') + np.ones(
653 654 655 656 657
                [4, 16, 16, 32]
            ).astype('float32')
            tensor = paddle.to_tensor(
                arr, core.VarDesc.VarType.FP32, core.CPUPlace()
            )
658 659 660 661
            self.assertEqual(tensor.stop_gradient, True)
            tensor.stop_gradient = False
            print("Set persistable")
            tensor.persistable = False
662 663 664
            tensor1 = paddle.to_tensor(
                arr1, core.VarDesc.VarType.FP32, core.CPUPlace()
            )
665 666
            tensor1.persistable = True
            self.assertEqual(tensor1.stop_gradient, True)
667
            np.testing.assert_array_equal(tensor.numpy(), arr)
668 669
            print("Test copy_")
            tensor.copy_(tensor1, True)
670
            self.assertEqual(tensor.persistable, False)
671 672
            self.assertEqual(tensor.shape, [4, 16])
            self.assertEqual(tensor.dtype, core.VarDesc.VarType.FP32)
673
            np.testing.assert_array_equal(tensor.numpy(), arr1)
674 675

            print("Test _copy_to")
676 677 678
            tensor2 = paddle.to_tensor(
                arr2, core.VarDesc.VarType.FP32, core.CPUPlace()
            )
679
            np.testing.assert_array_equal(tensor2.numpy(), arr2)
680 681 682 683
            self.assertTrue(tensor2.place.is_cpu_place())
            tensor2.persistable = True
            tensor2.stop_gradient = False
            if core.is_compiled_with_cuda():
684
                tensor3 = tensor2._copy_to(core.CUDAPlace(0), True)
685
                np.testing.assert_array_equal(tensor3.numpy(), arr2)
J
Jiabin Yang 已提交
686 687
                self.assertEqual(tensor3.persistable, True)
                self.assertEqual(tensor3.stop_gradient, True)
688
                self.assertTrue(tensor3.place.is_gpu_place())
J
Jiabin Yang 已提交
689 690

                tensor4 = tensor2.cuda(0, True)
691
                np.testing.assert_array_equal(tensor4.numpy(), arr2)
J
Jiabin Yang 已提交
692 693 694 695 696
                self.assertEqual(tensor4.persistable, True)
                self.assertEqual(tensor4.stop_gradient, False)
                self.assertTrue(tensor4.place.is_gpu_place())

                tensor5 = tensor4.cpu()
697
                np.testing.assert_array_equal(tensor5.numpy(), arr2)
J
Jiabin Yang 已提交
698 699 700 701 702 703
                self.assertEqual(tensor5.persistable, True)
                self.assertEqual(tensor5.stop_gradient, False)
                self.assertTrue(tensor5.place.is_cpu_place())

                tensor10 = paddle.to_tensor([1, 2, 3], place='gpu_pinned')
                tensor11 = tensor10._copy_to(core.CUDAPlace(0), True)
704 705 706
                np.testing.assert_array_equal(
                    tensor10.numpy(), tensor11.numpy()
                )
707
            else:
708
                tensor3 = tensor2._copy_to(core.CPUPlace(), True)
709
                np.testing.assert_array_equal(tensor3.numpy(), arr2)
J
Jiabin Yang 已提交
710 711
                self.assertEqual(tensor3.persistable, True)
                self.assertEqual(tensor3.stop_gradient, True)
712 713
                self.assertTrue(tensor3.place.is_cpu_place())

J
Jiabin Yang 已提交
714
                tensor4 = tensor2.cpu()
715
                np.testing.assert_array_equal(tensor4.numpy(), arr2)
J
Jiabin Yang 已提交
716 717 718 719
                self.assertEqual(tensor4.persistable, True)
                self.assertEqual(tensor4.stop_gradient, False)
                self.assertTrue(tensor4.place.is_cpu_place())

720 721
    def test_share_buffer_to(self):
        with _test_eager_guard():
722 723 724
            arr = np.ones([4, 16, 16, 32]).astype('float32')
            arr1 = np.zeros([4, 16]).astype('float32')
            arr2 = np.ones([4, 16, 16, 32]).astype('float32') + np.ones(
725 726
                [4, 16, 16, 32]
            ).astype('float32')
727 728
            tensor = None
            tensor2 = None
729 730 731
            tensor = paddle.to_tensor(
                arr, core.VarDesc.VarType.FP32, core.CPUPlace()
            )
B
Baibaifan 已提交
732
            tensor3 = core.eager.Tensor(value=tensor, place=core.CPUPlace())
733
            if core.is_compiled_with_cuda():
734 735 736
                tensor2 = paddle.to_tensor(
                    arr2, core.VarDesc.VarType.FP32, core.CUDAPlace(0)
                )
737
            else:
738 739 740
                tensor2 = paddle.to_tensor(
                    arr2, core.VarDesc.VarType.FP32, core.CPUPlace()
                )
741 742
            np.testing.assert_array_equal(tensor.numpy(), arr)
            np.testing.assert_array_equal(tensor2.numpy(), arr2)
743
            tensor2._share_buffer_to(tensor)
744 745
            np.testing.assert_array_equal(tensor.numpy(), arr2)
            np.testing.assert_array_equal(tensor2.numpy(), arr2)
746 747 748
            self.assertTrue(tensor._is_shared_buffer_with(tensor2))
            self.assertTrue(tensor2._is_shared_buffer_with(tensor))
            tensor._share_buffer_to(tensor3)
749
            np.testing.assert_array_equal(tensor3.numpy(), arr2)
750 751
            self.assertTrue(tensor3._is_shared_buffer_with(tensor))

752 753 754 755 756
    def test_share_underline_tensor_to(self):
        with _test_eager_guard():
            arr = np.ones([4, 16, 16, 32]).astype('float32')
            arr1 = np.zeros([4, 16]).astype('float32')
            arr2 = np.ones([4, 16, 16, 32]).astype('float32') + np.ones(
757 758
                [4, 16, 16, 32]
            ).astype('float32')
759 760
            tensor = None
            tensor2 = None
761 762 763
            tensor = paddle.to_tensor(
                arr, core.VarDesc.VarType.FP32, core.CPUPlace()
            )
764
            tensor3 = core.eager.Tensor()
765
            if core.is_compiled_with_cuda():
766 767 768
                tensor2 = paddle.to_tensor(
                    arr2, core.VarDesc.VarType.FP32, core.CUDAPlace(0)
                )
769
            else:
770 771 772
                tensor2 = paddle.to_tensor(
                    arr2, core.VarDesc.VarType.FP32, core.CPUPlace()
                )
773 774
            np.testing.assert_array_equal(tensor.numpy(), arr)
            np.testing.assert_array_equal(tensor2.numpy(), arr2)
775
            tensor2._share_underline_tensor_to(tensor)
776 777
            np.testing.assert_array_equal(tensor.numpy(), arr2)
            np.testing.assert_array_equal(tensor2.numpy(), arr2)
778 779 780
            self.assertTrue(tensor._is_shared_underline_tensor_with(tensor2))
            self.assertTrue(tensor2._is_shared_underline_tensor_with(tensor))
            tensor._share_underline_tensor_to(tensor3)
781
            np.testing.assert_array_equal(tensor3.numpy(), arr2)
782 783
            self.assertTrue(tensor3._is_shared_underline_tensor_with(tensor))

784
    def test_properties(self):
J
Jiabin Yang 已提交
785 786
        print("Test_properties")
        with _test_eager_guard():
787 788
            paddle.set_device("cpu")
            arr = np.ones([4, 16, 16, 32]).astype('float32')
789 790 791
            tensor = paddle.to_tensor(
                arr, core.VarDesc.VarType.FP32, core.CPUPlace()
            )
792 793 794 795 796 797 798 799 800
            self.assertEqual(tensor.shape, [4, 16, 16, 32])
            tensor.name = 'tensor_name_test'
            self.assertEqual(tensor.name, 'tensor_name_test')
            self.assertEqual(tensor.persistable, False)
            tensor.persistable = True
            self.assertEqual(tensor.persistable, True)
            tensor.persistable = False
            self.assertEqual(tensor.persistable, False)
            self.assertTrue(tensor.place.is_cpu_place())
801
            self.assertEqual(tensor._place_str, 'Place(cpu)')
802 803 804 805 806
            self.assertEqual(tensor.stop_gradient, True)
            tensor.stop_gradient = False
            self.assertEqual(tensor.stop_gradient, False)
            tensor.stop_gradient = True
            self.assertEqual(tensor.stop_gradient, True)
807
            self.assertEqual(tensor.type, core.VarDesc.VarType.LOD_TENSOR)
808

J
Jiabin Yang 已提交
809 810
    def test_global_properties(self):
        print("Test_global_properties")
J
Jiabin Yang 已提交
811 812
        _disable_legacy_dygraph()
        self.assertTrue(in_dygraph_mode())
J
Jiabin Yang 已提交
813
        with _test_eager_guard():
J
Jiabin Yang 已提交
814 815
            self.assertTrue(in_dygraph_mode())
        self.assertFalse(in_dygraph_mode())
J
Jiabin Yang 已提交
816 817 818 819 820

    def test_place_guard(self):
        if core.is_compiled_with_cuda():
            paddle.set_device("gpu:0")
            with paddle.fluid.framework._dygraph_place_guard(core.CPUPlace()):
J
Jiabin Yang 已提交
821
                self.assertTrue(
822 823
                    isinstance(_current_expected_place(), type(core.CPUPlace()))
                )
J
Jiabin Yang 已提交
824 825 826
        else:
            paddle.set_device("cpu")
            with paddle.fluid.framework._dygraph_place_guard(core.CPUPlace()):
J
Jiabin Yang 已提交
827
                self.assertTrue(
828 829
                    isinstance(_current_expected_place(), type(core.CPUPlace()))
                )
J
Jiabin Yang 已提交
830

831 832 833 834
    def test_value(self):
        with _test_eager_guard():
            arr = np.random.rand(4, 16, 16, 32).astype('float64')

835
            egr_tensor0 = core.eager.Tensor(value=arr)
836 837 838 839 840
            self.assertEqual(egr_tensor0.persistable, False)
            self.assertTrue("generated" in egr_tensor0.name)
            self.assertEqual(egr_tensor0.shape, [4, 16, 16, 32])
            self.assertTrue(
                egr_tensor0.place._equals(
841 842 843
                    paddle.fluid.framework._current_expected_place()
                )
            )
844 845
            self.assertEqual(egr_tensor0.dtype, core.VarDesc.VarType.FP64)
            self.assertEqual(egr_tensor0.stop_gradient, True)
846 847 848 849 850 851 852 853
            self.assertTrue(
                egr_tensor0.value().get_tensor()._dtype(),
                core.VarDesc.VarType.FP64,
            )
            self.assertTrue(
                egr_tensor0.value().get_tensor()._place(),
                paddle.fluid.framework._current_expected_place(),
            )
854 855
            self.assertTrue(egr_tensor0.value().get_tensor()._is_initialized())

856 857 858
    def test_set_value(self):
        with _test_eager_guard():
            ori_arr = np.random.rand(4, 16, 16, 32).astype('float32')
859
            egr_tensor = core.eager.Tensor(value=ori_arr)
860 861
            self.assertEqual(egr_tensor.stop_gradient, True)
            self.assertEqual(egr_tensor.shape, [4, 16, 16, 32])
862
            np.testing.assert_array_equal(egr_tensor.numpy(), ori_arr)
863 864
            ori_place = egr_tensor.place

J
Jiabin Yang 已提交
865
            new_arr = np.random.rand(4, 16, 16, 32).astype('float32')
866 867
            self.assertFalse(np.array_equal(egr_tensor.numpy(), new_arr))

J
Jiabin Yang 已提交
868
            egr_tensor.set_value(new_arr)
869 870
            self.assertEqual(egr_tensor.stop_gradient, True)
            self.assertTrue(egr_tensor.place._equals(ori_place))
J
Jiabin Yang 已提交
871
            self.assertEqual(egr_tensor.shape, [4, 16, 16, 32])
872
            np.testing.assert_array_equal(egr_tensor.numpy(), new_arr)
873

J
Jiabin Yang 已提交
874 875 876
    def test_sharding_related_api(self):
        with _test_eager_guard():
            arr0 = np.random.rand(4, 16, 16, 32).astype('float32')
877 878 879
            egr_tensor1 = core.eager.Tensor(
                arr0, core.CPUPlace(), True, False, "numpy_tensor1", False
            )
J
Jiabin Yang 已提交
880 881 882 883 884 885 886 887 888 889 890 891
            self.assertEqual(egr_tensor1._numel(), 32768)
            self.assertEqual(egr_tensor1._slice(0, 2)._numel(), 16384)

    def test_copy_gradient_from(self):
        with _test_eager_guard():
            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)
892
            np.testing.assert_array_equal(x.grad.numpy(), np_y)
J
Jiabin Yang 已提交
893 894 895 896 897 898 899 900 901

    def test_clear(self):
        with _test_eager_guard():
            np_x = np.random.random((3, 8, 8))
            x = paddle.to_tensor(np_x, dtype="float64")
            self.assertTrue(x._is_initialized())
            x._clear()
            self.assertFalse(x._is_initialized())

902
    def test_use_gpudnn(self):
903 904 905 906
        np_x = np.random.random((3, 8, 8))
        with _test_eager_guard():
            self.assertTrue(in_dygraph_mode())
            x = paddle.to_tensor(np_x, dtype="float64")
907
            y = x._use_gpudnn(False)
908
            np.testing.assert_array_equal(x.numpy(), y.numpy())
909
            y = x._use_gpudnn(True)
910 911 912 913 914
            np.testing.assert_array_equal(x.numpy(), y.numpy())

        self.assertFalse(in_dygraph_mode())
        x = paddle.to_tensor(np_x, dtype="float64")
        with self.assertRaises(AttributeError):
915
            x = x._use_gpudnn(False)
916

917

918 919 920 921 922 923 924 925 926 927 928
class EagerParamBaseUsageTestCase(unittest.TestCase):
    def test_print(self):
        with _test_eager_guard():
            linear = paddle.nn.Linear(3, 3, bias_attr=False)
            print(linear.weight)

    def test_copy(self):
        with _test_eager_guard():
            linear = paddle.nn.Linear(1, 3)
            linear_copy = copy.deepcopy(linear)
            linear_copy2 = linear.weight._copy_to(core.CPUPlace(), True)
929 930 931 932 933 934
            np.testing.assert_array_equal(
                linear.weight.numpy(), linear_copy.weight.numpy()
            )
            np.testing.assert_array_equal(
                linear.weight.numpy(), linear_copy2.numpy()
            )
935 936 937 938 939 940 941 942

    def func_fp16_initilaizer(self):
        paddle.set_default_dtype("float16")
        linear1 = paddle.nn.Linear(1, 3, bias_attr=False)
        linear2 = paddle.nn.Linear(
            1,
            3,
            bias_attr=False,
943 944
            weight_attr=paddle.fluid.initializer.Uniform(),
        )
945 946 947 948
        linear3 = paddle.nn.Linear(
            1,
            3,
            bias_attr=False,
949 950
            weight_attr=paddle.fluid.initializer.TruncatedNormalInitializer(),
        )
951 952 953 954
        linear4 = paddle.nn.Linear(
            1,
            3,
            bias_attr=False,
955 956
            weight_attr=paddle.fluid.initializer.MSRAInitializer(),
        )
957
        res = [
958 959 960
            linear1.weight.numpy(),
            linear2.weight.numpy(),
            linear3.weight.numpy(),
961
            linear4.weight.numpy(),
962 963 964 965 966 967 968 969 970 971 972 973 974 975
        ]
        paddle.set_default_dtype("float32")
        return res

    def test_fp16_initializer(self):
        res1 = list()
        res2 = list()
        paddle.seed(102)
        paddle.framework.random._manual_program_seed(102)
        with _test_eager_guard():
            res1 = self.func_fp16_initilaizer()
        res2 = self.func_fp16_initilaizer()

        for i in range(len(res1)):
976
            np.testing.assert_array_equal(res1[i], res2[i])
977 978

    def func_layer_helper_base(self, value):
979
        base = paddle.fluid.layer_helper_base.LayerHelperBase(
980 981
            "test_layer", "test_layer"
        )
982 983 984 985 986 987 988 989 990 991 992 993 994 995
        return base.to_variable(value).numpy()

    def func_base_to_variable(self, value):
        paddle.fluid.dygraph.base.to_variable(value)

    def test_to_variable(self):
        value = np.random.rand(4, 16, 16, 32).astype('float32')
        res1 = None
        res3 = None
        with _test_eager_guard():
            res1 = self.func_layer_helper_base(value)
            res3 = self.func_base_to_variable(value)
        res2 = self.func_layer_helper_base(value)
        res4 = self.func_base_to_variable(value)
996 997
        np.testing.assert_array_equal(res1, res2)
        np.testing.assert_array_equal(res3, res4)
998

999
    def test_backward_with_single_tensor(self):
1000 1001
        with _test_eager_guard():
            arr4 = np.random.rand(4, 16, 16, 32).astype('float32')
1002
            egr_tensor12 = core.eager.Tensor(arr4, core.CPUPlace())
1003 1004 1005 1006 1007 1008 1009 1010
            egr_tensor12.retain_grads()
            arr = np.ones([4, 16, 16, 32]).astype('float32')
            self.assertEqual(egr_tensor12.persistable, False)
            self.assertTrue("generated_tensor" in egr_tensor12.name)
            self.assertEqual(egr_tensor12.shape, [4, 16, 16, 32])
            self.assertEqual(egr_tensor12.dtype, core.VarDesc.VarType.FP32)
            self.assertEqual(egr_tensor12.stop_gradient, True)
            self.assertTrue(egr_tensor12.place._equals(paddle.fluid.CPUPlace()))
1011 1012
            np.testing.assert_array_equal(egr_tensor12.numpy(), arr4)
            np.testing.assert_array_equal(egr_tensor12.gradient(), None)
1013
            egr_tensor12.stop_gradient = False
1014
            egr_tensor12.backward()
1015
            np.testing.assert_array_equal(egr_tensor12.gradient(), arr)
1016

1017 1018 1019 1020 1021 1022 1023
    def test_set_value(self):
        with _test_eager_guard():
            linear = paddle.nn.Linear(1, 3)
            ori_place = linear.weight.place
            new_weight = np.ones([1, 3]).astype('float32')
            self.assertFalse(np.array_equal(linear.weight.numpy(), new_weight))

J
Jiabin Yang 已提交
1024
            linear.weight.set_value(new_weight)
1025
            np.testing.assert_array_equal(linear.weight.numpy(), new_weight)
1026 1027
            self.assertTrue(linear.weight.place._equals(ori_place))

1028

1029 1030 1031 1032
class EagerGuardTestCase(unittest.TestCase):
    def test__test_eager_guard(self):
        tracer = paddle.fluid.dygraph.tracer.Tracer()
        with _test_eager_guard(tracer):
J
Jiabin Yang 已提交
1033
            self.assertTrue(in_dygraph_mode())
1034 1035


1036 1037
if __name__ == "__main__":
    unittest.main()