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

import unittest
16 17

import gradient_checker
W
whs 已提交
18
import numpy as np
19
from decorator_helper import prog_scope
W
wanghuancoder 已提交
20
from eager_op_test import OpTest, convert_float_to_uint16, paddle_static_guard
21

22
import paddle
23 24
from paddle import fluid
from paddle.fluid import core
25
from paddle.tensor.manipulation import tensor_array_to_tensor
W
whs 已提交
26

27 28
paddle.enable_static()

W
whs 已提交
29

W
wanghuancoder 已提交
30 31 32 33 34 35 36 37 38 39 40 41 42
def slice_wrapper(
    Input,
    axes=[],
    StartsTensor=None,
    EndsTensor=None,
    infer_flags=[],
    decrease_axis=[],
):
    return paddle._C_ops.slice(
        Input, axes, StartsTensor, EndsTensor, infer_flags, decrease_axis
    )


43 44
# Situation 1: starts(list, no tensor), ends(list, no tensor)
# 1.1 without attr(decrease)
W
whs 已提交
45 46 47
class TestSliceOp(OpTest):
    def setUp(self):
        self.op_type = "slice"
X
xiaoguoguo626807 已提交
48 49
        self.prim_op_type = "prim"
        self.python_api = paddle.slice
50
        self.public_python_api = paddle.slice
W
whs 已提交
51 52 53 54 55 56
        self.config()
        self.inputs = {'Input': self.input}
        self.outputs = {'Out': self.out}
        self.attrs = {
            'axes': self.axes,
            'starts': self.starts,
57
            'ends': self.ends,
58
            'infer_flags': self.infer_flags,
W
whs 已提交
59 60 61
        }

    def config(self):
62
        self.input = np.random.random([3, 4, 5, 6]).astype("float64")
W
whs 已提交
63 64 65
        self.starts = [1, 0, 2]
        self.ends = [3, 3, 4]
        self.axes = [0, 1, 2]
66
        self.infer_flags = [1, 1, 1]
W
whs 已提交
67 68 69
        self.out = self.input[1:3, 0:3, 2:4, :]

    def test_check_output(self):
70
        self.check_output()
W
whs 已提交
71

72
    def test_check_grad_normal(self):
X
xiaoguoguo626807 已提交
73 74 75
        self.check_grad(
            ['Input'], 'Out', max_relative_error=0.006, check_prim=True
        )
76

W
whs 已提交
77

78 79
class TestCase1(TestSliceOp):
    def config(self):
80
        self.input = np.random.random([3, 4, 5, 6]).astype("float64")
81 82 83 84 85 86 87 88 89
        self.starts = [-3, 0, 2]
        self.ends = [3, 100, -1]
        self.axes = [0, 1, 2]
        self.infer_flags = [1, 1, 1]
        self.out = self.input[-3:3, 0:100, 2:-1, :]


class TestCase2(TestSliceOp):
    def config(self):
90
        self.input = np.random.random([3, 4, 5, 6]).astype("float64")
91 92 93 94 95 96 97
        self.starts = [-3, 0, 2]
        self.ends = [3, 100, -1]
        self.axes = [0, 1, 3]
        self.infer_flags = [1, 1, 1]
        self.out = self.input[-3:3, 0:100, :, 2:-1]


98 99 100
class TestSliceZerosShapeTensor(OpTest):
    def setUp(self):
        self.op_type = "slice"
X
xiaoguoguo626807 已提交
101 102
        self.prim_op_type = "prim"
        self.python_api = paddle.slice
103
        self.public_python_api = paddle.slice
104 105 106 107 108 109 110 111
        self.config()
        self.inputs = {'Input': self.input}
        self.outputs = {'Out': self.out}
        self.attrs = {
            'axes': self.axes,
            'starts': self.starts,
            'ends': self.ends,
            'infer_flags': self.infer_flags,
112
            'use_mkldnn': True,
113 114 115 116 117 118 119 120 121 122 123 124 125 126
        }

    def config(self):
        self.input = np.random.random([0, 0, 0]).astype("float32")
        self.starts = [1]
        self.ends = [2]
        self.axes = [0]
        self.infer_flags = []
        self.out = self.input[1:2]

    def test_check_output(self):
        self.check_output_with_place(paddle.CPUPlace())


127
# 1.2 with attr(decrease)
H
Hongyu Liu 已提交
128 129
class TestSliceOp_decs_dim(OpTest):
    def setUp(self):
130
        self.enable_cinn = True
H
Hongyu Liu 已提交
131
        self.op_type = "slice"
X
xiaoguoguo626807 已提交
132 133
        self.prim_op_type = "prim"
        self.python_api = paddle.slice
134
        self.public_python_api = paddle.slice
H
Hongyu Liu 已提交
135 136 137 138 139 140 141
        self.config()
        self.inputs = {'Input': self.input}
        self.outputs = {'Out': self.out}
        self.attrs = {
            'axes': self.axes,
            'starts': self.starts,
            'ends': self.ends,
142
            'infer_flags': self.infer_flags,
H
Hongyu Liu 已提交
143 144 145 146
            'decrease_axis': self.decrease_axis,
        }

    def config(self):
147
        self.input = np.random.random([3, 4, 5, 6]).astype("float64")
H
Hongyu Liu 已提交
148 149 150 151
        self.starts = [1, 0, 2]
        self.ends = [2, 3, 4]
        self.axes = [0, 1, 2]
        self.decrease_axis = [0]
152
        self.infer_flags = [1, 1, 1]
H
Hongyu Liu 已提交
153 154 155
        self.out = self.input[1, 0:3, 2:4, :]

    def test_check_output(self):
156
        self.check_output()
H
Hongyu Liu 已提交
157 158

    def test_check_grad_normal(self):
X
xiaoguoguo626807 已提交
159 160 161
        self.check_grad(
            ['Input'], 'Out', max_relative_error=0.006, check_prim=True
        )
H
Hongyu Liu 已提交
162 163


164 165 166
# Situation 2: starts(list, have tensor), ends(list, no tensor)
# without attr(decrease)
class TestSliceOp_starts_ListTensor(OpTest):
H
Hongyu Liu 已提交
167 168
    def setUp(self):
        self.op_type = "slice"
W
wanghuancoder 已提交
169
        self.python_api = slice_wrapper
H
Hongyu Liu 已提交
170
        self.config()
171 172 173

        starts_tensor = []
        for index, ele in enumerate(self.starts):
174
            starts_tensor.append(
175
                ("x" + str(index), np.ones(1).astype('int64') * ele)
176
            )
177 178

        self.inputs = {'Input': self.input, 'StartsTensorList': starts_tensor}
H
Hongyu Liu 已提交
179 180 181
        self.outputs = {'Out': self.out}
        self.attrs = {
            'axes': self.axes,
182
            'starts': self.starts_infer,
H
Hongyu Liu 已提交
183
            'ends': self.ends,
184
            'infer_flags': self.infer_flags,
H
Hongyu Liu 已提交
185 186 187
        }

    def config(self):
188
        self.input = np.random.random([3, 4, 5, 6]).astype("float64")
H
Hongyu Liu 已提交
189
        self.starts = [1, 0, 2]
190
        self.ends = [3, 3, 4]
H
Hongyu Liu 已提交
191
        self.axes = [0, 1, 2]
192 193 194 195
        self.infer_flags = [-1, 1, -1]
        self.out = self.input[1:3, 0:3, 2:4, :]

        self.starts_infer = [-1, 0, -1]
H
Hongyu Liu 已提交
196 197

    def test_check_output(self):
198
        self.check_output()
H
Hongyu Liu 已提交
199 200

    def test_check_grad_normal(self):
201
        self.check_grad(['Input'], 'Out', max_relative_error=0.006)
H
Hongyu Liu 已提交
202 203


204 205 206
# Situation 2: starts(list, have tensor), ends(list, no tensor)
#  with attr(decrease)
class TestSliceOp_decs_dim_starts_ListTensor(OpTest):
H
Hongyu Liu 已提交
207 208
    def setUp(self):
        self.op_type = "slice"
W
wanghuancoder 已提交
209
        self.python_api = slice_wrapper
H
Hongyu Liu 已提交
210
        self.config()
211 212 213

        starts_tensor = []
        for index, ele in enumerate(self.starts):
214
            starts_tensor.append(
215
                ("x" + str(index), np.ones(1).astype('int32') * ele)
216
            )
217 218 219

        self.inputs = {'Input': self.input, 'StartsTensorList': starts_tensor}

H
Hongyu Liu 已提交
220 221 222
        self.outputs = {'Out': self.out}
        self.attrs = {
            'axes': self.axes,
223
            'starts': self.starts_infer,
H
Hongyu Liu 已提交
224
            'ends': self.ends,
225
            'infer_flags': self.infer_flags,
H
Hongyu Liu 已提交
226 227 228 229
            'decrease_axis': self.decrease_axis,
        }

    def config(self):
230
        self.input = np.random.random([3, 4, 5, 6]).astype("float64")
231 232
        self.starts = [1, 0, 2]
        self.ends = [2, 3, 4]
H
Hongyu Liu 已提交
233
        self.axes = [0, 1, 2]
234 235 236 237 238
        self.decrease_axis = [0]
        self.infer_flags = [1, -1, 1]
        self.out = self.input[1, 0:3, 2:4, :]

        self.starts_infer = [1, -1, 2]
H
Hongyu Liu 已提交
239 240

    def test_check_output(self):
241
        self.check_output()
H
Hongyu Liu 已提交
242 243

    def test_check_grad_normal(self):
244
        self.check_grad(['Input'], 'Out', max_relative_error=0.006)
H
Hongyu Liu 已提交
245 246


247
class TestSliceOp_decs_dim_5_starts_ListTensor(
248 249
    TestSliceOp_decs_dim_starts_ListTensor
):
250
    def config(self):
251
        self.input = np.random.random([3, 4, 5, 6]).astype("float64")
252 253 254 255 256 257 258 259 260 261 262 263 264
        self.starts = [-1]
        self.ends = [1000000]
        self.axes = [3]
        self.decrease_axis = [3]
        self.infer_flags = [-1]
        self.out = self.input[:, :, :, -1]

        self.starts_infer = [-1]


# Situation 3: starts(tensor), ends(list, no tensor)
# with attr(decrease)
class TestSliceOp_decs_dim_starts_OneTensor(OpTest):
H
Hongyu Liu 已提交
265 266
    def setUp(self):
        self.op_type = "slice"
W
wanghuancoder 已提交
267
        self.python_api = slice_wrapper
H
Hongyu Liu 已提交
268
        self.config()
269 270
        self.inputs = {
            'Input': self.input,
271
            "StartsTensor": np.array(self.starts, dtype="int32"),
272
        }
H
Hongyu Liu 已提交
273 274 275
        self.outputs = {'Out': self.out}
        self.attrs = {
            'axes': self.axes,
276
            # 'starts': self.starts,
H
Hongyu Liu 已提交
277
            'ends': self.ends,
278
            'infer_flags': self.infer_flags,
H
Hongyu Liu 已提交
279 280 281 282
            'decrease_axis': self.decrease_axis,
        }

    def config(self):
283
        self.input = np.random.random([3, 4, 5, 6]).astype("float64")
284 285 286 287 288 289
        self.starts = [1, 0, 2]
        self.ends = [2, 3, 4]
        self.axes = [0, 1, 2]
        self.decrease_axis = [0]
        self.infer_flags = [-1, -1, -1]
        self.out = self.input[1, 0:3, 2:4, :]
H
Hongyu Liu 已提交
290 291

    def test_check_output(self):
292
        self.check_output()
H
Hongyu Liu 已提交
293 294

    def test_check_grad_normal(self):
295
        self.check_grad(['Input'], 'Out', max_relative_error=0.006)
H
Hongyu Liu 已提交
296 297


298 299 300
# Situation 4: starts(tensor), ends(tensor)
#  without attr(decrease)
class TestSliceOp_starts_OneTensor_ends_OneTensor(OpTest):
H
Hongyu Liu 已提交
301 302
    def setUp(self):
        self.op_type = "slice"
W
wanghuancoder 已提交
303
        self.python_api = slice_wrapper
H
Hongyu Liu 已提交
304
        self.config()
305 306 307

        self.inputs = {
            'Input': self.input,
308
            "StartsTensor": np.array(self.starts, dtype="int64"),
309
            "EndsTensor": np.array(self.ends, dtype="int32"),
310
        }
H
Hongyu Liu 已提交
311 312 313
        self.outputs = {'Out': self.out}
        self.attrs = {
            'axes': self.axes,
314 315
            # 'starts': self.starts,
            # 'ends': self.ends_infer,
316
            'infer_flags': self.infer_flags,
H
Hongyu Liu 已提交
317 318 319
        }

    def config(self):
320
        self.input = np.random.random([3, 4, 5, 6]).astype("float64")
321 322 323 324 325
        self.starts = [1, 0, 2]
        self.ends = [3, 3, 4]
        self.axes = [0, 1, 2]
        self.infer_flags = [-1, -1, -1]
        self.out = self.input[1:3, 0:3, 2:4, :]
H
Hongyu Liu 已提交
326 327

    def test_check_output(self):
328
        self.check_output()
H
Hongyu Liu 已提交
329 330

    def test_check_grad_normal(self):
331
        self.check_grad(['Input'], 'Out', max_relative_error=0.006)
H
Hongyu Liu 已提交
332 333


334 335 336 337 338
# Situation 5: starts(tensor), ends(tensor)
#  with attr(decrease)
class TestSliceOp_decs_dim_starts_and_ends_OneTensor(OpTest):
    def setUp(self):
        self.op_type = "slice"
W
wanghuancoder 已提交
339
        self.python_api = slice_wrapper
340 341 342
        self.config()
        self.inputs = {
            'Input': self.input,
343
            "StartsTensor": np.array(self.starts, dtype="int32"),
344
            "EndsTensor": np.array(self.ends, dtype="int32"),
345 346 347 348
        }
        self.outputs = {'Out': self.out}
        self.attrs = {
            'axes': self.axes,
349 350
            # 'starts': self.starts,
            # 'ends': self.ends,
351 352 353 354
            'infer_flags': self.infer_flags,
            'decrease_axis': self.decrease_axis,
        }

W
whs 已提交
355
    def config(self):
356
        self.input = np.random.random([3, 4, 5, 6]).astype("float64")
357 358
        self.starts = [1, 0, 2]
        self.ends = [2, 1, 4]
W
whs 已提交
359
        self.axes = [0, 1, 2]
360 361 362 363 364
        self.decrease_axis = [0, 1]
        self.infer_flags = [-1, -1, -1]
        self.out = self.input[1, 0, 2:4, :]

    def test_check_output(self):
365
        self.check_output()
366 367

    def test_check_grad_normal(self):
368
        self.check_grad(['Input'], 'Out', max_relative_error=0.006)
W
whs 已提交
369 370


371 372 373 374 375
# Situation 6: starts(tensor), ends(list, have tensor)
# without attr(decrease)
class TestSliceOp_starts_OneTensor_ends_ListTensor(OpTest):
    def setUp(self):
        self.op_type = "slice"
W
wanghuancoder 已提交
376
        self.python_api = slice_wrapper
377 378 379 380
        self.config()

        ends_tensor = []
        for index, ele in enumerate(self.ends):
381
            ends_tensor.append(
382
                ("y" + str(index), np.ones(1).astype('int32') * ele)
383
            )
384 385 386

        self.inputs = {
            'Input': self.input,
387
            "StartsTensor": np.array(self.starts, dtype="int32"),
388
            'EndsTensorList': ends_tensor,
389 390 391 392
        }
        self.outputs = {'Out': self.out}
        self.attrs = {
            'axes': self.axes,
393
            # 'starts': self.starts,
394
            'ends': self.ends_infer,
395
            'infer_flags': self.infer_flags,
396 397
        }

W
whs 已提交
398
    def config(self):
399
        self.input = np.random.random([3, 4, 5, 6]).astype("float64")
400 401 402 403 404 405 406 407 408
        self.starts = [1, 0, 2]
        self.ends = [3, 3, 4]
        self.axes = [0, 1, 2]
        self.infer_flags = [-1, -1, -1]
        self.out = self.input[1:3, 0:3, 2:4, :]

        self.ends_infer = [-1, 3, 4]

    def test_check_output(self):
409
        self.check_output()
410 411

    def test_check_grad_normal(self):
412
        self.check_grad(['Input'], 'Out', max_relative_error=0.006)
W
whs 已提交
413 414


415
# Test CUDA float16
416 417 418
@unittest.skipIf(
    not core.is_compiled_with_cuda(), "core is not compiled with CUDA"
)
419 420 421
class TestFP16(OpTest):
    def setUp(self):
        self.op_type = "slice"
X
xiaoguoguo626807 已提交
422 423
        self.prim_op_type = "prim"
        self.python_api = paddle.slice
424
        self.public_python_api = paddle.slice
425 426 427 428 429 430 431
        self.config()
        self.inputs = {'Input': self.input}
        self.outputs = {'Out': self.out}
        self.attrs = {
            'axes': self.axes,
            'starts': self.starts,
            'ends': self.ends,
432
            'infer_flags': self.infer_flags,
433 434
        }

435 436 437 438 439 440 441
    def config(self):
        self.dtype = "float16"
        self.input = np.random.random([3, 4, 5, 6]).astype(self.dtype)
        self.starts = [-3, 0, 2]
        self.ends = [3, 100, -1]
        self.axes = [0, 1, 3]
        self.out = self.input[-3:3, 0:100, :, 2:-1]
442
        self.infer_flags = [1, 1, 1]
443 444 445 446

    def test_check_output(self):
        place = core.CUDAPlace(0)
        if core.is_float16_supported(place):
447
            self.check_output_with_place(place, check_prim=True)
448 449 450

    def test_check_grad_normal(self):
        place = core.CUDAPlace(0)
X
xiaoguoguo626807 已提交
451
        print("core:", core.is_float16_supported(place))
452
        if core.is_float16_supported(place):
453
            self.check_grad_with_place(
X
xiaoguoguo626807 已提交
454 455 456 457
                place,
                ['Input'],
                'Out',
                check_prim=True,
458
            )
459 460


461 462 463
@unittest.skipIf(
    not core.is_compiled_with_cuda(), "core is not compiled with CUDA"
)
464 465 466
class TestFP16_2(OpTest):
    def setUp(self):
        self.op_type = "slice"
X
xiaoguoguo626807 已提交
467 468
        self.prim_op_type = "prim"
        self.python_api = paddle.slice
469
        self.public_python_api = paddle.slice
470 471 472 473 474 475 476
        self.config()
        self.inputs = {'Input': self.input}
        self.outputs = {'Out': self.out}
        self.attrs = {
            'axes': self.axes,
            'starts': self.starts,
            'ends': self.ends,
477
            'infer_flags': self.infer_flags,
478 479
        }

480 481
    def config(self):
        self.dtype = "float16"
Z
zhupengyang 已提交
482
        self.input = np.random.random([3, 4, 10]).astype(self.dtype)
483 484 485 486
        self.starts = [0]
        self.ends = [1]
        self.axes = [1]
        self.out = self.input[:, 0:1, :]
487
        self.infer_flags = [1]
488 489 490 491

    def test_check_output(self):
        place = core.CUDAPlace(0)
        if core.is_float16_supported(place):
492
            self.check_output_with_place(place, check_prim=True)
493 494 495 496

    def test_check_grad_normal(self):
        place = core.CUDAPlace(0)
        if core.is_float16_supported(place):
497 498 499 500 501
            self.check_grad_with_place(
                place,
                ['Input'],
                'Out',
                numeric_grad_delta=0.5,
X
xiaoguoguo626807 已提交
502
                check_prim=True,
503
            )
504 505


506 507 508
class TestBF16(OpTest):
    def setUp(self):
        self.op_type = "slice"
X
xiaoguoguo626807 已提交
509 510
        self.prim_op_type = "prim"
        self.python_api = paddle.slice
511
        self.public_python_api = paddle.slice
512 513 514 515 516 517 518
        self.config()
        self.inputs = {'Input': convert_float_to_uint16(self.input)}
        self.outputs = {'Out': convert_float_to_uint16(self.out)}
        self.attrs = {
            'axes': self.axes,
            'starts': self.starts,
            'ends': self.ends,
519
            'infer_flags': self.infer_flags,
520 521 522 523 524 525 526 527 528 529 530 531 532 533
        }

    def config(self):
        self.dtype = np.uint16
        self.input = np.random.random([3, 4, 5, 6]).astype(np.float32)
        self.starts = [-3, 0, 2]
        self.ends = [3, 100, -1]
        self.axes = [0, 1, 3]
        self.out = self.input[-3:3, 0:100, :, 2:-1]
        self.infer_flags = [1, 1, 1]

    def test_check_output(self):
        self.check_output()

534
    # pad not support bfloat16, so we can't test prim.
535 536 537 538
    def test_check_grad_normal(self):
        self.check_grad(['Input'], 'Out')


539
# Test python API
540
class TestSliceAPI(unittest.TestCase):
541
    def test_1(self):
W
wanghuancoder 已提交
542 543
        with paddle_static_guard():
            input = np.random.random([3, 4, 5, 6]).astype("float64")
544 545
            minus_1 = paddle.tensor.fill_constant([], "int32", -1)
            minus_3 = paddle.tensor.fill_constant([], "int64", -3)
W
wanghuancoder 已提交
546 547 548 549 550 551 552 553 554 555 556
            starts = paddle.static.data(
                name='starts', shape=[1, 3], dtype="float32"
            )
            starts.desc.set_need_check_feed(False)
            ends = paddle.static.data(name='ends', shape=[3], dtype="float32")
            ends.desc.set_need_check_feed(False)
            x = paddle.static.data(
                name="x",
                shape=[3, 4, 5, 6],
                dtype="float64",
            )
557

W
wanghuancoder 已提交
558 559
            # value_int64 is greater than 2147483647 which is the max of int32
            value_int64 = paddle.tensor.fill_constant([1], "int64", 2147483648)
560

W
wanghuancoder 已提交
561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591
            out_1 = paddle.slice(
                x,
                axes=[0, 1, 2],
                starts=[-3, 0, 2],
                ends=[value_int64, 100, -1],
            )
            out_2 = paddle.slice(
                x, axes=[0, 1, 3], starts=[minus_3, 0, 2], ends=[3, 100, -1]
            )
            out_3 = paddle.slice(
                x,
                axes=[0, 1, 3],
                starts=[minus_3, 0, 2],
                ends=[3, 100, minus_1],
            )
            out_4 = paddle.slice(x, axes=[0, 1, 2], starts=starts, ends=ends)

            out_5 = x[-3:3, 0:100, 2:-1]
            out_6 = x[minus_3:3, 0:100, :, 2:-1]
            out_7 = x[minus_1, 0:100, :, 2:minus_1]

            exe = fluid.Executor(place=fluid.CPUPlace())
            res_1, res_2, res_3, res_4, res_5, res_6, res_7 = exe.run(
                fluid.default_main_program(),
                feed={
                    "x": input,
                    'starts': np.array([-3, 0, 2]).astype("int32"),
                    'ends': np.array([3, 100, -1]).astype("int32"),
                },
                fetch_list=[out_1, out_2, out_3, out_4, out_5, out_6, out_7],
            )
592

W
wanghuancoder 已提交
593 594 595 596 597 598 599
            assert np.array_equal(res_1, input[-3:3, 0:100, 2:-1, :])
            assert np.array_equal(res_2, input[-3:3, 0:100, :, 2:-1])
            assert np.array_equal(res_3, input[-3:3, 0:100, :, 2:-1])
            assert np.array_equal(res_4, input[-3:3, 0:100, 2:-1, :])
            assert np.array_equal(res_5, input[-3:3, 0:100, 2:-1, :])
            assert np.array_equal(res_6, input[-3:3, 0:100, :, 2:-1])
            assert np.array_equal(res_7, input[-1, 0:100, :, 2:-1])
600 601


602 603 604 605 606 607 608
class TestSliceApiWithTensor(unittest.TestCase):
    def test_starts_ends_is_tensor(self):
        with paddle.fluid.dygraph.guard():
            a = paddle.rand(shape=[4, 5, 6], dtype='float32')
            axes = [0, 1, 2]
            starts = [-3, 0, 2]
            ends = [3, 2, 4]
609 610 611 612 613 614
            a_1 = paddle.slice(
                a,
                axes=axes,
                starts=paddle.to_tensor(starts, dtype='int32'),
                ends=paddle.to_tensor(ends, dtype='int32'),
            )
615 616
            a_2 = paddle.slice(a, axes=axes, starts=starts, ends=ends)

617
            np.testing.assert_array_equal(a_1.numpy(), a_2.numpy())
618

W
WeiXin 已提交
619 620 621 622 623 624 625 626 627 628 629 630 631 632
    def test_bool_tensor(self):
        with paddle.fluid.dygraph.guard():
            array = (np.arange(60).reshape([3, 4, 5]) % 3).astype('bool')
            tt = paddle.to_tensor(array)
            tt.stop_gradient = False

            starts = [0, 1, 2]
            ends = [3, 5, 4]
            axes = [0, 1, 2]

            y_paddle = paddle.slice(tt, axes, starts, ends)
            y_np = tt[0:3, 1:5, 2:4]

            self.assertTrue(paddle.bool == y_paddle.dtype)
633
            np.testing.assert_array_equal(y_paddle.numpy(), y_np)
W
WeiXin 已提交
634

635

H
hong 已提交
636 637 638
class TestSliceApiEager(unittest.TestCase):
    def test_slice_api(self):
        with paddle.fluid.dygraph.guard():
W
Weilong Wu 已提交
639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660
            a = paddle.rand(shape=[4, 5, 6], dtype='float32')
            a.stop_gradient = False
            axes = [0, 1, 2]
            starts = [-3, 0, 2]
            ends = [3, 2, 4]
            a_1 = paddle.slice(a, axes=axes, starts=starts, ends=ends)

            a_2 = paddle.slice(
                a,
                axes=axes,
                starts=paddle.to_tensor(starts),
                ends=paddle.to_tensor(ends),
            )
            np.testing.assert_array_equal(a_1.numpy(), a_2.numpy())
            a_1.backward()
            grad_truth = paddle.zeros_like(a)
            grad_truth[-3:3, 0:2, 2:4] = 1
            np.testing.assert_array_equal(grad_truth, a.gradient())

            np.testing.assert_allclose(
                a_1.numpy(), a[-3:3, 0:2, 2:4], rtol=1e-05
            )
H
hong 已提交
661 662


663 664 665 666 667 668 669 670 671
class TestSliceApiWithLoDTensorArray(unittest.TestCase):
    def setUp(self):
        self.shape = (3, 4)
        self.data = np.random.random(size=self.shape).astype('float32')
        self.idx = 0
        self.start = 0
        self.end = 2
        self.axis = 1

672 673 674 675 676
        self.place = (
            fluid.CUDAPlace(0)
            if fluid.is_compiled_with_cuda()
            else fluid.CPUPlace()
        )
677 678 679
        self.exe = fluid.Executor(self.place)

    def set_program_and_run(self, main_program, case_num):
W
wanghuancoder 已提交
680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728
        with paddle_static_guard():
            with fluid.program_guard(main_program):
                x = [
                    paddle.static.data(
                        name='x0', shape=self.shape, dtype="float32"
                    ),
                    paddle.static.data(
                        name='x1', shape=self.shape, dtype="float32"
                    ),
                    paddle.static.data(
                        name='x2', shape=self.shape, dtype="float32"
                    ),
                ]

                for each_x in x:
                    each_x.stop_gradient = False

                arr = paddle.tensor.create_array(dtype="float32")
                for i in range(3):
                    idx = paddle.tensor.array_length(arr)
                    arr = paddle.tensor.array_write(x=x[i], i=idx, array=arr)

                if case_num == 1:
                    self.sliced_arr = output = arr[0]

                elif case_num == 2:
                    end = (
                        paddle.tensor.array_length(arr) - 1
                    )  # dtype of end is int64
                    self.sliced_arr = slice_arr = arr[self.start : end]
                    output, _ = tensor_array_to_tensor(
                        slice_arr, axis=self.axis, use_stack=True
                    )
                elif case_num == 3:
                    value_int64 = paddle.tensor.fill_constant(
                        [1], "int64", 2147483648
                    )
                    self.sliced_arr = slice_arr = arr[self.start : value_int64]
                    output, _ = tensor_array_to_tensor(
                        slice_arr, axis=self.axis, use_stack=True
                    )

                loss = paddle.sum(output)
                fluid.backward.append_backward(loss)
                g_vars = list(
                    map(
                        main_program.global_block().var,
                        [each_x.name + "@GRAD" for each_x in x],
                    )
729
                )
W
wanghuancoder 已提交
730 731 732 733
                self.out, self.g_x0, self.g_x1, self.g_x2 = self.exe.run(
                    main_program,
                    feed={'x0': self.data, 'x1': self.data, 'x2': self.data},
                    fetch_list=[output] + g_vars,
734
                )
735 736 737 738 739 740 741

    def test_case_1(self):
        main_program = fluid.Program()
        self.set_program_and_run(main_program, 1)

        self.assertTrue(self.sliced_arr.type == core.VarDesc.VarType.LOD_TENSOR)
        self.assertEqual(self.sliced_arr.shape, self.shape)
742 743 744 745
        np.testing.assert_array_equal(self.out, self.data)
        np.testing.assert_array_equal(self.g_x0, np.ones_like(self.data))
        np.testing.assert_array_equal(self.g_x1, np.zeros_like(self.data))
        np.testing.assert_array_equal(self.g_x2, np.zeros_like(self.data))
746 747

    def test_case_2(self):
W
wanghuancoder 已提交
748 749 750
        with paddle_static_guard():
            main_program = fluid.Program()
            self.set_program_and_run(main_program, 2)
751

W
wanghuancoder 已提交
752 753 754 755 756 757 758 759 760 761
            self.assertTrue(
                self.sliced_arr.type == core.VarDesc.VarType.LOD_TENSOR_ARRAY
            )
            self.assertEqual(self.sliced_arr.shape, self.shape)
            np.testing.assert_array_equal(
                self.out, np.stack([self.data, self.data], axis=self.axis)
            )
            np.testing.assert_array_equal(self.g_x0, np.ones_like(self.data))
            np.testing.assert_array_equal(self.g_x1, np.ones_like(self.data))
            np.testing.assert_array_equal(self.g_x2, np.zeros_like(self.data))
762

763
    def test_case_3(self):
W
wanghuancoder 已提交
764 765 766
        with paddle_static_guard():
            main_program = fluid.Program()
            self.set_program_and_run(main_program, 3)
767

W
wanghuancoder 已提交
768 769 770 771 772 773 774 775 776 777 778
            self.assertTrue(
                self.sliced_arr.type == core.VarDesc.VarType.LOD_TENSOR_ARRAY
            )
            self.assertEqual(self.sliced_arr.shape, self.shape)
            np.testing.assert_array_equal(
                self.out,
                np.stack([self.data, self.data, self.data], axis=self.axis),
            )
            np.testing.assert_array_equal(self.g_x0, np.ones_like(self.data))
            np.testing.assert_array_equal(self.g_x1, np.ones_like(self.data))
            np.testing.assert_array_equal(self.g_x2, np.ones_like(self.data))
779

780

781 782 783 784 785
class TestImperativeVarBaseGetItem(unittest.TestCase):
    def test_getitem_with_long(self):
        with fluid.dygraph.guard():
            data = np.random.random((2, 80, 16128)).astype('float32')
            var = fluid.dygraph.to_variable(data)
786
            sliced = var[:, 10:, : var.shape[1]]  # var.shape[1] is 80L here
787 788
            self.assertEqual(sliced.shape, [2, 70, 80])

789
            sliced = var[:, var.shape[0] :, var.shape[0] : var.shape[1]]
790 791 792 793 794 795 796
            self.assertEqual(sliced.shape, [2, 78, 78])

    def test_getitem_with_float(self):
        def test_float_in_slice_item():
            with fluid.dygraph.guard():
                data = np.random.random((2, 80, 16128)).astype('float32')
                var = fluid.dygraph.to_variable(data)
797
                sliced = var[:, 1.1:, : var.shape[1]]
798 799 800 801 802 803 804 805 806 807 808 809

        self.assertRaises(Exception, test_float_in_slice_item)

        def test_float_in_index():
            with fluid.dygraph.guard():
                data = np.random.random((2, 80, 16128)).astype('float32')
                var = fluid.dygraph.to_variable(data)
                sliced = var[1.1]

        self.assertRaises(Exception, test_float_in_index)


810 811 812 813 814 815 816
class TestInferShape(unittest.TestCase):
    def test(self):
        x = paddle.ones(shape=[3, 4, 5])
        x.desc.set_shape([3, -1, 5])
        self.assertEqual(x.shape, (3, -1, 5))

        out0 = paddle.slice(x, axes=[1], starts=[0], ends=[3])
817
        self.assertEqual(out0.shape, (3, -1, 5))
818

819 820 821 822 823 824
    def test_axis_less_than_zero(self):
        # Using paddle.disable_static will make other unittests fail.
        with fluid.dygraph.guard():
            x_arr = np.arange(0, 24, dtype=np.float32).reshape([2, 3, 4])
            x = paddle.to_tensor(x_arr)

825 826 827 828 829 830 831 832
            pp_slice = paddle.slice(
                x,
                [
                    100,
                ],
                [0],
                [1],
            )
833
            np_slice = x_arr[:, :, 0:1]
834
            np.testing.assert_array_equal(pp_slice, np_slice)
835

836
            pp_slice = paddle.slice(x, (-100,), [0], [1])
837
            np_slice = x_arr[0:1]
838
            np.testing.assert_array_equal(pp_slice, np_slice)
839 840 841 842 843

            x_arr = np.array([], dtype=np.float32)
            x = paddle.to_tensor(np.reshape(x_arr, (0, 0, 0)))

            starts = paddle.to_tensor(
844 845
                np.reshape(np.array([], dtype=np.int32), (0,))
            )
846
            ends = paddle.to_tensor(
847 848
                np.reshape(np.array([], dtype=np.int32), (0,))
            )
849 850 851 852 853 854 855 856 857 858 859 860 861

            with self.assertRaises(ValueError):
                paddle.slice(x, [-1000000], starts, ends)

            with self.assertRaises(ValueError):
                paddle.slice(x, [1000000], starts, ends)

            with self.assertRaises(ValueError):
                paddle.slice(x, [], starts, ends)

            with self.assertRaises(ValueError):
                paddle.slice(x, 0, starts, ends)

862

863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883
class TestSliceOpError(unittest.TestCase):
    def test_dismatch_shape(self):
        with fluid.dygraph.guard():
            with self.assertRaises(ValueError):
                array = np.array([], dtype=np.float32)
                x = paddle.to_tensor(np.reshape(array, [0]), dtype='float32')
                paddle.slice(x, axes=[0], starts=[], ends=[])

            with self.assertRaises(ValueError):
                array = np.array([], dtype=np.float32)
                x = paddle.to_tensor(np.reshape(array, [0]), dtype='float32')
                paddle.slice(x, axes=[0], starts=[0], ends=[])

            # if shape match, pass
            array = np.array([], dtype=np.float32)
            x = paddle.to_tensor(np.reshape(array, [0]), dtype='float32')
            out = paddle.slice(x, axes=[0], starts=[0], ends=[0])
            self.assertEqual(out.numel(), 0)
            # self.assertEqual(out.shape)


884 885 886
@unittest.skipIf(
    not core.is_compiled_with_cuda(), "core is not compiled with CUDA"
)
887 888 889 890
class TestImperativeCUDAPinnedInput(unittest.TestCase):
    def test_input_cuda_pinned_var(self):
        with fluid.dygraph.guard():
            data = np.random.random((2, 80, 16128)).astype('float32')
W
Weilong Wu 已提交
891
            var = core.eager.Tensor(
892 893 894 895 896 897 898
                value=data,
                name='',
                persistable=False,
                place=fluid.CUDAPinnedPlace(),
                zero_copy=False,
            )
            sliced = var[:, 10:, : var.shape[1]]
899 900 901
            self.assertEqual(sliced.shape, [2, 70, 80])


902 903
class TestSliceDoubleGradCheck(unittest.TestCase):
    def slice_wrapper(self, x):
904 905 906
        return paddle.slice(
            x[0], axes=[0, 1, 2], starts=[-3, 0, 2], ends=[3, 2, 4]
        )
907 908 909 910 911 912 913

    @prog_scope()
    def func(self, place):
        # the shape of input variable should be clearly specified, not inlcude -1.
        eps = 0.005
        dtype = np.float32

G
GGBond8488 已提交
914
        data = paddle.static.data('data', [4, 5, 6], dtype)
915
        data.persistable = True
916 917 918
        out = paddle.slice(
            data, axes=[0, 1, 2], starts=[-3, 0, 2], ends=[3, 2, 4]
        )
919 920
        data_arr = np.random.uniform(-1, 1, data.shape).astype(dtype)

921 922 923 924 925 926
        gradient_checker.double_grad_check(
            [data], out, x_init=[data_arr], place=place, eps=eps
        )
        gradient_checker.double_grad_check_for_dygraph(
            self.slice_wrapper, [data], out, x_init=[data_arr], place=place
        )
927 928

    def test_grad(self):
W
wanghuancoder 已提交
929 930 931 932 933 934
        with paddle_static_guard():
            places = [fluid.CPUPlace()]
            if core.is_compiled_with_cuda():
                places.append(fluid.CUDAPlace(0))
            for p in places:
                self.func(p)
935 936 937 938


class TestSliceTripleGradCheck(unittest.TestCase):
    def slice_wrapper(self, x):
939 940 941
        return paddle.slice(
            x[0], axes=[0, 1, 2], starts=[-3, 0, 2], ends=[3, 2, 4]
        )
942 943 944 945 946 947 948

    @prog_scope()
    def func(self, place):
        # the shape of input variable should be clearly specified, not inlcude -1.
        eps = 0.005
        dtype = np.float32

G
GGBond8488 已提交
949
        data = paddle.static.data('data', [4, 5, 6], dtype)
950
        data.persistable = True
951 952 953
        out = paddle.slice(
            data, axes=[0, 1, 2], starts=[-3, 0, 2], ends=[3, 2, 4]
        )
954 955
        data_arr = np.random.uniform(-1, 1, data.shape).astype(dtype)

956 957 958 959 960 961
        gradient_checker.triple_grad_check(
            [data], out, x_init=[data_arr], place=place, eps=eps
        )
        gradient_checker.triple_grad_check_for_dygraph(
            self.slice_wrapper, [data], out, x_init=[data_arr], place=place
        )
962 963

    def test_grad(self):
W
wanghuancoder 已提交
964 965 966 967 968 969
        with paddle_static_guard():
            places = [fluid.CPUPlace()]
            if core.is_compiled_with_cuda():
                places.append(fluid.CUDAPlace(0))
            for p in places:
                self.func(p)
970 971


W
whs 已提交
972
if __name__ == '__main__':
H
hong 已提交
973
    paddle.enable_static()
W
whs 已提交
974
    unittest.main()