test_randperm_op.py 3.9 KB
Newer Older
C
cc 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#   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
import numpy as np
from op_test import OpTest
import paddle
import paddle.fluid.core as core
20
from paddle import Program, program_guard
C
cc 已提交
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36


def check_randperm_out(n, data_np):
    assert isinstance(data_np, np.ndarray), \
        "The input data_np should be np.ndarray."
    gt_sorted = np.arange(n)
    out_sorted = np.sort(data_np)
    return list(gt_sorted == out_sorted)


def error_msg(data_np):
    return "The sorted ground truth and sorted out should " + \
 "be equal, out = " + str(data_np)


def convert_dtype(dtype_str):
37 38 39 40 41
    dtype_str_list = ["int32", "int64", "float32", "float64"]
    dtype_num_list = [
        core.VarDesc.VarType.INT32, core.VarDesc.VarType.INT64,
        core.VarDesc.VarType.FP32, core.VarDesc.VarType.FP64
    ]
C
cc 已提交
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
    assert dtype_str in dtype_str_list, dtype_str + \
        " should in " + str(dtype_str_list)
    return dtype_num_list[dtype_str_list.index(dtype_str)]


class TestRandpermOp(OpTest):
    """ Test randperm op."""

    def setUp(self):
        self.op_type = "randperm"
        self.n = 200
        self.dtype = "int64"

        self.inputs = {}
        self.outputs = {"Out": np.zeros((self.n)).astype(self.dtype)}
        self.init_attrs()
        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])
        self.assertTrue(
            check_randperm_out(self.n, out_np), msg=error_msg(out_np))


75
class TestRandpermOpN(TestRandpermOp):
C
cc 已提交
76 77 78 79
    def init_attrs(self):
        self.n = 10000


80
class TestRandpermOpInt32(TestRandpermOp):
C
cc 已提交
81 82 83 84
    def init_attrs(self):
        self.dtype = "int32"


85
class TestRandpermOpFloat32(TestRandpermOp):
C
cc 已提交
86
    def init_attrs(self):
87
        self.dtype = "float32"
C
cc 已提交
88 89


90
class TestRandpermOpFloat64(TestRandpermOp):
C
cc 已提交
91
    def init_attrs(self):
92
        self.dtype = "float64"
C
cc 已提交
93 94 95 96


class TestRandpermOpError(unittest.TestCase):
    def test_errors(self):
97 98 99
        with program_guard(Program(), Program()):
            self.assertRaises(ValueError, paddle.randperm, -3)
            self.assertRaises(TypeError, paddle.randperm, 10, 'int8')
C
cc 已提交
100 101


102 103 104 105 106 107 108 109
class TestRandpermAPI(unittest.TestCase):
    def test_out(self):
        n = 10
        place = paddle.CUDAPlace(0) if core.is_compiled_with_cuda(
        ) else paddle.CPUPlace()
        with program_guard(Program(), Program()):
            x1 = paddle.randperm(n)
            x2 = paddle.randperm(n, 'float32')
C
cc 已提交
110

111 112
            exe = paddle.Executor(place)
            res = exe.run(fetch_list=[x1, x2])
C
cc 已提交
113

114 115 116 117
            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 已提交
118 119


120 121 122
class TestRandpermImperative(unittest.TestCase):
    def test_out(self):
        with paddle.imperative.guard():
C
cc 已提交
123
            n = 10
124 125 126 127 128
            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))
C
cc 已提交
129 130 131 132


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