test_strided_slice_op.py 31.3 KB
Newer Older
W
wangchaochaohu 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
# Copyright (c) 2019 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 numpy as np
W
wanghuancoder 已提交
18
from eager_op_test import OpTest
19

20
import paddle
21
from paddle import fluid
22 23

paddle.enable_static()
W
wangchaochaohu 已提交
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41


def strided_slice_native_forward(input, axes, starts, ends, strides):
    dim = input.ndim
    start = []
    end = []
    stride = []
    for i in range(dim):
        start.append(0)
        end.append(input.shape[i])
        stride.append(1)

    for i in range(len(axes)):
        start[axes[i]] = starts[i]
        end[axes[i]] = ends[i]
        stride[axes[i]] = strides[i]

    result = {
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
        1: lambda input, start, end, stride: input[
            start[0] : end[0] : stride[0]
        ],
        2: lambda input, start, end, stride: input[
            start[0] : end[0] : stride[0], start[1] : end[1] : stride[1]
        ],
        3: lambda input, start, end, stride: input[
            start[0] : end[0] : stride[0],
            start[1] : end[1] : stride[1],
            start[2] : end[2] : stride[2],
        ],
        4: lambda input, start, end, stride: input[
            start[0] : end[0] : stride[0],
            start[1] : end[1] : stride[1],
            start[2] : end[2] : stride[2],
            start[3] : end[3] : stride[3],
        ],
        5: lambda input, start, end, stride: input[
            start[0] : end[0] : stride[0],
            start[1] : end[1] : stride[1],
            start[2] : end[2] : stride[2],
            start[3] : end[3] : stride[3],
            start[4] : end[4] : stride[4],
        ],
        6: lambda input, start, end, stride: input[
            start[0] : end[0] : stride[0],
            start[1] : end[1] : stride[1],
            start[2] : end[2] : stride[2],
            start[3] : end[3] : stride[3],
            start[4] : end[4] : stride[4],
            start[5] : end[5] : stride[5],
        ],
W
wangchaochaohu 已提交
74 75 76 77 78 79 80 81 82
    }[dim](input, start, end, stride)

    return result


class TestStrideSliceOp(OpTest):
    def setUp(self):
        self.initTestCase()
        self.op_type = 'strided_slice'
83
        self.python_api = paddle.strided_slice
84 85 86
        self.output = strided_slice_native_forward(
            self.input, self.axes, self.starts, self.ends, self.strides
        )
W
wangchaochaohu 已提交
87 88 89 90 91 92 93

        self.inputs = {'Input': self.input}
        self.outputs = {'Out': self.output}
        self.attrs = {
            'axes': self.axes,
            'starts': self.starts,
            'ends': self.ends,
94
            'strides': self.strides,
95
            'infer_flags': self.infer_flags,
W
wangchaochaohu 已提交
96 97 98
        }

    def test_check_output(self):
W
wanghuancoder 已提交
99
        self.check_output()
W
wangchaochaohu 已提交
100 101

    def test_check_grad(self):
W
wanghuancoder 已提交
102
        self.check_grad({'Input'}, 'Out')
W
wangchaochaohu 已提交
103 104

    def initTestCase(self):
105
        self.input = np.random.rand(100)
W
wangchaochaohu 已提交
106 107 108 109
        self.axes = [0]
        self.starts = [-4]
        self.ends = [-3]
        self.strides = [1]
110
        self.infer_flags = [1]
W
wangchaochaohu 已提交
111 112 113 114


class TestStrideSliceOp1(TestStrideSliceOp):
    def initTestCase(self):
Z
zhupengyang 已提交
115
        self.input = np.random.rand(100)
W
wangchaochaohu 已提交
116 117 118 119
        self.axes = [0]
        self.starts = [3]
        self.ends = [8]
        self.strides = [1]
120
        self.infer_flags = [1]
W
wangchaochaohu 已提交
121 122 123 124


class TestStrideSliceOp2(TestStrideSliceOp):
    def initTestCase(self):
Z
zhupengyang 已提交
125
        self.input = np.random.rand(100)
W
wangchaochaohu 已提交
126 127 128 129
        self.axes = [0]
        self.starts = [5]
        self.ends = [0]
        self.strides = [-1]
130
        self.infer_flags = [1]
W
wangchaochaohu 已提交
131 132 133 134


class TestStrideSliceOp3(TestStrideSliceOp):
    def initTestCase(self):
Z
zhupengyang 已提交
135
        self.input = np.random.rand(100)
W
wangchaochaohu 已提交
136 137 138 139
        self.axes = [0]
        self.starts = [-1]
        self.ends = [-3]
        self.strides = [-1]
140
        self.infer_flags = [1]
W
wangchaochaohu 已提交
141 142 143 144


class TestStrideSliceOp4(TestStrideSliceOp):
    def initTestCase(self):
Z
zhupengyang 已提交
145
        self.input = np.random.rand(3, 4, 10)
W
wangchaochaohu 已提交
146 147 148 149
        self.axes = [0, 1, 2]
        self.starts = [0, -1, 0]
        self.ends = [2, -3, 5]
        self.strides = [1, -1, 1]
150
        self.infer_flags = [1, 1, 1]
W
wangchaochaohu 已提交
151 152 153 154


class TestStrideSliceOp5(TestStrideSliceOp):
    def initTestCase(self):
Z
zhupengyang 已提交
155
        self.input = np.random.rand(5, 5, 5)
W
wangchaochaohu 已提交
156 157 158 159
        self.axes = [0, 1, 2]
        self.starts = [1, 0, 0]
        self.ends = [2, 1, 3]
        self.strides = [1, 1, 1]
160
        self.infer_flags = [1, 1, 1]
W
wangchaochaohu 已提交
161 162 163 164


class TestStrideSliceOp6(TestStrideSliceOp):
    def initTestCase(self):
Z
zhupengyang 已提交
165
        self.input = np.random.rand(5, 5, 5)
W
wangchaochaohu 已提交
166 167 168 169
        self.axes = [0, 1, 2]
        self.starts = [1, -1, 0]
        self.ends = [2, -3, 3]
        self.strides = [1, -1, 1]
170
        self.infer_flags = [1, 1, 1]
W
wangchaochaohu 已提交
171 172 173 174


class TestStrideSliceOp7(TestStrideSliceOp):
    def initTestCase(self):
Z
zhupengyang 已提交
175
        self.input = np.random.rand(5, 5, 5)
W
wangchaochaohu 已提交
176 177 178 179
        self.axes = [0, 1, 2]
        self.starts = [1, 0, 0]
        self.ends = [2, 2, 3]
        self.strides = [1, 1, 1]
180
        self.infer_flags = [1, 1, 1]
W
wangchaochaohu 已提交
181 182 183 184


class TestStrideSliceOp8(TestStrideSliceOp):
    def initTestCase(self):
Z
zhupengyang 已提交
185
        self.input = np.random.rand(1, 100, 1)
W
wangchaochaohu 已提交
186 187 188 189
        self.axes = [1]
        self.starts = [1]
        self.ends = [2]
        self.strides = [1]
190
        self.infer_flags = [1]
W
wangchaochaohu 已提交
191 192 193 194


class TestStrideSliceOp9(TestStrideSliceOp):
    def initTestCase(self):
Z
zhupengyang 已提交
195
        self.input = np.random.rand(1, 100, 1)
W
wangchaochaohu 已提交
196 197 198 199
        self.axes = [1]
        self.starts = [-1]
        self.ends = [-2]
        self.strides = [-1]
200
        self.infer_flags = [1]
W
wangchaochaohu 已提交
201 202 203 204


class TestStrideSliceOp10(TestStrideSliceOp):
    def initTestCase(self):
Z
zhupengyang 已提交
205
        self.input = np.random.rand(10, 10)
W
wangchaochaohu 已提交
206 207 208 209
        self.axes = [0, 1]
        self.starts = [1, 0]
        self.ends = [2, 2]
        self.strides = [1, 1]
210
        self.infer_flags = [1, 1]
W
wangchaochaohu 已提交
211 212 213 214 215 216 217 218 219


class TestStrideSliceOp11(TestStrideSliceOp):
    def initTestCase(self):
        self.input = np.random.rand(3, 3, 3, 4)
        self.axes = [0, 1, 2, 3]
        self.starts = [1, 0, 0, 0]
        self.ends = [2, 2, 3, 4]
        self.strides = [1, 1, 1, 2]
220
        self.infer_flags = [1, 1, 1, 1]
W
wangchaochaohu 已提交
221 222 223 224 225 226 227 228 229


class TestStrideSliceOp12(TestStrideSliceOp):
    def initTestCase(self):
        self.input = np.random.rand(3, 3, 3, 4, 5)
        self.axes = [0, 1, 2, 3, 4]
        self.starts = [1, 0, 0, 0, 0]
        self.ends = [2, 2, 3, 4, 4]
        self.strides = [1, 1, 1, 1, 1]
230
        self.infer_flags = [1, 1, 1, 1]
W
wangchaochaohu 已提交
231 232 233 234 235 236 237 238 239


class TestStrideSliceOp13(TestStrideSliceOp):
    def initTestCase(self):
        self.input = np.random.rand(3, 3, 3, 6, 7, 8)
        self.axes = [0, 1, 2, 3, 4, 5]
        self.starts = [1, 0, 0, 0, 1, 2]
        self.ends = [2, 2, 3, 1, 2, 8]
        self.strides = [1, 1, 1, 1, 1, 2]
240 241 242
        self.infer_flags = [1, 1, 1, 1, 1]


243 244 245 246 247 248 249 250 251 252
class TestStrideSliceOp14(TestStrideSliceOp):
    def initTestCase(self):
        self.input = np.random.rand(4, 4, 4, 4)
        self.axes = [1, 2, 3]
        self.starts = [-5, 0, -7]
        self.ends = [-1, 2, 4]
        self.strides = [1, 1, 1]
        self.infer_flags = [1, 1, 1]


253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
class TestStrideSliceOpBool(TestStrideSliceOp):
    def test_check_grad(self):
        pass


class TestStrideSliceOpBool1D(TestStrideSliceOpBool):
    def initTestCase(self):
        self.input = np.random.rand(100).astype("bool")
        self.axes = [0]
        self.starts = [3]
        self.ends = [8]
        self.strides = [1]
        self.infer_flags = [1]


class TestStrideSliceOpBool2D(TestStrideSliceOpBool):
    def initTestCase(self):
        self.input = np.random.rand(10, 10).astype("bool")
        self.axes = [0, 1]
        self.starts = [1, 0]
        self.ends = [2, 2]
        self.strides = [1, 1]
        self.infer_flags = [1, 1]


class TestStrideSliceOpBool3D(TestStrideSliceOpBool):
    def initTestCase(self):
        self.input = np.random.rand(3, 4, 10).astype("bool")
        self.axes = [0, 1, 2]
        self.starts = [0, -1, 0]
        self.ends = [2, -3, 5]
        self.strides = [1, -1, 1]
        self.infer_flags = [1, 1, 1]


class TestStrideSliceOpBool4D(TestStrideSliceOpBool):
    def initTestCase(self):
        self.input = np.random.rand(3, 3, 3, 4).astype("bool")
        self.axes = [0, 1, 2, 3]
        self.starts = [1, 0, 0, 0]
        self.ends = [2, 2, 3, 4]
        self.strides = [1, 1, 1, 2]
        self.infer_flags = [1, 1, 1, 1]


class TestStrideSliceOpBool5D(TestStrideSliceOpBool):
    def initTestCase(self):
        self.input = np.random.rand(3, 3, 3, 4, 5).astype("bool")
        self.axes = [0, 1, 2, 3, 4]
        self.starts = [1, 0, 0, 0, 0]
        self.ends = [2, 2, 3, 4, 4]
        self.strides = [1, 1, 1, 1, 1]
        self.infer_flags = [1, 1, 1, 1]


class TestStrideSliceOpBool6D(TestStrideSliceOpBool):
    def initTestCase(self):
        self.input = np.random.rand(3, 3, 3, 6, 7, 8).astype("bool")
        self.axes = [0, 1, 2, 3, 4, 5]
        self.starts = [1, 0, 0, 0, 1, 2]
        self.ends = [2, 2, 3, 1, 2, 8]
        self.strides = [1, 1, 1, 1, 1, 2]
        self.infer_flags = [1, 1, 1, 1, 1]


318 319 320
class TestStridedSliceOp_starts_ListTensor(OpTest):
    def setUp(self):
        self.op_type = "strided_slice"
W
wanghuancoder 已提交
321
        self.python_api = paddle.strided_slice
322 323 324 325
        self.config()

        starts_tensor = []
        for index, ele in enumerate(self.starts):
326
            starts_tensor.append(
327
                ("x" + str(index), np.ones(1).astype('int32') * ele)
328
            )
329 330 331 332 333 334 335 336

        self.inputs = {'Input': self.input, 'StartsTensorList': starts_tensor}
        self.outputs = {'Out': self.output}
        self.attrs = {
            'axes': self.axes,
            'starts': self.starts_infer,
            'ends': self.ends,
            'strides': self.strides,
337
            'infer_flags': self.infer_flags,
338 339 340
        }

    def config(self):
341
        self.input = np.random.random([3, 4, 5, 6]).astype("float64")
342 343 344 345 346
        self.starts = [1, 0, 2]
        self.ends = [3, 3, 4]
        self.axes = [0, 1, 2]
        self.strides = [1, 1, 1]
        self.infer_flags = [1, -1, 1]
347 348 349
        self.output = strided_slice_native_forward(
            self.input, self.axes, self.starts, self.ends, self.strides
        )
350 351 352 353 354 355 356 357 358 359 360 361 362

        self.starts_infer = [1, 10, 2]

    def test_check_output(self):
        self.check_output()

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


class TestStridedSliceOp_ends_ListTensor(OpTest):
    def setUp(self):
        self.op_type = "strided_slice"
W
wanghuancoder 已提交
363
        self.python_api = paddle.strided_slice
364 365 366 367
        self.config()

        ends_tensor = []
        for index, ele in enumerate(self.ends):
368
            ends_tensor.append(
369
                ("x" + str(index), np.ones(1).astype('int32') * ele)
370
            )
371 372 373 374 375 376 377 378

        self.inputs = {'Input': self.input, 'EndsTensorList': ends_tensor}
        self.outputs = {'Out': self.output}
        self.attrs = {
            'axes': self.axes,
            'starts': self.starts,
            'ends': self.ends_infer,
            'strides': self.strides,
379
            'infer_flags': self.infer_flags,
380 381 382
        }

    def config(self):
383
        self.input = np.random.random([3, 4, 5, 6]).astype("float64")
384 385 386 387 388
        self.starts = [1, 0, 0]
        self.ends = [3, 3, 4]
        self.axes = [0, 1, 2]
        self.strides = [1, 1, 2]
        self.infer_flags = [1, -1, 1]
389 390 391
        self.output = strided_slice_native_forward(
            self.input, self.axes, self.starts, self.ends, self.strides
        )
392 393 394 395 396 397 398 399 400 401 402 403 404

        self.ends_infer = [3, 1, 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)


class TestStridedSliceOp_starts_Tensor(OpTest):
    def setUp(self):
        self.op_type = "strided_slice"
W
wanghuancoder 已提交
405
        self.python_api = paddle.strided_slice
406 407 408
        self.config()
        self.inputs = {
            'Input': self.input,
409
            "StartsTensor": np.array(self.starts, dtype="int32"),
410 411 412 413
        }
        self.outputs = {'Out': self.output}
        self.attrs = {
            'axes': self.axes,
414
            # 'starts': self.starts,
415 416 417 418 419 420
            'ends': self.ends,
            'strides': self.strides,
            'infer_flags': self.infer_flags,
        }

    def config(self):
421
        self.input = np.random.random([3, 4, 5, 6]).astype("float64")
422 423 424 425 426
        self.starts = [1, 0, 2]
        self.ends = [2, 3, 4]
        self.axes = [0, 1, 2]
        self.strides = [1, 1, 1]
        self.infer_flags = [-1, -1, -1]
427 428 429
        self.output = strided_slice_native_forward(
            self.input, self.axes, self.starts, self.ends, self.strides
        )
430 431 432 433 434 435 436 437 438 439 440

    def test_check_output(self):
        self.check_output()

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


class TestStridedSliceOp_ends_Tensor(OpTest):
    def setUp(self):
        self.op_type = "strided_slice"
W
wanghuancoder 已提交
441
        self.python_api = paddle.strided_slice
442 443 444
        self.config()
        self.inputs = {
            'Input': self.input,
445
            "EndsTensor": np.array(self.ends, dtype="int32"),
446 447 448 449 450
        }
        self.outputs = {'Out': self.output}
        self.attrs = {
            'axes': self.axes,
            'starts': self.starts,
451
            # 'ends': self.ends,
452 453 454 455 456
            'strides': self.strides,
            'infer_flags': self.infer_flags,
        }

    def config(self):
457
        self.input = np.random.random([3, 4, 5, 6]).astype("float64")
458 459 460 461 462
        self.starts = [1, 0, 2]
        self.ends = [2, 3, 4]
        self.axes = [0, 1, 2]
        self.strides = [1, 1, 1]
        self.infer_flags = [-1, -1, -1]
463 464 465
        self.output = strided_slice_native_forward(
            self.input, self.axes, self.starts, self.ends, self.strides
        )
466 467 468 469 470 471 472 473 474 475 476 477 478

    def test_check_output(self):
        self.check_output()

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


class TestStridedSliceOp_listTensor_Tensor(OpTest):
    def setUp(self):
        self.config()
        ends_tensor = []
        for index, ele in enumerate(self.ends):
479
            ends_tensor.append(
480
                ("x" + str(index), np.ones(1).astype('int32') * ele)
481
            )
482
        self.op_type = "strided_slice"
W
wanghuancoder 已提交
483
        self.python_api = paddle.strided_slice
484 485 486

        self.inputs = {
            'Input': self.input,
487
            "StartsTensor": np.array(self.starts, dtype="int32"),
488
            "EndsTensorList": ends_tensor,
489 490 491 492
        }
        self.outputs = {'Out': self.output}
        self.attrs = {
            'axes': self.axes,
493 494
            # 'starts': self.starts,
            # 'ends': self.ends,
495 496 497 498 499
            'strides': self.strides,
            'infer_flags': self.infer_flags,
        }

    def config(self):
500
        self.input = np.random.random([3, 4, 5, 6]).astype("float64")
501 502 503 504 505
        self.starts = [1, 0, 2]
        self.ends = [2, 3, 4]
        self.axes = [0, 1, 2]
        self.strides = [1, 1, 1]
        self.infer_flags = [-1, -1, -1]
506 507 508
        self.output = strided_slice_native_forward(
            self.input, self.axes, self.starts, self.ends, self.strides
        )
509 510 511 512 513 514 515 516 517 518 519

    def test_check_output(self):
        self.check_output()

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


class TestStridedSliceOp_strides_Tensor(OpTest):
    def setUp(self):
        self.op_type = "strided_slice"
W
wanghuancoder 已提交
520
        self.python_api = paddle.strided_slice
521 522 523
        self.config()
        self.inputs = {
            'Input': self.input,
524
            "StridesTensor": np.array(self.strides, dtype="int32"),
525 526 527 528 529 530
        }
        self.outputs = {'Out': self.output}
        self.attrs = {
            'axes': self.axes,
            'starts': self.starts,
            'ends': self.ends,
531
            # 'strides': self.strides,
532 533 534 535
            'infer_flags': self.infer_flags,
        }

    def config(self):
536
        self.input = np.random.random([3, 4, 5, 6]).astype("float64")
537 538 539 540 541
        self.starts = [1, -1, 2]
        self.ends = [2, 0, 4]
        self.axes = [0, 1, 2]
        self.strides = [1, -1, 1]
        self.infer_flags = [-1, -1, -1]
542 543 544
        self.output = strided_slice_native_forward(
            self.input, self.axes, self.starts, self.ends, self.strides
        )
545 546 547 548 549 550 551 552 553

    def test_check_output(self):
        self.check_output()

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


# Test python API
554
class TestStridedSliceAPI(unittest.TestCase):
555
    def test_1(self):
556
        input = np.random.random([3, 4, 5, 6]).astype("float64")
557 558
        minus_1 = paddle.tensor.fill_constant([1], "int32", -1)
        minus_3 = paddle.tensor.fill_constant([1], "int32", -3)
G
GGBond8488 已提交
559
        starts = paddle.static.data(name='starts', shape=[3], dtype='int32')
W
wanghuancoder 已提交
560
        ends = paddle.static.data(name='ends', shape=[3], dtype='int64')
G
GGBond8488 已提交
561
        strides = paddle.static.data(name='strides', shape=[3], dtype='int32')
562

G
GGBond8488 已提交
563
        x = paddle.static.data(
564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591
            name="x",
            shape=[3, 4, 5, 6],
            dtype="float64",
        )
        out_1 = paddle.strided_slice(
            x,
            axes=[0, 1, 2],
            starts=[-3, 0, 2],
            ends=[3, 100, -1],
            strides=[1, 1, 1],
        )
        out_2 = paddle.strided_slice(
            x,
            axes=[0, 1, 3],
            starts=[minus_3, 0, 2],
            ends=[3, 100, -1],
            strides=[1, 1, 1],
        )
        out_3 = paddle.strided_slice(
            x,
            axes=[0, 1, 3],
            starts=[minus_3, 0, 2],
            ends=[3, 100, minus_1],
            strides=[1, 1, 1],
        )
        out_4 = paddle.strided_slice(
            x, axes=[0, 1, 2], starts=starts, ends=ends, strides=strides
        )
592

593 594 595
        out_5 = x[-3:3, 0:100:2, -1:2:-1]
        out_6 = x[minus_3:3:1, 0:100:2, :, minus_1:2:minus_1]
        out_7 = x[minus_1, 0:100:2, :, -1:2:-1]
596 597 598 599 600 601 602

        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"),
603
                'ends': np.array([3, 2147483648, -1]).astype("int64"),
604
                'strides': np.array([1, 1, 1]).astype("int32"),
605
            },
606 607
            fetch_list=[out_1, out_2, out_3, out_4, out_5, out_6, out_7],
        )
608 609 610 611
        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, :])
612 613 614
        assert np.array_equal(res_5, input[-3:3, 0:100:2, -1:2:-1, :])
        assert np.array_equal(res_6, input[-3:3, 0:100:2, :, -1:2:-1])
        assert np.array_equal(res_7, input[-1, 0:100:2, :, -1:2:-1])
W
wangchaochaohu 已提交
615

616 617 618 619 620 621
    def test_dygraph_op(self):
        x = paddle.zeros(shape=[3, 4, 5, 6], dtype="float32")
        axes = [1, 2, 3]
        starts = [-3, 0, 2]
        ends = [3, 2, 4]
        strides_1 = [1, 1, 1]
622 623 624
        sliced_1 = paddle.strided_slice(
            x, axes=axes, starts=starts, ends=ends, strides=strides_1
        )
625 626
        assert sliced_1.shape == (3, 2, 2, 2)

627 628 629 630
    @unittest.skipIf(
        not paddle.is_compiled_with_cuda(),
        "Cannot use CUDAPinnedPlace in CPU only version",
    )
631 632
    def test_cuda_pinned_place(self):
        with paddle.fluid.dygraph.guard():
633 634 635
            x = paddle.to_tensor(
                np.random.randn(2, 10), place=paddle.CUDAPinnedPlace()
            )
636 637
            self.assertTrue(x.place.is_cuda_pinned_place())
            y = x[:, ::2]
638
            self.assertFalse(x.place.is_cuda_pinned_place())
639 640
            self.assertFalse(y.place.is_cuda_pinned_place())

W
wangchaochaohu 已提交
641

642 643
class ArrayLayer(paddle.nn.Layer):
    def __init__(self, input_size=224, output_size=10, array_size=1):
644
        super().__init__()
645 646 647 648
        self.input_size = input_size
        self.output_size = output_size
        self.array_size = array_size
        for i in range(self.array_size):
649 650 651 652 653
            setattr(
                self,
                self.create_name(i),
                paddle.nn.Linear(input_size, output_size),
            )
654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721

    def create_name(self, index):
        return 'linear_' + str(index)

    def forward(self, inps):
        array = []
        for i in range(self.array_size):
            linear = getattr(self, self.create_name(i))
            array.append(linear(inps))

        tensor_array = self.create_tensor_array(array)

        tensor_array = self.array_slice(tensor_array)

        array1 = paddle.concat(tensor_array)
        array2 = paddle.concat(tensor_array[::-1])
        return array1 + array2 * array2

    def get_all_grads(self, param_name='weight'):
        grads = []
        for i in range(self.array_size):
            linear = getattr(self, self.create_name(i))
            param = getattr(linear, param_name)

            g = param.grad
            if g is not None:
                g = g.numpy()

            grads.append(g)

        return grads

    def clear_all_grad(self):
        param_names = ['weight', 'bias']
        for i in range(self.array_size):
            linear = getattr(self, self.create_name(i))
            for p in param_names:
                param = getattr(linear, p)
                param.clear_gradient()

    def array_slice(self, array):
        return array

    def create_tensor_array(self, tensors):
        tensor_array = None
        for i, tensor in enumerate(tensors):
            index = paddle.full(shape=[1], dtype='int64', fill_value=i)
            if tensor_array is None:
                tensor_array = paddle.tensor.array_write(tensor, i=index)
            else:
                paddle.tensor.array_write(tensor, i=index, array=tensor_array)
        return tensor_array


class TestStridedSliceTensorArray(unittest.TestCase):
    def setUp(self):
        paddle.disable_static()

    def grad_equal(self, g1, g2):
        if g1 is None:
            g1 = np.zeros_like(g2)
        if g2 is None:
            g2 = np.zeros_like(g1)
        return np.array_equal(g1, g2)

    def is_grads_equal(self, g1, g2):
        for i, g in enumerate(g1):

722 723 724 725
            self.assertTrue(
                self.grad_equal(g, g2[i]),
                msg="gradient_1:\n{} \ngradient_2:\n{}".format(g, g2),
            )
726 727 728 729 730

    def is_grads_equal_zeros(self, grads):
        for g in grads:
            self.assertTrue(
                self.grad_equal(np.zeros_like(g), g),
731 732
                msg="The gradient should be zeros, but received \n{}".format(g),
            )
733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751

    def create_case(self, net):
        inps1 = paddle.randn([1, net.input_size], dtype='float32')
        inps2 = inps1.detach().clone()
        l1 = net(inps1)
        s1 = l1.numpy()
        l1.sum().backward()
        grads_dy = net.get_all_grads()
        net.clear_all_grad()
        grads_zeros = net.get_all_grads()

        self.is_grads_equal_zeros(grads_zeros)

        func = paddle.jit.to_static(net.forward)
        l2 = func(inps2)
        s2 = l2.numpy()
        l2.sum().backward()
        grads_static = net.get_all_grads()
        net.clear_all_grad()
752
        # compare result of dygraph and static
753
        self.is_grads_equal(grads_static, grads_dy)
754 755 756
        np.testing.assert_array_equal(
            s1,
            s2,
757 758 759 760
            err_msg='dygraph graph result:\n{} \nstatic dygraph result:\n{}'.format(
                l1.numpy(), l2.numpy()
            ),
        )
761 762 763 764 765 766 767

    def test_strided_slice_tensor_array_cuda_pinned_place(self):
        if paddle.device.is_compiled_with_cuda():
            with paddle.fluid.dygraph.guard():

                class Simple(paddle.nn.Layer):
                    def __init__(self):
768
                        super().__init__()
769 770 771 772

                    def forward(self, inps):
                        tensor_array = None
                        for i, tensor in enumerate(inps):
773 774 775
                            index = paddle.full(
                                shape=[1], dtype='int64', fill_value=i
                            )
776 777
                            if tensor_array is None:
                                tensor_array = paddle.tensor.array_write(
778 779
                                    tensor, i=index
                                )
780
                            else:
781 782 783
                                paddle.tensor.array_write(
                                    tensor, i=index, array=tensor_array
                                )
784 785 786 787 788 789 790 791

                        array1 = paddle.concat(tensor_array)
                        array2 = paddle.concat(tensor_array[::-1])
                        return array1 + array2 * array2

                net = Simple()
                func = paddle.jit.to_static(net.forward)

792 793 794 795 796 797 798 799 800 801
                inps1 = paddle.to_tensor(
                    np.random.randn(2, 10),
                    place=paddle.CUDAPinnedPlace(),
                    stop_gradient=False,
                )
                inps2 = paddle.to_tensor(
                    np.random.randn(2, 10),
                    place=paddle.CUDAPinnedPlace(),
                    stop_gradient=False,
                )
802 803 804 805 806 807 808 809 810

                self.assertTrue(inps1.place.is_cuda_pinned_place())
                self.assertTrue(inps2.place.is_cuda_pinned_place())

                result = func([inps1, inps2])

                self.assertFalse(result.place.is_cuda_pinned_place())

    def test_strided_slice_tensor_array(self):
811
        class Net01(ArrayLayer):
812 813 814
            def array_slice(self, tensors):
                return tensors[::-1]

815
        self.create_case(Net01(array_size=10))
816

817
        class Net02(ArrayLayer):
818 819 820
            def array_slice(self, tensors):
                return tensors[::-2]

821
        self.create_case(Net02(input_size=112, array_size=11))
822

823
        class Net03(ArrayLayer):
824 825 826
            def array_slice(self, tensors):
                return tensors[::-3]

827
        self.create_case(Net03(input_size=112, array_size=9))
828

829
        class Net04(ArrayLayer):
830 831 832
            def array_slice(self, tensors):
                return tensors[1::-4]

833
        self.create_case(Net04(input_size=112, array_size=9))
834

835
        class Net05(ArrayLayer):
836 837 838
            def array_slice(self, tensors):
                return tensors[:7:-4]

839
        self.create_case(Net05(input_size=112, array_size=9))
840

841
        class Net06(ArrayLayer):
842 843 844
            def array_slice(self, tensors):
                return tensors[8:0:-4]

845
        self.create_case(Net06(input_size=112, array_size=9))
846

847
        class Net07(ArrayLayer):
848 849 850
            def array_slice(self, tensors):
                return tensors[8:1:-4]

851
        self.create_case(Net07(input_size=112, array_size=9))
852

853
        class Net08(ArrayLayer):
854 855 856
            def array_slice(self, tensors):
                return tensors[::2]

857
        self.create_case(Net08(input_size=112, array_size=11))
858

859
        class Net09(ArrayLayer):
860 861 862
            def array_slice(self, tensors):
                return tensors[::3]

863
        self.create_case(Net09(input_size=112, array_size=9))
864

865
        class Net10(ArrayLayer):
866 867 868
            def array_slice(self, tensors):
                return tensors[1::4]

869
        self.create_case(Net10(input_size=112, array_size=9))
870

871
        class Net11(ArrayLayer):
872 873 874
            def array_slice(self, tensors):
                return tensors[:8:4]

875
        self.create_case(Net11(input_size=112, array_size=9))
876

877
        class Net12(ArrayLayer):
878 879 880
            def array_slice(self, tensors):
                return tensors[1:8:4]

881
        self.create_case(Net12(input_size=112, array_size=9))
882

883
        class Net13(ArrayLayer):
884 885 886
            def array_slice(self, tensors):
                return tensors[8:10:4]

887
        self.create_case(Net13(input_size=112, array_size=13))
888

889
        class Net14(ArrayLayer):
890 891 892
            def array_slice(self, tensors):
                return tensors[3:10:4]

893
        self.create_case(Net14(input_size=112, array_size=13))
894

895
        class Net15(ArrayLayer):
896 897 898
            def array_slice(self, tensors):
                return tensors[2:10:4]

899
        self.create_case(Net15(input_size=112, array_size=13))
900

901
        class Net16(ArrayLayer):
902 903 904
            def array_slice(self, tensors):
                return tensors[3:10:3]

905
        self.create_case(Net16(input_size=112, array_size=13))
906

907
        class Net17(ArrayLayer):
908 909 910
            def array_slice(self, tensors):
                return tensors[3:15:3]

911
        self.create_case(Net17(input_size=112, array_size=13))
912

913
        class Net18(ArrayLayer):
914 915 916
            def array_slice(self, tensors):
                return tensors[0:15:3]

917
        self.create_case(Net18(input_size=112, array_size=13))
918

919
        class Net19(ArrayLayer):
920 921 922
            def array_slice(self, tensors):
                return tensors[-1:-5:-3]

923
        self.create_case(Net19(input_size=112, array_size=13))
924

925
        class Net20(ArrayLayer):
926 927 928
            def array_slice(self, tensors):
                return tensors[-1:-6:-3]

929
        self.create_case(Net20(input_size=112, array_size=13))
930

931
        class Net21(ArrayLayer):
932 933 934
            def array_slice(self, tensors):
                return tensors[-3:-6:-3]

935
        self.create_case(Net21(input_size=112, array_size=13))
936

937
        class Net22(ArrayLayer):
938 939 940
            def array_slice(self, tensors):
                return tensors[-5:-1:3]

941
        self.create_case(Net22(input_size=112, array_size=13))
942

943
        class Net23(ArrayLayer):
944 945 946
            def array_slice(self, tensors):
                return tensors[-6:-1:3]

947
        self.create_case(Net23(input_size=112, array_size=13))
948

949
        class Net24(ArrayLayer):
950 951 952
            def array_slice(self, tensors):
                return tensors[-6:-3:3]

953
        self.create_case(Net24(input_size=112, array_size=13))
954

955
        class Net25(ArrayLayer):
956 957 958
            def array_slice(self, tensors):
                return tensors[0::3]

959
        self.create_case(Net25(input_size=112, array_size=13))
960

961
        class Net26(ArrayLayer):
962 963 964
            def array_slice(self, tensors):
                return tensors[-60:20:3]

965
        self.create_case(Net26(input_size=112, array_size=13))
966

967
        class Net27(ArrayLayer):
968 969 970
            def array_slice(self, tensors):
                return tensors[-3:-60:-3]

971
        self.create_case(Net27(input_size=112, array_size=13))
972 973


974 975 976
@unittest.skipIf(
    not fluid.core.is_compiled_with_cuda(), "core is not compiled with CUDA"
)
977 978 979
class TestStridedSliceFloat16(unittest.TestCase):
    def init_test_case(self):
        self.op_type = 'strided_slice'
W
wanghuancoder 已提交
980
        self.python_api = paddle.strided_slice
981 982 983 984 985 986 987 988 989 990 991 992
        self.input_shape = [3, 3, 3, 6, 7, 8]
        self.axes = [0, 1, 2, 3, 4, 5]
        self.starts = [1, 0, 0, 0, 1, 2]
        self.ends = [2, 2, 3, 1, 2, 8]
        self.strides = [1, 1, 1, 1, 1, 2]
        self.infer_flags = [1, 1, 1, 1, 1]

    def check_main(self, x_np, dtype):
        paddle.disable_static()
        x_np = x_np.astype(dtype)
        x = paddle.to_tensor(x_np)
        x.stop_gradient = False
993 994 995
        output = strided_slice_native_forward(
            x, self.axes, self.starts, self.ends, self.strides
        )
996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013
        x_grad = paddle.grad(output, x)
        output_np = output[0].numpy().astype('float32')
        x_grad_np = x_grad[0].numpy().astype('float32')
        paddle.enable_static()
        return output_np, x_grad_np

    def test_check(self):
        self.init_test_case()
        x_np = np.random.random(self.input_shape).astype("float16")

        output_np_fp16, x_grad_np_fp16 = self.check_main(x_np, 'float16')
        output_np_fp32, x_grad_np_fp32 = self.check_main(x_np, 'float32')

        np.testing.assert_allclose(output_np_fp16, output_np_fp32)

        np.testing.assert_allclose(x_grad_np_fp16, x_grad_np_fp32)


W
wangchaochaohu 已提交
1014 1015
if __name__ == "__main__":
    unittest.main()