test_split_op.py 18.8 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.

15
from __future__ import print_function
16
import paddle
Y
Yancey 已提交
17 18
import unittest
import numpy as np
19
from op_test import OpTest, convert_float_to_uint16
20
import paddle.fluid as fluid
21
from paddle.fluid import compiler, Program, program_guard, core
H
hong 已提交
22
from paddle.fluid.framework import _test_eager_guard
Y
Yancey 已提交
23 24 25


class TestSplitOp(OpTest):
26

Y
Yancey 已提交
27
    def setUp(self):
T
fix ut  
typhoonzero 已提交
28
        self._set_op_type()
29
        self.dtype = self.get_dtype()
Y
Yancey1989 已提交
30
        axis = 1
31 32 33 34 35 36 37 38 39 40 41 42
        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)}
            self.outputs = {'Out': [('out%d' % i, convert_float_to_uint16(out[i])) \
                for i in range(len(out))]}
        else:
            x = np.random.random((4, 5, 6)).astype(self.dtype)
            out = np.split(x, [2, 3], axis)
            self.inputs = {'X': x}
            self.outputs = {'Out': [('out%d' % i, out[i]) \
                for i in range(len(out))]}
Y
Yancey1989 已提交
43
        self.attrs = {'axis': axis, 'sections': [2, 1, 2]}
Y
Yancey 已提交
44

45
    def get_dtype(self):
46
        return "float64"
47

T
typhoonzero 已提交
48 49 50
    def _set_op_type(self):
        self.op_type = "split"

Y
Yancey 已提交
51 52 53
    def test_check_output(self):
        self.check_output()

Y
Yancey1989 已提交
54 55
    def test_check_grad(self):
        self.check_grad(['X'], ['out0', 'out1', 'out2'])
Y
Yancey 已提交
56 57


58 59
# test with attr(num)
class TestSplitOp_2(OpTest):
60

61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
    def setUp(self):
        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,
            'num': self.num
        }

        out = np.split(self.x, self.indices_or_sections, self.axis)
        self.outputs = {'Out': [('out%d' % i, out[i]) \
                                for i in range(len(out))]}

    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):
84
        return "float64"
85 86 87 88 89 90 91 92 93 94 95 96 97

    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):
98

99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120
    def setUp(self):
        self._set_op_type()
        self.dtype = self.get_dtype()
        self.init_data()
        self.inputs = {
            'X': self.x,
            'AxisTensor': np.array([self.axis]).astype("int32")
        }
        self.attrs = {'sections': self.sections, 'num': self.num}

        out = np.split(self.x, self.indices_or_sections, self.axis)
        self.outputs = {'Out': [('out%d' % i, out[i]) \
                                for i in range(len(out))]}

    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):
121
        return "float64"
122 123 124 125 126 127 128 129 130 131 132 133 134

    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):
135

136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
    def setUp(self):
        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):
            sections_tensor.append(("x" + str(index), np.ones(
                (1)).astype('int32') * ele))

        self.inputs['SectionsTensorList'] = sections_tensor

        self.attrs = {
            'axis': self.axis,
            'sections': self.sections_infer,
            'num': self.num
        }

        out = np.split(self.x, self.indices_or_sections, self.axis)
        self.outputs = {'Out': [('out%d' % i, out[i]) \
                                for i in range(len(out))]}

    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):
168
        return "float64"
169 170 171 172 173 174 175 176 177 178 179 180

    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):
181

182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
    def setUp(self):
        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,
            'num': self.num
        }

        out = np.split(self.x, self.indices_or_sections, self.axis)
        self.outputs = {'Out': [('out%d' % i, out[i]) \
                                for i in range(len(out))]}

    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):
205
        return "float64"
206 207 208 209 210 211 212 213 214 215 216

    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 已提交
217
class TestSplitByrefOp(OpTest):
218

T
typhoonzero 已提交
219 220 221 222
    def _set_op_type(self):
        self.op_type = "split_byref"


223 224 225 226
#----------------Split Fp16----------------


def create_test_fp16(parent):
227

228 229
    @unittest.skipIf(not core.is_compiled_with_cuda(),
                     "core is not compiled with CUDA")
230
    class TestSplitFp16(parent):
231

232 233 234 235 236 237 238 239 240 241 242 243 244
        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)

245 246 247 248
#----------------Split Bf16----------------


def create_test_bf16(parent):
249

250 251 252
    @unittest.skipIf(not core.is_compiled_with_cuda(),
                     "core is not compiled with CUDA")
    class TestSplitBf16(parent):
253

254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
        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)

271

272
class TestSplitAPI(unittest.TestCase):
273

274 275
    def test_api(self):
        input_1 = np.random.random([4, 5, 6]).astype("int32")
276 277 278
        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)
279 280 281 282
        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')

        out_0, out_1, out_2 = fluid.layers.split(
283 284 285 286
            input=x_1,
            num_or_sections=[positive_2_int64, positive_1_int32, -1],
            dim=positive_1_int64)

287 288 289
        out_3, out_4, out_5 = fluid.layers.split(input=x_1,
                                                 num_or_sections=[2, 1, 2],
                                                 dim=positive_1_int32)
290 291 292
        fluid.layers.split(input=x_2, num_or_sections=2, dim=2)

        exe = fluid.Executor(place=fluid.CPUPlace())
293 294 295 296 297 298 299
        [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])
300 301 302 303 304 305 306 307 308 309

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


310
class TestSplitOpError(unittest.TestCase):
311

312 313 314 315 316 317 318 319 320
    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():
                x6 = fluid.layers.data(shape=[4], dtype='float16', name='x3')
                fluid.layers.split(input=x6, num_or_sections=2, dim=3.2)

            self.assertRaises(TypeError, test_axis_type)

321 322 323 324 325 326 327 328
            # The type of axis in split_op should be int or Variable.
            def test_axis_variable_type():
                x9 = fluid.layers.data(shape=[4], dtype='float16', name='x9')
                x10 = fluid.layers.data(shape=[1], dtype='float16', name='x10')
                fluid.layers.split(input=x9, num_or_sections=2, dim=x10)

            self.assertRaises(TypeError, test_axis_variable_type)

329 330 331 332 333 334 335
            # The type of num_or_sections in split_op should be int, tuple or list.
            def test_num_or_sections_type():
                x6 = fluid.layers.data(shape=[4], dtype='float16', name='x4')
                fluid.layers.split(input=x6, num_or_sections=2.1, dim=3)

            self.assertRaises(TypeError, test_num_or_sections_type)

336 337 338 339 340 341 342 343 344 345 346 347 348 349
            def test_num_or_sections_type_tensor():
                x7 = fluid.layers.data(shape=[4], dtype='float16', name='x5')
                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():
                x8 = fluid.layers.data(shape=[4], dtype='float16', name='x6')
                paddle.split(input=x8, num_or_sections=2, dim=3.2)

            self.assertRaises(TypeError, test_axis_type_tensor)


class API_TestSplit(unittest.TestCase):
350

351 352 353 354
    def test_out(self):
        with fluid.program_guard(fluid.Program(), fluid.Program()):
            data1 = fluid.layers.data('data1', shape=[4, 6, 6], dtype='float64')
            data2 = fluid.layers.data('data2', shape=[1], dtype='int32')
355
            x0, x1, x2 = paddle.split(data1, num_or_sections=3, axis=data2)
356 357 358 359
            place = fluid.CPUPlace()
            exe = fluid.Executor(place)
            input1 = np.random.random([4, 6, 6]).astype('float64')
            input2 = np.array([2]).astype('int32')
360 361 362 363
            r0, r1, r2, = exe.run(feed={
                "data1": input1,
                "data2": input2
            },
364 365 366 367 368 369 370 371
                                  fetch_list=[x0, x1, x2])
            ex_x0, ex_x1, ex_x2 = np.split(input1, 3, axis=2)
            self.assertTrue(np.allclose(ex_x0, r0))
            self.assertTrue(np.allclose(ex_x1, r1))
            self.assertTrue(np.allclose(ex_x2, r2))


class API_TestSplit2(unittest.TestCase):
372

373 374 375
    def test_out(self):
        with fluid.program_guard(fluid.Program(), fluid.Program()):
            data1 = fluid.layers.data('data1', shape=[4, 6, 6], dtype='float64')
376
            x0, x1, x2 = paddle.split(data1, num_or_sections=3, axis=2)
377 378 379 380 381 382 383 384 385 386 387 388
            place = fluid.CPUPlace()
            exe = fluid.Executor(place)
            input1 = np.random.random([4, 6, 6]).astype('float64')
            r0, r1, r2, = exe.run(feed={"data1": input1},
                                  fetch_list=[x0, x1, x2])
            ex_x0, ex_x1, ex_x2 = np.split(input1, 3, axis=2)
            self.assertTrue(np.allclose(ex_x0, r0))
            self.assertTrue(np.allclose(ex_x1, r1))
            self.assertTrue(np.allclose(ex_x2, r2))


class API_TestSplit3(unittest.TestCase):
389

390 391 392
    def test_out(self):
        with fluid.program_guard(fluid.Program(), fluid.Program()):
            data = fluid.layers.data('data', shape=[-1, 10], dtype='float64')
393
            x0, x1 = paddle.split(data, num_or_sections=(3, 7), axis=1)
394 395 396 397 398 399 400 401 402 403
            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])
            ex_x0, ex_x1 = np.split(input1, (3, ), axis=1)
            self.assertTrue(np.allclose(ex_x0, r0))
            self.assertTrue(np.allclose(ex_x1, r1))


class API_TestSplit4(unittest.TestCase):
404

405 406 407 408
    def test_out(self):
        with fluid.program_guard(fluid.Program(), fluid.Program()):
            data = fluid.layers.data('data', shape=[-1, 10], dtype='float64')
            index = fluid.layers.data('index', shape=[1], dtype='int32')
409
            x0, x1 = paddle.split(data, num_or_sections=(3, index), axis=1)
410 411 412 413
            place = fluid.CPUPlace()
            exe = fluid.Executor(place)
            input1 = np.random.random([1, 10]).astype('float64')
            input2 = np.array([7]).astype('int32')
414 415 416 417
            r0, r1 = exe.run(feed={
                "data": input1,
                "index": input2
            },
418 419 420 421 422 423 424
                             fetch_list=[x0, x1])
            ex_x0, ex_x1 = np.split(input1, (3, ), axis=1)
            self.assertTrue(np.allclose(ex_x0, r0))
            self.assertTrue(np.allclose(ex_x1, r1))


class API_TestDygraphSplit(unittest.TestCase):
425

426 427 428 429
    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 已提交
430
            input = paddle.to_tensor(input_1)
431 432 433 434 435
            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 已提交
436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453

            with _test_eager_guard():
                # 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
                self.assertTrue(np.allclose(input.gradient(), manul_grad))
                self.assertTrue(np.allclose(ex_x0, eager_x0_out))
                self.assertTrue(np.allclose(ex_x1, eager_x1_out))
                self.assertTrue(np.allclose(ex_x2, eager_x2_out))

454 455 456 457 458 459 460 461
        self.assertTrue(np.allclose(ex_x0, x0_out))
        self.assertTrue(np.allclose(ex_x1, x1_out))
        self.assertTrue(np.allclose(ex_x2, x2_out))

    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 已提交
462
            input = paddle.to_tensor(input_1)
463 464 465 466 467 468 469 470 471 472 473 474 475
            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)
        self.assertTrue(np.allclose(ex_x0, x0_out))
        self.assertTrue(np.allclose(ex_x1, x1_out))
        self.assertTrue(np.allclose(ex_x2, x2_out))

    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 已提交
476
            input = paddle.to_tensor(input_1)
477
            num1 = paddle.full(shape=[1], fill_value=2, dtype='int32')
478 479 480
            x0, x1, x2 = paddle.split(input,
                                      num_or_sections=[num1, 2, 2],
                                      axis=1)
481 482 483 484 485 486 487 488 489
            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)
        self.assertTrue(np.allclose(ex_x0, x0_out))
        self.assertTrue(np.allclose(ex_x1, x1_out))
        self.assertTrue(np.allclose(ex_x2, x2_out))

    def test_axis_tensor_input(self):
490 491 492
        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 已提交
493
            input = paddle.to_tensor(input_1)
494
            num1 = paddle.full(shape=[1], fill_value=1, dtype='int32')
495 496 497
            x0, x1, x2 = paddle.split(input,
                                      num_or_sections=[2, 2, 2],
                                      axis=num1)
498 499 500 501 502 503 504 505
            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)
        self.assertTrue(np.allclose(ex_x0, x0_out))
        self.assertTrue(np.allclose(ex_x1, x1_out))
        self.assertTrue(np.allclose(ex_x2, x2_out))

506 507 508 509 510 511 512 513
    def func_negative_one_section(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)
            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()
514
        np.testing.assert_array_equal(x0_out, input.numpy())
515 516 517 518 519 520

    def test_negative_one_section(self):
        with _test_eager_guard():
            self.func_negative_one_section()
        self.func_negative_one_section()

521

522
class API_TestEmptySplit(unittest.TestCase):
523

524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541
    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()
            ex_x0, ex_x1, ex_x2 = np.split(input_1, [
                5,
                5,
            ])
        self.assertTrue(np.allclose(ex_x0, x0_out))
        self.assertTrue(np.allclose(ex_x1, x1_out))
        self.assertTrue(np.allclose(ex_x2, x2_out))


Y
Yancey 已提交
542
if __name__ == '__main__':
543
    paddle.enable_static()
Y
Yancey 已提交
544
    unittest.main()