“523513b95bf92b9501e60e194408be13fa6d59ab”上不存在“git@gitcode.net:dcloud/unidocs-uni-app-x-zh.git”
test_fill_constant_op.py 15.9 KB
Newer Older
1
#   Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
D
dzhwinter 已提交
2
#
D
dzhwinter 已提交
3 4 5
# 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
D
dzhwinter 已提交
6
#
D
dzhwinter 已提交
7
#     http://www.apache.org/licenses/LICENSE-2.0
D
dzhwinter 已提交
8
#
D
dzhwinter 已提交
9 10 11 12 13 14
# 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.

15
import unittest
16

17
import numpy as np
18
from eager_op_test import OpTest, convert_float_to_uint16
19

20
import paddle
21
import paddle.fluid as fluid
22
import paddle.fluid.core as core
23
from paddle.fluid import Program, program_guard
24
from paddle.fluid.op import Operator
T
tangwei12 已提交
25

26

27 28 29 30 31
def fill_wrapper(shape, value=0.0):
    out = paddle.full(shape=shape, fill_value=value)
    return out


L
liym27 已提交
32
# Situation 1: Attr(shape) is a list(without tensor)
33 34
class TestFillConstantOp1(OpTest):
    def setUp(self):
35
        '''Test fill_constant op with specified value'''
36
        self.op_type = "fill_constant"
37
        self.python_api = fill_wrapper
38 39 40 41 42 43 44 45 46 47 48

        self.inputs = {}
        self.attrs = {'shape': [123, 92], 'value': 3.8}
        self.outputs = {'Out': np.full((123, 92), 3.8)}

    def test_check_output(self):
        self.check_output()


class TestFillConstantOp2(OpTest):
    def setUp(self):
49
        '''Test fill_constant op with default value'''
50
        self.op_type = "fill_constant"
51
        self.python_api = fill_wrapper
52 53 54 55 56 57 58 59 60

        self.inputs = {}
        self.attrs = {'shape': [123, 92]}
        self.outputs = {'Out': np.full((123, 92), 0.0)}

    def test_check_output(self):
        self.check_output()


61 62
class TestFillConstantOp3(OpTest):
    def setUp(self):
63
        '''Test fill_constant op with specified int64 value'''
64
        self.op_type = "fill_constant"
65
        self.python_api = fill_wrapper
66 67 68 69 70 71 72 73 74 75 76

        self.inputs = {}
        self.attrs = {'shape': [123, 92], 'value': 10000000000}
        self.outputs = {'Out': np.full((123, 92), 10000000000)}

    def test_check_output(self):
        self.check_output()


class TestFillConstantOp4(OpTest):
    def setUp(self):
77
        '''Test fill_constant op with specified int value'''
78
        self.op_type = "fill_constant"
79
        self.python_api = fill_wrapper
80 81 82 83 84 85 86 87 88

        self.inputs = {}
        self.attrs = {'shape': [123, 92], 'value': 3}
        self.outputs = {'Out': np.full((123, 92), 3)}

    def test_check_output(self):
        self.check_output()


89 90 91
@unittest.skipIf(
    not core.is_compiled_with_cuda(), "core is not compiled with CUDA"
)
92 93
class TestFillConstantBF16Op(OpTest):
    def setUp(self):
94
        '''Test fill_constant op with specified value'''
95
        self.op_type = "fill_constant"
96
        self.python_api = fill_wrapper
97 98 99 100 101
        self.dtype = np.uint16
        self.inputs = {}
        self.attrs = {
            'shape': [123, 92],
            'value': 3.8,
102
            'dtype': core.VarDesc.VarType.BF16,
103 104 105 106 107 108 109 110
        }
        self.outputs = {'Out': convert_float_to_uint16(np.full((123, 92), 3.8))}

    def test_check_output(self):
        place = core.CUDAPlace(0)
        self.check_output_with_place(place)


111
class TestFillConstantOpWithSelectedRows(unittest.TestCase):
T
tangwei12 已提交
112 113 114 115 116 117
    def check_with_place(self, place):
        scope = core.Scope()
        # create Out Variable
        out = scope.var('Out').get_selected_rows()

        # create and run fill_constant_op operator
118 119 120
        fill_constant_op = Operator(
            "fill_constant", shape=[123, 92], value=3.8, Out='Out'
        )
T
tangwei12 已提交
121 122 123
        fill_constant_op.run(scope, place)

        # get result from Out
T
tangwei12 已提交
124 125 126
        result_array = np.array(out.get_tensor())
        full_array = np.full((123, 92), 3.8, 'float32')

127
        np.testing.assert_array_equal(result_array, full_array)
T
tangwei12 已提交
128 129 130

    def test_fill_constant_with_selected_rows(self):
        places = [core.CPUPlace()]
T
tangwei12 已提交
131 132 133
        if core.is_compiled_with_cuda():
            places.append(core.CUDAPlace(0))

T
tangwei12 已提交
134 135 136 137
        for place in places:
            self.check_with_place(place)


L
liym27 已提交
138 139 140
# Situation 2: Attr(shape) is a list(with tensor)
class TestFillConstantOp1_ShapeTensorList(OpTest):
    def setUp(self):
141
        '''Test fill_constant op with specified value'''
L
liym27 已提交
142
        self.op_type = "fill_constant"
143
        self.python_api = fill_wrapper
L
liym27 已提交
144 145 146
        self.init_data()
        shape_tensor_list = []
        for index, ele in enumerate(self.shape):
147 148 149
            shape_tensor_list.append(
                ("x" + str(index), np.ones((1)).astype('int32') * ele)
            )
L
liym27 已提交
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165

        self.inputs = {"ShapeTensorList": shape_tensor_list}
        self.attrs = {'shape': self.infer_shape, 'value': self.value}
        self.outputs = {'Out': np.full(self.shape, self.value)}

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

    def test_check_output(self):
        self.check_output()


class TestFillConstantOp2_ShapeTensorList(OpTest):
    def setUp(self):
166
        '''Test fill_constant op with default value'''
L
liym27 已提交
167
        self.op_type = "fill_constant"
168
        self.python_api = fill_wrapper
L
liym27 已提交
169 170 171
        self.init_data()
        shape_tensor_list = []
        for index, ele in enumerate(self.shape):
172 173 174
            shape_tensor_list.append(
                ("x" + str(index), np.ones((1)).astype('int32') * ele)
            )
L
liym27 已提交
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204

        self.inputs = {"ShapeTensorList": shape_tensor_list}
        self.attrs = {'shape': self.infer_shape}
        self.outputs = {'Out': np.full(self.shape, 0.0)}

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

    def test_check_output(self):
        self.check_output()


class TestFillConstantOp3_ShapeTensorList(TestFillConstantOp1_ShapeTensorList):
    def init_data(self):
        self.shape = [123, 92]
        self.infer_shape = [123, -1]
        self.value = 10000000000


class TestFillConstantOp4_ShapeTensorList(TestFillConstantOp1_ShapeTensorList):
    def init_data(self):
        self.shape = [123, 92]
        self.infer_shape = [123, -1]
        self.value = 3


# Situation 3: shape is a tensor
class TestFillConstantOp1_ShapeTensor(OpTest):
    def setUp(self):
205
        '''Test fill_constant op with specified value'''
L
liym27 已提交
206
        self.op_type = "fill_constant"
207
        self.python_api = fill_wrapper
L
liym27 已提交
208 209 210 211 212 213 214 215 216 217 218 219 220 221
        self.init_data()

        self.inputs = {"ShapeTensor": np.array(self.shape).astype("int32")}
        self.attrs = {'value': self.value}
        self.outputs = {'Out': np.full(self.shape, self.value)}

    def init_data(self):
        self.shape = [123, 92]
        self.value = 3.8

    def test_check_output(self):
        self.check_output()


W
wangchaochaohu 已提交
222 223 224
# Situation 4: value is a tensor
class TestFillConstantOp1_ValueTensor(OpTest):
    def setUp(self):
225
        '''Test fill_constant op with specified value'''
W
wangchaochaohu 已提交
226
        self.op_type = "fill_constant"
227
        self.python_api = fill_wrapper
W
wangchaochaohu 已提交
228 229 230 231
        self.init_data()

        self.inputs = {
            "ShapeTensor": np.array(self.shape).astype("int32"),
232
            'ValueTensor': np.array([self.value]).astype("float32"),
W
wangchaochaohu 已提交
233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
        }
        self.attrs = {'value': self.value + 1.0}
        self.outputs = {'Out': np.full(self.shape, self.value)}

    def init_data(self):
        self.shape = [123, 92]
        self.value = 3.8
        self.dtype = np.float32

    def test_check_output(self):
        self.check_output()


# Situation 5: value is a tensor
class TestFillConstantOp2_ValueTensor(OpTest):
    def setUp(self):
249
        '''Test fill_constant op with specified value'''
W
wangchaochaohu 已提交
250
        self.op_type = "fill_constant"
251
        self.python_api = fill_wrapper
W
wangchaochaohu 已提交
252 253 254 255
        self.init_data()

        self.inputs = {
            "ShapeTensor": np.array(self.shape).astype("int32"),
256
            'ValueTensor': np.array([self.value]).astype("int32"),
W
wangchaochaohu 已提交
257 258 259 260 261 262 263 264 265 266 267 268 269
        }
        self.attrs = {'value': self.value, 'dtype': 2}
        self.outputs = {'Out': np.full(self.shape, self.value)}

    def init_data(self):
        self.shape = [123, 92]
        self.value = 3
        self.dtype = np.int32

    def test_check_output(self):
        self.check_output()


270
# Test python API
271
class TestFillConstantAPI(unittest.TestCase):
L
liym27 已提交
272
    def test_api(self):
273

274
        positive_2_int32 = fluid.layers.fill_constant([1], "int32", 2)
275
        positive_2_int64 = fluid.layers.fill_constant([1], "int64", 2)
276

277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 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 320
        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"
        )

        out_1 = fluid.layers.fill_constant(
            shape=[1, 2], dtype="float32", value=1.1
        )

        out_2 = fluid.layers.fill_constant(
            shape=[1, positive_2_int32], dtype="float32", value=1.1
        )

        out_3 = fluid.layers.fill_constant(
            shape=[1, positive_2_int64], dtype="float32", value=1.1
        )

        out_4 = fluid.layers.fill_constant(
            shape=shape_tensor_int32, dtype="float32", value=1.1
        )

        out_5 = fluid.layers.fill_constant(
            shape=shape_tensor_int64, dtype="float32", value=1.1
        )

        out_6 = fluid.layers.fill_constant(
            shape=shape_tensor_int64, dtype=np.float32, value=1.1
        )

        val1 = fluid.layers.fill_constant(
            shape=[1], dtype=np.float32, value=1.1
        )
        val2 = fluid.layers.fill_constant(
            shape=[1], dtype=np.float64, value=1.1
        )
        out_7 = fluid.layers.fill_constant(
            shape=shape_tensor_int64, dtype=np.float32, value=val1
        )

        out_8 = fluid.layers.fill_constant(
            shape=shape_tensor_int64, dtype=np.float32, value=val2
        )
W
wangchaochaohu 已提交
321

L
liym27 已提交
322
        exe = fluid.Executor(place=fluid.CPUPlace())
323
        res_1, res_2, res_3, res_4, res_5, res_6, res_7, res_8 = exe.run(
L
liym27 已提交
324
            fluid.default_main_program(),
325 326 327 328
            feed={
                "shape_tensor_int32": np.array([1, 2]).astype("int32"),
                "shape_tensor_int64": np.array([1, 2]).astype("int64"),
            },
329 330
            fetch_list=[out_1, out_2, out_3, out_4, out_5, out_6, out_7, out_8],
        )
L
liym27 已提交
331 332 333 334

        assert np.array_equal(res_1, np.full([1, 2], 1.1, dtype="float32"))
        assert np.array_equal(res_2, np.full([1, 2], 1.1, dtype="float32"))
        assert np.array_equal(res_3, np.full([1, 2], 1.1, dtype="float32"))
335 336
        assert np.array_equal(res_4, np.full([1, 2], 1.1, dtype="float32"))
        assert np.array_equal(res_5, np.full([1, 2], 1.1, dtype="float32"))
337
        assert np.array_equal(res_6, np.full([1, 2], 1.1, dtype="float32"))
W
wangchaochaohu 已提交
338
        assert np.array_equal(res_7, np.full([1, 2], 1.1, dtype="float32"))
339 340 341 342 343 344 345 346
        assert np.array_equal(res_8, np.full([1, 2], 1.1, dtype="float32"))


class TestFillConstantImperative(unittest.TestCase):
    def test_api(self):
        with fluid.dygraph.guard():
            data1 = np.array([1, 2]).astype('int32')
            data2 = np.array([1.1]).astype('float32')
347
            data3 = np.array([88]).astype('int32')
348 349
            shape = fluid.dygraph.to_variable(data1)
            val = fluid.dygraph.to_variable(data2)
350
            value = fluid.dygraph.to_variable(data3)
351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374
            res1 = fluid.layers.fill_constant(
                shape=[1, 2], dtype='float32', value=1.1
            )
            res2 = fluid.layers.fill_constant(
                shape=shape, dtype='float32', value=1.1
            )
            res3 = fluid.layers.fill_constant(
                shape=shape, dtype='float32', value=val
            )
            res4 = fluid.layers.fill_constant(
                shape=shape, dtype='int32', value=value
            )
            assert np.array_equal(
                res1.numpy(), np.full([1, 2], 1.1, dtype="float32")
            )
            assert np.array_equal(
                res2.numpy(), np.full([1, 2], 1.1, dtype="float32")
            )
            assert np.array_equal(
                res3.numpy(), np.full([1, 2], 1.1, dtype="float32")
            )
            assert np.array_equal(
                res4.numpy(), np.full([1, 2], 88, dtype="int32")
            )
L
liym27 已提交
375

376 377 378 379 380 381 382 383 384 385
    def test_nan(self):
        with fluid.dygraph.guard():
            res = fluid.layers.fill_constant([1], 'float32', np.nan)
            self.assertTrue(np.isnan(res.numpy().item(0)))

    def test_inf(self):
        with fluid.dygraph.guard():
            res = fluid.layers.fill_constant([1], 'float32', np.inf)
            self.assertTrue(np.isinf(res.numpy().item(0)))

L
Leo Chen 已提交
386 387 388 389 390 391
    def test_ninf(self):
        with fluid.dygraph.guard():
            res = fluid.layers.fill_constant([1], 'float32', np.NINF)
            self.assertTrue(np.isinf(res.numpy().item(0)))
            self.assertEqual(np.NINF, res.numpy().item(0))

L
liym27 已提交
392

393
class TestFillConstantOpError(unittest.TestCase):
394 395
    def test_errors(self):
        with program_guard(Program(), Program()):
396
            # for ci coverage
G
GGBond8488 已提交
397
            x1 = paddle.static.data(name='x1', shape=[-1, 1], dtype="int16")
398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413
            self.assertRaises(
                TypeError,
                fluid.layers.fill_constant,
                shape=[1],
                value=5,
                dtype='uint4',
            )

            self.assertRaises(
                TypeError,
                fluid.layers.fill_constant,
                shape=[1.1],
                value=5,
                dtype='float32',
                out=x1,
            )
414

415
            # The argument dtype of fill_constant_op must be one of bool, float16,
416
            # float32, float64, uint8, int16, int32 or int64
G
GGBond8488 已提交
417
            x2 = paddle.static.data(name='x2', shape=[-1, 1], dtype="int32")
L
liym27 已提交
418

419 420 421 422 423 424 425 426
            self.assertRaises(
                TypeError,
                fluid.layers.fill_constant,
                shape=[1],
                value=5,
                dtype='float64',
                out=x2,
            )
427

428
            x3 = np.random.randn(100, 100).astype('int32')
429 430 431 432 433 434 435 436
            self.assertRaises(
                TypeError,
                fluid.layers.fill_constant,
                shape=[100, 100],
                value=5,
                dtype='float64',
                out=x3,
            )
437

438
            # The argument shape's type of fill_constant_op must be list, tuple or Variable.
L
liym27 已提交
439 440 441 442 443
            def test_shape_type():
                fluid.layers.fill_constant(shape=1, dtype="float32", value=1)

            self.assertRaises(TypeError, test_shape_type)

444 445
            # The shape dtype of fill_constant_op must be int32 or int64.
            def test_shape_tensor_dtype():
446 447 448 449 450 451
                shape = fluid.data(
                    name="shape_tensor", shape=[2], dtype="float32"
                )
                fluid.layers.fill_constant(
                    shape=shape, dtype="float32", value=1
                )
452 453 454 455

            self.assertRaises(TypeError, test_shape_tensor_dtype)

            def test_shape_tensor_list_dtype():
456 457 458 459 460 461
                shape = fluid.data(
                    name="shape_tensor_list", shape=[1], dtype="bool"
                )
                fluid.layers.fill_constant(
                    shape=[shape, 2], dtype="float32", value=1
                )
462 463 464

            self.assertRaises(TypeError, test_shape_tensor_list_dtype)

465

466 467
class TestFillConstantOp_ValueTensorBf16(OpTest):
    def setUp(self):
468
        '''Test fill_constant op with specified value'''
469
        self.op_type = "fill_constant"
470
        self.python_api = fill_wrapper
471 472 473
        self.init_data()

        self.inputs = {
474 475 476 477
            "ShapeTensor": np.array(self.shape).astype("int32"),
            'ValueTensor': convert_float_to_uint16(
                np.array([self.value]).astype("float32")
            ),
478 479 480 481 482 483 484 485 486 487 488
        }
        self.attrs = {'value': self.value, 'dtype': core.VarDesc.VarType.BF16}
        self.outputs = {'Out': np.full(self.shape, self.value)}

    def init_data(self):
        self.shape = [123, 92]
        self.value = 3.0
        self.dtype = np.uint16
        self.mkldnn_data_type = "bfloat16"

    def test_check_output(self):
489 490
        # no dynamic graph test for mkldnn
        self.check_output_with_place(core.CPUPlace(), check_dygraph=False)
491 492


493
if __name__ == "__main__":
494
    paddle.enable_static()
495
    unittest.main()