test_mode_op.py 8.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#   Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import unittest
16

17
import numpy as np
18 19 20 21 22
from eager_op_test import (
    OpTest,
    convert_float_to_uint16,
    convert_uint16_to_float,
)
23

24
import paddle
25
from paddle import fluid
26
from paddle.fluid import core
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41


def _mode1D(a):
    sorted_inds = np.argsort(a, kind='stable')
    sorted_array = a[sorted_inds]
    max_freq = 0
    cur_freq = 0
    mode = -1
    for i in range(len(sorted_array)):
        cur_freq += 1
        if i == len(sorted_array) - 1 or sorted_array[i] != sorted_array[i + 1]:
            if cur_freq > max_freq:
                mode = sorted_array[i]
                index = sorted_inds[i]
                max_freq = cur_freq
42
            cur_freq = 0
43 44 45 46 47 48 49
    return mode, index


def cal_mode(a, axis, keepdim=False):
    if axis < 0:
        axis = len(a.shape) + axis
    in_dims = list(range(a.ndim))
50
    a_view = np.transpose(a, in_dims[:axis] + in_dims[axis + 1 :] + [axis])
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
    inds = np.ndindex(a_view.shape[:-1])
    modes = np.empty(a_view.shape[:-1], dtype=a.dtype)
    indexes = np.empty(a_view.shape[:-1], dtype=np.int64)
    for ind in inds:
        modes[ind], indexes[ind] = _mode1D(a_view[ind])
    if keepdim:
        newshape = list(a.shape)
        newshape[axis] = 1
        modes = modes.reshape(newshape)
        indexes = indexes.reshape(newshape)
    return modes, indexes


class TestModeOp(OpTest):
    def init_args(self):
        self.axis = 1
67 68 69 70 71 72 73 74
        self.input_shape = (2, 64, 1)

    def init_input_data(self):
        self.input_data = np.random.rand(*self.input_shape).astype(self.dtype)
        self.inputs = {'X': self.input_data}

    def init_dtype(self):
        self.dtype = np.float64
75 76 77

    def setUp(self):
        self.op_type = "mode"
78
        self.python_api = paddle.mode
79
        self.init_dtype()
80
        self.init_args()
81
        self.init_input_data()
82 83 84 85
        self.attrs = {'axis': self.axis}
        output, indices = cal_mode(self.input_data, axis=self.axis)
        self.outputs = {'Out': output, 'Indices': indices}

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
    def init_numeric_grads(self):
        if self.axis < 0:
            axis = len(self.input_data.shape) + self.axis
        else:
            axis = self.axis
        if self.dtype == np.float64:
            dtype = np.float64
        else:
            dtype = np.float32
        grad = np.zeros(self.input_data.shape).astype(dtype)
        in_dims = list(range(grad.ndim))
        if axis == len(self.input_data.shape) - 1:
            a_view = grad
        else:
            a_view = np.transpose(
                grad,
                in_dims[:axis] + in_dims[axis + 1 :] + [axis],
            )
        idx = np.array(self.outputs['Indices']).flatten()
        inds = np.ndindex(a_view.shape[:-1])
        for i, ind in enumerate(inds):
            a_view[ind][idx[i]] = 1 / np.prod(self.outputs['Indices'].shape)
        if axis == len(self.input_data.shape) - 1:
            grad = a_view
        else:
            grad = np.transpose(
                a_view,
                in_dims[:axis] + in_dims[-1:] + in_dims[axis:-1],
            )
        return grad

117 118
    def test_check_output(self):
        paddle.enable_static()
W
wanghuancoder 已提交
119
        self.check_output()
120 121 122

    def test_check_grad(self):
        paddle.enable_static()
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
        grad = self.init_numeric_grads()
        self.check_grad({'X'}, 'Out', user_defined_grads=[grad])


@unittest.skipIf(
    not core.is_compiled_with_cuda(), "core is not compiled with CUDA"
)
class TestModeFP16Op(TestModeOp):
    def init_dtype(self):
        self.dtype = np.float16


@unittest.skipIf(
    not core.is_compiled_with_cuda()
    or not core.is_bfloat16_supported(core.CUDAPlace(0)),
    "core is not compiled with CUDA and not support the bfloat16",
)
class TestModeBF16Op(TestModeOp):
    def init_dtype(self):
        self.dtype = np.uint16

    def init_input_data(self):
        self.input_data = np.random.rand(*self.input_shape).astype(np.float32)
        self.input_data = convert_uint16_to_float(
            convert_float_to_uint16(self.input_data)
        )
        self.inputs = {'X': convert_float_to_uint16(self.input_data)}

    def test_check_output(self):
        place = core.CUDAPlace(0)
        paddle.enable_static()
        if core.is_bfloat16_supported(place):
            self.check_output_with_place(place)

    def test_check_grad(self):
        place = core.CUDAPlace(0)
        paddle.enable_static()
        grad = self.init_numeric_grads()
161

162 163 164 165
        if core.is_bfloat16_supported(place):
            self.check_grad_with_place(
                place, {'X'}, 'Out', user_defined_grads=[grad]
            )
166

167 168

class TestModeOpLastdim(TestModeOp):
169 170
    def init_args(self):
        self.axis = -1
171
        self.input_shape = (2, 1, 1, 2, 30)
172 173


174 175 176 177 178 179 180
@unittest.skipIf(
    not core.is_compiled_with_cuda(), "core is not compiled with CUDA"
)
class TestModeFP16OpLastdim(TestModeFP16Op):
    def init_args(self):
        self.axis = -1
        self.input_shape = (2, 1, 1, 2, 30)
181

182 183 184 185 186 187 188 189

@unittest.skipIf(
    not core.is_compiled_with_cuda(), "core is not compiled with CUDA"
)
class TestModeBF16OpLastdim(TestModeBF16Op):
    def init_args(self):
        self.axis = -1
        self.input_shape = (2, 1, 1, 2, 30)
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204


class TestModeOpKernels(unittest.TestCase):
    def setUp(self):
        self.axises = [-1, 1]
        np.random.seed(666)
        self.inputs = np.ceil(np.random.rand(2, 10, 10) * 1000)

    def test_mode_op(self):
        def test_cpu_kernel():
            paddle.set_device('cpu')
            tensor = paddle.to_tensor(self.inputs)
            for axis in self.axises:
                value_expect, indice_expect = cal_mode(self.inputs, axis)
                v, inds = paddle.mode(tensor, axis)
205
                np.testing.assert_allclose(v.numpy(), value_expect, rtol=1e-05)
206

207 208 209
                value_expect, indice_expect = cal_mode(
                    self.inputs, axis, keepdim=True
                )
210
                v, inds = paddle.mode(tensor, axis, keepdim=True)
211
                np.testing.assert_allclose(v.numpy(), value_expect, rtol=1e-05)
212 213 214 215 216 217 218

        def test_gpu_kernel():
            paddle.set_device('gpu')
            tensor = paddle.to_tensor(self.inputs)
            for axis in self.axises:
                value_expect, indice_expect = cal_mode(self.inputs, axis)
                v, inds = paddle.mode(tensor, axis)
219
                np.testing.assert_allclose(v.numpy(), value_expect, rtol=1e-05)
220

221 222 223
                value_expect, indice_expect = cal_mode(
                    self.inputs, axis, keepdim=True
                )
224
                v, inds = paddle.mode(tensor, axis, keepdim=True)
225
                np.testing.assert_allclose(v.numpy(), value_expect, rtol=1e-05)
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245

        paddle.disable_static()
        test_cpu_kernel()
        if fluid.core.is_compiled_with_cuda():
            test_gpu_kernel()


class TestModeOpErrors(unittest.TestCase):
    def setUp(self):
        self.x = paddle.uniform([2, 10, 20, 25], dtype='float32')

        def test_dim_range_error():
            self.x.mode(axis=5)

        self.assertRaises(ValueError, test_dim_range_error)


class TestModeOpInStatic(unittest.TestCase):
    def setUp(self):
        np.random.seed(666)
246 247 248
        self.input_data = np.ceil(
            np.random.random((2, 10, 10)) * 1000, dtype=np.float64
        )
249 250 251

    def test_run_static(self):
        paddle.enable_static()
252 253 254 255 256 257
        with paddle.static.program_guard(
            paddle.static.Program(), paddle.static.Program()
        ):
            input_tensor = paddle.static.data(
                name="x", shape=[2, 10, 10], dtype="float64"
            )
258 259 260 261

            result = paddle.mode(input_tensor, axis=1)
            expect_value = cal_mode(self.input_data, axis=1)[0]
            exe = paddle.static.Executor(paddle.CPUPlace())
262 263 264
            paddle_result = exe.run(
                feed={"x": self.input_data}, fetch_list=[result]
            )[0]
265
            np.testing.assert_allclose(paddle_result, expect_value, rtol=1e-05)
266 267


268 269 270 271 272 273 274 275 276 277 278 279
class TestModeZeroError(unittest.TestCase):
    def test_errors(self):
        with paddle.fluid.dygraph.guard():

            def test_0_size():
                array = np.array([], dtype=np.float32)
                x = paddle.to_tensor(np.reshape(array, [0, 0]), dtype='float32')
                paddle.mode(x, axis=0)

            self.assertRaises(ValueError, test_0_size)


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