test_cummax_op.py 8.1 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 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
#   Copyright (c) 2023 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 sys
import unittest

import numpy as np
from eager_op_test import OpTest

import paddle
from paddle import fluid
from paddle.fluid import core


def cummax_dim2(arr, axis=None):
    if axis is None:
        arr = arr.flatten()
        cummax = np.maximum.accumulate(arr)
        shape = arr.shape
        indices = np.zeros(shape).astype('int32')
        max_val = -sys.maxsize
        max_ind = 0
        for i in range(shape[0]):
            if arr[i] >= max_val:
                max_val = max(arr[i], max_val)
                max_ind = i
                indices[i] = i
            else:
                indices[i] = max_ind
    else:
        cummax = np.maximum.accumulate(arr, axis)
        shape = arr.shape
        indices = np.zeros(shape).astype('int32')
        if axis < 0:
            axis = axis + len(shape)
        if axis == 0:
            for j in range(shape[1]):
                max_ind = 0
                max_val = -sys.maxsize
                for i in range(shape[0]):
                    if arr[i][j] >= max_val:
                        max_val = arr[i][j]
                        max_ind = i
                        indices[i][j] = i
                    else:
                        indices[i][j] = max_ind
        elif axis == 1:
            for i in range(shape[0]):
                max_ind = 0
                max_val = -sys.maxsize
                for j in range(shape[1]):
                    if arr[i][j] >= max_val:
                        max_val = arr[i][j]
                        max_ind = j
                        indices[i][j] = j
                    else:
                        indices[i][j] = max_ind
        else:
            raise Exception("unfeasible axis")
    return cummax, indices


class TestCummaxOp(OpTest):
    def setUp(self):
        self.op_type = "cummax"
        self.python_api = paddle.cummax
        self.dtype = np.float64
        self.axis = -1
        self.indices_type = 3
        self.input_data = np.random.random((10, 10)).astype(self.dtype)
        self.set_attrs()

        self.inputs = {'x': self.input_data}
        self.attrs = {'axis': self.axis, 'dtype': self.indices_type}
        self.np_res, self.np_ind = cummax_dim2(self.input_data, axis=self.axis)
        self.outputs = {'out': self.np_res, 'indices': self.np_ind}

    def set_attrs(self):
        pass

    def test_check_output(self):
        paddle.enable_static()
        self.check_output()

    def test_check_grad(self):
        paddle.enable_static()
        self.check_grad(['x'], 'out')


class TestCummaxOpAxis1(TestCummaxOp):
    def set_attrs(self):
        self.axis = 0


class TestCummaxOpAxis2(TestCummaxOp):
    def set_attrs(self):
        self.axis = -2


class TestCummaxOpIndexType(TestCummaxOp):
    def set_attrs(self):
        self.indices_type = 2


class TestCummaxAPI(unittest.TestCase):
    def run_cases(self):
        data_np = np.random.random((100, 100)).astype(np.float32)
        data = paddle.to_tensor(data_np)

        y, indices = paddle.cummax(data)
        z, ind = cummax_dim2(data_np)
        np.testing.assert_array_equal(z, y.numpy())
        np.testing.assert_array_equal(ind, indices.numpy())

        y, indices = paddle.cummax(data, axis=0)
        z, ind = cummax_dim2(data_np, axis=0)
        np.testing.assert_array_equal(z, y.numpy())
        np.testing.assert_array_equal(ind, indices.numpy())

        y, indices = paddle.cummax(data, axis=-1)
        z, ind = cummax_dim2(data_np, axis=-1)
        np.testing.assert_array_equal(z, y.numpy())
        np.testing.assert_array_equal(ind, indices.numpy())

        y, indices = paddle.cummax(data, axis=-2)
        z, ind = cummax_dim2(data_np, axis=-2)
        np.testing.assert_array_equal(z, y.numpy())
        np.testing.assert_array_equal(ind, indices.numpy())

        y, indices = paddle.cummax(data, axis=-2, dtype='int32')
        z, ind = cummax_dim2(data_np, axis=-2)
        np.testing.assert_array_equal(z, y.numpy())
        np.testing.assert_array_equal(ind, indices.numpy())
        self.assertTrue(indices.dtype == core.VarDesc.VarType.INT32)

        data_np = np.random.randint(0, 10, size=(100, 100)).astype(np.int32)
        data = paddle.to_tensor(data_np)
        y, indices = paddle.cummax(data, axis=0)
        z, ind = cummax_dim2(data_np, axis=0)
        np.testing.assert_array_equal(z, y.numpy())
        np.testing.assert_array_equal(ind, indices.numpy())

    def run_static(self, use_gpu=False):
        with fluid.program_guard(fluid.Program()):
            data_np = np.random.random((100, 100)).astype(np.float32)
            x = paddle.static.data('x', [100, 100])
            y1, indices1 = paddle.cummax(x)
            y2, indices2 = paddle.cummax(x, axis=0)
            y3, indices3 = paddle.cummax(x, axis=-1)
            y4, indices4 = paddle.cummax(x, axis=-2)
            y5, indices5 = paddle.cummax(x, axis=-2, dtype=np.int32)

            place = fluid.CUDAPlace(0) if use_gpu else fluid.CPUPlace()
            exe = fluid.Executor(place)
            exe.run(fluid.default_startup_program())
            out = exe.run(
                feed={'x': data_np},
                fetch_list=[
                    y1.name,
                    indices1.name,
                    y2.name,
                    indices2.name,
                    y3.name,
                    indices3.name,
                    y4.name,
                    indices4.name,
                    y5.name,
                    indices5.name,
                ],
            )

            z, ind = cummax_dim2(data_np)
            np.testing.assert_allclose(z, out[0], rtol=1e-05)
            np.testing.assert_allclose(ind, out[1], rtol=1e-05)

            z, ind = cummax_dim2(data_np, axis=0)
            np.testing.assert_allclose(z, out[2], rtol=1e-05)
            np.testing.assert_allclose(ind, out[3], rtol=1e-05)

            z, ind = cummax_dim2(data_np, axis=-1)
            np.testing.assert_allclose(z, out[4], rtol=1e-05)
            np.testing.assert_allclose(ind, out[5], rtol=1e-05)

            z, ind = cummax_dim2(data_np, axis=-2)
            np.testing.assert_allclose(z, out[6], rtol=1e-05)
            np.testing.assert_allclose(ind, out[7], rtol=1e-05)

            z, ind = cummax_dim2(data_np, axis=-2)
            np.testing.assert_allclose(z, out[8], rtol=1e-05)
            np.testing.assert_allclose(ind, out[9], rtol=1e-05)

    def test_cpu(self):
        paddle.disable_static(paddle.fluid.CPUPlace())
        self.run_cases()
        paddle.enable_static()
        self.run_static()

    def test_gpu(self):
        if not fluid.core.is_compiled_with_cuda():
            return
        paddle.disable_static(paddle.fluid.CUDAPlace(0))
        self.run_cases()
        paddle.enable_static()
        self.run_static(use_gpu=True)

    def test_errors(self):
        paddle.enable_static()
        with fluid.program_guard(fluid.Program()):

            def test_x_type():
                data = [1, 2, 3]
                y, indices = paddle.cummax(data, axis=0)

            self.assertRaises(TypeError, test_x_type)
        paddle.disable_static()

        def test_indices_type():
            data_np = np.random.random((10, 10)).astype(np.float32)
            data = paddle.to_tensor(data_np)
            y, indices = paddle.cummax(data, dtype='float32')

        self.assertRaises(ValueError, test_indices_type)

        def test_axis_outrange():
            data_np = np.random.random(100).astype(np.float32)
            data = paddle.to_tensor(data_np)
            y, indices = paddle.cummax(data, axis=-2)

        self.assertRaises(IndexError, test_axis_outrange)


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