test_randint_op.py 5.4 KB
Newer Older
S
silingtong123 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
# 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.

from __future__ import print_function

import unittest
import numpy as np
from op_test import OpTest
import paddle
21 22
from paddle.fluid import core
from paddle import Program, program_guard
S
silingtong123 已提交
23 24 25


def output_hist(out):
26
    hist, _ = np.histogram(out, range=(-10, 10))
S
silingtong123 已提交
27 28 29 30 31 32 33 34 35 36 37 38 39 40
    hist = hist.astype("float32")
    hist /= float(out.size)
    prob = 0.1 * np.ones((10))
    return hist, prob


class TestRandintOp(OpTest):
    def setUp(self):
        self.op_type = "randint"
        self.inputs = {}
        self.init_attrs()
        self.outputs = {"Out": np.zeros((10000, 784)).astype("float32")}

    def init_attrs(self):
41
        self.attrs = {"shape": [10000, 784], "low": -10, "high": 10, "seed": 10}
S
silingtong123 已提交
42 43 44 45 46 47 48 49 50
        self.output_hist = output_hist

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

    def verify_output(self, outs):
        hist, prob = self.output_hist(np.array(outs[0]))
        self.assertTrue(
            np.allclose(
51
                hist, prob, rtol=0, atol=0.001), "hist: " + str(hist))
S
silingtong123 已提交
52 53 54 55


class TestRandintOpError(unittest.TestCase):
    def test_errors(self):
56 57 58 59
        with program_guard(Program(), Program()):
            self.assertRaises(TypeError, paddle.randint, 5, shape=np.array([2]))
            self.assertRaises(TypeError, paddle.randint, 5, dtype='float32')
            self.assertRaises(ValueError, paddle.randint, 5, 5)
60
            self.assertRaises(ValueError, paddle.randint, -5)
S
silingtong123 已提交
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75


class TestRandintOp_attr_tensorlist(OpTest):
    def setUp(self):
        self.op_type = "randint"
        self.new_shape = (10000, 784)
        shape_tensor = []
        for index, ele in enumerate(self.new_shape):
            shape_tensor.append(("x" + str(index), np.ones(
                (1)).astype("int64") * ele))
        self.inputs = {'ShapeTensorList': shape_tensor}
        self.init_attrs()
        self.outputs = {"Out": np.zeros((10000, 784)).astype("int32")}

    def init_attrs(self):
76
        self.attrs = {"low": -10, "high": 10, "seed": 10}
S
silingtong123 已提交
77 78 79 80 81 82 83 84 85
        self.output_hist = output_hist

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

    def verify_output(self, outs):
        hist, prob = self.output_hist(np.array(outs[0]))
        self.assertTrue(
            np.allclose(
86
                hist, prob, rtol=0, atol=0.001), "hist: " + str(hist))
S
silingtong123 已提交
87 88 89 90 91 92 93 94 95 96


class TestRandint_attr_tensor(OpTest):
    def setUp(self):
        self.op_type = "randint"
        self.inputs = {"ShapeTensor": np.array([10000, 784]).astype("int64")}
        self.init_attrs()
        self.outputs = {"Out": np.zeros((10000, 784)).astype("int64")}

    def init_attrs(self):
97
        self.attrs = {"low": -10, "high": 10, "seed": 10}
S
silingtong123 已提交
98 99 100 101 102 103 104 105 106
        self.output_hist = output_hist

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

    def verify_output(self, outs):
        hist, prob = self.output_hist(np.array(outs[0]))
        self.assertTrue(
            np.allclose(
107
                hist, prob, rtol=0, atol=0.001), "hist: " + str(hist))
S
silingtong123 已提交
108 109 110 111 112


# Test python API
class TestRandintAPI(unittest.TestCase):
    def test_api(self):
113
        with program_guard(Program(), Program()):
S
silingtong123 已提交
114
            # results are from [0, 5).
115
            out1 = paddle.randint(5)
S
silingtong123 已提交
116
            # shape is a list and dtype is 'int32'
117
            out2 = paddle.randint(
S
silingtong123 已提交
118 119
                low=-100, high=100, shape=[64, 64], dtype='int32')
            # shape is a tuple and dtype is 'int64'
120
            out3 = paddle.randint(
S
silingtong123 已提交
121 122
                low=-100, high=100, shape=(32, 32, 3), dtype='int64')
            # shape is a tensorlist and dtype is 'float32'
123 124 125 126
            dim_1 = paddle.fill_constant([1], "int64", 32)
            dim_2 = paddle.fill_constant([1], "int32", 50)
            out4 = paddle.randint(
                low=-100, high=100, shape=[dim_1, 5, dim_2], dtype='int32')
S
silingtong123 已提交
127
            # shape is a tensor and dtype is 'float64'
128 129 130
            var_shape = paddle.nn.data(
                name='var_shape', shape=[2], dtype="int64")
            out5 = paddle.randint(
S
silingtong123 已提交
131 132
                low=1, high=1000, shape=var_shape, dtype='int64')

133 134 135
            place = paddle.CUDAPlace(0) if core.is_compiled_with_cuda(
            ) else paddle.CPUPlace()
            exe = paddle.Executor(place)
S
silingtong123 已提交
136 137
            outs = exe.run(
                feed={'var_shape': np.array([100, 100]).astype('int64')},
138
                fetch_list=[out1, out2, out3, out4, out5])
S
silingtong123 已提交
139 140


141 142 143 144 145 146 147 148 149 150
class TestRandintImperative(unittest.TestCase):
    def test_api(self):
        n = 10
        with paddle.imperative.guard():
            x1 = paddle.randint(n, shape=[10], dtype="int32")
            x2 = paddle.tensor.randint(n)
            x3 = paddle.tensor.random.randint(n)
            for i in [x1, x2, x3]:
                for j in i.numpy().tolist():
                    self.assertTrue((j >= 0 and j < n))
S
silingtong123 已提交
151 152 153 154


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