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

15 16
from __future__ import print_function

W
whs 已提交
17 18
import unittest
import numpy as np
19
import paddle.fluid.core as core
20
from op_test import OpTest, convert_float_to_uint16
21
import paddle.fluid as fluid
22
import paddle.fluid.layers as layers
23
import paddle
24
from paddle.fluid.framework import _test_eager_guard, _enable_legacy_dygraph
25 26 27
import gradient_checker
from decorator_helper import prog_scope
import paddle.fluid.layers as layers
W
whs 已提交
28

29 30
paddle.enable_static()

W
whs 已提交
31

32 33
# Situation 1: starts(list, no tensor), ends(list, no tensor)
# 1.1 without attr(decrease)
W
whs 已提交
34
class TestSliceOp(OpTest):
35

W
whs 已提交
36 37 38 39 40 41 42 43
    def setUp(self):
        self.op_type = "slice"
        self.config()
        self.inputs = {'Input': self.input}
        self.outputs = {'Out': self.out}
        self.attrs = {
            'axes': self.axes,
            'starts': self.starts,
44 45
            'ends': self.ends,
            '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 57 58
        self.out = self.input[1:3, 0:3, 2:4, :]

    def test_check_output(self):
        self.check_output()

59 60 61
    def test_check_grad_normal(self):
        self.check_grad(['Input'], 'Out', max_relative_error=0.006)

W
whs 已提交
62

63
class TestCase1(TestSliceOp):
64

65
    def config(self):
66
        self.input = np.random.random([3, 4, 5, 6]).astype("float64")
67 68 69 70 71 72 73 74
        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):
75

76
    def config(self):
77
        self.input = np.random.random([3, 4, 5, 6]).astype("float64")
78 79 80 81 82 83 84
        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]


85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
class TestSliceZerosShapeTensor(OpTest):

    def setUp(self):
        self.op_type = "slice"
        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,
            'use_mkldnn': True
        }

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


112
# 1.2 with attr(decrease)
H
Hongyu Liu 已提交
113
class TestSliceOp_decs_dim(OpTest):
114

H
Hongyu Liu 已提交
115 116 117 118 119 120 121 122 123
    def setUp(self):
        self.op_type = "slice"
        self.config()
        self.inputs = {'Input': self.input}
        self.outputs = {'Out': self.out}
        self.attrs = {
            'axes': self.axes,
            'starts': self.starts,
            'ends': self.ends,
124
            'infer_flags': self.infer_flags,
H
Hongyu Liu 已提交
125 126 127 128
            'decrease_axis': self.decrease_axis,
        }

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

    def test_check_output(self):
        self.check_output()

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


144
class TestSliceOp_decs_dim_2(TestSliceOp_decs_dim):
145

146
    def config(self):
147
        self.input = np.random.random([3, 4, 5, 6]).astype("float64")
148 149 150 151 152 153 154 155 156
        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):
157

158
    def config(self):
159
        self.input = np.random.random([3, 4, 5, 6]).astype("float64")
160 161 162 163 164 165 166 167 168
        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):
169

170
    def config(self):
171
        self.input = np.random.random([3, 4, 5, 7]).astype("float64")
172 173 174 175 176 177 178 179 180
        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):
181

182
    def config(self):
183
        self.input = np.random.random([3, 4, 5, 6]).astype("float64")
184 185 186 187 188 189 190 191 192
        self.starts = [-1]
        self.ends = [1000000]
        self.axes = [3]
        self.decrease_axis = [3]
        self.infer_flags = [1, 1, 1]
        self.out = self.input[:, :, :, -1]


class TestSliceOp_decs_dim_6(TestSliceOp_decs_dim):
193

194
    def config(self):
195
        self.input = np.random.random([3, 4, 5, 6]).astype("float64")
196 197 198 199 200 201 202 203 204 205 206
        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):
207

H
Hongyu Liu 已提交
208 209 210
    def setUp(self):
        self.op_type = "slice"
        self.config()
211 212 213 214

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

        self.inputs = {'Input': self.input, 'StartsTensorList': starts_tensor}
H
Hongyu Liu 已提交
218 219 220
        self.outputs = {'Out': self.out}
        self.attrs = {
            'axes': self.axes,
221
            'starts': self.starts_infer,
H
Hongyu Liu 已提交
222
            'ends': self.ends,
223
            'infer_flags': self.infer_flags
H
Hongyu Liu 已提交
224 225 226
        }

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

    def test_check_output(self):
        self.check_output()

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


243 244 245
# Situation 2: starts(list, have tensor), ends(list, no tensor)
#  with attr(decrease)
class TestSliceOp_decs_dim_starts_ListTensor(OpTest):
246

H
Hongyu Liu 已提交
247 248 249
    def setUp(self):
        self.op_type = "slice"
        self.config()
250 251 252 253 254 255 256 257

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

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

H
Hongyu Liu 已提交
258 259 260
        self.outputs = {'Out': self.out}
        self.attrs = {
            'axes': self.axes,
261
            'starts': self.starts_infer,
H
Hongyu Liu 已提交
262
            'ends': self.ends,
263
            'infer_flags': self.infer_flags,
H
Hongyu Liu 已提交
264 265 266 267
            'decrease_axis': self.decrease_axis,
        }

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

    def test_check_output(self):
        self.check_output()

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


285 286
class TestSliceOp_decs_dim_5_starts_ListTensor(
        TestSliceOp_decs_dim_starts_ListTensor):
287

288
    def config(self):
289
        self.input = np.random.random([3, 4, 5, 6]).astype("float64")
290 291 292 293 294 295 296 297 298 299 300 301 302
        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):
303

H
Hongyu Liu 已提交
304 305 306
    def setUp(self):
        self.op_type = "slice"
        self.config()
307 308
        self.inputs = {
            'Input': self.input,
309
            "StartsTensor": np.array(self.starts, dtype="int32")
310
        }
H
Hongyu Liu 已提交
311 312 313
        self.outputs = {'Out': self.out}
        self.attrs = {
            'axes': self.axes,
314
            #'starts': self.starts,
H
Hongyu Liu 已提交
315
            'ends': self.ends,
316
            'infer_flags': self.infer_flags,
H
Hongyu Liu 已提交
317 318 319 320
            'decrease_axis': self.decrease_axis,
        }

    def config(self):
321
        self.input = np.random.random([3, 4, 5, 6]).astype("float64")
322 323 324 325 326 327
        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 已提交
328 329 330 331 332 333 334 335

    def test_check_output(self):
        self.check_output()

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


336 337 338
# Situation 4: starts(tensor), ends(tensor)
#  without attr(decrease)
class TestSliceOp_starts_OneTensor_ends_OneTensor(OpTest):
339

H
Hongyu Liu 已提交
340 341 342
    def setUp(self):
        self.op_type = "slice"
        self.config()
343 344 345

        self.inputs = {
            'Input': self.input,
346 347
            "StartsTensor": np.array(self.starts, dtype="int64"),
            "EndsTensor": np.array(self.ends, dtype="int32")
348
        }
H
Hongyu Liu 已提交
349 350 351
        self.outputs = {'Out': self.out}
        self.attrs = {
            'axes': self.axes,
352 353 354
            #'starts': self.starts,
            #'ends': self.ends_infer,
            'infer_flags': self.infer_flags
H
Hongyu Liu 已提交
355 356 357
        }

    def config(self):
358
        self.input = np.random.random([3, 4, 5, 6]).astype("float64")
359 360 361 362 363
        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 已提交
364 365 366 367 368 369 370 371

    def test_check_output(self):
        self.check_output()

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


372 373 374
# Situation 5: starts(tensor), ends(tensor)
#  with attr(decrease)
class TestSliceOp_decs_dim_starts_and_ends_OneTensor(OpTest):
375

376 377 378 379 380
    def setUp(self):
        self.op_type = "slice"
        self.config()
        self.inputs = {
            'Input': self.input,
381 382
            "StartsTensor": np.array(self.starts, dtype="int32"),
            "EndsTensor": np.array(self.ends, dtype="int32")
383 384 385 386 387 388 389 390 391 392
        }
        self.outputs = {'Out': self.out}
        self.attrs = {
            'axes': self.axes,
            #'starts': self.starts,
            #'ends': self.ends,
            'infer_flags': self.infer_flags,
            'decrease_axis': self.decrease_axis,
        }

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

    def test_check_output(self):
        self.check_output()

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


409 410 411
# Situation 6: starts(tensor), ends(list, have tensor)
# without attr(decrease)
class TestSliceOp_starts_OneTensor_ends_ListTensor(OpTest):
412

413 414 415 416 417 418 419 420 421 422 423
    def setUp(self):
        self.op_type = "slice"
        self.config()

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

        self.inputs = {
            'Input': self.input,
424
            "StartsTensor": np.array(self.starts, dtype="int32"),
425 426 427 428 429 430 431 432 433 434
            'EndsTensorList': ends_tensor
        }
        self.outputs = {'Out': self.out}
        self.attrs = {
            'axes': self.axes,
            #'starts': self.starts,
            'ends': self.ends_infer,
            'infer_flags': self.infer_flags
        }

W
whs 已提交
435
    def config(self):
436
        self.input = np.random.random([3, 4, 5, 6]).astype("float64")
437 438 439 440 441 442 443 444 445 446 447 448 449
        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):
        self.check_output()

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


452
# Test CUDA float16
453 454
@unittest.skipIf(not core.is_compiled_with_cuda(),
                 "core is not compiled with CUDA")
455
class TestFP16(OpTest):
456

457 458 459 460 461 462 463 464 465 466 467 468
    def setUp(self):
        self.op_type = "slice"
        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
        }

469 470 471 472 473 474 475
    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]
476
        self.infer_flags = [1, 1, 1]
477 478 479 480 481 482 483 484 485

    def test_check_output(self):
        place = core.CUDAPlace(0)
        if core.is_float16_supported(place):
            self.check_output_with_place(place, atol=1e-5)

    def test_check_grad_normal(self):
        place = core.CUDAPlace(0)
        if core.is_float16_supported(place):
486 487 488
            self.check_grad_with_place(place, ['Input'],
                                       'Out',
                                       max_relative_error=0.006)
489 490


491 492
@unittest.skipIf(not core.is_compiled_with_cuda(),
                 "core is not compiled with CUDA")
493
class TestFP16_2(OpTest):
494

495 496 497 498 499 500 501 502 503 504 505 506
    def setUp(self):
        self.op_type = "slice"
        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
        }

507 508
    def config(self):
        self.dtype = "float16"
Z
zhupengyang 已提交
509
        self.input = np.random.random([3, 4, 10]).astype(self.dtype)
510 511 512 513
        self.starts = [0]
        self.ends = [1]
        self.axes = [1]
        self.out = self.input[:, 0:1, :]
514
        self.infer_flags = [1]
515 516 517 518 519 520 521 522 523

    def test_check_output(self):
        place = core.CUDAPlace(0)
        if core.is_float16_supported(place):
            self.check_output_with_place(place, atol=1e-5)

    def test_check_grad_normal(self):
        place = core.CUDAPlace(0)
        if core.is_float16_supported(place):
524 525 526 527
            self.check_grad_with_place(place, ['Input'],
                                       'Out',
                                       max_relative_error=0.006,
                                       numeric_grad_delta=0.5)
528 529


530
class TestBF16(OpTest):
531

532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559
    def setUp(self):
        self.op_type = "slice"
        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,
            'infer_flags': self.infer_flags
        }

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


560
# Test python API
561
class TestSliceAPI(unittest.TestCase):
562

563
    def test_1(self):
564
        input = np.random.random([3, 4, 5, 6]).astype("float64")
565
        minus_1 = fluid.layers.fill_constant([1], "int32", -1)
566
        minus_3 = fluid.layers.fill_constant([1], "int64", -3)
567 568 569 570 571 572 573 574 575 576 577
        starts = fluid.layers.data(name='starts',
                                   shape=[1, 3],
                                   append_batch_size=False)
        ends = fluid.layers.data(name='ends',
                                 shape=[3],
                                 append_batch_size=False)

        x = fluid.layers.data(name="x",
                              shape=[3, 4, 5, 6],
                              append_batch_size=False,
                              dtype="float64")
578

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

582 583 584 585 586 587 588 589 590 591 592 593
        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])
594
        out_4 = paddle.slice(x, axes=[0, 1, 2], starts=starts, ends=ends)
595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618

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

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


619
class TestSliceApiWithTensor(unittest.TestCase):
620

621 622 623 624 625 626
    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]
627 628 629 630
            a_1 = paddle.slice(a,
                               axes=axes,
                               starts=paddle.to_tensor(starts, dtype='int32'),
                               ends=paddle.to_tensor(ends, dtype='int32'))
631 632
            a_2 = paddle.slice(a, axes=axes, starts=starts, ends=ends)

633
            np.testing.assert_array_equal(a_1.numpy(), a_2.numpy())
634

W
WeiXin 已提交
635 636 637 638 639 640 641 642 643 644 645 646 647 648
    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)
649
            np.testing.assert_array_equal(y_paddle.numpy(), y_np)
W
WeiXin 已提交
650

651

H
hong 已提交
652
class TestSliceApiEager(unittest.TestCase):
653

H
hong 已提交
654 655 656 657 658 659 660 661 662 663
    def test_slice_api(self):
        with paddle.fluid.dygraph.guard():
            with _test_eager_guard():
                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)

664 665 666 667
                a_2 = paddle.slice(a,
                                   axes=axes,
                                   starts=paddle.to_tensor(starts),
                                   ends=paddle.to_tensor(ends))
668
                np.testing.assert_array_equal(a_1.numpy(), a_2.numpy())
H
hong 已提交
669 670 671
                a_1.backward()
                grad_truth = paddle.zeros_like(a)
                grad_truth[-3:3, 0:2, 2:4] = 1
672
                np.testing.assert_array_equal(grad_truth, a.gradient())
H
hong 已提交
673

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


679
class TestSliceApiWithLoDTensorArray(unittest.TestCase):
680

681 682 683 684 685 686 687 688
    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

689 690
        self.place = fluid.CUDAPlace(
            0) if fluid.is_compiled_with_cuda() else fluid.CPUPlace()
691 692 693 694 695
        self.exe = fluid.Executor(self.place)

    def set_program_and_run(self, main_program, case_num):
        with fluid.program_guard(main_program):
            x = [
696 697 698
                fluid.data(name='x0', shape=self.shape, dtype="float32"),
                fluid.data(name='x1', shape=self.shape, dtype="float32"),
                fluid.data(name='x2', shape=self.shape, dtype="float32")
699 700 701 702 703 704 705 706 707 708 709 710 711 712
            ]

            for each_x in x:
                each_x.stop_gradient = False

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

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

            elif case_num == 2:
713 714
                end = fluid.layers.array_length(
                    arr) - 1  # dtype of end is int64
715
                self.sliced_arr = slice_arr = arr[self.start:end]
716 717 718
                output, _ = fluid.layers.tensor_array_to_tensor(slice_arr,
                                                                axis=self.axis,
                                                                use_stack=True)
719 720 721 722
            elif case_num == 3:
                value_int64 = fluid.layers.fill_constant([1], "int64",
                                                         2147483648)
                self.sliced_arr = slice_arr = arr[self.start:value_int64]
723 724 725
                output, _ = fluid.layers.tensor_array_to_tensor(slice_arr,
                                                                axis=self.axis,
                                                                use_stack=True)
726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744

            loss = fluid.layers.reduce_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]))
            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)

    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)
745 746 747 748
        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))
749 750 751 752 753 754 755 756

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

        self.assertTrue(
            self.sliced_arr.type == core.VarDesc.VarType.LOD_TENSOR_ARRAY)
        self.assertEqual(self.sliced_arr.shape, self.shape)
757 758 759 760 761
        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 764 765 766 767 768 769
    def test_case_3(self):
        main_program = fluid.Program()
        self.set_program_and_run(main_program, 3)

        self.assertTrue(
            self.sliced_arr.type == core.VarDesc.VarType.LOD_TENSOR_ARRAY)
        self.assertEqual(self.sliced_arr.shape, self.shape)
770 771 772 773 774 775
        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))
776

777

778
class TestImperativeVarBaseGetItem(unittest.TestCase):
779

780 781 782 783 784 785 786 787 788 789 790
    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)
            sliced = var[:, 10:, :var.shape[1]]  # var.shape[1] is 80L here
            self.assertEqual(sliced.shape, [2, 70, 80])

            sliced = var[:, var.shape[0]:, var.shape[0]:var.shape[1]]
            self.assertEqual(sliced.shape, [2, 78, 78])

    def test_getitem_with_float(self):
791

792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808
        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)
                sliced = var[:, 1.1:, :var.shape[1]]

        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)


809
class TestInferShape(unittest.TestCase):
810

811 812 813 814 815 816
    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
            pp_slice = paddle.slice(x, [
                100,
            ], [0], [1])
828
            np_slice = x_arr[:, :, 0:1]
829
            np.testing.assert_array_equal(pp_slice, np_slice)
830

831
            pp_slice = paddle.slice(x, (-100, ), [0], [1])
832
            np_slice = x_arr[0:1]
833
            np.testing.assert_array_equal(pp_slice, np_slice)
834 835 836 837 838

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

            starts = paddle.to_tensor(
839
                np.reshape(np.array([], dtype=np.int32), (0, )))
840
            ends = paddle.to_tensor(
841
                np.reshape(np.array([], dtype=np.int32), (0, )))
842 843 844 845 846 847 848 849 850 851 852 853 854

            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)

855

856 857 858
@unittest.skipIf(not core.is_compiled_with_cuda(),
                 "core is not compiled with CUDA")
class TestImperativeCUDAPinnedInput(unittest.TestCase):
859

860
    def test_input_cuda_pinned_var(self):
861
        _enable_legacy_dygraph()
862 863
        with fluid.dygraph.guard():
            data = np.random.random((2, 80, 16128)).astype('float32')
864 865 866 867 868
            var = core.VarBase(value=data,
                               name='',
                               persistable=False,
                               place=fluid.CUDAPinnedPlace(),
                               zero_copy=False)
869 870 871 872
            sliced = var[:, 10:, :var.shape[1]]
            self.assertEqual(sliced.shape, [2, 70, 80])


873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958
class TestSliceDoubleGradCheck(unittest.TestCase):

    def slice_wrapper(self, x):
        return paddle.slice(x[0],
                            axes=[0, 1, 2],
                            starts=[-3, 0, 2],
                            ends=[3, 2, 4])

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

        data = layers.data('data', [4, 5, 6], False, dtype)
        data.persistable = True
        out = paddle.slice(data,
                           axes=[0, 1, 2],
                           starts=[-3, 0, 2],
                           ends=[3, 2, 4])
        data_arr = np.random.uniform(-1, 1, data.shape).astype(dtype)

        gradient_checker.double_grad_check([data],
                                           out,
                                           x_init=[data_arr],
                                           place=place,
                                           eps=eps)
        fluid.set_flags({"FLAGS_retain_grad_for_all_tensor": True})
        gradient_checker.double_grad_check_for_dygraph(self.slice_wrapper,
                                                       [data],
                                                       out,
                                                       x_init=[data_arr],
                                                       place=place)

    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):
        return paddle.slice(x[0],
                            axes=[0, 1, 2],
                            starts=[-3, 0, 2],
                            ends=[3, 2, 4])

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

        data = layers.data('data', [4, 5, 6], False, dtype)
        data.persistable = True
        out = paddle.slice(data,
                           axes=[0, 1, 2],
                           starts=[-3, 0, 2],
                           ends=[3, 2, 4])
        data_arr = np.random.uniform(-1, 1, data.shape).astype(dtype)

        gradient_checker.triple_grad_check([data],
                                           out,
                                           x_init=[data_arr],
                                           place=place,
                                           eps=eps)
        fluid.set_flags({"FLAGS_retain_grad_for_all_tensor": True})
        gradient_checker.triple_grad_check_for_dygraph(self.slice_wrapper,
                                                       [data],
                                                       out,
                                                       x_init=[data_arr],
                                                       place=place)

    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 已提交
959
if __name__ == '__main__':
H
hong 已提交
960
    paddle.enable_static()
W
whs 已提交
961
    unittest.main()