test_empty_op.py 9.9 KB
Newer Older
1
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
2 3 4 5 6 7 8 9 10 11 12 13 14 15
#
# 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

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

20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
import paddle
import paddle.fluid as fluid
from paddle.fluid.framework import convert_np_dtype_to_dtype_


# Situation 1: Attr(shape) is a list(without tensor)
class TestEmptyOp(OpTest):
    def setUp(self):
        self.op_type = "empty"
        self.init_config()

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

    def verify_output(self, outs):
        data_type = outs[0].dtype
        if data_type in ['float32', 'float64', 'int32', 'int64']:
            max_value = np.nanmax(outs[0])
            min_value = np.nanmin(outs[0])

            always_full_zero = max_value == 0.0 and min_value == 0.0
41
            always_non_full_zero = max_value >= min_value
42 43 44 45
            self.assertTrue(
                always_full_zero or always_non_full_zero,
                'always_full_zero or always_non_full_zero.',
            )
46 47
        elif data_type in ['bool']:
            total_num = outs[0].size
48 49
            true_num = np.sum(outs[0])
            false_num = np.sum(~outs[0])
50 51 52 53
            self.assertTrue(
                total_num == true_num + false_num,
                'The value should always be True or False.',
            )
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
        else:
            self.assertTrue(False, 'invalid data type')

    def init_config(self):
        shape = [500, 3]
        dtype = 'float32'
        dtype_inner = convert_np_dtype_to_dtype_(dtype)
        self.attrs = {'shape': shape, 'dtype': dtype_inner}
        self.inputs = {}
        self.outputs = {'Out': np.zeros(shape).astype(dtype)}


class TestEmptyOp2(TestEmptyOp):
    def init_config(self):
        shape = [500, 3]
        dtype = 'float64'
        dtype_inner = convert_np_dtype_to_dtype_(dtype)
        self.attrs = {'shape': shape, 'dtype': dtype_inner}
        self.inputs = {}
        self.outputs = {'Out': np.zeros(shape).astype(dtype)}


class TestEmptyOp3(TestEmptyOp):
    def init_config(self):
        shape = [500, 3]
        dtype = 'int32'
        dtype_inner = convert_np_dtype_to_dtype_(dtype)
        self.attrs = {'shape': shape, 'dtype': dtype_inner}
        self.inputs = {}
        self.outputs = {'Out': np.zeros(shape).astype(dtype)}


class TestEmptyOp4(TestEmptyOp):
    def init_config(self):
        shape = [500, 3]
        dtype = 'int64'
        dtype_inner = convert_np_dtype_to_dtype_(dtype)
        self.attrs = {'shape': shape, 'dtype': dtype_inner}
        self.inputs = {}
        self.outputs = {'Out': np.zeros(shape).astype(dtype)}


class TestEmptyOp5(TestEmptyOp):
    def init_config(self):
        shape = [500, 3]
        dtype = 'bool'
        dtype_inner = convert_np_dtype_to_dtype_(dtype)
        self.attrs = {'shape': shape, 'dtype': dtype_inner}
        self.inputs = {}
        self.outputs = {'Out': np.zeros(shape).astype(dtype)}


# Situation 2: shape is a tensor
class TestEmptyOp_ShapeTensor(OpTest):
    def setUp(self):
        self.op_type = "empty"
        self.init_config()

    def init_config(self):
        self.shape = [500, 3]
        dtype = 'float32'
        dtype_inner = convert_np_dtype_to_dtype_(dtype)
        self.attrs = {'dtype': dtype_inner}
        self.inputs = {"ShapeTensor": np.array(self.shape).astype("int32")}
        self.outputs = {'Out': np.zeros(self.shape).astype(dtype)}

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

    def verify_output(self, outs):
        data_type = outs[0].dtype
        if data_type in ['float32', 'float64', 'int32', 'int64']:
            max_value = np.nanmax(outs[0])
            min_value = np.nanmin(outs[0])

            always_full_zero = max_value == 0.0 and min_value == 0.0
130
            always_non_full_zero = max_value >= min_value
131 132 133 134
            self.assertTrue(
                always_full_zero or always_non_full_zero,
                'always_full_zero or always_non_full_zero.',
            )
135 136
        elif data_type in ['bool']:
            total_num = outs[0].size
137 138
            true_num = np.sum(outs[0])
            false_num = np.sum(~outs[0])
139 140 141 142
            self.assertTrue(
                total_num == true_num + false_num,
                'The value should always be True or False.',
            )
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
        else:
            self.assertTrue(False, 'invalid data type')


# Situation 3: Attr(shape) is a list(with tensor)
class TestEmptyOp_ShapeTensorList(OpTest):
    def setUp(self):
        self.op_type = "empty"
        self.init_config()

    def init_config(self):
        self.shape = [123, 92]
        self.infer_shape = [-1, 92]

        dtype = 'float32'
        dtype_inner = convert_np_dtype_to_dtype_(dtype)

        shape_tensor_list = []
        for index, ele in enumerate(self.shape):
162 163 164
            shape_tensor_list.append(
                ("x" + str(index), np.ones((1)).astype('int32') * ele)
            )
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179

        self.inputs = {"ShapeTensorList": shape_tensor_list}
        self.attrs = {'shape': self.infer_shape, 'dtype': dtype_inner}
        self.outputs = {'Out': np.zeros(self.shape).astype(dtype)}

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

    def verify_output(self, outs):
        data_type = outs[0].dtype
        if data_type in ['float32', 'float64', 'int32', 'int64']:
            max_value = np.nanmax(outs[0])
            min_value = np.nanmin(outs[0])

            always_full_zero = max_value == 0.0 and min_value == 0.0
180
            always_non_full_zero = max_value >= min_value
181 182 183 184
            self.assertTrue(
                always_full_zero or always_non_full_zero,
                'always_full_zero or always_non_full_zero.',
            )
185 186
        elif data_type in ['bool']:
            total_num = outs[0].size
187 188
            true_num = np.sum(outs[0])
            false_num = np.sum(~outs[0])
189 190 191 192
            self.assertTrue(
                total_num == true_num + false_num,
                'The value should always be True or False.',
            )
193 194 195 196 197 198 199 200
        else:
            self.assertTrue(False, 'invalid data type')


class TestEmptyAPI(unittest.TestCase):
    def __check_out__(self, out, dtype='float32'):
        max_value = np.nanmax(np.array(out))
        min_value = np.nanmin(np.array(out))
201
        always_non_full_zero = max_value >= min_value
202
        always_full_zero = max_value == 0.0 and min_value == 0.0
203 204 205 206
        self.assertTrue(
            always_full_zero or always_non_full_zero,
            'always_full_zero or always_non_full_zero.',
        )
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

    def test_dygraph_api_out(self):
        paddle.disable_static()
        shape = [200, 3]
        out = paddle.empty(shape=shape)
        self.__check_out__(out)
        paddle.enable_static()

    def test_dygraph_api_out_2(self):
        paddle.disable_static()
        shape_data = np.array([200, 3]).astype('int32')
        shape = paddle.to_tensor(shape_data)
        out = paddle.empty(shape=shape)
        self.__check_out__(out)
        paddle.enable_static()

    def test_dygraph_api_out_3(self):
        paddle.disable_static()
        shape_data = np.array([200, 3]).astype('int64')
        shape = paddle.to_tensor(shape_data)
        out = paddle.empty(shape=shape)
        self.__check_out__(out)
        paddle.enable_static()

    def test_dygraph_api_attr(self):
        paddle.disable_static()
        shape = [200, 3]
        dtype = 'float64'
        out = paddle.empty(shape=shape, dtype=dtype)
        self.__check_out__(out, dtype)
        paddle.enable_static()

    def test_static_graph(self):
        dtype = 'float64'

242 243
        positive_2_int32 = paddle.tensor.fill_constant([1], "int32", 3)
        positive_2_int64 = paddle.tensor.fill_constant([1], "int64", 3)
244

245 246 247 248 249 250 251 252 253
        shape_tensor_int32 = fluid.data(
            name="shape_tensor_int32", shape=[2], dtype="int32"
        )
        shape_tensor_int64 = fluid.data(
            name="shape_tensor_int64", shape=[2], dtype="int64"
        )
        shape_tensor_unknown = fluid.data(
            name="shape_tensor_unknown", shape=[-1], dtype="int64"
        )
254 255 256 257 258 259

        out_1 = paddle.empty(shape=[200, 3], dtype=dtype)
        out_2 = paddle.empty(shape=shape_tensor_int32, dtype=dtype)
        out_3 = paddle.empty(shape=shape_tensor_int64, dtype=dtype)
        out_4 = paddle.empty(shape=[200, positive_2_int32], dtype=dtype)
        out_5 = paddle.empty(shape=[200, positive_2_int64], dtype=dtype)
260
        out_6 = paddle.empty(shape=shape_tensor_unknown, dtype=dtype)
261 262 263

        place = paddle.CPUPlace()
        exe = paddle.static.Executor(place)
264
        res_1, res_2, res_3, res_4, res_5, res_6 = exe.run(
265 266 267 268
            fluid.default_main_program(),
            feed={
                "shape_tensor_int32": np.array([200, 3]).astype("int32"),
                "shape_tensor_int64": np.array([200, 3]).astype("int64"),
269
                "shape_tensor_unknown": np.array([200, 3]).astype("int64"),
270
            },
271 272
            fetch_list=[out_1, out_2, out_3, out_4, out_5, out_6],
        )
273 274 275 276 277 278

        self.__check_out__(res_1, dtype)
        self.__check_out__(res_2, dtype)
        self.__check_out__(res_3, dtype)
        self.__check_out__(res_4, dtype)
        self.__check_out__(res_5, dtype)
279
        self.__check_out__(res_6, dtype)
280 281 282 283 284 285 286 287 288 289 290 291 292 293


class TestEmptyError(unittest.TestCase):
    def test_attr(self):
        def test_dtype():
            shape = [200, 3]
            dtype = 'uint8'
            result = paddle.empty(shape=shape, dtype=dtype)

        self.assertRaises(TypeError, test_dtype)


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