test_variable.py 42.7 KB
Newer Older
1
#   Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
D
dzhwinter 已提交
2
#
D
dzhwinter 已提交
3 4 5
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
D
dzhwinter 已提交
6
#
D
dzhwinter 已提交
7
#     http://www.apache.org/licenses/LICENSE-2.0
D
dzhwinter 已提交
8
#
D
dzhwinter 已提交
9 10 11 12 13 14
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

Y
Yu Yang 已提交
15
import unittest
W
WeiXin 已提交
16 17
from functools import reduce

18 19
import numpy as np

20
import paddle
21 22
from paddle import fluid
from paddle.fluid import core
23 24 25 26 27
from paddle.fluid.framework import (
    Program,
    convert_np_dtype_to_dtype_,
    default_main_program,
)
Y
Yu Yang 已提交
28

29 30
paddle.enable_static()

Y
Yu Yang 已提交
31 32

class TestVariable(unittest.TestCase):
33 34 35
    def setUp(self):
        np.random.seed(2022)

Y
Yu Yang 已提交
36
    def test_np_dtype_convert(self):
37
        DT = core.VarDesc.VarType
38
        convert = convert_np_dtype_to_dtype_
Y
Yu Yang 已提交
39 40 41 42 43 44 45
        self.assertEqual(DT.FP32, convert(np.float32))
        self.assertEqual(DT.FP16, convert("float16"))
        self.assertEqual(DT.FP64, convert("float64"))
        self.assertEqual(DT.INT32, convert("int32"))
        self.assertEqual(DT.INT16, convert("int16"))
        self.assertEqual(DT.INT64, convert("int64"))
        self.assertEqual(DT.BOOL, convert("bool"))
Q
qingqing01 已提交
46 47
        self.assertEqual(DT.INT8, convert("int8"))
        self.assertEqual(DT.UINT8, convert("uint8"))
Y
Yu Yang 已提交
48

Y
Yu Yang 已提交
49
    def test_var(self):
Y
Yu Yang 已提交
50
        b = default_main_program().current_block()
51 52 53
        w = b.create_var(
            dtype="float64", shape=[784, 100], lod_level=0, name="fc.w"
        )
54
        self.assertNotEqual(str(w), "")
55
        self.assertEqual(core.VarDesc.VarType.FP64, w.dtype)
Y
Yu Yang 已提交
56 57
        self.assertEqual((784, 100), w.shape)
        self.assertEqual("fc.w", w.name)
58
        self.assertEqual("fc.w@GRAD", w.grad_name)
Y
Yu Yang 已提交
59 60 61
        self.assertEqual(0, w.lod_level)

        w = b.create_var(name='fc.w')
62
        self.assertEqual(core.VarDesc.VarType.FP64, w.dtype)
Y
Yu Yang 已提交
63 64
        self.assertEqual((784, 100), w.shape)
        self.assertEqual("fc.w", w.name)
65
        self.assertEqual("fc.w@GRAD", w.grad_name)
Y
Yu Yang 已提交
66 67
        self.assertEqual(0, w.lod_level)

68 69 70
        self.assertRaises(
            ValueError, lambda: b.create_var(name="fc.w", shape=(24, 100))
        )
Y
Yu Yang 已提交
71

72 73 74 75 76
        w = b.create_var(
            dtype=paddle.fluid.core.VarDesc.VarType.STRINGS,
            shape=[1],
            name="str_var",
        )
77 78
        self.assertEqual(None, w.lod_level)

79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
    def test_element_size(self):
        with fluid.program_guard(Program(), Program()):
            x = paddle.static.data(name='x1', shape=[2], dtype='bool')
            self.assertEqual(x.element_size(), 1)

            x = paddle.static.data(name='x2', shape=[2], dtype='float16')
            self.assertEqual(x.element_size(), 2)

            x = paddle.static.data(name='x3', shape=[2], dtype='float32')
            self.assertEqual(x.element_size(), 4)

            x = paddle.static.data(name='x4', shape=[2], dtype='float64')
            self.assertEqual(x.element_size(), 8)

            x = paddle.static.data(name='x5', shape=[2], dtype='int8')
            self.assertEqual(x.element_size(), 1)

            x = paddle.static.data(name='x6', shape=[2], dtype='int16')
            self.assertEqual(x.element_size(), 2)

            x = paddle.static.data(name='x7', shape=[2], dtype='int32')
            self.assertEqual(x.element_size(), 4)

            x = paddle.static.data(name='x8', shape=[2], dtype='int64')
            self.assertEqual(x.element_size(), 8)

            x = paddle.static.data(name='x9', shape=[2], dtype='uint8')
            self.assertEqual(x.element_size(), 1)

Y
Yu Yang 已提交
108 109 110
    def test_step_scopes(self):
        prog = Program()
        b = prog.current_block()
111 112 113
        var = b.create_var(
            name='step_scopes', type=core.VarDesc.VarType.STEP_SCOPES
        )
Y
Yu Yang 已提交
114 115
        self.assertEqual(core.VarDesc.VarType.STEP_SCOPES, var.type)

W
wopeizl 已提交
116
    def _test_slice(self, place):
W
wopeizl 已提交
117 118 119 120 121
        b = default_main_program().current_block()
        w = b.create_var(dtype="float64", shape=[784, 100, 100], lod_level=0)

        for i in range(3):
            nw = w[i]
H
Hongyu Liu 已提交
122
            self.assertEqual((100, 100), nw.shape)
W
wopeizl 已提交
123 124 125 126

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

H
Hongyu Liu 已提交
127
        nw = w[:, :]
W
wopeizl 已提交
128 129
        self.assertEqual((784, 100, 100), nw.shape)

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

H
Hongyu Liu 已提交
133 134 135 136 137 138 139
        nw = w[1, 1, 1]

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

        nw = w[:, :, :-1]
        self.assertEqual((784, 100, 99), nw.shape)
W
wopeizl 已提交
140 141 142 143 144 145

        self.assertEqual(0, nw.lod_level)

        main = fluid.Program()
        with fluid.program_guard(main):
            exe = fluid.Executor(place)
146 147 148 149 150 151 152
            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')
153
            var = paddle.assign(tensor_array)
W
wopeizl 已提交
154 155 156
            var1 = var[0, 1, 1]
            var2 = var[1:]
            var3 = var[0:1]
H
Hongyu Liu 已提交
157 158
            var4 = var[::-1]
            var5 = var[1, 1:, 1:]
159
            var_reshape = paddle.reshape(var, [3, -1, 3])
H
Hongyu Liu 已提交
160 161 162 163 164 165 166 167 168 169
            var6 = var_reshape[:, :, -1]
            var7 = var[:, :, :-1]
            var8 = var[:1, :1, :1]
            var9 = var[:-1, :-1, :-1]
            var10 = var[::-1, :1, :-1]
            var11 = var[:-1, ::-1, -1:]
            var12 = var[1:2, 2:, ::-1]
            var13 = var[2:10, 2:, -2:-1]
            var14 = var[1:-1, 0:2, ::-1]
            var15 = var[::-1, ::-1, ::-1]
W
wopeizl 已提交
170

G
GGBond8488 已提交
171
            x = paddle.static.data(name='x', shape=[-1, 13], dtype='float32')
C
Charles-hit 已提交
172
            y = paddle.static.nn.fc(x, size=1, activation=None)
H
Hongyu Liu 已提交
173
            y_1 = y[:, 0]
W
wopeizl 已提交
174 175
            feeder = fluid.DataFeeder(place=place, feed_list=[x])
            data = []
176
            data.append(np.random.randint(10, size=[13]).astype('float32'))
W
wopeizl 已提交
177 178
            exe.run(fluid.default_startup_program())

179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200
            local_out = exe.run(
                main,
                feed=feeder.feed([data]),
                fetch_list=[
                    var,
                    var1,
                    var2,
                    var3,
                    var4,
                    var5,
                    var6,
                    var7,
                    var8,
                    var9,
                    var10,
                    var11,
                    var12,
                    var13,
                    var14,
                    var15,
                ],
            )
W
wopeizl 已提交
201

202 203 204 205 206 207
            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(
208 209
                local_out[6], tensor_array.reshape((3, -1, 3))[:, :, -1]
            )
210
            np.testing.assert_array_equal(local_out[7], tensor_array[:, :, :-1])
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
            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]
            )
            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]
            )
W
wopeizl 已提交
235

236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
    def _test_slice_index_tensor(self, place):
        data = np.random.rand(2, 3).astype("float32")
        prog = paddle.static.Program()
        with paddle.static.program_guard(prog):
            x = paddle.assign(data)
            idx0 = [1, 0]
            idx1 = [0, 1]
            idx2 = [0, 0]
            idx3 = [1, 1]

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

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

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

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

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

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

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

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

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

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

290 291 292 293 294
    def _test_slice_index_ellipsis(self, place):
        data = np.random.rand(2, 3, 4).astype("float32")
        prog = paddle.static.Program()
        with paddle.static.program_guard(prog):
            x = paddle.assign(data)
295
            y = paddle.assign([1, 2, 3, 4])
296 297 298 299
            out1 = x[0:, ..., 1:]
            out2 = x[0:, ...]
            out3 = x[..., 1:]
            out4 = x[...]
W
WeiXin 已提交
300 301
            out5 = x[[1, 0], [0, 0]]
            out6 = x[([1, 0], [0, 0])]
302
            out7 = y[..., 0]
303 304

        exe = paddle.static.Executor(place)
305 306 307
        result = exe.run(
            prog, fetch_list=[out1, out2, out3, out4, out5, out6, out7]
        )
308

W
WeiXin 已提交
309
        expected = [
310 311 312 313 314 315 316
            data[0:, ..., 1:],
            data[0:, ...],
            data[..., 1:],
            data[...],
            data[[1, 0], [0, 0]],
            data[([1, 0], [0, 0])],
            np.array([1]),
W
WeiXin 已提交
317
        ]
318 319 320 321 322

        self.assertTrue((result[0] == expected[0]).all())
        self.assertTrue((result[1] == expected[1]).all())
        self.assertTrue((result[2] == expected[2]).all())
        self.assertTrue((result[3] == expected[3]).all())
W
WeiXin 已提交
323 324
        self.assertTrue((result[4] == expected[4]).all())
        self.assertTrue((result[5] == expected[5]).all())
325
        self.assertTrue((result[6] == expected[6]).all())
326

327 328
        with self.assertRaises(IndexError):
            res = x[[1.2, 0]]
W
wopeizl 已提交
329

330
    def _test_slice_index_list_bool(self, place):
Z
zyfncg 已提交
331 332
        data = np.random.rand(2, 3, 4).astype("float32")
        np_idx = np.array([[True, False, False], [True, False, True]])
333 334 335 336 337
        prog = paddle.static.Program()
        with paddle.static.program_guard(prog):
            x = paddle.assign(data)
            idx0 = [True, False]
            idx1 = [False, True]
Z
zyfncg 已提交
338 339 340 341
            idx2 = [True, True]
            idx3 = [False, False, 1]
            idx4 = [True, False, 0]
            idx5 = paddle.assign(np_idx)
342 343 344 345 346

            out0 = x[idx0]
            out1 = x[idx1]
            out2 = x[idx2]
            out3 = x[idx3]
Z
zyfncg 已提交
347 348 349 350
            out4 = x[idx4]
            out5 = x[idx5]
            out6 = x[x < 0.36]
            out7 = x[x > 0.6]
351 352

        exe = paddle.static.Executor(place)
Z
zyfncg 已提交
353
        result = exe.run(
354 355
            prog, fetch_list=[out0, out1, out2, out3, out4, out5, out6, out7]
        )
356

Z
zyfncg 已提交
357
        expected = [
358 359 360 361 362 363 364 365
            data[idx0],
            data[idx1],
            data[idx2],
            data[idx3],
            data[idx4],
            data[np_idx],
            data[data < 0.36],
            data[data > 0.6],
Z
zyfncg 已提交
366
        ]
367 368 369 370 371

        self.assertTrue((result[0] == expected[0]).all())
        self.assertTrue((result[1] == expected[1]).all())
        self.assertTrue((result[2] == expected[2]).all())
        self.assertTrue((result[3] == expected[3]).all())
Z
zyfncg 已提交
372 373 374 375
        self.assertTrue((result[4] == expected[4]).all())
        self.assertTrue((result[5] == expected[5]).all())
        self.assertTrue((result[6] == expected[6]).all())
        self.assertTrue((result[7] == expected[7]).all())
376

Z
zyfncg 已提交
377 378 379
        with self.assertRaises(IndexError):
            res = x[[True, False, False]]
        with self.assertRaises(ValueError):
380 381
            with paddle.static.program_guard(prog):
                res = x[[False, False]]
382

383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399
    def _test_slice_index_scalar_bool(self, place):
        data = np.random.rand(1, 3, 4).astype("float32")
        np_idx = np.array([True])
        prog = paddle.static.Program()
        with paddle.static.program_guard(prog):
            x = paddle.assign(data)
            idx = paddle.assign(np_idx)

            out = x[idx]

        exe = paddle.static.Executor(place)
        result = exe.run(prog, fetch_list=[out])

        expected = [data[np_idx]]

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

400 401
    def test_slice(self):
        places = [fluid.CPUPlace()]
W
wopeizl 已提交
402
        if core.is_compiled_with_cuda():
403 404 405 406 407 408
            places.append(core.CUDAPlace(0))

        for place in places:
            self._test_slice(place)
            self._test_slice_index_tensor(place)
            self._test_slice_index_list(place)
409
            self._test_slice_index_ellipsis(place)
410
            self._test_slice_index_list_bool(place)
411
            self._test_slice_index_scalar_bool(place)
W
wopeizl 已提交
412

413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
    def _tostring(self):
        b = default_main_program().current_block()
        w = b.create_var(dtype="float64", lod_level=0)
        self.assertTrue(isinstance(str(w), str))

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

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

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

429
    def test_fake_interface_only_api(self):
430 431 432
        b = default_main_program().current_block()
        var = b.create_var(dtype="float64", lod_level=0)
        with fluid.dygraph.guard():
433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448
            self.assertRaises(AssertionError, var.numpy)
            self.assertRaises(AssertionError, var.backward)
            self.assertRaises(AssertionError, var.gradient)
            self.assertRaises(AssertionError, var.clear_gradient)

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

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

            self.assertFalse(var.stop_gradient)
449
            var.stop_gradient = True
450 451 452 453 454 455
            self.assertTrue(var.stop_gradient)

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

457 458 459
    def test_create_selected_rows(self):
        b = default_main_program().current_block()

460 461 462 463 464 465 466
        var = b.create_var(
            name="var",
            shape=[1, 1],
            dtype="float32",
            type=fluid.core.VarDesc.VarType.SELECTED_ROWS,
            persistable=True,
        )
467 468 469 470 471 472

        def _test():
            var.lod_level()

        self.assertRaises(Exception, _test)

473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500
    def test_size(self):
        prog = paddle.static.Program()
        with paddle.static.program_guard(prog):
            x = paddle.assign(np.random.rand(2, 3, 4).astype("float32"))
            exe = paddle.static.Executor(fluid.CPUPlace())
            exe.run(paddle.static.default_startup_program())

            output = exe.run(prog, fetch_list=[x.size()])
            self.assertEqual(output[0], [24])

    def test_detach(self):
        b = default_main_program().current_block()
        x = b.create_var(shape=[2, 3, 5], dtype="float64", lod_level=0)
        detach_x = x.detach()
        self.assertEqual(x.persistable, detach_x.persistable)
        self.assertEqual(x.shape, detach_x.shape)
        self.assertEqual(x.dtype, detach_x.dtype)
        self.assertEqual(x.type, detach_x.type)
        self.assertTrue(detach_x.stop_gradient)

        xx = b.create_var(name='xx', type=core.VarDesc.VarType.STEP_SCOPES)
        self.assertRaises(AssertionError, xx.detach)

        startup = paddle.static.Program()
        main = paddle.static.Program()
        scope = fluid.core.Scope()
        with paddle.static.scope_guard(scope):
            with paddle.static.program_guard(main, startup):
501 502 503
                x = paddle.static.data(
                    name='x', shape=[3, 2, 1], dtype='float32'
                )
504 505 506 507 508
                x.persistable = True
                feed_data = np.ones(shape=[3, 2, 1], dtype=np.float32)
                detach_x = x.detach()
                exe = paddle.static.Executor(paddle.CPUPlace())
                exe.run(startup)
509 510 511
                result = exe.run(
                    main, feed={'x': feed_data}, fetch_list=[x, detach_x]
                )
512 513 514 515 516 517 518 519 520
                self.assertTrue((result[1] == feed_data).all())
                self.assertTrue((result[0] == result[1]).all())

                modified_value = np.zeros(shape=[3, 2, 1], dtype=np.float32)
                detach_x.set_value(modified_value, scope)
                result = exe.run(main, fetch_list=[x, detach_x])
                self.assertTrue((result[1] == modified_value).all())
                self.assertTrue((result[0] == result[1]).all())

521 522 523
                modified_value = np.random.uniform(
                    -1, 1, size=[3, 2, 1]
                ).astype('float32')
524 525 526 527 528
                x.set_value(modified_value, scope)
                result = exe.run(main, fetch_list=[x, detach_x])
                self.assertTrue((result[1] == modified_value).all())
                self.assertTrue((result[0] == result[1]).all())

Y
Yu Yang 已提交
529

530
class TestVariableSlice(unittest.TestCase):
531 532 533
    def setUp(self):
        np.random.seed(2022)

534 535 536 537 538 539 540 541 542
    def _test_item_none(self, place):
        data = np.random.rand(2, 3, 4).astype("float32")
        prog = paddle.static.Program()
        with paddle.static.program_guard(prog):
            x = paddle.assign(data)
            out0 = x[0:, None, 1:]
            out1 = x[0:, None]
            out2 = x[None, 1:]
            out3 = x[None]
543
            out4 = x[..., None, :, None]
544

545
        outs = [out0, out1, out2, out3, out4]
546 547 548 549
        exe = paddle.static.Executor(place)
        result = exe.run(prog, fetch_list=outs)

        expected = [
550 551 552 553 554
            data[0:, None, 1:],
            data[0:, None],
            data[None, 1:],
            data[None],
            data[..., None, :, None],
555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575
        ]
        for i in range(len(outs)):
            self.assertEqual(outs[i].shape, expected[i].shape)
            self.assertTrue((result[i] == expected[i]).all())

    def _test_item_none_and_decrease(self, place):
        data = np.random.rand(2, 3, 4).astype("float32")
        prog = paddle.static.Program()
        with paddle.static.program_guard(prog):
            x = paddle.assign(data)
            out0 = x[0, 1:, None]
            out1 = x[0, None]
            out2 = x[None, 1]
            out3 = x[None]
            out4 = x[0, 0, 0, None]
            out5 = x[None, 0, 0, 0, None]

        outs = [out0, out1, out2, out3, out4, out5]
        exe = paddle.static.Executor(place)
        result = exe.run(prog, fetch_list=outs)
        expected = [
576 577 578 579 580 581
            data[0, 1:, None],
            data[0, None],
            data[None, 1],
            data[None],
            data[0, 0, 0, None],
            data[None, 0, 0, 0, None],
582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597
        ]

        for i in range(len(outs)):
            self.assertEqual(outs[i].shape, expected[i].shape)
            self.assertTrue((result[i] == expected[i]).all())

    def test_slice(self):
        places = [fluid.CPUPlace()]
        if core.is_compiled_with_cuda():
            places.append(core.CUDAPlace(0))

        for place in places:
            self._test_item_none(place)
            self._test_item_none_and_decrease(place)


W
WeiXin 已提交
598
class TestListIndex(unittest.TestCase):
J
JYChen 已提交
599 600 601 602 603 604 605 606 607 608 609 610 611
    # note(chenjianye):
    # Non-tuple sequence for multidimensional indexing is supported in numpy < 1.23.
    # For List case, the outermost `[]` will be treated as tuple `()` in version less than 1.23,
    # which is used to wrap index elements for multiple axes.
    # And from 1.23, this will be treat as a whole and only works on one axis.
    #
    # e.g. x[[[0],[1]]] == x[([0],[1])] == x[[0],[1]] (in version < 1.23)
    #      x[[[0],[1]]] == x[array([[0],[1]])] (in version >= 1.23)
    #
    # Here, we just modify the code to remove the impact of numpy version changes,
    # changing x[[[0],[1]]] to x[tuple([[0],[1]])] == x[([0],[1])] == x[[0],[1]].
    # Whether the paddle behavior in this case will change is still up for debate.

612 613 614
    def setUp(self):
        np.random.seed(2022)

W
WeiXin 已提交
615 616 617 618 619 620 621
    def numel(self, shape):
        return reduce(lambda x, y: x * y, shape)

    def test_static_graph_list_index(self):
        paddle.enable_static()

        inps_shape = [3, 4, 5, 2]
622 623 624
        array = np.arange(self.numel(inps_shape), dtype='float32').reshape(
            inps_shape
        )
W
WeiXin 已提交
625 626 627 628 629 630 631 632 633 634

        index_shape = [3, 3, 2, 1]
        index = np.arange(self.numel(index_shape)).reshape(index_shape)

        for _ in range(3):
            program = paddle.static.Program()

            index_mod = (index % (array.shape[0])).tolist()

            with paddle.static.program_guard(program):
635 636 637
                x = paddle.static.data(
                    name='x', shape=array.shape, dtype='float32'
                )
W
WeiXin 已提交
638 639 640

                y = x[index_mod]

641 642 643 644 645
                place = (
                    paddle.fluid.CPUPlace()
                    if not paddle.fluid.core.is_compiled_with_cuda()
                    else paddle.fluid.CUDAPlace(0)
                )
W
WeiXin 已提交
646 647 648 649 650 651 652

                prog = paddle.static.default_main_program()
                exe = paddle.static.Executor(place)

                exe.run(paddle.static.default_startup_program())
                fetch_list = [y.name]

J
JYChen 已提交
653
                getitem_np = array[tuple(index_mod)]
654 655 656
                getitem_pp = exe.run(
                    prog, feed={x.name: array}, fetch_list=fetch_list
                )
657
                np.testing.assert_array_equal(getitem_np, getitem_pp[0])
W
WeiXin 已提交
658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674

            array = array[0]
            index = index[0]

    def test_dygraph_list_index(self):
        paddle.disable_static()

        inps_shape = [3, 4, 5, 3]
        array = np.arange(self.numel(inps_shape)).reshape(inps_shape)

        index_shape = [2, 3, 4, 5, 6]
        index = np.arange(self.numel(index_shape)).reshape(index_shape)
        for _ in range(len(inps_shape) - 1):

            pt = paddle.to_tensor(array)
            index_mod = (index % (array.shape[-1])).tolist()
            try:
J
JYChen 已提交
675
                getitem_np = array[tuple(index_mod)]
W
WeiXin 已提交
676 677 678 679 680 681 682 683

            except:
                with self.assertRaises(ValueError):
                    getitem_pp = pt[index_mod]
                array = array[0]
                index = index[0]
                continue
            getitem_pp = pt[index_mod]
684
            np.testing.assert_array_equal(getitem_np, getitem_pp.numpy())
W
WeiXin 已提交
685 686 687 688 689 690 691

            array = array[0]
            index = index[0]

    def test_static_graph_list_index_muti_dim(self):
        paddle.enable_static()
        inps_shape = [3, 4, 5]
692 693 694
        array = np.arange(self.numel(inps_shape), dtype='float32').reshape(
            inps_shape
        )
W
WeiXin 已提交
695 696 697 698 699 700

        index_shape = [2, 2]
        index1 = np.arange(self.numel(index_shape)).reshape(index_shape)
        index2 = np.arange(self.numel(index_shape)).reshape(index_shape) + 2

        value_shape = [3, 2, 2, 3]
701 702 703 704 705 706
        value_np = (
            np.arange(self.numel(value_shape), dtype='float32').reshape(
                value_shape
            )
            + 100
        )
W
WeiXin 已提交
707 708 709 710 711 712 713 714 715

        index_mod1 = (index1 % (min(array.shape))).tolist()
        index_mod2 = (index2 % (min(array.shape))).tolist()

        program = paddle.static.Program()
        with paddle.static.program_guard(program):

            x = paddle.static.data(name='x', shape=array.shape, dtype='float32')

716 717 718 719 720 721 722 723 724
            value = paddle.static.data(
                name='value', shape=value_np.shape, dtype='float32'
            )
            index1 = paddle.static.data(
                name='index1', shape=index1.shape, dtype='int32'
            )
            index2 = paddle.static.data(
                name='index2', shape=index2.shape, dtype='int32'
            )
W
WeiXin 已提交
725 726 727

            y = x[index1, index2]

728 729 730 731 732
            place = (
                paddle.fluid.CPUPlace()
                if not paddle.fluid.core.is_compiled_with_cuda()
                else paddle.fluid.CUDAPlace(0)
            )
W
WeiXin 已提交
733 734 735 736 737 738 739 740 741 742

            prog = paddle.static.default_main_program()
            exe = paddle.static.Executor(place)

            exe.run(paddle.static.default_startup_program())
            fetch_list = [y.name]
            array2 = array.copy()

            y2 = array2[index_mod1, index_mod2]

743 744 745 746 747 748 749 750 751
            getitem_pp = exe.run(
                prog,
                feed={
                    x.name: array,
                    index1.name: index_mod1,
                    index2.name: index_mod2,
                },
                fetch_list=fetch_list,
            )
W
WeiXin 已提交
752

753 754 755
            np.testing.assert_array_equal(
                y2,
                getitem_pp[0],
756 757
                err_msg='\n numpy:{},\n paddle:{}'.format(y2, getitem_pp[0]),
            )
W
WeiXin 已提交
758 759 760 761

    def test_dygraph_list_index_muti_dim(self):
        paddle.disable_static()
        inps_shape = [3, 4, 5]
762 763 764
        array = np.arange(self.numel(inps_shape), dtype='float32').reshape(
            inps_shape
        )
W
WeiXin 已提交
765 766 767 768 769 770

        index_shape = [2, 2]
        index1 = np.arange(self.numel(index_shape)).reshape(index_shape)
        index2 = np.arange(self.numel(index_shape)).reshape(index_shape) + 2

        value_shape = [3, 2, 2, 3]
771 772 773 774 775 776
        value_np = (
            np.arange(self.numel(value_shape), dtype='float32').reshape(
                value_shape
            )
            + 100
        )
W
WeiXin 已提交
777 778 779 780 781 782 783 784 785 786

        index_mod1 = (index1 % (min(array.shape))).tolist()
        index_mod2 = (index2 % (min(array.shape))).tolist()

        x = paddle.to_tensor(array)
        index_t1 = paddle.to_tensor(index_mod1)
        index_t2 = paddle.to_tensor(index_mod2)

        y_np = array[index_t1, index_t2]
        y = x[index_t1, index_t2]
787
        np.testing.assert_array_equal(y.numpy(), y_np)
W
WeiXin 已提交
788

789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805
    def run_getitem_list_index(self, array, index):
        x = paddle.static.data(name='x', shape=array.shape, dtype='float32')

        y = x[index]
        place = paddle.fluid.CPUPlace()

        prog = paddle.static.default_main_program()
        exe = paddle.static.Executor(place)

        exe.run(paddle.static.default_startup_program())
        fetch_list = [y.name]
        array2 = array.copy()

        try:
            value_np = array2[index]
        except:
            with self.assertRaises(ValueError):
806 807 808
                getitem_pp = exe.run(
                    prog, feed={x.name: array}, fetch_list=fetch_list
                )
809 810 811
            return
        getitem_pp = exe.run(prog, feed={x.name: array}, fetch_list=fetch_list)

812 813 814
        np.testing.assert_allclose(
            value_np, getitem_pp[0], rtol=1e-5, atol=1e-8
        )
815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842

    def test_static_graph_getitem_bool_index(self):
        paddle.enable_static()

        # case 1:
        array = np.ones((4, 2, 3), dtype='float32')
        value_np = np.random.random((2, 3)).astype('float32')
        index = np.array([True, False, False, False])
        program = paddle.static.Program()
        with paddle.static.program_guard(program):
            self.run_getitem_list_index(array, index)

        # case 2:
        array = np.ones((4, 2, 3), dtype='float32')
        value_np = np.random.random((2, 3)).astype('float32')
        index = np.array([False, True, False, False])
        program = paddle.static.Program()
        with paddle.static.program_guard(program):
            self.run_getitem_list_index(array, index)

        # case 3:
        array = np.ones((4, 2, 3), dtype='float32')
        value_np = np.random.random((2, 3)).astype('float32')
        index = np.array([True, True, True, True])
        program = paddle.static.Program()
        with paddle.static.program_guard(program):
            self.run_getitem_list_index(array, index)

W
WeiXin 已提交
843 844 845
    def run_setitem_list_index(self, array, index, value_np):
        x = paddle.static.data(name='x', shape=array.shape, dtype='float32')

846 847 848
        value = paddle.static.data(
            name='value', shape=value_np.shape, dtype='float32'
        )
W
WeiXin 已提交
849 850 851 852 853 854 855 856 857 858 859 860

        x[index] = value
        y = x
        place = paddle.fluid.CPUPlace()

        prog = paddle.static.default_main_program()
        exe = paddle.static.Executor(place)

        exe.run(paddle.static.default_startup_program())
        fetch_list = [y.name]
        array2 = array.copy()
        try:
J
JYChen 已提交
861 862 863 864 865
            index = (
                tuple(index)
                if isinstance(index, list) and isinstance(index[0], list)
                else index
            )
W
WeiXin 已提交
866 867 868
            array2[index] = value_np
        except:
            with self.assertRaises(ValueError):
869 870 871 872 873
                setitem_pp = exe.run(
                    prog,
                    feed={x.name: array, value.name: value_np},
                    fetch_list=fetch_list,
                )
W
WeiXin 已提交
874
            return
875 876 877 878 879
        setitem_pp = exe.run(
            prog,
            feed={x.name: array, value.name: value_np},
            fetch_list=fetch_list,
        )
W
WeiXin 已提交
880

881
        np.testing.assert_allclose(array2, setitem_pp[0], rtol=1e-5, atol=1e-8)
W
WeiXin 已提交
882 883 884 885 886

    def test_static_graph_setitem_list_index(self):
        paddle.enable_static()
        # case 1:
        inps_shape = [3, 4, 5, 2, 3]
887 888 889
        array = np.arange(self.numel(inps_shape), dtype='float32').reshape(
            inps_shape
        )
W
WeiXin 已提交
890 891 892 893 894

        index_shape = [3, 3, 1, 2]
        index = np.arange(self.numel(index_shape)).reshape(index_shape)

        value_shape = inps_shape[3:]
895 896 897 898 899 900
        value_np = (
            np.arange(self.numel(value_shape), dtype='float32').reshape(
                value_shape
            )
            + 100
        )
W
WeiXin 已提交
901 902 903 904 905 906 907 908 909 910 911 912 913 914

        for _ in range(3):
            program = paddle.static.Program()

            index_mod = (index % (min(array.shape))).tolist()

            with paddle.static.program_guard(program):
                self.run_setitem_list_index(array, index_mod, value_np)

            array = array[0]
            index = index[0]

        # case 2:
        inps_shape = [3, 4, 5, 4, 3]
915 916 917
        array = np.arange(self.numel(inps_shape), dtype='float32').reshape(
            inps_shape
        )
W
WeiXin 已提交
918 919 920 921 922

        index_shape = [4, 3, 2, 2]
        index = np.arange(self.numel(index_shape)).reshape(index_shape)

        value_shape = [3]
923 924 925 926 927 928
        value_np = (
            np.arange(self.numel(value_shape), dtype='float32').reshape(
                value_shape
            )
            + 100
        )
W
WeiXin 已提交
929 930 931 932 933 934 935 936 937 938 939 940 941

        for _ in range(4):
            program = paddle.static.Program()
            index_mod = (index % (min(array.shape))).tolist()

            with paddle.static.program_guard(program):
                self.run_setitem_list_index(array, index_mod, value_np)

            array = array[0]
            index = index[0]

        # case 3:
        inps_shape = [3, 4, 5, 3, 3]
942 943 944
        array = np.arange(self.numel(inps_shape), dtype='float32').reshape(
            inps_shape
        )
W
WeiXin 已提交
945 946 947 948 949

        index_shape = [4, 3, 2, 2]
        index = np.arange(self.numel(index_shape)).reshape(index_shape)

        value_shape = [3, 2, 2, 3]
950 951 952 953 954 955
        value_np = (
            np.arange(self.numel(value_shape), dtype='float32').reshape(
                value_shape
            )
            + 100
        )
W
WeiXin 已提交
956 957 958
        index_mod = (index % (min(array.shape))).tolist()
        self.run_setitem_list_index(array, index_mod, value_np)

959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994
    def test_static_graph_setitem_bool_index(self):
        paddle.enable_static()

        # case 1:
        array = np.ones((4, 2, 3), dtype='float32')
        value_np = np.random.random((2, 3)).astype('float32')
        index = np.array([True, False, False, False])
        program = paddle.static.Program()
        with paddle.static.program_guard(program):
            self.run_setitem_list_index(array, index, value_np)

        # case 2:
        array = np.ones((4, 2, 3), dtype='float32')
        value_np = np.random.random((2, 3)).astype('float32')
        index = np.array([False, True, False, False])
        program = paddle.static.Program()
        with paddle.static.program_guard(program):
            self.run_setitem_list_index(array, index, value_np)

        # case 3:
        array = np.ones((4, 2, 3), dtype='float32')
        value_np = np.random.random((2, 3)).astype('float32')
        index = np.array([True, True, True, True])
        program = paddle.static.Program()
        with paddle.static.program_guard(program):
            self.run_setitem_list_index(array, index, value_np)

    def test_static_graph_setitem_bool_scalar_index(self):
        paddle.enable_static()
        array = np.ones((1, 2, 3), dtype='float32')
        value_np = np.random.random((2, 3)).astype('float32')
        index = np.array([True])
        program = paddle.static.Program()
        with paddle.static.program_guard(program):
            self.run_setitem_list_index(array, index, value_np)

W
WeiXin 已提交
995 996 997
    def test_static_graph_tensor_index_setitem_muti_dim(self):
        paddle.enable_static()
        inps_shape = [3, 4, 5, 4]
998 999 1000
        array = np.arange(self.numel(inps_shape), dtype='float32').reshape(
            inps_shape
        )
W
WeiXin 已提交
1001 1002

        index_shape = [2, 3, 4]
1003 1004 1005 1006 1007 1008 1009 1010 1011
        index1 = np.arange(self.numel(index_shape), dtype='int32').reshape(
            index_shape
        )
        index2 = (
            np.arange(self.numel(index_shape), dtype='int32').reshape(
                index_shape
            )
            + 2
        )
W
WeiXin 已提交
1012 1013

        value_shape = [4]
1014 1015 1016 1017 1018 1019
        value_np = (
            np.arange(self.numel(value_shape), dtype='float32').reshape(
                value_shape
            )
            + 100
        )
W
WeiXin 已提交
1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032
        for _ in range(3):

            index_mod1 = index1 % (min(array.shape))
            index_mod2 = index2 % (min(array.shape))

            array2 = array.copy()
            array2[index_mod1, index_mod2] = value_np
            array3 = array.copy()
            array3[index_mod1] = value_np

            program = paddle.static.Program()
            with paddle.static.program_guard(program):

1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048
                x1 = paddle.static.data(
                    name='x1', shape=array.shape, dtype='float32'
                )
                x2 = paddle.static.data(
                    name='x2', shape=array.shape, dtype='float32'
                )

                value = paddle.static.data(
                    name='value', shape=value_np.shape, dtype='float32'
                )
                index_1 = paddle.static.data(
                    name='index_1', shape=index1.shape, dtype='int32'
                )
                index_2 = paddle.static.data(
                    name='index_2', shape=index2.shape, dtype='int32'
                )
W
WeiXin 已提交
1049 1050 1051 1052

                x1[index_1, index_2] = value
                x2[index_1] = value

1053 1054 1055 1056 1057
                place = (
                    paddle.fluid.CPUPlace()
                    if not paddle.fluid.core.is_compiled_with_cuda()
                    else paddle.fluid.CUDAPlace(0)
                )
W
WeiXin 已提交
1058 1059 1060 1061 1062 1063 1064

                prog = paddle.static.default_main_program()
                exe = paddle.static.Executor(place)

                exe.run(paddle.static.default_startup_program())
                fetch_list = [x1.name, x2.name]

1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075
                setitem_pp = exe.run(
                    prog,
                    feed={
                        x1.name: array,
                        x2.name: array,
                        value.name: value_np,
                        index_1.name: index_mod1,
                        index_2.name: index_mod2,
                    },
                    fetch_list=fetch_list,
                )
1076 1077 1078 1079
                np.testing.assert_array_equal(
                    array2,
                    setitem_pp[0],
                    err_msg='\n numpy:{},\n paddle:{}'.format(
1080 1081 1082
                        array2, setitem_pp[0]
                    ),
                )
1083 1084 1085 1086
                np.testing.assert_array_equal(
                    array3,
                    setitem_pp[1],
                    err_msg='\n numpy:{},\n paddle:{}'.format(
1087 1088 1089
                        array3, setitem_pp[1]
                    ),
                )
W
WeiXin 已提交
1090 1091 1092 1093 1094 1095 1096
            array = array[0]
            index1 = index1[0]
            index2 = index2[0]

    def test_static_graph_array_index_muti_dim(self):
        paddle.enable_static()
        inps_shape = [3, 4, 5, 4]
1097 1098 1099
        array = np.arange(self.numel(inps_shape), dtype='float32').reshape(
            inps_shape
        )
W
WeiXin 已提交
1100 1101

        index_shape = [2, 3, 4]
1102 1103 1104 1105 1106 1107 1108 1109 1110
        index1 = np.arange(self.numel(index_shape), dtype='int32').reshape(
            index_shape
        )
        index2 = (
            np.arange(self.numel(index_shape), dtype='int32').reshape(
                index_shape
            )
            + 2
        )
W
WeiXin 已提交
1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125

        for _ in range(3):
            index_mod1 = index1 % (min(array.shape))
            index_mod2 = index2 % (min(array.shape))

            array2 = array.copy()
            array2[index_mod1, index_mod2] = 1
            y_np1 = array2[index_mod2, index_mod1]
            array3 = array.copy()
            array3[index_mod1] = 2.5
            y_np2 = array3[index_mod2]

            program = paddle.static.Program()
            with paddle.static.program_guard(program):

1126 1127 1128 1129 1130 1131
                x1 = paddle.static.data(
                    name='x1', shape=array.shape, dtype='float32'
                )
                x2 = paddle.static.data(
                    name='x2', shape=array.shape, dtype='float32'
                )
W
WeiXin 已提交
1132 1133 1134 1135 1136

                x1[index_mod1, index_mod2] = 1
                x2[index_mod1] = 2.5
                y1 = x1[index_mod2, index_mod1]
                y2 = x2[index_mod2]
1137 1138 1139 1140 1141
                place = (
                    paddle.fluid.CPUPlace()
                    if not paddle.fluid.core.is_compiled_with_cuda()
                    else paddle.fluid.CUDAPlace(0)
                )
W
WeiXin 已提交
1142 1143 1144 1145 1146 1147

                prog = paddle.static.default_main_program()
                exe = paddle.static.Executor(place)
                exe.run(paddle.static.default_startup_program())
                fetch_list = [x1.name, x2.name, y1.name, y2.name]

1148 1149 1150 1151 1152
                setitem_pp = exe.run(
                    prog,
                    feed={x1.name: array, x2.name: array},
                    fetch_list=fetch_list,
                )
1153 1154 1155 1156
                np.testing.assert_array_equal(
                    array2,
                    setitem_pp[0],
                    err_msg='\n numpy:{},\n paddle:{}'.format(
1157 1158 1159
                        array2, setitem_pp[0]
                    ),
                )
1160 1161 1162 1163
                np.testing.assert_array_equal(
                    array3,
                    setitem_pp[1],
                    err_msg='\n numpy:{},\n paddle:{}'.format(
1164 1165 1166
                        array3, setitem_pp[1]
                    ),
                )
1167 1168 1169 1170 1171

                np.testing.assert_array_equal(
                    y_np1,
                    setitem_pp[2],
                    err_msg='\n numpy:{},\n paddle:{}'.format(
1172 1173 1174
                        y_np1, setitem_pp[2]
                    ),
                )
1175 1176 1177 1178
                np.testing.assert_array_equal(
                    y_np2,
                    setitem_pp[3],
                    err_msg='\n numpy:{},\n paddle:{}'.format(
1179 1180 1181
                        y_np2, setitem_pp[3]
                    ),
                )
W
WeiXin 已提交
1182 1183 1184 1185 1186 1187 1188
            array = array[0]
            index1 = index1[0]
            index2 = index2[0]

    def test_dygraph_array_index_muti_dim(self):
        paddle.disable_static()
        inps_shape = [3, 4, 5, 4]
1189 1190 1191
        array = np.arange(self.numel(inps_shape), dtype='float32').reshape(
            inps_shape
        )
W
WeiXin 已提交
1192
        index_shape = [2, 3, 4]
1193 1194 1195 1196 1197 1198 1199 1200 1201
        index1 = np.arange(self.numel(index_shape), dtype='int32').reshape(
            index_shape
        )
        index2 = (
            np.arange(self.numel(index_shape), dtype='int32').reshape(
                index_shape
            )
            + 2
        )
W
WeiXin 已提交
1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215

        for _ in range(3):

            index_mod1 = index1 % (min(array.shape))
            index_mod2 = index2 % (min(array.shape))
            index_mod_t1 = paddle.to_tensor(index_mod1)
            index_mod_t2 = paddle.to_tensor(index_mod2)
            # 2 dim getitem
            array1 = array.copy()
            y_np1 = array1[index_mod2, index_mod1]
            tensor1 = paddle.to_tensor(array)

            y_t1 = tensor1[index_mod_t2, index_mod_t1]

1216 1217 1218
            np.testing.assert_array_equal(
                y_t1.numpy(),
                y_np1,
1219 1220
                err_msg='\n numpy:{},\n paddle:{}'.format(y_np1, y_t1.numpy()),
            )
W
WeiXin 已提交
1221 1222 1223 1224 1225 1226
            # 1 dim getitem
            array2 = array.copy()
            y_np2 = array2[index_mod2]
            tensor2 = paddle.to_tensor(array)

            y_t2 = tensor2[index_mod_t2]
1227 1228 1229
            np.testing.assert_array_equal(
                y_t2.numpy(),
                y_np2,
1230 1231
                err_msg='\n numpy:{},\n paddle:{}'.format(y_np2, y_t2.numpy()),
            )
W
WeiXin 已提交
1232 1233 1234 1235 1236

            # 2 dim setitem
            array1 = array.copy()
            array1[index_mod1, index_mod2] = 1
            tensor1[index_mod_t1, index_mod_t2] = 1
1237 1238 1239 1240
            np.testing.assert_array_equal(
                tensor1.numpy(),
                array1,
                err_msg='\n numpy:{},\n paddle:{}'.format(
1241 1242 1243
                    array1, tensor1.numpy()
                ),
            )
W
WeiXin 已提交
1244 1245 1246 1247 1248 1249 1250
            # 1 dim setitem
            array2 = array.copy()

            array2[index_mod1] = 2.5

            tensor2[index_mod_t1] = 2.5

1251 1252 1253 1254
            np.testing.assert_array_equal(
                tensor2.numpy(),
                array2,
                err_msg='\n numpy:{},\n paddle:{}'.format(
1255 1256 1257
                    array2, tensor2.numpy()
                ),
            )
W
WeiXin 已提交
1258 1259 1260 1261 1262 1263

            array = array[0]
            index1 = index1[0]
            index2 = index2[0]


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