test_randperm_op.py 9.7 KB
Newer Older
C
cc 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#   Copyright (c) 2020 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

C
cc 已提交
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

C
cc 已提交
24
import paddle
25
from paddle.fluid import core
26
from paddle.static import Program, program_guard
C
cc 已提交
27 28 29


def check_randperm_out(n, data_np):
30 31 32
    assert isinstance(
        data_np, np.ndarray
    ), "The input data_np should be np.ndarray."
C
cc 已提交
33 34 35 36 37 38
    gt_sorted = np.arange(n)
    out_sorted = np.sort(data_np)
    return list(gt_sorted == out_sorted)


def error_msg(data_np):
39 40 41 42 43
    return (
        "The sorted ground truth and sorted out should "
        + "be equal, out = "
        + str(data_np)
    )
C
cc 已提交
44 45 46


def convert_dtype(dtype_str):
47 48 49 50 51 52 53 54
    dtype_str_list = [
        "int32",
        "int64",
        "float16",
        "float32",
        "float64",
        "uint16",
    ]
55
    dtype_num_list = [
56 57
        core.VarDesc.VarType.INT32,
        core.VarDesc.VarType.INT64,
58
        core.VarDesc.VarType.FP16,
59 60
        core.VarDesc.VarType.FP32,
        core.VarDesc.VarType.FP64,
61
        core.VarDesc.VarType.BF16,
62
    ]
63 64 65
    assert dtype_str in dtype_str_list, (
        dtype_str + " should in " + str(dtype_str_list)
    )
C
cc 已提交
66 67 68 69
    return dtype_num_list[dtype_str_list.index(dtype_str)]


class TestRandpermOp(OpTest):
70
    """Test randperm op."""
C
cc 已提交
71 72 73

    def setUp(self):
        self.op_type = "randperm"
Z
zyfncg 已提交
74
        self.python_api = paddle.randperm
C
cc 已提交
75 76 77
        self.n = 200
        self.dtype = "int64"

78
        self.init_attrs()
C
cc 已提交
79
        self.inputs = {}
80
        self.outputs = {"Out": np.zeros(self.n).astype(self.dtype)}
C
cc 已提交
81 82 83 84 85 86 87 88 89 90 91 92 93
        self.attrs = {
            "n": self.n,
            "dtype": convert_dtype(self.dtype),
        }

    def init_attrs(self):
        pass

    def test_check_output(self):
        self.check_output_customized(self.verify_output)

    def verify_output(self, outs):
        out_np = np.array(outs[0])
94 95 96
        self.assertTrue(
            check_randperm_out(self.n, out_np), msg=error_msg(out_np)
        )
C
cc 已提交
97 98


99
class TestRandpermOpN(TestRandpermOp):
C
cc 已提交
100 101 102 103
    def init_attrs(self):
        self.n = 10000


104
class TestRandpermOpInt32(TestRandpermOp):
C
cc 已提交
105 106 107 108
    def init_attrs(self):
        self.dtype = "int32"


109
class TestRandpermOpFloat32(TestRandpermOp):
C
cc 已提交
110
    def init_attrs(self):
111
        self.dtype = "float32"
C
cc 已提交
112 113


114
class TestRandpermOpFloat64(TestRandpermOp):
C
cc 已提交
115
    def init_attrs(self):
116
        self.dtype = "float64"
C
cc 已提交
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
class TestRandpermFP16Op(TestRandpermOp):
    def init_attrs(self):
        self.dtype = "float16"


@unittest.skipIf(
    not core.is_compiled_with_cuda()
    or not core.is_bfloat16_supported(core.CUDAPlace(0)),
    "core is not compiled with CUDA or not support bfloat16",
)
class TestRandpermBF16Op(OpTest):
    def setUp(self):
        self.op_type = "randperm"
        self.python_api = paddle.randperm
        self.n = 200

        self.init_attrs()
        self.inputs = {}
        self.outputs = {"Out": np.zeros(self.n).astype(self.np_dtype)}
        self.attrs = {
            "n": self.n,
            "dtype": convert_dtype(self.dtype),
        }

        self.outputs['Out'] = convert_float_to_uint16(self.outputs['Out'])
        self.place = core.CUDAPlace(0)

    def init_attrs(self):
        self.dtype = "uint16"
        self.np_dtype = np.float32

    def test_check_output(self):
        self.check_output_with_place_customized(self.verify_output, self.place)

    def verify_output(self, outs):
        out_np = convert_uint16_to_float(np.array(outs[0]))
        self.assertTrue(
            check_randperm_out(self.n, out_np), msg=error_msg(out_np)
        )


C
cc 已提交
160 161
class TestRandpermOpError(unittest.TestCase):
    def test_errors(self):
162 163 164
        with program_guard(Program(), Program()):
            self.assertRaises(ValueError, paddle.randperm, -3)
            self.assertRaises(TypeError, paddle.randperm, 10, 'int8')
C
cc 已提交
165 166


167 168 169
class TestRandpermAPI(unittest.TestCase):
    def test_out(self):
        n = 10
170 171 172 173 174
        place = (
            paddle.CUDAPlace(0)
            if core.is_compiled_with_cuda()
            else paddle.CPUPlace()
        )
175 176 177
        with program_guard(Program(), Program()):
            x1 = paddle.randperm(n)
            x2 = paddle.randperm(n, 'float32')
C
cc 已提交
178

179
            exe = paddle.static.Executor(place)
180
            res = exe.run(fetch_list=[x1, x2])
C
cc 已提交
181

182 183 184 185
            self.assertEqual(res[0].dtype, np.int64)
            self.assertEqual(res[1].dtype, np.float32)
            self.assertTrue(check_randperm_out(n, res[0]))
            self.assertTrue(check_randperm_out(n, res[1]))
C
cc 已提交
186 187


188 189
class TestRandpermImperative(unittest.TestCase):
    def test_out(self):
190 191 192 193 194
        paddle.disable_static()
        n = 10
        for dtype in ['int32', np.int64, 'float32', 'float64']:
            data_p = paddle.randperm(n, dtype)
            data_np = data_p.numpy()
195 196 197
            self.assertTrue(
                check_randperm_out(n, data_np), msg=error_msg(data_np)
            )
198
        paddle.enable_static()
C
cc 已提交
199 200


Z
zyfncg 已提交
201 202 203 204
class TestRandpermEager(unittest.TestCase):
    def test_out(self):
        paddle.disable_static()
        n = 10
205 206 207 208 209 210
        for dtype in ['int32', np.int64, 'float32', 'float64']:
            data_p = paddle.randperm(n, dtype)
            data_np = data_p.numpy()
            self.assertTrue(
                check_randperm_out(n, data_np), msg=error_msg(data_np)
            )
Z
zyfncg 已提交
211 212 213
        paddle.enable_static()


214 215 216 217 218 219 220 221 222 223 224 225 226
class TestRandomValue(unittest.TestCase):
    def test_fixed_random_number(self):
        # Test GPU Fixed random number, which is generated by 'curandStatePhilox4_32_10_t'
        if not paddle.is_compiled_with_cuda():
            return

        print("Test Fixed Random number on GPU------>")
        paddle.disable_static()
        paddle.set_device('gpu')
        paddle.seed(2021)

        x = paddle.randperm(30000, dtype='int32').numpy()
        expect = [
227 228 229 230 231 232 233 234 235 236
            24562,
            8409,
            9379,
            10328,
            20503,
            18059,
            9681,
            21883,
            11783,
            27413,
237
        ]
238
        np.testing.assert_array_equal(x[0:10], expect)
239
        expect = [
240 241 242 243 244 245 246 247 248 249
            29477,
            27100,
            9643,
            16637,
            8605,
            16892,
            27767,
            2724,
            1612,
            13096,
250
        ]
251
        np.testing.assert_array_equal(x[10000:10010], expect)
252
        expect = [
253 254 255 256 257 258 259 260 261 262
            298,
            4104,
            16479,
            22714,
            28684,
            7510,
            14667,
            9950,
            15940,
            28343,
263
        ]
264
        np.testing.assert_array_equal(x[20000:20010], expect)
265 266 267

        x = paddle.randperm(30000, dtype='int64').numpy()
        expect = [
268 269 270 271 272 273 274 275 276 277
            6587,
            1909,
            5525,
            23001,
            6488,
            14981,
            14355,
            3083,
            29561,
            8171,
278
        ]
279
        np.testing.assert_array_equal(x[0:10], expect)
280
        expect = [
281 282 283 284 285 286 287 288 289 290
            23460,
            12394,
            22501,
            5427,
            20185,
            9100,
            5127,
            1651,
            25806,
            4818,
291
        ]
292
        np.testing.assert_array_equal(x[10000:10010], expect)
293
        expect = [5829, 4508, 16193, 24836, 8526, 242, 9984, 9243, 1977, 11839]
294
        np.testing.assert_array_equal(x[20000:20010], expect)
295 296 297

        x = paddle.randperm(30000, dtype='float32').numpy()
        expect = [
298 299 300 301 302 303 304 305 306 307
            5154.0,
            10537.0,
            14362.0,
            29843.0,
            27185.0,
            28399.0,
            27561.0,
            4144.0,
            22906.0,
            10705.0,
308
        ]
309
        np.testing.assert_array_equal(x[0:10], expect)
310
        expect = [
311 312 313 314 315 316 317 318 319 320
            1958.0,
            18414.0,
            20090.0,
            21910.0,
            22746.0,
            27346.0,
            22347.0,
            3002.0,
            4564.0,
            26991.0,
321
        ]
322
        np.testing.assert_array_equal(x[10000:10010], expect)
323
        expect = [
324 325 326 327 328 329 330 331 332 333
            25580.0,
            12606.0,
            553.0,
            16387.0,
            29536.0,
            4241.0,
            20946.0,
            16899.0,
            16339.0,
            4662.0,
334
        ]
335
        np.testing.assert_array_equal(x[20000:20010], expect)
336 337 338

        x = paddle.randperm(30000, dtype='float64').numpy()
        expect = [
339 340 341 342 343 344 345 346 347 348
            19051.0,
            2449.0,
            21940.0,
            11121.0,
            282.0,
            7330.0,
            13747.0,
            24321.0,
            21147.0,
            9163.0,
349
        ]
350
        np.testing.assert_array_equal(x[0:10], expect)
351
        expect = [
352 353 354 355 356 357 358 359 360 361
            15483.0,
            1315.0,
            5723.0,
            20954.0,
            13251.0,
            25539.0,
            5074.0,
            1823.0,
            14945.0,
            17624.0,
362
        ]
363
        np.testing.assert_array_equal(x[10000:10010], expect)
364
        expect = [
365 366 367 368 369 370 371 372 373 374
            10516.0,
            2552.0,
            29970.0,
            5941.0,
            986.0,
            8007.0,
            24805.0,
            26753.0,
            12202.0,
            21404.0,
375
        ]
376
        np.testing.assert_array_equal(x[20000:20010], expect)
377 378 379
        paddle.enable_static()


C
cc 已提交
380 381
if __name__ == "__main__":
    unittest.main()