test_fill_constant_op.py 16.4 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 16
from __future__ import print_function

17 18
import unittest
import numpy as np
19
from op_test import OpTest
20

21
import paddle
T
tangwei12 已提交
22 23
import paddle.fluid.core as core
from paddle.fluid.op import Operator
24 25
import paddle.fluid as fluid
from paddle.fluid import compiler, Program, program_guard
26
import numpy as np
T
tangwei12 已提交
27

28

L
liym27 已提交
29
# Situation 1: Attr(shape) is a list(without tensor)
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
class TestFillConstantOp1(OpTest):
    def setUp(self):
        '''Test fill_constant op with specified value
        '''
        self.op_type = "fill_constant"

        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):
        '''Test fill_constant op with default value
        '''
        self.op_type = "fill_constant"

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

    def test_check_output(self):
        self.check_output()


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
class TestFillConstantOp3(OpTest):
    def setUp(self):
        '''Test fill_constant op with specified int64 value
        '''
        self.op_type = "fill_constant"

        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):
        '''Test fill_constant op with specified int value
        '''
        self.op_type = "fill_constant"

        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()


86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
class TestFillConstantOp5(unittest.TestCase):
    def test_errors(self):
        with fluid.program_guard(fluid.Program()):
            data = fluid.data(name="X", shape=[1], dtype="float32")
            out = paddle.zeros(shape=[1], out=data, dtype="float32")
            place = fluid.CPUPlace()
            exe = fluid.Executor(place)
            result = exe.run(feed={"X": np.array(
                [0.1], dtype="float32")},
                             fetch_list=[data, out])
            self.assertEqual(result[0], result[1])
        with fluid.program_guard(fluid.Program()):
            data = fluid.data(name="X", shape=[1], dtype="float32")
            out = paddle.ones(shape=[1], out=data, dtype="float32")
            place = fluid.CPUPlace()
            exe = fluid.Executor(place)
            result = exe.run(feed={"X": np.array(
                [0.1], dtype="float32")},
                             fetch_list=[data, out])
            self.assertEqual(result[0], result[1])


108
class TestFillConstantOpWithSelectedRows(unittest.TestCase):
T
tangwei12 已提交
109 110 111 112 113 114 115 116 117 118 119
    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
        fill_constant_op = Operator(
            "fill_constant", shape=[123, 92], value=3.8, Out='Out')
        fill_constant_op.run(scope, place)

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

        self.assertTrue(np.array_equal(result_array, full_array))
T
tangwei12 已提交
124 125 126

    def test_fill_constant_with_selected_rows(self):
        places = [core.CPUPlace()]
T
tangwei12 已提交
127 128 129
        if core.is_compiled_with_cuda():
            places.append(core.CUDAPlace(0))

T
tangwei12 已提交
130 131 132 133
        for place in places:
            self.check_with_place(place)


L
liym27 已提交
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 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 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 205 206 207 208 209 210 211 212 213 214 215
# Situation 2: Attr(shape) is a list(with tensor)
class TestFillConstantOp1_ShapeTensorList(OpTest):
    def setUp(self):
        '''Test fill_constant op with specified value
        '''
        self.op_type = "fill_constant"
        self.init_data()
        shape_tensor_list = []
        for index, ele in enumerate(self.shape):
            shape_tensor_list.append(("x" + str(index), np.ones(
                (1)).astype('int32') * ele))

        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):
        '''Test fill_constant op with default value
        '''
        self.op_type = "fill_constant"
        self.init_data()
        shape_tensor_list = []
        for index, ele in enumerate(self.shape):
            shape_tensor_list.append(("x" + str(index), np.ones(
                (1)).astype('int32') * ele))

        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):
        '''Test fill_constant op with specified value
        '''
        self.op_type = "fill_constant"
        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 已提交
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 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
# Situation 4: value is a tensor
class TestFillConstantOp1_ValueTensor(OpTest):
    def setUp(self):
        '''Test fill_constant op with specified value
        '''
        self.op_type = "fill_constant"
        self.init_data()

        self.inputs = {
            "ShapeTensor": np.array(self.shape).astype("int32"),
            'ValueTensor': np.array([self.value]).astype("float32")
        }
        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):
        '''Test fill_constant op with specified value
        '''
        self.op_type = "fill_constant"
        self.init_data()

        self.inputs = {
            "ShapeTensor": np.array(self.shape).astype("int32"),
            'ValueTensor': np.array([self.value]).astype("int32")
        }
        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()


264
# Test python API
265
class TestFillConstantAPI(unittest.TestCase):
L
liym27 已提交
266
    def test_api(self):
267

268
        positive_2_int32 = fluid.layers.fill_constant([1], "int32", 2)
269
        positive_2_int64 = fluid.layers.fill_constant([1], "int64", 2)
270

271 272 273 274
        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")
L
liym27 已提交
275 276 277

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

L
liym27 已提交
279
        out_2 = fluid.layers.fill_constant(
280
            shape=[1, positive_2_int32], dtype="float32", value=1.1)
L
liym27 已提交
281 282

        out_3 = fluid.layers.fill_constant(
283 284 285 286 287 288 289
            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)
L
liym27 已提交
290

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

W
wangchaochaohu 已提交
294 295 296 297
        val = fluid.layers.fill_constant(shape=[1], dtype=np.float32, value=1.1)
        out_7 = fluid.layers.fill_constant(
            shape=shape_tensor_int64, dtype=np.float32, value=val)

L
liym27 已提交
298
        exe = fluid.Executor(place=fluid.CPUPlace())
W
wangchaochaohu 已提交
299
        res_1, res_2, res_3, res_4, res_5, res_6, res_7 = exe.run(
L
liym27 已提交
300
            fluid.default_main_program(),
301 302 303 304
            feed={
                "shape_tensor_int32": np.array([1, 2]).astype("int32"),
                "shape_tensor_int64": np.array([1, 2]).astype("int64"),
            },
W
wangchaochaohu 已提交
305
            fetch_list=[out_1, out_2, out_3, out_4, out_5, out_6, out_7])
L
liym27 已提交
306 307 308 309

        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"))
310 311
        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"))
312
        assert np.array_equal(res_6, np.full([1, 2], 1.1, dtype="float32"))
W
wangchaochaohu 已提交
313
        assert np.array_equal(res_7, np.full([1, 2], 1.1, dtype="float32"))
L
liym27 已提交
314 315


316
class TestFillConstantOpError(unittest.TestCase):
317 318
    def test_errors(self):
        with program_guard(Program(), Program()):
L
liym27 已提交
319
            #for ci coverage
320 321 322 323 324 325 326 327
            x1 = fluid.layers.data(name='x1', shape=[1], dtype="int16")
            self.assertRaises(
                ValueError,
                fluid.layers.fill_constant,
                shape=[1],
                value=5,
                dtype='uint4')
            self.assertRaises(
328
                TypeError,
329 330 331 332 333
                fluid.layers.fill_constant,
                shape=[1],
                value=5,
                dtype='int16',
                out=x1)
334 335

            # The argument dtype of fill_constant_op must be one of bool, float16,
336 337
            #float32, float64, int32 or int64
            x2 = fluid.layers.data(name='x2', shape=[1], dtype="int32")
L
liym27 已提交
338

339 340 341 342 343 344 345 346 347 348 349 350 351 352
            self.assertRaises(
                TypeError,
                fluid.layers.fill_constant,
                shape=[1],
                value=5,
                dtype='uint8')
            self.assertRaises(
                TypeError,
                fluid.layers.fill_constant,
                shape=[1],
                value=5,
                dtype='float64',
                out=x2)

353 354 355 356 357 358 359 360 361
            x3 = np.random.randn(100, 100).astype('int32')
            self.assertRaises(
                TypeError,
                fluid.layers.fill_constant,
                shape=[100, 100],
                value=5,
                dtype='float64',
                out=x3)

362
            # The argument shape's type of fill_constant_op must be list, tuple or Variable.
L
liym27 已提交
363 364 365 366 367
            def test_shape_type():
                fluid.layers.fill_constant(shape=1, dtype="float32", value=1)

            self.assertRaises(TypeError, test_shape_type)

368
            # The argument shape's size of fill_constant_op must not be 0.
L
liym27 已提交
369 370 371 372 373
            def test_shape_size():
                fluid.layers.fill_constant(shape=[], dtype="float32", value=1)

            self.assertRaises(AssertionError, test_shape_size)

374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390
            # The shape dtype of fill_constant_op must be int32 or int64.
            def test_shape_tensor_dtype():
                shape = fluid.data(
                    name="shape_tensor", shape=[2], dtype="float32")
                fluid.layers.fill_constant(
                    shape=shape, dtype="float32", value=1)

            self.assertRaises(TypeError, test_shape_tensor_dtype)

            def test_shape_tensor_list_dtype():
                shape = fluid.data(
                    name="shape_tensor_list", shape=[1], dtype="bool")
                fluid.layers.fill_constant(
                    shape=[shape, 2], dtype="float32", value=1)

            self.assertRaises(TypeError, test_shape_tensor_list_dtype)

391

392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459
class ApiZerosTest(unittest.TestCase):
    def test_out(self):
        with fluid.program_guard(fluid.Program()):
            zeros = paddle.zeros(shape=[10], dtype="float64")
            place = fluid.CPUPlace()
            exe = fluid.Executor(place)
            result, = exe.run(fetch_list=[zeros])
            expected_result = np.zeros(10, dtype="float64")
        self.assertEqual((result == expected_result).all(), True)

        with fluid.program_guard(fluid.Program()):
            zeros = paddle.zeros(shape=[10], dtype="int64")
            place = fluid.CPUPlace()
            exe = fluid.Executor(place)
            result, = exe.run(fetch_list=[zeros])
            expected_result = np.zeros(10, dtype="int64")
        self.assertEqual((result == expected_result).all(), True)

        with fluid.program_guard(fluid.Program()):
            zeros = paddle.zeros(shape=[10], dtype="int64", device="cpu")
            place = fluid.CPUPlace()
            exe = fluid.Executor(place)
            result, = exe.run(fetch_list=[zeros])
            expected_result = np.zeros(10, dtype="int64")
        self.assertEqual((result == expected_result).all(), True)


class ApiOnesTest(unittest.TestCase):
    def test_out(self):
        with fluid.program_guard(fluid.Program()):
            ones = paddle.ones(shape=[10], dtype="float64")
            place = fluid.CPUPlace()
            exe = fluid.Executor(place)
            result, = exe.run(fetch_list=[ones])
            expected_result = np.ones(10, dtype="float64")
        self.assertEqual((result == expected_result).all(), True)

        with fluid.program_guard(fluid.Program()):
            ones = paddle.ones(shape=[10], dtype="int64")
            place = fluid.CPUPlace()
            exe = fluid.Executor(place)
            result, = exe.run(fetch_list=[ones])
            expected_result = np.ones(10, dtype="int64")
        self.assertEqual((result == expected_result).all(), True)

        with fluid.program_guard(fluid.Program()):
            ones = paddle.ones(shape=[10], dtype="int64", device="cpu")
            place = fluid.CPUPlace()
            exe = fluid.Executor(place)
            result, = exe.run(fetch_list=[ones])
            expected_result = np.ones(10, dtype="int64")
        self.assertEqual((result == expected_result).all(), True)


class ApiOnesZerosError(unittest.TestCase):
    def test_errors(self):
        def test_error1():
            with fluid.program_guard(fluid.Program()):
                ones = paddle.ones(shape=10, dtype="int64", device="opu")

        self.assertRaises(ValueError, test_error1)

        def test_error2():
            with fluid.program_guard(fluid.Program()):
                ones = paddle.ones(shape=10, dtype="int64", device="opu")

        self.assertRaises(ValueError, test_error2)

460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483
        def test_error3():
            with fluid.program_guard(fluid.Program()):
                ones = fluid.layers.ones(shape=10, dtype="int64")

        self.assertRaises(TypeError, test_error3)

        def test_error4():
            with fluid.program_guard(fluid.Program()):
                ones = fluid.layers.ones(shape=[10], dtype="int8")

        self.assertRaises(TypeError, test_error4)

        def test_error5():
            with fluid.program_guard(fluid.Program()):
                ones = fluid.layers.zeros(shape=10, dtype="int64")

        self.assertRaises(TypeError, test_error5)

        def test_error6():
            with fluid.program_guard(fluid.Program()):
                ones = fluid.layers.zeros(shape=[10], dtype="int8")

        self.assertRaises(TypeError, test_error6)

484

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