test_slice_op.py 16.6 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
21
import paddle.fluid as fluid
W
whs 已提交
22 23


24 25
# Situation 1: starts(list, no tensor), ends(list, no tensor)
# 1.1 without attr(decrease)
W
whs 已提交
26 27 28 29 30 31 32 33 34
class TestSliceOp(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,
35 36
            'ends': self.ends,
            'infer_flags': self.infer_flags
W
whs 已提交
37 38 39
        }

    def config(self):
40
        self.input = np.random.random([3, 4, 5, 6]).astype("float64")
W
whs 已提交
41 42 43
        self.starts = [1, 0, 2]
        self.ends = [3, 3, 4]
        self.axes = [0, 1, 2]
44
        self.infer_flags = [1, 1, 1]
W
whs 已提交
45 46 47 48 49
        self.out = self.input[1:3, 0:3, 2:4, :]

    def test_check_output(self):
        self.check_output()

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

W
whs 已提交
53

54 55
class TestCase1(TestSliceOp):
    def config(self):
56
        self.input = np.random.random([3, 4, 5, 6]).astype("float64")
57 58 59 60 61 62 63 64 65
        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):
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, 3]
        self.infer_flags = [1, 1, 1]
        self.out = self.input[-3:3, 0:100, :, 2:-1]


# 1.2 with attr(decrease)
H
Hongyu Liu 已提交
75 76 77 78 79 80 81 82 83 84
class TestSliceOp_decs_dim(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,
85
            'infer_flags': self.infer_flags,
H
Hongyu Liu 已提交
86 87 88 89
            'decrease_axis': self.decrease_axis,
        }

    def config(self):
90
        self.input = np.random.random([3, 4, 5, 6]).astype("float64")
H
Hongyu Liu 已提交
91 92 93 94
        self.starts = [1, 0, 2]
        self.ends = [2, 3, 4]
        self.axes = [0, 1, 2]
        self.decrease_axis = [0]
95
        self.infer_flags = [1, 1, 1]
H
Hongyu Liu 已提交
96 97 98 99 100 101 102 103 104
        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)


105 106
class TestSliceOp_decs_dim_2(TestSliceOp_decs_dim):
    def config(self):
107
        self.input = np.random.random([3, 4, 5, 6]).astype("float64")
108 109 110 111 112 113 114 115 116 117
        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):
118
        self.input = np.random.random([3, 4, 5, 6]).astype("float64")
119 120 121 122 123 124 125 126 127 128
        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):
129
        self.input = np.random.random([3, 4, 5, 7]).astype("float64")
130 131 132 133 134 135 136 137 138 139
        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):
140
        self.input = np.random.random([3, 4, 5, 6]).astype("float64")
141 142 143 144 145 146 147 148 149 150
        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):
    def config(self):
151
        self.input = np.random.random([3, 4, 5, 6]).astype("float64")
152 153 154 155 156 157 158 159 160 161 162
        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 已提交
163 164 165
    def setUp(self):
        self.op_type = "slice"
        self.config()
166 167 168 169 170 171 172

        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 已提交
173 174 175
        self.outputs = {'Out': self.out}
        self.attrs = {
            'axes': self.axes,
176
            'starts': self.starts_infer,
H
Hongyu Liu 已提交
177
            'ends': self.ends,
178
            'infer_flags': self.infer_flags
H
Hongyu Liu 已提交
179 180 181
        }

    def config(self):
182
        self.input = np.random.random([3, 4, 5, 6]).astype("float64")
H
Hongyu Liu 已提交
183
        self.starts = [1, 0, 2]
184
        self.ends = [3, 3, 4]
H
Hongyu Liu 已提交
185
        self.axes = [0, 1, 2]
186 187 188 189
        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 已提交
190 191 192 193 194 195 196 197

    def test_check_output(self):
        self.check_output()

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


198 199 200
# Situation 2: starts(list, have tensor), ends(list, no tensor)
#  with attr(decrease)
class TestSliceOp_decs_dim_starts_ListTensor(OpTest):
H
Hongyu Liu 已提交
201 202 203
    def setUp(self):
        self.op_type = "slice"
        self.config()
204 205 206 207 208 209 210 211

        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 已提交
212 213 214
        self.outputs = {'Out': self.out}
        self.attrs = {
            'axes': self.axes,
215
            'starts': self.starts_infer,
H
Hongyu Liu 已提交
216
            'ends': self.ends,
217
            'infer_flags': self.infer_flags,
H
Hongyu Liu 已提交
218 219 220 221
            'decrease_axis': self.decrease_axis,
        }

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

    def test_check_output(self):
        self.check_output()

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


239 240 241
class TestSliceOp_decs_dim_5_starts_ListTensor(
        TestSliceOp_decs_dim_starts_ListTensor):
    def config(self):
242
        self.input = np.random.random([3, 4, 5, 6]).astype("float64")
243 244 245 246 247 248 249 250 251 252 253 254 255
        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 已提交
256 257 258
    def setUp(self):
        self.op_type = "slice"
        self.config()
259 260 261 262 263
        self.inputs = {
            'Input': self.input,
            "StartsTensor": np.array(
                self.starts, dtype="int32")
        }
H
Hongyu Liu 已提交
264 265 266
        self.outputs = {'Out': self.out}
        self.attrs = {
            'axes': self.axes,
267
            #'starts': self.starts,
H
Hongyu Liu 已提交
268
            'ends': self.ends,
269
            'infer_flags': self.infer_flags,
H
Hongyu Liu 已提交
270 271 272 273
            'decrease_axis': self.decrease_axis,
        }

    def config(self):
274
        self.input = np.random.random([3, 4, 5, 6]).astype("float64")
275 276 277 278 279 280
        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 已提交
281 282 283 284 285 286 287 288

    def test_check_output(self):
        self.check_output()

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


289 290 291
# Situation 4: starts(tensor), ends(tensor)
#  without attr(decrease)
class TestSliceOp_starts_OneTensor_ends_OneTensor(OpTest):
H
Hongyu Liu 已提交
292 293 294
    def setUp(self):
        self.op_type = "slice"
        self.config()
295 296 297 298 299 300 301 302

        self.inputs = {
            'Input': self.input,
            "StartsTensor": np.array(
                self.starts, dtype="int32"),
            "EndsTensor": np.array(
                self.ends, dtype="int32")
        }
H
Hongyu Liu 已提交
303 304 305
        self.outputs = {'Out': self.out}
        self.attrs = {
            'axes': self.axes,
306 307 308
            #'starts': self.starts,
            #'ends': self.ends_infer,
            'infer_flags': self.infer_flags
H
Hongyu Liu 已提交
309 310 311
        }

    def config(self):
312
        self.input = np.random.random([3, 4, 5, 6]).astype("float64")
313 314 315 316 317
        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 已提交
318 319 320 321 322 323 324 325

    def test_check_output(self):
        self.check_output()

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


326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347
# 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"
        self.config()
        self.inputs = {
            'Input': self.input,
            "StartsTensor": np.array(
                self.starts, dtype="int32"),
            "EndsTensor": np.array(
                self.ends, dtype="int32")
        }
        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 已提交
348
    def config(self):
349
        self.input = np.random.random([3, 4, 5, 6]).astype("float64")
350 351
        self.starts = [1, 0, 2]
        self.ends = [2, 1, 4]
W
whs 已提交
352
        self.axes = [0, 1, 2]
353 354 355 356 357 358 359 360 361
        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 已提交
362 363


364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389
# 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"
        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,
            "StartsTensor": np.array(
                self.starts, dtype="int32"),
            '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 已提交
390
    def config(self):
391
        self.input = np.random.random([3, 4, 5, 6]).astype("float64")
392 393 394 395 396 397 398 399 400 401 402 403 404
        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 已提交
405 406


407
# Test CUDA float16
408 409
@unittest.skipIf(not core.is_compiled_with_cuda(),
                 "core is not compiled with CUDA")
410 411 412 413 414 415 416 417 418 419 420 421 422
class TestFP16(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
        }

423 424 425 426 427 428 429
    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]
430
        self.infer_flags = [1, 1, 1]
431 432 433 434 435 436 437 438 439 440 441 442 443

    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):
            self.check_grad_with_place(
                place, ['Input'], 'Out', max_relative_error=0.006)


444 445
@unittest.skipIf(not core.is_compiled_with_cuda(),
                 "core is not compiled with CUDA")
446 447 448 449 450 451 452 453 454 455 456 457 458
class TestFP16_2(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
        }

459 460 461 462 463 464 465
    def config(self):
        self.dtype = "float16"
        self.input = np.random.random([3, 4, 5]).astype(self.dtype)
        self.starts = [0]
        self.ends = [1]
        self.axes = [1]
        self.out = self.input[:, 0:1, :]
466
        self.infer_flags = [1]
467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482

    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):
            self.check_grad_with_place(
                place, ['Input'],
                'Out',
                max_relative_error=0.006,
                numeric_grad_delta=0.5)


483
# Test python API
484
class TestSliceAPI(unittest.TestCase):
485
    def test_1(self):
486
        input = np.random.random([3, 4, 5, 6]).astype("float64")
487 488 489 490 491 492 493 494 495 496 497
        minus_1 = fluid.layers.fill_constant([1], "int32", -1)
        minus_3 = fluid.layers.fill_constant([1], "int32", -3)
        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,
498
            dtype="float64")
499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530

        out_1 = fluid.layers.slice(
            x, axes=[0, 1, 2], starts=[-3, 0, 2], ends=[3, 100, -1])
        out_2 = fluid.layers.slice(
            x, axes=[0, 1, 3], starts=[minus_3, 0, 2], ends=[3, 100, -1])
        out_3 = fluid.layers.slice(
            x, axes=[0, 1, 3], starts=[minus_3, 0, 2], ends=[3, 100, minus_1])
        out_4 = fluid.layers.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])

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


W
whs 已提交
531 532
if __name__ == '__main__':
    unittest.main()