test_arg_min_max_v2_op.py 15.2 KB
Newer Older
W
wawltor 已提交
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

W
wawltor 已提交
17
import numpy as np
18
from eager_op_test import OpTest
19

W
wawltor 已提交
20
import paddle
21 22
from paddle import fluid
from paddle.fluid import Program, core, program_guard
W
wawltor 已提交
23 24 25 26 27 28 29 30 31 32 33 34


def create_kernel_case(op_type, numpy_op_type):
    class ArgMinMaxKernelBaseCase(OpTest):
        def initTestCase(self):
            self.op_type = op_type
            self.numpy_op_type = numpy_op_type
            self.axis = 0

        def setUp(self):
            np.random.seed(123)
            self.initTestCase()
35 36 37 38
            if op_type == 'arg_min':
                self.python_api = paddle.tensor.argmin
            else:
                self.python_api = paddle.tensor.argmax
W
wawltor 已提交
39 40
            self.dims = (4, 5, 6)
            self.dtype = "float64"
41
            self.x = 1000 * np.random.random(self.dims).astype(self.dtype)
W
wawltor 已提交
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
            self.inputs = {'X': self.x}
            self.attrs = {"axis": self.axis}
            self.numpy_op = eval("np.%s" % (numpy_op_type))
            self.outputs = {'Out': self.numpy_op(self.x, axis=self.axis)}

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

    class ArgMinMaxKernelCase0(ArgMinMaxKernelBaseCase):
        def initTestCase(self):
            self.op_type = op_type
            self.numpy_op_type = numpy_op_type
            self.axis = 1

    class ArgMinMaxKernelCase1(ArgMinMaxKernelBaseCase):
        def initTestCase(self):
            self.op_type = op_type
            self.numpy_op_type = numpy_op_type
            self.axis = 2

    class ArgMinMaxKernelCase2(ArgMinMaxKernelBaseCase):
        def initTestCase(self):
            self.op_type = op_type
            self.numpy_op_type = numpy_op_type
            self.axis = -1

    class ArgMinMaxKernelCase3(ArgMinMaxKernelBaseCase):
        def initTestCase(self):
            self.op_type = op_type
            self.numpy_op_type = numpy_op_type
            self.axis = -2

    class ArgMinMaxKernelCase4(ArgMinMaxKernelBaseCase):
        def setUp(self):
            self.initTestCase()
78 79 80 81
            if op_type == 'arg_min':
                self.python_api = paddle.tensor.argmin
            else:
                self.python_api = paddle.tensor.argmax
W
wawltor 已提交
82 83
            self.dims = (4, 5, 6)
            self.dtype = "float64"
84
            self.x = 1000 * np.random.random(self.dims).astype(self.dtype)
W
wawltor 已提交
85 86 87 88
            self.inputs = {'X': self.x}
            self.attrs = {"axis": self.axis, "keepdims": True}
            self.numpy_op = eval("np.%s" % (numpy_op_type))
            self.outputs = {
89
                'Out': self.numpy_op(self.x, axis=self.axis).reshape((1, 5, 6))
W
wawltor 已提交
90 91 92 93 94
            }

    class ArgMinMaxKernelCase5(ArgMinMaxKernelBaseCase):
        def setUp(self):
            self.initTestCase()
95 96 97 98
            if op_type == 'arg_min':
                self.python_api = paddle.tensor.argmin
            else:
                self.python_api = paddle.tensor.argmax
99
            self.dims = 4
W
wawltor 已提交
100
            self.dtype = "float64"
101
            self.x = 1000 * np.random.random(self.dims).astype(self.dtype)
W
wawltor 已提交
102 103 104 105
            self.inputs = {'X': self.x}
            self.attrs = {"axis": self.axis, "flatten": True}
            self.numpy_op = eval("np.%s" % (numpy_op_type))
            self.outputs = {
106
                'Out': self.numpy_op(self.x.flatten(), axis=self.axis)
W
wawltor 已提交
107 108 109 110 111
            }

    class ArgMinMaxKernelCase6(ArgMinMaxKernelBaseCase):
        def setUp(self):
            self.initTestCase()
112 113 114 115
            if op_type == 'arg_min':
                self.python_api = paddle.tensor.argmin
            else:
                self.python_api = paddle.tensor.argmax
116
            self.dims = 4
W
wawltor 已提交
117
            self.dtype = "float64"
118
            self.x = 1000 * np.random.random(self.dims).astype(self.dtype)
W
wawltor 已提交
119 120 121 122
            self.inputs = {'X': self.x}
            self.attrs = {"axis": self.axis, "flatten": True, "keepdims": True}
            self.numpy_op = eval("np.%s" % (numpy_op_type))
            self.outputs = {
123
                'Out': np.array(self.numpy_op(self.x.flatten(), axis=self.axis))
W
wawltor 已提交
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
            }

    cls_name = "ArgMinMaxKernelBaseCase_%s" % (op_type)
    ArgMinMaxKernelBaseCase.__name__ = cls_name
    globals()[cls_name] = ArgMinMaxKernelBaseCase

    cls_name = "ArgMinMaxKernelCase0_%s" % (op_type)
    ArgMinMaxKernelCase0.__name__ = cls_name
    globals()[cls_name] = ArgMinMaxKernelCase0

    cls_name = "ArgMinMaxKernelCase1_%s" % (op_type)
    ArgMinMaxKernelCase1.__name__ = cls_name
    globals()[cls_name] = ArgMinMaxKernelCase1

    cls_name = "ArgMinMaxKernelCase2_%s" % (op_type)
    ArgMinMaxKernelCase2.__name__ = cls_name
    globals()[cls_name] = ArgMinMaxKernelCase2

    cls_name = "ArgMinMaxKernelCase3_%s" % (op_type)
    ArgMinMaxKernelCase3.__name__ = cls_name
    globals()[cls_name] = ArgMinMaxKernelCase3

    cls_name = "ArgMinMaxKernelCase4_%s" % (op_type)
    ArgMinMaxKernelCase4.__name__ = cls_name
    globals()[cls_name] = ArgMinMaxKernelCase4

    cls_name = "ArgMinMaxKernelCase5_%s" % (op_type)
    ArgMinMaxKernelCase5.__name__ = cls_name
    globals()[cls_name] = ArgMinMaxKernelCase5

    cls_name = "ArgMinMaxKernelCase6_%s" % (op_type)
    ArgMinMaxKernelCase6.__name__ = cls_name
    globals()[cls_name] = ArgMinMaxKernelCase6


for op_type, numpy_op_type in zip(['arg_max', 'arg_min'], ['argmax', 'argmin']):
    create_kernel_case(op_type, numpy_op_type)


def create_test_case(op_type):
    class ArgMaxMinTestCase(unittest.TestCase):
        def setUp(self):
            np.random.seed(123)
            self.input_data = np.random.rand(10, 10).astype("float32")
            self.places = []
            self.places.append(fluid.CPUPlace())
            if core.is_compiled_with_cuda():
                self.places.append(paddle.CUDAPlace(0))
            self.op = eval("paddle.%s" % (op_type))
            self.numpy_op = eval("np.%s" % (op_type))

        def run_static(self, place):
            paddle.enable_static()
            with paddle.static.program_guard(paddle.static.Program()):
178 179 180
                data_var = paddle.static.data(
                    name="data", shape=[10, 10], dtype="float32"
                )
W
wawltor 已提交
181 182 183
                op = eval("paddle.%s" % (op_type))
                result = op(data_var)
                exe = paddle.static.Executor(place)
184 185 186
                result_data = exe.run(
                    feed={"data": self.input_data}, fetch_list=[result]
                )
W
wawltor 已提交
187
                expected_data = self.numpy_op(self.input_data)
188 189 190
                self.assertTrue(
                    (result_data == np.array(expected_data)).all(), True
                )
W
wawltor 已提交
191 192

            with paddle.static.program_guard(paddle.static.Program()):
193 194 195
                data_var = paddle.static.data(
                    name="data", shape=[10, 10], dtype="float32"
                )
W
wawltor 已提交
196 197 198
                op = eval("paddle.%s" % (op_type))
                result = op(data_var, axis=1)
                exe = paddle.static.Executor(place)
199 200 201
                result_data = exe.run(
                    feed={"data": self.input_data}, fetch_list=[result]
                )
W
wawltor 已提交
202 203 204 205
                expected_data = self.numpy_op(self.input_data, axis=1)
                self.assertTrue((result_data == expected_data).all(), True)

            with paddle.static.program_guard(paddle.static.Program()):
206 207 208
                data_var = paddle.static.data(
                    name="data", shape=[10, 10], dtype="float32"
                )
W
wawltor 已提交
209 210 211
                op = eval("paddle.%s" % (op_type))
                result = op(data_var, axis=-1)
                exe = paddle.static.Executor(place)
212 213 214
                result_data = exe.run(
                    feed={"data": self.input_data}, fetch_list=[result]
                )
W
wawltor 已提交
215 216 217 218
                expected_data = self.numpy_op(self.input_data, axis=-1)
                self.assertTrue((result_data == expected_data).all(), True)

            with paddle.static.program_guard(paddle.static.Program()):
219 220 221
                data_var = paddle.static.data(
                    name="data", shape=[10, 10], dtype="float32"
                )
W
wawltor 已提交
222 223 224 225

                op = eval("paddle.%s" % (op_type))
                result = op(data_var, axis=-1, keepdim=True)
                exe = paddle.static.Executor(place)
226 227 228
                result_data = exe.run(
                    feed={"data": self.input_data}, fetch_list=[result]
                )
229
                expected_data = self.numpy_op(self.input_data, axis=-1).reshape(
230 231
                    (10, 1)
                )
W
wawltor 已提交
232 233 234 235
                self.assertTrue((result_data == expected_data).all(), True)

            with paddle.static.program_guard(paddle.static.Program()):
                op = eval("paddle.%s" % (op_type))
236 237 238
                data_var = paddle.static.data(
                    name="data", shape=[10, 10], dtype="float32"
                )
W
wawltor 已提交
239 240 241 242
                result = op(data_var, axis=-1, name="test_arg_api")
                self.assertTrue("test_arg_api" in result.name)

        def run_dygraph(self, place):
243
            paddle.disable_static(place)
W
wawltor 已提交
244 245 246
            op = eval("paddle.%s" % (op_type))
            data_tensor = paddle.to_tensor(self.input_data)

247
            # case 1
W
wawltor 已提交
248 249 250 251
            result_data = op(data_tensor)
            excepted_data = self.numpy_op(self.input_data)
            self.assertTrue((result_data.numpy() == excepted_data).all(), True)

252
            # case 2
W
wawltor 已提交
253 254 255 256
            result_data = op(data_tensor, axis=1)
            excepted_data = self.numpy_op(self.input_data, axis=1)
            self.assertTrue((result_data.numpy() == excepted_data).all(), True)

257
            # case 3
W
wawltor 已提交
258 259 260 261
            result_data = op(data_tensor, axis=-1)
            excepted_data = self.numpy_op(self.input_data, axis=-1)
            self.assertTrue((result_data.numpy() == excepted_data).all(), True)

262
            # case 4
W
wawltor 已提交
263 264
            result_data = op(data_tensor, axis=-1, keepdim=True)
            excepted_data = self.numpy_op(self.input_data, axis=-1)
265
            excepted_data = excepted_data.reshape((10, 1))
W
wawltor 已提交
266 267
            self.assertTrue((result_data.numpy() == excepted_data).all(), True)

268
            # case 5
W
wawltor 已提交
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
            result_data = op(data_tensor, axis=-1, keepdim=True, dtype="int32")
            self.assertTrue(result_data.numpy().dtype == np.int32)

            # case for dim 4, 5, 6, for test case coverage
            input_data = np.random.rand(5, 5, 5, 5)
            excepted_data = self.numpy_op(input_data, axis=0)
            result_data = op(paddle.to_tensor(input_data), axis=0)
            self.assertTrue((result_data.numpy() == excepted_data).all(), True)

            input_data = np.random.rand(4, 4, 4, 4, 4)
            excepted_data = self.numpy_op(input_data, axis=0)
            result_data = op(paddle.to_tensor(input_data), axis=0)
            self.assertTrue((result_data.numpy() == excepted_data).all(), True)

            input_data = np.random.rand(3, 3, 3, 3, 3, 3)
            excepted_data = self.numpy_op(input_data, axis=0)
            result_data = op(paddle.to_tensor(input_data), axis=0)
            self.assertTrue((result_data.numpy() == excepted_data).all(), True)

        def test_case(self):
            for place in self.places:
                self.run_static(place)
                self.run_dygraph(place)

293
    cls_name = f"ArgMaxMinTestCase_{op_type}"
W
wawltor 已提交
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
    ArgMaxMinTestCase.__name__ = cls_name
    globals()[cls_name] = ArgMaxMinTestCase


for op_type in ['argmin', 'argmax']:
    create_test_case(op_type)


class TestArgMinMaxOpError(unittest.TestCase):
    def test_errors(self):
        paddle.enable_static()
        with program_guard(Program(), Program()):

            def test_argmax_x_type():
                x1 = [1, 2, 3]
                output = paddle.argmax(x=x1)

            self.assertRaises(TypeError, test_argmax_x_type)

            def test_argmin_x_type():
                x2 = [1, 2, 3]
                output = paddle.argmin(x=x2)

            self.assertRaises(TypeError, test_argmin_x_type)

            def test_argmax_attr_type():
320 321 322
                data = paddle.static.data(
                    name="test_argmax", shape=[10], dtype="float32"
                )
W
wawltor 已提交
323 324
                output = paddle.argmax(x=data, dtype="float32")

325
            self.assertRaises(TypeError, test_argmax_attr_type)
W
wawltor 已提交
326 327

            def test_argmin_attr_type():
328 329 330
                data = paddle.static.data(
                    name="test_argmax", shape=[10], dtype="float32"
                )
W
wawltor 已提交
331 332
                output = paddle.argmin(x=data, dtype="float32")

333 334 335
            self.assertRaises(TypeError, test_argmin_attr_type)

            def test_argmax_axis_type():
336 337 338
                data = paddle.static.data(
                    name="test_argmax", shape=[10], dtype="float32"
                )
339 340 341 342 343
                output = paddle.argmax(x=data, axis=1.2)

            self.assertRaises(TypeError, test_argmax_axis_type)

            def test_argmin_axis_type():
344 345 346
                data = paddle.static.data(
                    name="test_argmin", shape=[10], dtype="float32"
                )
347 348 349
                output = paddle.argmin(x=data, axis=1.2)

            self.assertRaises(TypeError, test_argmin_axis_type)
W
wawltor 已提交
350

351
            def test_argmax_dtype_type():
352 353 354
                data = paddle.static.data(
                    name="test_argmax", shape=[10], dtype="float32"
                )
355
                output = paddle.argmax(x=data, dtype=None)
356

357
            self.assertRaises(ValueError, test_argmax_dtype_type)
358 359

            def test_argmin_dtype_type():
360 361 362
                data = paddle.static.data(
                    name="test_argmin", shape=[10], dtype="float32"
                )
363
                output = paddle.argmin(x=data, dtype=None)
364

365
            self.assertRaises(ValueError, test_argmin_dtype_type)
366

W
wawltor 已提交
367

368 369 370 371 372 373 374 375 376 377 378 379 380
class TestArgMaxOpFp16(unittest.TestCase):
    def test_fp16(self):
        x_np = np.random.random((10, 16)).astype('float16')
        with paddle.static.program_guard(paddle.static.Program()):
            x = paddle.static.data(shape=[10, 16], name='x', dtype='float16')
            out = paddle.argmax(x)
            if core.is_compiled_with_cuda():
                place = paddle.CUDAPlace(0)
                exe = paddle.static.Executor(place)
                exe.run(paddle.static.default_startup_program())
                out = exe.run(feed={'x': x_np}, fetch_list=[out])


381 382 383 384 385 386 387 388 389 390 391 392 393
class TestArgMinOpFp16(unittest.TestCase):
    def test_fp16(self):
        x_np = np.random.random((10, 16)).astype('float16')
        with paddle.static.program_guard(paddle.static.Program()):
            x = paddle.static.data(shape=[10, 16], name='x', dtype='float16')
            out = paddle.argmin(x)
            if core.is_compiled_with_cuda():
                place = paddle.CUDAPlace(0)
                exe = paddle.static.Executor(place)
                exe.run(paddle.static.default_startup_program())
                out = exe.run(feed={'x': x_np}, fetch_list=[out])


W
wawltor 已提交
394 395
if __name__ == '__main__':
    unittest.main()