test_split_op.py 24.6 KB
Newer Older
1
#   Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
D
dzhwinter 已提交
2
#
D
dzhwinter 已提交
3 4 5
# 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
D
dzhwinter 已提交
6
#
D
dzhwinter 已提交
7
#     http://www.apache.org/licenses/LICENSE-2.0
D
dzhwinter 已提交
8
#
D
dzhwinter 已提交
9 10 11 12 13 14
# 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.

Y
Yancey 已提交
15
import unittest
16

Y
Yancey 已提交
17
import numpy as np
18
from eager_op_test import OpTest, convert_float_to_uint16
19 20

import paddle
21
import paddle.fluid as fluid
22
from paddle.fluid import Program, core, program_guard
Y
Yancey 已提交
23 24 25 26


class TestSplitOp(OpTest):
    def setUp(self):
27 28
        self.python_api = paddle.split
        self.python_out_sig = ['out0', 'out1', 'out2']
T
fix ut  
typhoonzero 已提交
29
        self._set_op_type()
30
        self.dtype = self.get_dtype()
Y
Yancey1989 已提交
31
        axis = 1
32 33 34 35
        if self.dtype == np.uint16:
            x = np.random.random((4, 5, 6)).astype(np.float32)
            out = np.split(x, [2, 3], axis)
            self.inputs = {'X': convert_float_to_uint16(x)}
36 37 38 39 40 41
            self.outputs = {
                'Out': [
                    ('out%d' % i, convert_float_to_uint16(out[i]))
                    for i in range(len(out))
                ]
            }
42 43 44 45
        else:
            x = np.random.random((4, 5, 6)).astype(self.dtype)
            out = np.split(x, [2, 3], axis)
            self.inputs = {'X': x}
46 47 48
            self.outputs = {
                'Out': [('out%d' % i, out[i]) for i in range(len(out))]
            }
Y
Yancey1989 已提交
49
        self.attrs = {'axis': axis, 'sections': [2, 1, 2]}
Y
Yancey 已提交
50

51
    def get_dtype(self):
52
        return "float64"
53

T
typhoonzero 已提交
54 55 56
    def _set_op_type(self):
        self.op_type = "split"

Y
Yancey 已提交
57 58 59
    def test_check_output(self):
        self.check_output()

Y
Yancey1989 已提交
60 61
    def test_check_grad(self):
        self.check_grad(['X'], ['out0', 'out1', 'out2'])
Y
Yancey 已提交
62 63


64 65 66
# test with attr(num)
class TestSplitOp_2(OpTest):
    def setUp(self):
67 68
        self.python_api = paddle.split
        self.python_out_sig = ['out0', 'out1', 'out2']
69 70 71 72 73 74 75
        self._set_op_type()
        self.dtype = self.get_dtype()
        self.init_data()
        self.inputs = {'X': self.x}
        self.attrs = {
            'axis': self.axis,
            'sections': self.sections,
76
            'num': self.num,
77 78 79
        }

        out = np.split(self.x, self.indices_or_sections, self.axis)
80
        self.outputs = {'Out': [('out%d' % i, out[i]) for i in range(len(out))]}
81 82 83 84 85 86 87 88 89

    def init_data(self):
        self.x = np.random.random((4, 5, 6)).astype(self.dtype)
        self.axis = 2
        self.sections = []
        self.num = 3
        self.indices_or_sections = 3

    def get_dtype(self):
90
        return "float64"
91 92 93 94 95 96 97 98 99 100 101 102 103 104

    def _set_op_type(self):
        self.op_type = "split"

    def test_check_output(self):
        self.check_output()

    def test_check_grad(self):
        self.check_grad(['X'], ['out0', 'out1', 'out2'])


# attr(axis) is Tensor
class TestSplitOp_AxisTensor(OpTest):
    def setUp(self):
105 106
        self.python_api = paddle.split
        self.python_out_sig = ['out0', 'out1', 'out2']
107 108 109 110 111
        self._set_op_type()
        self.dtype = self.get_dtype()
        self.init_data()
        self.inputs = {
            'X': self.x,
112
            'AxisTensor': np.array([self.axis]).astype("int32"),
113 114 115 116
        }
        self.attrs = {'sections': self.sections, 'num': self.num}

        out = np.split(self.x, self.indices_or_sections, self.axis)
117
        self.outputs = {'Out': [('out%d' % i, out[i]) for i in range(len(out))]}
118 119 120 121 122 123 124 125 126

    def init_data(self):
        self.x = np.random.random((4, 5, 6)).astype(self.dtype)
        self.axis = 2
        self.sections = []
        self.num = 3
        self.indices_or_sections = 3

    def get_dtype(self):
127
        return "float64"
128 129 130 131 132 133 134 135 136 137 138 139 140 141

    def _set_op_type(self):
        self.op_type = "split"

    def test_check_output(self):
        self.check_output()

    def test_check_grad(self):
        self.check_grad(['X'], ['out0', 'out1', 'out2'])


# attr(sections) is list containing Tensor
class TestSplitOp_SectionsTensor(OpTest):
    def setUp(self):
142 143
        self.python_api = paddle.split
        self.python_out_sig = ['out0', 'out1', 'out2']
144 145 146 147 148 149 150
        self._set_op_type()
        self.dtype = self.get_dtype()
        self.init_data()
        self.inputs = {'X': self.x}

        sections_tensor = []
        for index, ele in enumerate(self.sections):
151 152 153
            sections_tensor.append(
                ("x" + str(index), np.ones((1)).astype('int32') * ele)
            )
154 155 156 157 158 159

        self.inputs['SectionsTensorList'] = sections_tensor

        self.attrs = {
            'axis': self.axis,
            'sections': self.sections_infer,
160
            'num': self.num,
161 162 163
        }

        out = np.split(self.x, self.indices_or_sections, self.axis)
164
        self.outputs = {'Out': [('out%d' % i, out[i]) for i in range(len(out))]}
165 166 167 168 169 170 171 172 173 174

    def init_data(self):
        self.x = np.random.random((4, 5, 6)).astype(self.dtype)
        self.axis = 1
        self.sections = [2, 1, 2]
        self.sections_infer = [-1, -1, -1]
        self.num = 0
        self.indices_or_sections = [2, 3]

    def get_dtype(self):
175
        return "float64"
176 177 178 179 180 181 182 183 184 185 186 187 188

    def _set_op_type(self):
        self.op_type = "split"

    def test_check_output(self):
        self.check_output()

    def test_check_grad(self):
        self.check_grad(['X'], ['out0', 'out1', 'out2'])


class TestSplitOp_unk_section(OpTest):
    def setUp(self):
189 190
        self.python_api = paddle.split
        self.python_out_sig = ['out0', 'out1', 'out2']
191 192 193 194 195 196 197
        self._set_op_type()
        self.dtype = self.get_dtype()
        self.init_data()
        self.inputs = {'X': self.x}
        self.attrs = {
            'axis': self.axis,
            'sections': self.sections,
198
            'num': self.num,
199 200 201
        }

        out = np.split(self.x, self.indices_or_sections, self.axis)
202
        self.outputs = {'Out': [('out%d' % i, out[i]) for i in range(len(out))]}
203 204 205 206 207 208 209 210 211

    def init_data(self):
        self.x = np.random.random((4, 5, 6)).astype(self.dtype)
        self.axis = 2
        self.sections = [2, 1, -1]
        self.num = 0
        self.indices_or_sections = [2, 3]

    def get_dtype(self):
212
        return "float64"
213 214 215 216 217 218 219 220 221 222 223

    def _set_op_type(self):
        self.op_type = "split"

    def test_check_output(self):
        self.check_output()

    def test_check_grad(self):
        self.check_grad(['X'], ['out0', 'out1', 'out2'])


T
typhoonzero 已提交
224 225 226 227 228
class TestSplitByrefOp(OpTest):
    def _set_op_type(self):
        self.op_type = "split_byref"


229
# ----------------Split Fp16----------------
230 231 232


def create_test_fp16(parent):
233 234 235
    @unittest.skipIf(
        not core.is_compiled_with_cuda(), "core is not compiled with CUDA"
    )
236 237 238 239 240 241 242 243 244 245 246 247 248 249
    class TestSplitFp16(parent):
        def get_dtype(self):
            return np.float16

        def test_check_grad(self):
            pass

    cls_name = "{0}_{1}".format(parent.__name__, "Fp16")
    TestSplitFp16.__name__ = cls_name
    globals()[cls_name] = TestSplitFp16


create_test_fp16(TestSplitOp)

250
# ----------------Split Bf16----------------
251 252 253


def create_test_bf16(parent):
254 255 256
    @unittest.skipIf(
        not core.is_compiled_with_cuda(), "core is not compiled with CUDA"
    )
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274
    class TestSplitBf16(parent):
        def get_dtype(self):
            return np.uint16

        def test_check_output(self):
            place = core.CUDAPlace(0)
            self.check_output_with_place(place)

        def test_check_grad(self):
            pass

    cls_name = "{0}_{1}".format(parent.__name__, "Bf16")
    TestSplitBf16.__name__ = cls_name
    globals()[cls_name] = TestSplitBf16


create_test_bf16(TestSplitOp)

275

276
class TestSplitAPI(unittest.TestCase):
277 278
    def test_api(self):
        input_1 = np.random.random([4, 5, 6]).astype("int32")
279 280 281
        positive_1_int32 = fluid.layers.fill_constant([1], "int32", 1)
        positive_1_int64 = fluid.layers.fill_constant([1], "int64", 1)
        positive_2_int64 = fluid.layers.fill_constant([1], "int64", 2)
282 283 284
        x_1 = fluid.data(shape=[4, 5, 6], dtype='int32', name='x_1')
        x_2 = fluid.data(shape=[4, 5, None], dtype='int32', name='x_2')

285 286
        out_0, out_1, out_2 = paddle.split(
            x=x_1,
287
            num_or_sections=[positive_2_int64, positive_1_int32, -1],
288
            axis=positive_1_int64,
289
        )
290

291 292
        out_3, out_4, out_5 = paddle.split(
            x=x_1, num_or_sections=[2, 1, 2], axis=positive_1_int32
293
        )
294
        paddle.split(x=x_2, num_or_sections=2, axis=2)
295 296

        exe = fluid.Executor(place=fluid.CPUPlace())
297 298 299 300 301
        [res_0, res_1, res_2, res_3, res_4, res_5] = exe.run(
            fluid.default_main_program(),
            feed={"x_1": input_1, "x_2": input_1},
            fetch_list=[out_0, out_1, out_2, out_3, out_4, out_5],
        )
302 303 304 305 306 307 308 309 310 311

        out = np.split(input_1, [2, 3], 1)
        assert np.array_equal(res_0, out[0])
        assert np.array_equal(res_1, out[1])
        assert np.array_equal(res_2, out[2])
        assert np.array_equal(res_3, out[0])
        assert np.array_equal(res_4, out[1])
        assert np.array_equal(res_5, out[2])


312
class TestSplitOpError(unittest.TestCase):
313 314 315 316
    def test_errors(self):
        with program_guard(Program(), Program()):
            # The type of axis in split_op should be int or Variable.
            def test_axis_type():
G
GGBond8488 已提交
317 318 319
                x6 = paddle.static.data(
                    shape=[-1, 4], dtype='float16', name='x3'
                )
320
                paddle.split(x=x6, num_or_sections=2, axis=3.2)
321 322 323

            self.assertRaises(TypeError, test_axis_type)

324 325
            # The type of axis in split_op should be int or Variable.
            def test_axis_variable_type():
G
GGBond8488 已提交
326 327 328 329 330 331
                x9 = paddle.static.data(
                    shape=[-1, 4], dtype='float16', name='x9'
                )
                x10 = paddle.static.data(
                    shape=[-1, 1], dtype='float16', name='x10'
                )
332
                paddle.split(x=x9, num_or_sections=2, axis=x10)
333 334 335

            self.assertRaises(TypeError, test_axis_variable_type)

336 337
            # The type of num_or_sections in split_op should be int, tuple or list.
            def test_num_or_sections_type():
G
GGBond8488 已提交
338 339 340
                x6 = paddle.static.data(
                    shape=[-1, 4], dtype='float16', name='x4'
                )
341
                paddle.split(x=x6, num_or_sections=2.1, axis=3)
342 343 344

            self.assertRaises(TypeError, test_num_or_sections_type)

345
            def test_num_or_sections_type_tensor():
G
GGBond8488 已提交
346 347 348
                x7 = paddle.static.data(
                    shape=[-1, 4], dtype='float16', name='x5'
                )
349 350 351 352 353
                paddle.split(input=x7, num_or_sections=2.1, dim=3)

            self.assertRaises(TypeError, test_num_or_sections_type_tensor)

            def test_axis_type_tensor():
G
GGBond8488 已提交
354 355 356
                x8 = paddle.static.data(
                    shape=[-1, 4], dtype='float16', name='x6'
                )
357 358 359 360
                paddle.split(input=x8, num_or_sections=2, dim=3.2)

            self.assertRaises(TypeError, test_axis_type_tensor)

张春乔 已提交
361 362 363 364 365 366 367 368
        with paddle.fluid.dygraph.guard():

            def test_0_num_tensor():
                x = paddle.uniform([1, 1, 1], dtype='float32')
                paddle.split(x, num_or_sections=0)

            self.assertRaises(ValueError, test_0_num_tensor)

369 370 371 372

class API_TestSplit(unittest.TestCase):
    def test_out(self):
        with fluid.program_guard(fluid.Program(), fluid.Program()):
G
GGBond8488 已提交
373 374 375 376 377 378
            data1 = paddle.static.data(
                'data1', shape=[-1, 4, 6, 6], dtype='float64'
            )
            data1.desc.set_need_check_feed(False)
            data2 = paddle.static.data('data2', shape=[-1, 1], dtype='int32')
            data2.desc.set_need_check_feed(False)
379
            x0, x1, x2 = paddle.split(data1, num_or_sections=3, axis=data2)
380 381 382 383
            place = fluid.CPUPlace()
            exe = fluid.Executor(place)
            input1 = np.random.random([4, 6, 6]).astype('float64')
            input2 = np.array([2]).astype('int32')
384 385 386
            r0, r1, r2, = exe.run(
                feed={"data1": input1, "data2": input2}, fetch_list=[x0, x1, x2]
            )
387
            ex_x0, ex_x1, ex_x2 = np.split(input1, 3, axis=2)
388 389 390
            np.testing.assert_allclose(ex_x0, r0, rtol=1e-05)
            np.testing.assert_allclose(ex_x1, r1, rtol=1e-05)
            np.testing.assert_allclose(ex_x2, r2, rtol=1e-05)
391 392 393 394 395


class API_TestSplit2(unittest.TestCase):
    def test_out(self):
        with fluid.program_guard(fluid.Program(), fluid.Program()):
G
GGBond8488 已提交
396 397 398 399
            data1 = paddle.static.data(
                'data1', shape=[-1, 4, 6, 6], dtype='float64'
            )
            data1.desc.set_need_check_feed(False)
400
            x0, x1, x2 = paddle.split(data1, num_or_sections=3, axis=2)
401 402 403
            place = fluid.CPUPlace()
            exe = fluid.Executor(place)
            input1 = np.random.random([4, 6, 6]).astype('float64')
404 405 406 407 408
            (
                r0,
                r1,
                r2,
            ) = exe.run(feed={"data1": input1}, fetch_list=[x0, x1, x2])
409
            ex_x0, ex_x1, ex_x2 = np.split(input1, 3, axis=2)
410 411 412
            np.testing.assert_allclose(ex_x0, r0, rtol=1e-05)
            np.testing.assert_allclose(ex_x1, r1, rtol=1e-05)
            np.testing.assert_allclose(ex_x2, r2, rtol=1e-05)
413 414 415 416 417


class API_TestSplit3(unittest.TestCase):
    def test_out(self):
        with fluid.program_guard(fluid.Program(), fluid.Program()):
G
GGBond8488 已提交
418
            data = paddle.static.data('data', shape=[-1, 10], dtype='float64')
419
            x0, x1 = paddle.split(data, num_or_sections=(3, 7), axis=1)
420 421 422 423
            place = fluid.CPUPlace()
            exe = fluid.Executor(place)
            input1 = np.random.random([1, 10]).astype('float64')
            r0, r1 = exe.run(feed={"data": input1}, fetch_list=[x0, x1])
424
            ex_x0, ex_x1 = np.split(input1, (3,), axis=1)
425 426
            np.testing.assert_allclose(ex_x0, r0, rtol=1e-05)
            np.testing.assert_allclose(ex_x1, r1, rtol=1e-05)
427 428 429 430 431


class API_TestSplit4(unittest.TestCase):
    def test_out(self):
        with fluid.program_guard(fluid.Program(), fluid.Program()):
G
GGBond8488 已提交
432 433
            data = paddle.static.data('data', shape=[-1, 10], dtype='float64')
            index = paddle.static.data('index', shape=[1], dtype='int32')
434
            x0, x1 = paddle.split(data, num_or_sections=(3, index), axis=1)
435 436 437 438
            place = fluid.CPUPlace()
            exe = fluid.Executor(place)
            input1 = np.random.random([1, 10]).astype('float64')
            input2 = np.array([7]).astype('int32')
439 440 441 442
            r0, r1 = exe.run(
                feed={"data": input1, "index": input2}, fetch_list=[x0, x1]
            )
            ex_x0, ex_x1 = np.split(input1, (3,), axis=1)
443 444
            np.testing.assert_allclose(ex_x0, r0, rtol=1e-05)
            np.testing.assert_allclose(ex_x1, r1, rtol=1e-05)
445 446


C
Charles-hit 已提交
447 448
class API_TestSplit5(unittest.TestCase):
    def test_out(self):
449 450 451
        for use_cuda in (
            [False, True] if core.is_compiled_with_cuda() else [False]
        ):
C
Charles-hit 已提交
452 453 454 455 456 457 458 459 460 461 462 463 464 465 466
            place = paddle.CUDAPlace(0) if use_cuda else paddle.CPUPlace()
            with fluid.program_guard(fluid.Program(), fluid.Program()):
                input_1 = np.random.random([5, 4]).astype("int32")
                # input is a variable which shape is [5, 4]
                input = paddle.to_tensor(input_1)
                n = paddle.full([1], 5, dtype='int32')
                out = paddle.split(input, [n])
                exe = paddle.static.Executor(place=place)
                re = exe.run(fetch_list=[out])
                re = re[0]
                ex_out = np.split(input_1, [5])
                ex_out = ex_out[0]
                np.testing.assert_allclose(ex_out, re, rtol=1e-05)


467 468 469
class API_TestSplit6(unittest.TestCase):
    def test_out(self):
        with fluid.program_guard(fluid.Program(), fluid.Program()):
G
GGBond8488 已提交
470
            data = paddle.static.data('data', shape=[-1, 10], dtype='float64')
471 472 473 474 475
            x0, x1 = paddle.split(data, num_or_sections=[1, 1], axis=0)
            place = fluid.CPUPlace()
            exe = fluid.Executor(place)
            input1 = np.random.random([2, 10]).astype('float64')
            r0, r1 = exe.run(feed={"data": input1}, fetch_list=[x0, x1])
476
            ex_x0, ex_x1 = np.split(input1, (1,), axis=0)
477 478 479 480
            np.testing.assert_allclose(ex_x0, r0, rtol=1e-05)
            np.testing.assert_allclose(ex_x1, r1, rtol=1e-05)


C
Charles-hit 已提交
481 482 483 484 485 486
class API_TestDygraphFluidSplit(unittest.TestCase):
    def test_out1(self):
        with fluid.dygraph.guard():
            input_1 = np.random.random([4, 6, 6]).astype("int32")
            # input is a variable which shape is [4, 6, 6]
            input = paddle.to_tensor(input_1)
487
            x0, x1, x2 = paddle.split(input, num_or_sections=3, axis=1)
C
Charles-hit 已提交
488 489 490 491
            x0_out = x0.numpy()
            x1_out = x1.numpy()
            x2_out = x2.numpy()
            ex_x0, ex_x1, ex_x2 = np.split(input_1, 3, axis=1)
492 493 494
            # input is a variable which shape is [4, 6, 6]
            input = paddle.to_tensor(input_1)
            input.stop_gradient = False
495
            x0, x1, x2 = paddle.split(input, num_or_sections=3, axis=1)
496 497 498 499 500 501 502 503 504 505 506
            eager_x0_out = x0.numpy()
            eager_x1_out = x1.numpy()
            eager_x2_out = x2.numpy()
            loss = x0.sum()
            loss.backward()
            manul_grad = np.zeros_like(input_1)
            manul_grad[:, :2, :] = 1
            np.testing.assert_allclose(input.gradient(), manul_grad, rtol=1e-05)
            np.testing.assert_allclose(ex_x0, eager_x0_out, rtol=1e-05)
            np.testing.assert_allclose(ex_x1, eager_x1_out, rtol=1e-05)
            np.testing.assert_allclose(ex_x2, eager_x2_out, rtol=1e-05)
C
Charles-hit 已提交
507 508 509 510 511 512 513 514 515 516

        np.testing.assert_allclose(ex_x0, x0_out, rtol=1e-05)
        np.testing.assert_allclose(ex_x1, x1_out, rtol=1e-05)
        np.testing.assert_allclose(ex_x2, x2_out, rtol=1e-05)

    def test_out2(self):
        with fluid.dygraph.guard():
            input_1 = np.random.random([4, 6, 6]).astype("int32")
            # input is a variable which shape is [4, 6, 6]
            input = paddle.to_tensor(input_1)
517
            x0, x1, x2 = paddle.split(input, [2, 2, 2], axis=1)
C
Charles-hit 已提交
518 519 520 521
            x0_out = x0.numpy()
            x1_out = x1.numpy()
            x2_out = x2.numpy()
            ex_x0, ex_x1, ex_x2 = np.split(input_1, 3, axis=1)
522 523 524
            # input is a variable which shape is [4, 6, 6]
            input = paddle.to_tensor(input_1)
            input.stop_gradient = False
525
            x0, x1, x2 = paddle.split(input, [2, 2, 2], axis=1)
526 527 528 529 530 531 532 533 534 535 536
            eager_x0_out = x0.numpy()
            eager_x1_out = x1.numpy()
            eager_x2_out = x2.numpy()
            loss = x0.sum()
            loss.backward()
            manul_grad = np.zeros_like(input_1)
            manul_grad[:, :2, :] = 1
            np.testing.assert_allclose(input.gradient(), manul_grad, rtol=1e-05)
            np.testing.assert_allclose(ex_x0, eager_x0_out, rtol=1e-05)
            np.testing.assert_allclose(ex_x1, eager_x1_out, rtol=1e-05)
            np.testing.assert_allclose(ex_x2, eager_x2_out, rtol=1e-05)
C
Charles-hit 已提交
537 538 539 540 541 542

        np.testing.assert_allclose(ex_x0, x0_out, rtol=1e-05)
        np.testing.assert_allclose(ex_x1, x1_out, rtol=1e-05)
        np.testing.assert_allclose(ex_x2, x2_out, rtol=1e-05)


543
class API_TestDygraphSplit(unittest.TestCase):
544 545 546 547
    def test_out1(self):
        with fluid.dygraph.guard():
            input_1 = np.random.random([4, 6, 6]).astype("int32")
            # input is a variable which shape is [4, 6, 6]
H
hong 已提交
548
            input = paddle.to_tensor(input_1)
549 550 551 552 553
            x0, x1, x2 = paddle.split(input, num_or_sections=3, axis=1)
            x0_out = x0.numpy()
            x1_out = x1.numpy()
            x2_out = x2.numpy()
            ex_x0, ex_x1, ex_x2 = np.split(input_1, 3, axis=1)
H
hong 已提交
554

555 556 557 558 559 560 561 562 563 564 565 566 567 568 569
            # input is a variable which shape is [4, 6, 6]
            input = paddle.to_tensor(input_1)
            input.stop_gradient = False
            x0, x1, x2 = paddle.split(input, num_or_sections=3, axis=1)
            eager_x0_out = x0.numpy()
            eager_x1_out = x1.numpy()
            eager_x2_out = x2.numpy()
            loss = x0.sum()
            loss.backward()
            manul_grad = np.zeros_like(input_1)
            manul_grad[:, :2, :] = 1
            np.testing.assert_allclose(input.gradient(), manul_grad, rtol=1e-05)
            np.testing.assert_allclose(ex_x0, eager_x0_out, rtol=1e-05)
            np.testing.assert_allclose(ex_x1, eager_x1_out, rtol=1e-05)
            np.testing.assert_allclose(ex_x2, eager_x2_out, rtol=1e-05)
H
hong 已提交
570

571 572 573
        np.testing.assert_allclose(ex_x0, x0_out, rtol=1e-05)
        np.testing.assert_allclose(ex_x1, x1_out, rtol=1e-05)
        np.testing.assert_allclose(ex_x2, x2_out, rtol=1e-05)
574 575 576 577 578

    def test_out2(self):
        with fluid.dygraph.guard():
            input_1 = np.random.random([4, 6, 6]).astype("bool")
            # input is a variable which shape is [4, 6, 6]
H
hong 已提交
579
            input = paddle.to_tensor(input_1)
580 581 582 583 584
            x0, x1, x2 = paddle.split(input, num_or_sections=3, axis=1)
            x0_out = x0.numpy()
            x1_out = x1.numpy()
            x2_out = x2.numpy()
            ex_x0, ex_x1, ex_x2 = np.split(input_1, 3, axis=1)
585 586 587
        np.testing.assert_allclose(ex_x0, x0_out, rtol=1e-05)
        np.testing.assert_allclose(ex_x1, x1_out, rtol=1e-05)
        np.testing.assert_allclose(ex_x2, x2_out, rtol=1e-05)
588

C
Charles-hit 已提交
589 590 591 592 593 594 595 596 597 598 599
    def test_out3(self):
        with fluid.dygraph.guard():
            np.random.seed(2021)
            input_1 = np.random.random([4, 6, 6]).astype("int32")
            # input is a variable which shape is [4, 6, 6]
            input = paddle.to_tensor(input_1)
            out_dy = paddle.split(input, [6], axis=1)
            out_dy = out_dy[0]
            out_dy_np = out_dy.numpy()
            ex_out = np.split(input_1, [6], axis=1)
            ex_out = ex_out[0]
600 601 602 603 604
            input = paddle.to_tensor(input_1)
            out_eager = paddle.split(input, [6], axis=1)
            out_eager = out_eager[0]
            out_eager_np = out_dy.numpy()
            np.testing.assert_allclose(ex_out, out_eager_np, rtol=1e-05)
C
Charles-hit 已提交
605 606
        np.testing.assert_allclose(ex_out, out_dy_np, rtol=1e-05)

607 608 609 610
    def test_out_tensor_input(self):
        with fluid.dygraph.guard():
            input_1 = np.random.random([4, 6, 6]).astype("int32")
            # input is a variable which shape is [4, 6, 6]
H
hong 已提交
611
            input = paddle.to_tensor(input_1)
612
            num1 = paddle.full(shape=[1], fill_value=2, dtype='int32')
613 614 615
            x0, x1, x2 = paddle.split(
                input, num_or_sections=[num1, 2, 2], axis=1
            )
616 617 618 619
            x0_out = x0.numpy()
            x1_out = x1.numpy()
            x2_out = x2.numpy()
            ex_x0, ex_x1, ex_x2 = np.split(input_1, 3, axis=1)
620 621 622
        np.testing.assert_allclose(ex_x0, x0_out, rtol=1e-05)
        np.testing.assert_allclose(ex_x1, x1_out, rtol=1e-05)
        np.testing.assert_allclose(ex_x2, x2_out, rtol=1e-05)
623 624

    def test_axis_tensor_input(self):
625 626 627
        with fluid.dygraph.guard():
            input_1 = np.random.random([4, 6, 6]).astype("int32")
            # input is a variable which shape is [4, 6, 6]
H
hong 已提交
628
            input = paddle.to_tensor(input_1)
629
            num1 = paddle.full(shape=[1], fill_value=1, dtype='int32')
630 631 632
            x0, x1, x2 = paddle.split(
                input, num_or_sections=[2, 2, 2], axis=num1
            )
633 634 635 636
            x0_out = x0.numpy()
            x1_out = x1.numpy()
            x2_out = x2.numpy()
            ex_x0, ex_x1, ex_x2 = np.split(input_1, 3, axis=1)
637 638 639
        np.testing.assert_allclose(ex_x0, x0_out, rtol=1e-05)
        np.testing.assert_allclose(ex_x1, x1_out, rtol=1e-05)
        np.testing.assert_allclose(ex_x2, x2_out, rtol=1e-05)
640

641
    def test_negative_one_section(self):
642 643 644 645 646 647 648
        with fluid.dygraph.guard():
            input_1 = np.random.random([4, 6, 6]).astype("int32")
            # input is a variable which shape is [4, 6, 6]
            input = paddle.to_tensor(input_1)
            num1 = paddle.full(shape=[1], fill_value=1, dtype='int32')
            x0 = paddle.split(input, num_or_sections=[-1], axis=num1)
            x0_out = x0[0].numpy()
649
        np.testing.assert_array_equal(x0_out, input.numpy())
650

651

652 653 654 655 656 657 658 659 660 661
class API_TestEmptySplit(unittest.TestCase):
    def test_axis_input_empty_section(self):
        with fluid.dygraph.guard():
            input_1 = np.random.random([8, 6, 6]).astype("float32")
            # input is a variable which shape is [8, 6, 6]
            input = paddle.to_tensor(input_1)
            x0, x1, x2 = paddle.split(input, num_or_sections=[5, 0, 3])
            x0_out = x0.numpy()
            x1_out = x1.numpy()
            x2_out = x2.numpy()
662 663 664 665 666 667 668
            ex_x0, ex_x1, ex_x2 = np.split(
                input_1,
                [
                    5,
                    5,
                ],
            )
669 670 671
        np.testing.assert_allclose(ex_x0, x0_out, rtol=1e-05)
        np.testing.assert_allclose(ex_x1, x1_out, rtol=1e-05)
        np.testing.assert_allclose(ex_x2, x2_out, rtol=1e-05)
672 673


Y
Yancey 已提交
674
if __name__ == '__main__':
675
    paddle.enable_static()
Y
Yancey 已提交
676
    unittest.main()