test_splits_api.py 5.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 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 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 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 168
# Copyright (c) 2022 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
import numpy as np
import paddle
import paddle.fluid as fluid
import paddle.fluid.core as core


def func_ref(func, x, num_or_sections):
    # Convert the num_or_sections in paddle to indices_or_sections in numpy
    # Do not support -1
    if isinstance(num_or_sections, int):
        indices_or_sections = num_or_sections
    else:
        indices_or_sections = np.cumsum(num_or_sections)[:-1]
    return func(x, indices_or_sections)


# TODO: add other split API, such as dsplit、hsplit
test_list = [
    (paddle.vsplit, np.vsplit),
]


class TestSplitsAPI(unittest.TestCase):

    def setUp(self):
        self.rtol = 1e-5
        self.atol = 1e-8
        self.set_input()

    def set_input(self):
        self.shape = [4, 5, 2]
        self.num_or_sections = 2
        self.x_np = np.random.uniform(-1, 1, self.shape).astype('float64')
        self.place = paddle.CUDAPlace(0) if core.is_compiled_with_cuda() \
            else paddle.CPUPlace()

    def test_static_api(self):
        paddle.enable_static()
        for func, func_type in test_list:
            with paddle.static.program_guard(paddle.static.Program()):
                x = paddle.fluid.data('X', self.x_np.shape, self.x_np.dtype)
                out = func(x, self.num_or_sections)
                exe = paddle.static.Executor(self.place)
                res = exe.run(feed={'X': self.x_np}, fetch_list=[out])
            out_ref = func_ref(func_type, self.x_np, self.num_or_sections)
            for n, p in zip(out_ref, res):
                np.testing.assert_allclose(n, p, rtol=self.rtol, atol=self.atol)

    def test_dygraph_api(self):
        paddle.disable_static(self.place)
        x = paddle.to_tensor(self.x_np)
        for func, func_type in test_list:
            out = func(x, self.num_or_sections)
            out_ref = func_ref(func_type, self.x_np, self.num_or_sections)
            for n, p in zip(out_ref, out):
                np.testing.assert_allclose(n,
                                           p.numpy(),
                                           rtol=self.rtol,
                                           atol=self.atol)
        paddle.enable_static()


class TestSplitsSections(TestSplitsAPI):
    """
        Test num_or_sections which is a list and date type is float64.
    """

    def set_input(self):
        self.shape = [6, 2, 4]
        self.num_or_sections = [2, 1, 3]
        self.x_np = np.random.uniform(-1, 1, self.shape).astype('float64')
        self.place = paddle.CUDAPlace(0) if core.is_compiled_with_cuda() \
            else paddle.CPUPlace()


class TestSplitsFloat32(TestSplitsAPI):
    """
        Test num_or_sections which is an integer and data type is float32.
    """

    def set_input(self):
        self.shape = [2, 3, 4]
        self.num_or_sections = 2
        self.x_np = np.random.uniform(-1, 1, self.shape).astype('float32')
        self.place = paddle.CUDAPlace(0) if core.is_compiled_with_cuda() \
            else paddle.CPUPlace()


class TestSplitsInt32(TestSplitsAPI):
    """
        Test data type int32.
    """

    def set_input(self):
        self.shape = [5, 1, 2]
        self.num_or_sections = 5
        self.x_np = np.random.uniform(-1, 1, self.shape).astype('int32')
        self.place = paddle.CUDAPlace(0) if core.is_compiled_with_cuda() \
            else paddle.CPUPlace()


class TestSplitsInt64(TestSplitsAPI):
    """
        Test data type int64.
    """

    def set_input(self):
        self.shape = [4, 3, 2]
        self.num_or_sections = 2
        self.x_np = np.random.uniform(-1, 1, self.shape).astype('int64')
        self.place = paddle.CUDAPlace(0) if core.is_compiled_with_cuda() \
            else paddle.CPUPlace()


class TestSplitsCPU(TestSplitsAPI):
    """
        Test cpu place and num_or_sections which is a tuple.
    """

    def set_input(self):
        self.shape = [8, 2, 3, 5]
        self.num_or_sections = (2, 3, 3)
        self.x_np = np.random.uniform(-1, 1, self.shape).astype('float64')
        self.place = paddle.CPUPlace()


class TestSplitsError(unittest.TestCase):
    """
        Test the situation that input shape less than 2.
    """

    def setUp(self):
        self.num_or_sections = 1
        self.place = paddle.CUDAPlace(0) if core.is_compiled_with_cuda() \
            else paddle.CPUPlace()

    def test_static_error(self):
        paddle.enable_static()
        for func, _ in test_list:
            with paddle.static.program_guard(paddle.static.Program()):
                x = paddle.fluid.data('X', [5], 'float32')
                self.assertRaises(ValueError, func, x, self.num_or_sections)

    def test_dygraph_error(self):
        paddle.disable_static(self.place)
        for func, _ in test_list:
            x_np = np.random.randn(2)
            x = paddle.to_tensor(x_np, dtype='float64')
            self.assertRaises(ValueError, func, x, self.num_or_sections)


if __name__ == '__main__':
    unittest.main()