test_slice_op.py 32.6 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
20
from op_test import OpTest, convert_float_to_uint16
21

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

27 28
paddle.enable_static()

W
whs 已提交
29

30 31
# Situation 1: starts(list, no tensor), ends(list, no tensor)
# 1.1 without attr(decrease)
W
whs 已提交
32 33 34
class TestSliceOp(OpTest):
    def setUp(self):
        self.op_type = "slice"
X
xiaoguoguo626807 已提交
35 36
        self.prim_op_type = "prim"
        self.python_api = paddle.slice
37
        self.enable_cinn = True
W
whs 已提交
38 39 40 41 42 43
        self.config()
        self.inputs = {'Input': self.input}
        self.outputs = {'Out': self.out}
        self.attrs = {
            'axes': self.axes,
            'starts': self.starts,
44
            'ends': self.ends,
45
            'infer_flags': self.infer_flags,
W
whs 已提交
46 47 48
        }

    def config(self):
49
        self.input = np.random.random([3, 4, 5, 6]).astype("float64")
W
whs 已提交
50 51 52
        self.starts = [1, 0, 2]
        self.ends = [3, 3, 4]
        self.axes = [0, 1, 2]
53
        self.infer_flags = [1, 1, 1]
W
whs 已提交
54 55 56
        self.out = self.input[1:3, 0:3, 2:4, :]

    def test_check_output(self):
X
xiaoguoguo626807 已提交
57
        self.check_output(check_prim=True)
W
whs 已提交
58

59
    def test_check_grad_normal(self):
X
xiaoguoguo626807 已提交
60 61 62
        self.check_grad(
            ['Input'], 'Out', max_relative_error=0.006, check_prim=True
        )
63

W
whs 已提交
64

65 66
class TestCase1(TestSliceOp):
    def config(self):
67
        self.input = np.random.random([3, 4, 5, 6]).astype("float64")
68 69 70 71 72 73 74 75 76
        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):
77
        self.enable_cinn = True
78
        self.input = np.random.random([3, 4, 5, 6]).astype("float64")
79 80 81 82 83 84 85
        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]


86 87 88
class TestSliceZerosShapeTensor(OpTest):
    def setUp(self):
        self.op_type = "slice"
X
xiaoguoguo626807 已提交
89 90
        self.prim_op_type = "prim"
        self.python_api = paddle.slice
91 92 93 94 95 96 97 98
        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,
99
            'use_mkldnn': True,
100 101 102 103 104 105 106 107 108 109 110 111 112 113
        }

    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())


114
# 1.2 with attr(decrease)
H
Hongyu Liu 已提交
115 116
class TestSliceOp_decs_dim(OpTest):
    def setUp(self):
117
        self.enable_cinn = True
H
Hongyu Liu 已提交
118
        self.op_type = "slice"
X
xiaoguoguo626807 已提交
119 120
        self.prim_op_type = "prim"
        self.python_api = paddle.slice
H
Hongyu Liu 已提交
121 122 123 124 125 126 127
        self.config()
        self.inputs = {'Input': self.input}
        self.outputs = {'Out': self.out}
        self.attrs = {
            'axes': self.axes,
            'starts': self.starts,
            'ends': self.ends,
128
            'infer_flags': self.infer_flags,
H
Hongyu Liu 已提交
129 130 131 132
            'decrease_axis': self.decrease_axis,
        }

    def config(self):
133
        self.input = np.random.random([3, 4, 5, 6]).astype("float64")
H
Hongyu Liu 已提交
134 135 136 137
        self.starts = [1, 0, 2]
        self.ends = [2, 3, 4]
        self.axes = [0, 1, 2]
        self.decrease_axis = [0]
138
        self.infer_flags = [1, 1, 1]
H
Hongyu Liu 已提交
139 140 141
        self.out = self.input[1, 0:3, 2:4, :]

    def test_check_output(self):
X
xiaoguoguo626807 已提交
142
        self.check_output(check_prim=True)
H
Hongyu Liu 已提交
143 144

    def test_check_grad_normal(self):
X
xiaoguoguo626807 已提交
145 146 147
        self.check_grad(
            ['Input'], 'Out', max_relative_error=0.006, check_prim=True
        )
H
Hongyu Liu 已提交
148 149


150 151
class TestSliceOp_decs_dim_2(TestSliceOp_decs_dim):
    def config(self):
152
        self.enable_cinn = True
153
        self.input = np.random.random([3, 4, 5, 6]).astype("float64")
154 155 156 157 158 159 160 161 162 163
        self.starts = [1, 0, 2]
        self.ends = [2, 1, 4]
        self.axes = [0, 1, 2]
        self.decrease_axis = [0, 1]
        self.infer_flags = [1, 1, 1]
        self.out = self.input[1, 0, 2:4, :]


class TestSliceOp_decs_dim_3(TestSliceOp_decs_dim):
    def config(self):
164
        self.enable_cinn = True
165
        self.input = np.random.random([3, 4, 5, 6]).astype("float64")
166 167 168 169 170 171 172 173 174 175
        self.starts = [-1, 0, 2]
        self.ends = [1000000, 1, 4]
        self.axes = [0, 1, 2]
        self.decrease_axis = [0, 1]
        self.infer_flags = [1, 1, 1]
        self.out = self.input[-1, 0, 2:4, :]


class TestSliceOp_decs_dim_4(TestSliceOp_decs_dim):
    def config(self):
X
xiaoguoguo626807 已提交
176
        self.enable_cinn = True
177
        self.input = np.random.random([3, 4, 5, 7]).astype("float64")
178 179 180 181 182 183 184 185 186 187
        self.starts = [0, 1, 2, 3]
        self.ends = [1, 2, 3, 4]
        self.axes = [0, 1, 2, 3]
        self.decrease_axis = [0, 1, 2, 3]
        self.infer_flags = [1, 1, 1]
        self.out = self.input[0, 1, 2, 3:4]


class TestSliceOp_decs_dim_5(TestSliceOp_decs_dim):
    def config(self):
188
        self.enable_cinn = True
189
        self.input = np.random.random([3, 4, 5, 6]).astype("float64")
190 191 192 193 194 195 196 197
        self.starts = [-1]
        self.ends = [1000000]
        self.axes = [3]
        self.decrease_axis = [3]
        self.infer_flags = [1, 1, 1]
        self.out = self.input[:, :, :, -1]


X
xiaoguoguo626807 已提交
198
# test_6 with test_2 with test_3
199 200
class TestSliceOp_decs_dim_6(TestSliceOp_decs_dim):
    def config(self):
201
        self.enable_cinn = True
202
        self.input = np.random.random([3, 4, 5, 6]).astype("float64")
203 204 205 206 207 208 209 210 211 212 213
        self.starts = [0, 1, 2, 3]
        self.ends = [1, 2, 3, 4]
        self.axes = [0, 1, 2, 3]
        self.decrease_axis = [0, 1, 2, 3]
        self.infer_flags = [1, 1, 1]
        self.out = self.input[0, 1, 2, 3:4]


# Situation 2: starts(list, have tensor), ends(list, no tensor)
# without attr(decrease)
class TestSliceOp_starts_ListTensor(OpTest):
H
Hongyu Liu 已提交
214 215
    def setUp(self):
        self.op_type = "slice"
X
xiaoguoguo626807 已提交
216
        self.python_api = paddle.slice
H
Hongyu Liu 已提交
217
        self.config()
218 219 220

        starts_tensor = []
        for index, ele in enumerate(self.starts):
221 222 223
            starts_tensor.append(
                ("x" + str(index), np.ones((1)).astype('int64') * ele)
            )
224 225

        self.inputs = {'Input': self.input, 'StartsTensorList': starts_tensor}
H
Hongyu Liu 已提交
226 227 228
        self.outputs = {'Out': self.out}
        self.attrs = {
            'axes': self.axes,
229
            'starts': self.starts_infer,
H
Hongyu Liu 已提交
230
            'ends': self.ends,
231
            'infer_flags': self.infer_flags,
H
Hongyu Liu 已提交
232 233 234
        }

    def config(self):
235
        self.input = np.random.random([3, 4, 5, 6]).astype("float64")
H
Hongyu Liu 已提交
236
        self.starts = [1, 0, 2]
237
        self.ends = [3, 3, 4]
H
Hongyu Liu 已提交
238
        self.axes = [0, 1, 2]
239 240 241 242
        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 已提交
243 244

    def test_check_output(self):
245
        self.check_output()
H
Hongyu Liu 已提交
246 247

    def test_check_grad_normal(self):
248
        self.check_grad(['Input'], 'Out', max_relative_error=0.006)
H
Hongyu Liu 已提交
249 250


251 252 253
# Situation 2: starts(list, have tensor), ends(list, no tensor)
#  with attr(decrease)
class TestSliceOp_decs_dim_starts_ListTensor(OpTest):
H
Hongyu Liu 已提交
254 255
    def setUp(self):
        self.op_type = "slice"
X
xiaoguoguo626807 已提交
256
        self.python_api = paddle.slice
H
Hongyu Liu 已提交
257
        self.config()
258 259 260

        starts_tensor = []
        for index, ele in enumerate(self.starts):
261 262 263
            starts_tensor.append(
                ("x" + str(index), np.ones((1)).astype('int32') * ele)
            )
264 265 266

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

H
Hongyu Liu 已提交
267 268 269
        self.outputs = {'Out': self.out}
        self.attrs = {
            'axes': self.axes,
270
            'starts': self.starts_infer,
H
Hongyu Liu 已提交
271
            'ends': self.ends,
272
            'infer_flags': self.infer_flags,
H
Hongyu Liu 已提交
273 274 275 276
            'decrease_axis': self.decrease_axis,
        }

    def config(self):
277
        self.input = np.random.random([3, 4, 5, 6]).astype("float64")
278 279
        self.starts = [1, 0, 2]
        self.ends = [2, 3, 4]
H
Hongyu Liu 已提交
280
        self.axes = [0, 1, 2]
281 282 283 284 285
        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 已提交
286 287

    def test_check_output(self):
288
        self.check_output()
H
Hongyu Liu 已提交
289 290

    def test_check_grad_normal(self):
291
        self.check_grad(['Input'], 'Out', max_relative_error=0.006)
H
Hongyu Liu 已提交
292 293


294
class TestSliceOp_decs_dim_5_starts_ListTensor(
295 296
    TestSliceOp_decs_dim_starts_ListTensor
):
297
    def config(self):
298
        self.input = np.random.random([3, 4, 5, 6]).astype("float64")
299 300 301 302 303 304 305 306 307 308 309 310 311
        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 已提交
312 313
    def setUp(self):
        self.op_type = "slice"
X
xiaoguoguo626807 已提交
314
        self.python_api = paddle.slice
H
Hongyu Liu 已提交
315
        self.config()
316 317
        self.inputs = {
            'Input': self.input,
318
            "StartsTensor": np.array(self.starts, dtype="int32"),
319
        }
H
Hongyu Liu 已提交
320 321 322
        self.outputs = {'Out': self.out}
        self.attrs = {
            'axes': self.axes,
323
            # 'starts': self.starts,
H
Hongyu Liu 已提交
324
            'ends': self.ends,
325
            'infer_flags': self.infer_flags,
H
Hongyu Liu 已提交
326 327 328 329
            'decrease_axis': self.decrease_axis,
        }

    def config(self):
330
        self.input = np.random.random([3, 4, 5, 6]).astype("float64")
331 332 333 334 335 336
        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 已提交
337 338

    def test_check_output(self):
339
        self.check_output()
H
Hongyu Liu 已提交
340 341

    def test_check_grad_normal(self):
342
        self.check_grad(['Input'], 'Out', max_relative_error=0.006)
H
Hongyu Liu 已提交
343 344


345 346 347
# Situation 4: starts(tensor), ends(tensor)
#  without attr(decrease)
class TestSliceOp_starts_OneTensor_ends_OneTensor(OpTest):
H
Hongyu Liu 已提交
348 349
    def setUp(self):
        self.op_type = "slice"
X
xiaoguoguo626807 已提交
350
        self.python_api = paddle.slice
H
Hongyu Liu 已提交
351
        self.config()
352 353 354

        self.inputs = {
            'Input': self.input,
355
            "StartsTensor": np.array(self.starts, dtype="int64"),
356
            "EndsTensor": np.array(self.ends, dtype="int32"),
357
        }
H
Hongyu Liu 已提交
358 359 360
        self.outputs = {'Out': self.out}
        self.attrs = {
            'axes': self.axes,
361 362
            # 'starts': self.starts,
            # 'ends': self.ends_infer,
363
            'infer_flags': self.infer_flags,
H
Hongyu Liu 已提交
364 365 366
        }

    def config(self):
367
        self.input = np.random.random([3, 4, 5, 6]).astype("float64")
368 369 370 371 372
        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 已提交
373 374

    def test_check_output(self):
375
        self.check_output()
H
Hongyu Liu 已提交
376 377

    def test_check_grad_normal(self):
378
        self.check_grad(['Input'], 'Out', max_relative_error=0.006)
H
Hongyu Liu 已提交
379 380


381 382 383 384 385
# 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"
X
xiaoguoguo626807 已提交
386
        self.python_api = paddle.slice
387 388 389
        self.config()
        self.inputs = {
            'Input': self.input,
390
            "StartsTensor": np.array(self.starts, dtype="int32"),
391
            "EndsTensor": np.array(self.ends, dtype="int32"),
392 393 394 395
        }
        self.outputs = {'Out': self.out}
        self.attrs = {
            'axes': self.axes,
396 397
            # 'starts': self.starts,
            # 'ends': self.ends,
398 399 400 401
            'infer_flags': self.infer_flags,
            'decrease_axis': self.decrease_axis,
        }

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

    def test_check_output(self):
412
        self.check_output()
413 414

    def test_check_grad_normal(self):
415
        self.check_grad(['Input'], 'Out', max_relative_error=0.006)
W
whs 已提交
416 417


418 419 420 421 422
# 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"
X
xiaoguoguo626807 已提交
423
        self.python_api = paddle.slice
424 425 426 427
        self.config()

        ends_tensor = []
        for index, ele in enumerate(self.ends):
428 429 430
            ends_tensor.append(
                ("y" + str(index), np.ones((1)).astype('int32') * ele)
            )
431 432 433

        self.inputs = {
            'Input': self.input,
434
            "StartsTensor": np.array(self.starts, dtype="int32"),
435
            'EndsTensorList': ends_tensor,
436 437 438 439
        }
        self.outputs = {'Out': self.out}
        self.attrs = {
            'axes': self.axes,
440
            # 'starts': self.starts,
441
            'ends': self.ends_infer,
442
            'infer_flags': self.infer_flags,
443 444
        }

W
whs 已提交
445
    def config(self):
446
        self.input = np.random.random([3, 4, 5, 6]).astype("float64")
447 448 449 450 451 452 453 454 455
        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):
456
        self.check_output()
457 458

    def test_check_grad_normal(self):
459
        self.check_grad(['Input'], 'Out', max_relative_error=0.006)
W
whs 已提交
460 461


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

482 483 484 485 486 487 488
    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]
489
        self.infer_flags = [1, 1, 1]
490 491 492 493

    def test_check_output(self):
        place = core.CUDAPlace(0)
        if core.is_float16_supported(place):
X
xiaoguoguo626807 已提交
494
            self.check_output_with_place(place, atol=1e-5, check_prim=True)
495 496 497

    def test_check_grad_normal(self):
        place = core.CUDAPlace(0)
X
xiaoguoguo626807 已提交
498
        print("core:", core.is_float16_supported(place))
499
        if core.is_float16_supported(place):
500
            self.check_grad_with_place(
X
xiaoguoguo626807 已提交
501 502 503 504 505
                place,
                ['Input'],
                'Out',
                max_relative_error=0.006,
                check_prim=True,
506
            )
507 508


509 510 511
@unittest.skipIf(
    not core.is_compiled_with_cuda(), "core is not compiled with CUDA"
)
512 513 514
class TestFP16_2(OpTest):
    def setUp(self):
        self.op_type = "slice"
X
xiaoguoguo626807 已提交
515 516
        self.prim_op_type = "prim"
        self.python_api = paddle.slice
517 518 519 520 521 522 523
        self.config()
        self.inputs = {'Input': self.input}
        self.outputs = {'Out': self.out}
        self.attrs = {
            'axes': self.axes,
            'starts': self.starts,
            'ends': self.ends,
524
            'infer_flags': self.infer_flags,
525 526
        }

527 528
    def config(self):
        self.dtype = "float16"
Z
zhupengyang 已提交
529
        self.input = np.random.random([3, 4, 10]).astype(self.dtype)
530 531 532 533
        self.starts = [0]
        self.ends = [1]
        self.axes = [1]
        self.out = self.input[:, 0:1, :]
534
        self.infer_flags = [1]
535 536 537 538

    def test_check_output(self):
        place = core.CUDAPlace(0)
        if core.is_float16_supported(place):
X
xiaoguoguo626807 已提交
539
            self.check_output_with_place(place, atol=1e-5, check_prim=True)
540 541 542 543

    def test_check_grad_normal(self):
        place = core.CUDAPlace(0)
        if core.is_float16_supported(place):
544 545 546 547 548 549
            self.check_grad_with_place(
                place,
                ['Input'],
                'Out',
                max_relative_error=0.006,
                numeric_grad_delta=0.5,
X
xiaoguoguo626807 已提交
550
                check_prim=True,
551
            )
552 553


554 555 556
class TestBF16(OpTest):
    def setUp(self):
        self.op_type = "slice"
X
xiaoguoguo626807 已提交
557 558
        self.prim_op_type = "prim"
        self.python_api = paddle.slice
559 560 561 562 563 564 565
        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,
566
            'infer_flags': self.infer_flags,
567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584
        }

    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()

    def test_check_grad_normal(self):
        self.check_grad(['Input'], 'Out')


585
# Test python API
586
class TestSliceAPI(unittest.TestCase):
587
    def test_1(self):
588
        input = np.random.random([3, 4, 5, 6]).astype("float64")
589
        minus_1 = fluid.layers.fill_constant([1], "int32", -1)
590
        minus_3 = fluid.layers.fill_constant([1], "int64", -3)
G
GGBond8488 已提交
591 592
        starts = paddle.static.data(
            name='starts', shape=[1, 3], dtype="float32"
593
        )
G
GGBond8488 已提交
594 595 596 597
        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(
598 599 600 601
            name="x",
            shape=[3, 4, 5, 6],
            dtype="float64",
        )
602

603 604 605
        # value_int64 is greater than 2147483647 which is the max of int32
        value_int64 = fluid.layers.fill_constant([1], "int64", 2147483648)

606 607 608 609 610 611 612 613 614
        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]
        )
615
        out_4 = paddle.slice(x, axes=[0, 1, 2], starts=starts, ends=ends)
616 617 618 619 620 621 622 623 624 625 626

        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"),
627
                'ends': np.array([3, 100, -1]).astype("int32"),
628
            },
629 630
            fetch_list=[out_1, out_2, out_3, out_4, out_5, out_6, out_7],
        )
631 632 633 634 635 636 637 638 639 640

        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])


641 642 643 644 645 646 647
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]
648 649 650 651 652 653
            a_1 = paddle.slice(
                a,
                axes=axes,
                starts=paddle.to_tensor(starts, dtype='int32'),
                ends=paddle.to_tensor(ends, dtype='int32'),
            )
654 655
            a_2 = paddle.slice(a, axes=axes, starts=starts, ends=ends)

656
            np.testing.assert_array_equal(a_1.numpy(), a_2.numpy())
657

W
WeiXin 已提交
658 659 660 661 662 663 664 665 666 667 668 669 670 671
    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)
672
            np.testing.assert_array_equal(y_paddle.numpy(), y_np)
W
WeiXin 已提交
673

674

H
hong 已提交
675 676 677
class TestSliceApiEager(unittest.TestCase):
    def test_slice_api(self):
        with paddle.fluid.dygraph.guard():
W
Weilong Wu 已提交
678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699
            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 已提交
700 701


702 703 704 705 706 707 708 709 710
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

711 712 713 714 715
        self.place = (
            fluid.CUDAPlace(0)
            if fluid.is_compiled_with_cuda()
            else fluid.CPUPlace()
        )
716 717 718 719 720
        self.exe = fluid.Executor(self.place)

    def set_program_and_run(self, main_program, case_num):
        with fluid.program_guard(main_program):
            x = [
721 722
                fluid.data(name='x0', shape=self.shape, dtype="float32"),
                fluid.data(name='x1', shape=self.shape, dtype="float32"),
723
                fluid.data(name='x2', shape=self.shape, dtype="float32"),
724 725 726 727 728
            ]

            for each_x in x:
                each_x.stop_gradient = False

729
            arr = paddle.tensor.create_array(dtype="float32")
730
            for i in range(3):
731
                idx = paddle.tensor.array_length(arr)
732
                arr = paddle.tensor.array_write(x=x[i], i=idx, array=arr)
733 734 735 736 737

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

            elif case_num == 2:
738
                end = (
739
                    paddle.tensor.array_length(arr) - 1
740 741
                )  # dtype of end is int64
                self.sliced_arr = slice_arr = arr[self.start : end]
742
                output, _ = tensor_array_to_tensor(
743 744
                    slice_arr, axis=self.axis, use_stack=True
                )
745
            elif case_num == 3:
746 747 748 749
                value_int64 = fluid.layers.fill_constant(
                    [1], "int64", 2147483648
                )
                self.sliced_arr = slice_arr = arr[self.start : value_int64]
750
                output, _ = tensor_array_to_tensor(
751 752
                    slice_arr, axis=self.axis, use_stack=True
                )
753

754
            loss = paddle.sum(output)
755 756
            fluid.backward.append_backward(loss)
            g_vars = list(
757 758 759 760 761 762 763 764 765 766
                map(
                    main_program.global_block().var,
                    [each_x.name + "@GRAD" for each_x in x],
                )
            )
            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,
            )
767 768 769 770 771 772 773

    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)
774 775 776 777
        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))
778 779 780 781 782 783

    def test_case_2(self):
        main_program = fluid.Program()
        self.set_program_and_run(main_program, 2)

        self.assertTrue(
784 785
            self.sliced_arr.type == core.VarDesc.VarType.LOD_TENSOR_ARRAY
        )
786
        self.assertEqual(self.sliced_arr.shape, self.shape)
787
        np.testing.assert_array_equal(
788 789
            self.out, np.stack([self.data, self.data], axis=self.axis)
        )
790 791 792
        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))
793

794 795 796 797 798
    def test_case_3(self):
        main_program = fluid.Program()
        self.set_program_and_run(main_program, 3)

        self.assertTrue(
799 800
            self.sliced_arr.type == core.VarDesc.VarType.LOD_TENSOR_ARRAY
        )
801
        self.assertEqual(self.sliced_arr.shape, self.shape)
802
        np.testing.assert_array_equal(
803 804 805
            self.out,
            np.stack([self.data, self.data, self.data], axis=self.axis),
        )
806 807 808
        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))
809

810

811 812 813 814 815
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)
816
            sliced = var[:, 10:, : var.shape[1]]  # var.shape[1] is 80L here
817 818
            self.assertEqual(sliced.shape, [2, 70, 80])

819
            sliced = var[:, var.shape[0] :, var.shape[0] : var.shape[1]]
820 821 822 823 824 825 826
            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)
827
                sliced = var[:, 1.1:, : var.shape[1]]
828 829 830 831 832 833 834 835 836 837 838 839

        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)


840 841 842 843 844 845 846
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])
847
        self.assertEqual(out0.shape, (3, -1, 5))
848

849 850 851 852 853 854
    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)

855 856 857 858 859 860 861 862
            pp_slice = paddle.slice(
                x,
                [
                    100,
                ],
                [0],
                [1],
            )
863
            np_slice = x_arr[:, :, 0:1]
864
            np.testing.assert_array_equal(pp_slice, np_slice)
865

866
            pp_slice = paddle.slice(x, (-100,), [0], [1])
867
            np_slice = x_arr[0:1]
868
            np.testing.assert_array_equal(pp_slice, np_slice)
869 870 871 872 873

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

            starts = paddle.to_tensor(
874 875
                np.reshape(np.array([], dtype=np.int32), (0,))
            )
876
            ends = paddle.to_tensor(
877 878
                np.reshape(np.array([], dtype=np.int32), (0,))
            )
879 880 881 882 883 884 885 886 887 888 889 890 891

            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)

892

893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913
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)


914 915 916
@unittest.skipIf(
    not core.is_compiled_with_cuda(), "core is not compiled with CUDA"
)
917 918 919 920
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 已提交
921
            var = core.eager.Tensor(
922 923 924 925 926 927 928
                value=data,
                name='',
                persistable=False,
                place=fluid.CUDAPinnedPlace(),
                zero_copy=False,
            )
            sliced = var[:, 10:, : var.shape[1]]
929 930 931
            self.assertEqual(sliced.shape, [2, 70, 80])


932 933
class TestSliceDoubleGradCheck(unittest.TestCase):
    def slice_wrapper(self, x):
934 935 936
        return paddle.slice(
            x[0], axes=[0, 1, 2], starts=[-3, 0, 2], ends=[3, 2, 4]
        )
937 938 939 940 941 942 943

    @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 已提交
944
        data = paddle.static.data('data', [4, 5, 6], dtype)
945
        data.persistable = True
946 947 948
        out = paddle.slice(
            data, axes=[0, 1, 2], starts=[-3, 0, 2], ends=[3, 2, 4]
        )
949 950
        data_arr = np.random.uniform(-1, 1, data.shape).astype(dtype)

951 952 953 954 955 956
        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
        )
957 958 959 960 961 962 963 964 965 966 967 968

    def test_grad(self):
        paddle.enable_static()
        places = [fluid.CPUPlace()]
        if core.is_compiled_with_cuda():
            places.append(fluid.CUDAPlace(0))
        for p in places:
            self.func(p)


class TestSliceTripleGradCheck(unittest.TestCase):
    def slice_wrapper(self, x):
969 970 971
        return paddle.slice(
            x[0], axes=[0, 1, 2], starts=[-3, 0, 2], ends=[3, 2, 4]
        )
972 973 974 975 976 977 978

    @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 已提交
979
        data = paddle.static.data('data', [4, 5, 6], dtype)
980
        data.persistable = True
981 982 983
        out = paddle.slice(
            data, axes=[0, 1, 2], starts=[-3, 0, 2], ends=[3, 2, 4]
        )
984 985
        data_arr = np.random.uniform(-1, 1, data.shape).astype(dtype)

986 987 988 989 990 991
        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
        )
992 993 994 995 996 997 998 999 1000 1001

    def test_grad(self):
        paddle.enable_static()
        places = [fluid.CPUPlace()]
        if core.is_compiled_with_cuda():
            places.append(fluid.CUDAPlace(0))
        for p in places:
            self.func(p)


W
whs 已提交
1002
if __name__ == '__main__':
H
hong 已提交
1003
    paddle.enable_static()
W
whs 已提交
1004
    unittest.main()