test_initializer.py 42.5 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
import numpy as np
18
import math
19 20
import unittest

21
import paddle
22
import paddle.fluid as fluid
23 24
import paddle.fluid.framework as framework
import paddle.fluid.initializer as initializer
25
from paddle.fluid.core import VarDesc
26 27 28 29

DELTA = 0.00001


30 31 32
def check_cast_op(op):
    return op.type == 'cast' and \
           op.attr('in_dtype') == VarDesc.VarType.FP32 and \
33
           op.attr('out_dtype') in [VarDesc.VarType.FP16, VarDesc.VarType.BF16]
34 35


36 37 38 39 40 41 42 43
def output_hist(out):
    hist, _ = np.histogram(out, range=(-1, 1))
    hist = hist.astype("float32")
    hist /= float(out.size)
    prob = 0.1 * np.ones((10))
    return hist, prob


44
class TestConstantInitializer(unittest.TestCase):
45

46 47 48 49 50
    def test_calculate_gain(self):
        self.assertEqual(paddle.nn.initializer.calculate_gain('sigmoid'), 1)
        self.assertEqual(paddle.nn.initializer.calculate_gain('linear'), 1)
        self.assertEqual(paddle.nn.initializer.calculate_gain('conv2d'), 1)
        self.assertEqual(paddle.nn.initializer.calculate_gain('tanh'), 5.0 / 3)
51 52 53 54
        self.assertEqual(paddle.nn.initializer.calculate_gain('relu'),
                         math.sqrt(2.0))
        self.assertEqual(paddle.nn.initializer.calculate_gain('leaky_relu', 1),
                         1)
55 56
        self.assertEqual(paddle.nn.initializer.calculate_gain('selu'), 3.0 / 4)

57
    def test_constant_initializer_default_value(self, dtype="float32"):
58 59 60 61
        """Test the constant initializer with default value
        """
        program = framework.Program()
        block = program.global_block()
62 63
        for _ in range(2):
            block.create_parameter(
64
                dtype=dtype,
65 66 67 68
                shape=[5, 10],
                lod_level=0,
                name="param",
                initializer=initializer.ConstantInitializer())
69
        num_ops = 1
70
        self.assertEqual(len(block.ops), num_ops)
71 72 73
        init_op = block.ops[0]
        self.assertEqual(init_op.type, 'fill_constant')
        self.assertAlmostEqual(init_op.attr('value'), 0.0, delta=DELTA)
74
        return block
75

76
    def test_constant_initializer(self, dtype="float32"):
77 78 79 80
        """Test constant initializer with supplied value
        """
        program = framework.Program()
        block = program.global_block()
81 82
        for _ in range(2):
            block.create_parameter(
83
                dtype=dtype,
84 85 86 87
                shape=[5, 10],
                lod_level=0,
                name="param",
                initializer=initializer.ConstantInitializer(2.3))
88
        num_ops = 1
89
        self.assertEqual(len(block.ops), num_ops)
90 91 92
        init_op = block.ops[0]
        self.assertEqual(init_op.type, 'fill_constant')
        self.assertAlmostEqual(init_op.attr('value'), 2.3, delta=DELTA)
93 94 95 96 97
        return block

    def test_constant_initializer_fp16(self):
        """Test constant initializer with float16
        """
98 99
        self.test_constant_initializer_default_value("float16")
        self.test_constant_initializer("float16")
100

101 102 103 104 105 106 107
    def test_constant_initializer_bf16(self):
        """Test constant initializer with bfloat16
           No cast operator has been added here
        """
        self.test_constant_initializer_default_value("uint16")
        self.test_constant_initializer("uint16")

108 109

class TestUniformInitializer(unittest.TestCase):
110

111
    def test_uniform_initializer_default_value(self, dtype="float32"):
112 113 114 115
        """Test the uniform initializer with default value
        """
        program = framework.Program()
        block = program.global_block()
116
        for _ in range(2):
117 118 119 120 121
            block.create_parameter(dtype=dtype,
                                   shape=[5, 10],
                                   lod_level=0,
                                   name="param",
                                   initializer=initializer.UniformInitializer())
122
        num_ops = 2 if dtype == "float16" else 1
123
        self.assertEqual(len(block.ops), num_ops)
124 125 126 127 128
        init_op = block.ops[0]
        self.assertEqual(init_op.type, 'uniform_random')
        self.assertAlmostEqual(init_op.attr('min'), -1.0, delta=DELTA)
        self.assertAlmostEqual(init_op.attr('max'), 1.0, delta=DELTA)
        self.assertEqual(init_op.attr('seed'), 0)
129
        return block
130

D
dzhwinter 已提交
131 132 133 134 135 136
    def test_uniform_initializer_random_seed(self):
        """Test the uniform initializer with manually setting seed
        """
        program = framework.Program()
        program.random_seed = 123
        block = program.global_block()
137
        for _ in range(2):
138 139 140 141 142
            block.create_parameter(dtype="float32",
                                   shape=[5, 10],
                                   lod_level=0,
                                   name="param1",
                                   initializer=initializer.UniformInitializer())
143 144 145 146
            block.create_parameter(
                dtype="float32",
                shape=[5, 10],
                lod_level=0,
Q
qiaolongfei 已提交
147
                name="param2",
148
                initializer=initializer.UniformInitializer(seed=456))
D
dzhwinter 已提交
149
        init_op = block.ops[1]
150
        self.assertEqual(init_op.attr("seed"), 456)
D
dzhwinter 已提交
151
        init_op1 = block.ops[0]
152
        self.assertEqual(init_op1.attr("seed"), 123)
D
dzhwinter 已提交
153

154
    def test_uniform_initializer(self, dtype="float32"):
155 156 157 158
        """Test uniform initializer with supplied attributes
        """
        program = framework.Program()
        block = program.global_block()
159
        for _ in range(2):
160 161 162 163 164 165
            block.create_parameter(dtype=dtype,
                                   shape=[5, 10],
                                   lod_level=0,
                                   name="param",
                                   initializer=initializer.UniformInitializer(
                                       -4.2, 3.1, 123))
166
        num_ops = 2 if dtype == "float16" else 1
167
        self.assertEqual(len(block.ops), num_ops)
168 169 170 171 172
        init_op = block.ops[0]
        self.assertEqual(init_op.type, 'uniform_random')
        self.assertAlmostEqual(init_op.attr('min'), -4.2, delta=DELTA)
        self.assertAlmostEqual(init_op.attr('max'), 3.1, delta=DELTA)
        self.assertEqual(init_op.attr('seed'), 123)
173
        return block
174

175
    def test_uniform_initializer_two_op(self, dtype="float32"):
176 177 178 179 180
        """Test uniform initializer with supplied attributes
        """
        program = framework.Program()
        block = program.global_block()
        for i in range(2):
181 182 183 184 185 186
            block.create_parameter(dtype=dtype,
                                   shape=[5, 10],
                                   lod_level=0,
                                   name="param",
                                   initializer=initializer.UniformInitializer(
                                       -4.2, float(i), 123))
187
        num_ops = 2 if dtype == "float16" else 1
188
        self.assertEqual(len(block.ops), num_ops)
189 190 191
        init_op0 = block.ops[0]
        self.assertEqual(init_op0.type, 'uniform_random')
        self.assertAlmostEqual(init_op0.attr('min'), -4.2, delta=DELTA)
Q
qiaolongfei 已提交
192
        self.assertAlmostEqual(init_op0.attr('max'), 0.0, delta=DELTA)
193
        self.assertEqual(init_op0.attr('seed'), 123)
194 195 196 197 198 199 200 201 202 203 204
        return block

    def test_uniform_initializer_fp16(self):
        """Test uniform initializer with float16
        """
        block = self.test_uniform_initializer_default_value("float16")
        self.assertTrue(check_cast_op(block.ops[1]))
        block = self.test_uniform_initializer(dtype="float16")
        self.assertTrue(check_cast_op(block.ops[1]))
        block = self.test_uniform_initializer_two_op("float16")
        self.assertTrue(check_cast_op(block.ops[1]))
205

206 207
    def test_uniform_initializer_bf16(self):
        """Test uniform initializer with bfloat16
208
           No cast operator has been added here
209 210 211 212 213
        """
        block = self.test_uniform_initializer_default_value("uint16")
        block = self.test_uniform_initializer(dtype="uint16")
        block = self.test_uniform_initializer_two_op("uint16")

214 215

class TestNormalInitializer(unittest.TestCase):
216

217 218 219 220 221
    def test_normal_initializer_default_value(self):
        """Test the normal initializer with default value
        """
        program = framework.Program()
        block = program.global_block()
222
        for _ in range(2):
223 224 225 226 227
            block.create_parameter(dtype="float32",
                                   shape=[5, 10],
                                   lod_level=0,
                                   name="param",
                                   initializer=initializer.NormalInitializer())
228 229 230 231 232 233 234
        self.assertEqual(len(block.ops), 1)
        init_op = block.ops[0]
        self.assertEqual(init_op.type, 'gaussian_random')
        self.assertAlmostEqual(init_op.attr('mean'), 0.0, delta=DELTA)
        self.assertAlmostEqual(init_op.attr('std'), 1.0, delta=DELTA)
        self.assertEqual(init_op.attr('seed'), 0)

235
    def test_normal_initializer(self, dtype="float32"):
236 237 238 239
        """Test normal initializer with supplied attributes
        """
        program = framework.Program()
        block = program.global_block()
240
        for _ in range(2):
241 242 243 244 245 246
            block.create_parameter(dtype=dtype,
                                   shape=[5, 10],
                                   lod_level=0,
                                   name="param",
                                   initializer=initializer.NormalInitializer(
                                       2.3, 1.9, 123))
247
        num_ops = 2 if (dtype == "float16" or dtype == "uint16") else 1
248
        self.assertEqual(len(block.ops), num_ops)
249 250 251 252 253
        init_op = block.ops[0]
        self.assertEqual(init_op.type, 'gaussian_random')
        self.assertAlmostEqual(init_op.attr('mean'), 2.3, delta=DELTA)
        self.assertAlmostEqual(init_op.attr('std'), 1.9, delta=DELTA)
        self.assertEqual(init_op.attr('seed'), 123)
254 255 256 257 258
        return block

    def test_normal_initializer_fp16(self):
        """Test normal initializer with float16
        """
259
        self.test_normal_initializer("float16")
260

261 262 263
    def test_normal_initializer_bf16(self):
        """Test normal initializer with bfloat16
        """
264
        self.test_normal_initializer("uint16")
265

266

267
class TestXavierInitializer(unittest.TestCase):
268

269 270 271 272 273 274
    def test_uniform_xavier_initializer(self):
        """Test Xavier initializer with uniform distribution on
           for matrix multiply.
        """
        program = framework.Program()
        block = program.global_block()
275 276 277 278 279 280 281
        for _ in range(2):
            param = block.create_parameter(
                dtype="float32",
                shape=[5, 10],
                lod_level=0,
                name="param",
                initializer=initializer.XavierInitializer())
282 283 284 285 286 287 288 289 290 291 292 293 294 295
        self.assertEqual(len(block.ops), 1)
        init_op = block.ops[0]
        self.assertEqual(init_op.type, 'uniform_random')
        limit = np.sqrt(6.0 / (param.shape[0] + param.shape[1]))
        self.assertAlmostEqual(init_op.attr('min'), -limit, delta=DELTA)
        self.assertAlmostEqual(init_op.attr('max'), limit, delta=DELTA)
        self.assertEqual(init_op.attr('seed'), 0)

    def test_uniform_xavier_initializer_conv(self):
        """Test Xavier initializer with uniform distribution on
           for convolutions.
        """
        program = framework.Program()
        block = program.global_block()
296 297 298 299 300 301 302
        for _ in range(2):
            param = block.create_parameter(
                dtype="float32",
                shape=[5, 10, 15, 20],
                lod_level=0,
                name="param",
                initializer=initializer.XavierInitializer())
303 304 305 306
        self.assertEqual(len(block.ops), 1)
        init_op = block.ops[0]
        self.assertEqual(init_op.type, 'uniform_random')
        receptive_field_size = float(15 * 20)
307 308
        limit = np.sqrt(
            6.0 / ((param.shape[0] + param.shape[1]) * receptive_field_size))
309 310 311 312 313 314 315 316 317 318
        self.assertAlmostEqual(init_op.attr('min'), -limit, delta=DELTA)
        self.assertAlmostEqual(init_op.attr('max'), limit, delta=DELTA)
        self.assertEqual(init_op.attr('seed'), 0)

    def test_normal_xavier_initializer(self):
        """Test Xavier initializer with normal distribution on
           for matrix multiply.
        """
        program = framework.Program()
        block = program.global_block()
319 320 321 322 323 324 325
        for _ in range(2):
            param = block.create_parameter(
                dtype="float32",
                shape=[5, 10],
                lod_level=0,
                name="param",
                initializer=initializer.XavierInitializer(uniform=False))
326 327 328 329 330 331 332 333 334 335 336 337 338 339
        self.assertEqual(len(block.ops), 1)
        init_op = block.ops[0]
        self.assertEqual(init_op.type, 'gaussian_random')
        std = np.sqrt(2.0 / (param.shape[0] + param.shape[1]))
        self.assertAlmostEqual(init_op.attr('mean'), 0.0, delta=DELTA)
        self.assertAlmostEqual(init_op.attr('std'), std, delta=DELTA)
        self.assertEqual(init_op.attr('seed'), 0)

    def test_normal_xavier_initializer_conv(self):
        """Test Xavier initializer with normal distribution on
           for convolutions.
        """
        program = framework.Program()
        block = program.global_block()
340 341 342 343 344 345 346
        for _ in range(2):
            param = block.create_parameter(
                dtype="float32",
                shape=[5, 10, 15, 20],
                lod_level=0,
                name="param",
                initializer=initializer.XavierInitializer(uniform=False))
347 348 349 350
        self.assertEqual(len(block.ops), 1)
        init_op = block.ops[0]
        self.assertEqual(init_op.type, 'gaussian_random')
        receptive_field_size = float(15 * 20)
351 352
        std = np.sqrt(
            2.0 / ((param.shape[0] + param.shape[1]) * receptive_field_size))
353 354 355 356
        self.assertAlmostEqual(init_op.attr('mean'), 0.0, delta=DELTA)
        self.assertAlmostEqual(init_op.attr('std'), std, delta=DELTA)
        self.assertEqual(init_op.attr('seed'), 0)

357 358 359
    def test_xavier_initializer_supplied_arguments(self,
                                                   dtype="float32",
                                                   uniform=True):
360 361 362 363
        """Test the Xavier initializer with supplied arguments
        """
        program = framework.Program()
        block = program.global_block()
364
        for _ in range(2):
365 366 367 368 369 370 371 372 373 374 375
            block.create_parameter(dtype=dtype,
                                   shape=[5, 10],
                                   lod_level=0,
                                   name="param",
                                   initializer=initializer.XavierInitializer(
                                       uniform=uniform,
                                       fan_in=12,
                                       fan_out=23,
                                       seed=134))
        num_ops = 2 if (dtype == "float16" or
                        (dtype == "uint16" and not uniform)) else 1
376
        self.assertEqual(len(block.ops), num_ops)
377
        init_op = block.ops[0]
378 379 380 381 382 383 384
        if uniform:
            self.assertEqual(init_op.type, 'uniform_random')
            limit = np.sqrt(6.0 / (12 + 23))
            self.assertAlmostEqual(init_op.attr('min'), -limit, delta=DELTA)
            self.assertAlmostEqual(init_op.attr('max'), limit, delta=DELTA)
        else:
            self.assertEqual(init_op.type, 'gaussian_random')
385
        self.assertEqual(init_op.attr('seed'), 134)
386 387 388 389 390 391 392
        return block

    def test_xavier_initializer_fp16(self):
        """Test the Xavier initializer with float16
        """
        block = self.test_xavier_initializer_supplied_arguments("float16")
        self.assertTrue(check_cast_op(block.ops[1]))
393

394 395 396
    def test_xavier_initializer_bf16(self):
        """Test the Xavier initializer with bfloat16
        """
397 398 399 400 401 402
        block_uniform = self.test_xavier_initializer_supplied_arguments(
            "uint16")
        self.assertEqual(len(block_uniform.ops), 1)
        block_gaussian = self.test_xavier_initializer_supplied_arguments(
            "uint16", False)
        self.assertTrue(check_cast_op(block_gaussian.ops[1]))
403

404

405
class TestMSRAInitializer(unittest.TestCase):
406

407 408 409 410 411 412
    def test_uniform_msra_initializer(self):
        """Test MSRA initializer with uniform distribution on
           for matrix multiply.
        """
        program = framework.Program()
        block = program.global_block()
413 414 415 416 417 418 419
        for _ in range(2):
            param = block.create_parameter(
                dtype="float32",
                shape=[5, 10],
                lod_level=0,
                name="param",
                initializer=initializer.MSRAInitializer())
420 421 422 423 424 425 426 427 428 429 430 431 432 433
        self.assertEqual(len(block.ops), 1)
        init_op = block.ops[0]
        self.assertEqual(init_op.type, 'uniform_random')
        limit = np.sqrt(6.0 / param.shape[0])
        self.assertAlmostEqual(init_op.attr('min'), -limit, delta=DELTA)
        self.assertAlmostEqual(init_op.attr('max'), limit, delta=DELTA)
        self.assertEqual(init_op.attr('seed'), 0)

    def test_uniform_msra_initializer_conv(self):
        """Test MSRA initializer with uniform distribution on
           for convolutions.
        """
        program = framework.Program()
        block = program.global_block()
434 435 436 437 438 439 440
        for _ in range(2):
            param = block.create_parameter(
                dtype="float32",
                shape=[5, 10, 15, 20],
                lod_level=0,
                name="param",
                initializer=initializer.MSRAInitializer())
441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
        self.assertEqual(len(block.ops), 1)
        init_op = block.ops[0]
        self.assertEqual(init_op.type, 'uniform_random')
        receptive_field_size = float(15 * 20)
        limit = np.sqrt(6.0 / (param.shape[1] * receptive_field_size))
        self.assertAlmostEqual(init_op.attr('min'), -limit, delta=DELTA)
        self.assertAlmostEqual(init_op.attr('max'), limit, delta=DELTA)
        self.assertEqual(init_op.attr('seed'), 0)

    def test_normal_msra_initializer(self):
        """Test MSRA initializer with normal distribution on
           for matrix multiply.
        """
        program = framework.Program()
        block = program.global_block()
456 457 458 459 460 461 462
        for _ in range(2):
            param = block.create_parameter(
                dtype="float32",
                shape=[5, 10],
                lod_level=0,
                name="param",
                initializer=initializer.MSRAInitializer(uniform=False))
463 464 465 466 467 468 469 470 471 472 473 474 475 476
        self.assertEqual(len(block.ops), 1)
        init_op = block.ops[0]
        self.assertEqual(init_op.type, 'gaussian_random')
        std = np.sqrt(2.0 / param.shape[0])
        self.assertAlmostEqual(init_op.attr('mean'), 0.0, delta=DELTA)
        self.assertAlmostEqual(init_op.attr('std'), std, delta=DELTA)
        self.assertEqual(init_op.attr('seed'), 0)

    def test_normal_msra_initializer_conv(self):
        """Test MSRA initializer with normal distribution on
           for convolutions.
        """
        program = framework.Program()
        block = program.global_block()
477 478 479 480 481 482 483
        for _ in range(2):
            param = block.create_parameter(
                dtype="float32",
                shape=[5, 10, 15, 20],
                lod_level=0,
                name="param",
                initializer=initializer.MSRAInitializer(uniform=False))
484 485 486 487 488 489 490 491 492
        self.assertEqual(len(block.ops), 1)
        init_op = block.ops[0]
        self.assertEqual(init_op.type, 'gaussian_random')
        receptive_field_size = float(15 * 20)
        std = np.sqrt(2.0 / (param.shape[1] * receptive_field_size))
        self.assertAlmostEqual(init_op.attr('mean'), 0.0, delta=DELTA)
        self.assertAlmostEqual(init_op.attr('std'), std, delta=DELTA)
        self.assertEqual(init_op.attr('seed'), 0)

493
    def test_msra_initializer_supplied_arguments(self, dtype="float32"):
494 495 496 497
        """Test the MSRA initializer with supplied arguments
        """
        program = framework.Program()
        block = program.global_block()
498
        for _ in range(2):
499 500 501 502 503 504
            block.create_parameter(dtype=dtype,
                                   shape=[5, 10],
                                   lod_level=0,
                                   name="param",
                                   initializer=initializer.MSRAInitializer(
                                       fan_in=12, seed=134))
505
        num_ops = 2 if dtype == "float16" else 1
506
        self.assertEqual(len(block.ops), num_ops)
507 508 509 510 511 512
        init_op = block.ops[0]
        self.assertEqual(init_op.type, 'uniform_random')
        limit = np.sqrt(6.0 / 12)
        self.assertAlmostEqual(init_op.attr('min'), -limit, delta=DELTA)
        self.assertAlmostEqual(init_op.attr('max'), limit, delta=DELTA)
        self.assertEqual(init_op.attr('seed'), 134)
513
        return block
514

515 516 517 518 519
    def test_msra_initializer_fp16(self):
        """Test the MSRA initializer with float16
        """
        block = self.test_msra_initializer_supplied_arguments("float16")
        self.assertTrue(check_cast_op(block.ops[1]))
520

521 522 523 524 525
    def test_msra_initializer_bf16(self):
        """Test the MSRA initializer with bfloat16
        """
        block = self.test_msra_initializer_supplied_arguments("uint16")

526 527

class TestBilinearInitializer(unittest.TestCase):
528

529
    def test_bilinear_initializer(self, dtype="float32"):
530 531 532 533
        """Test the bilinear initializer with supplied arguments
        """
        program = framework.Program()
        block = program.global_block()
534 535
        for _ in range(2):
            block.create_parameter(
536
                dtype=dtype,
537 538 539 540
                shape=[8, 1, 3, 3],
                lod_level=0,
                name="param",
                initializer=initializer.BilinearInitializer())
541
        num_ops = 2 if dtype in ["float16", "uint16", "float64"] else 1
542
        self.assertEqual(len(block.ops), num_ops)
543 544
        init_op = block.ops[0]
        self.assertEqual(init_op.type, 'assign_value')
545 546
        return block

547 548 549
    def test_bilinear_initializer_fp64(self):
        self.test_bilinear_initializer(dtype='float64')

550 551 552 553 554
    def test_bilinear_initializer_fp16(self):
        """Test the bilinear initializer with supplied arguments
        """
        block = self.test_bilinear_initializer("float16")
        self.assertTrue(check_cast_op(block.ops[1]))
555

556 557 558 559 560 561
    def test_bilinear_initializer_bf16(self):
        """Test the bilinear initializer with supplied arguments
        """
        block = self.test_bilinear_initializer("uint16")
        self.assertTrue(check_cast_op(block.ops[1]))

562 563 564
    def test_type_error(self):
        self.assertRaises(TypeError, self.test_bilinear_initializer, 'int32')

565

Q
Qiao Longfei 已提交
566
class TestNumpyArrayInitializer(unittest.TestCase):
567

568
    def test_numpy_array_initializer(self, dtype="float32"):
Q
Qiao Longfei 已提交
569 570 571 572 573
        """Test the numpy array initializer with supplied arguments
        """
        import numpy
        program = framework.Program()
        block = program.global_block()
574
        np_array = numpy.random.random((10000)).astype(dtype)
Q
Qiao Longfei 已提交
575 576 577 578 579 580 581
        for _ in range(2):
            block.create_parameter(
                dtype=np_array.dtype,
                shape=np_array.shape,
                lod_level=0,
                name="param",
                initializer=initializer.NumpyArrayInitializer(np_array))
582
        num_ops = 2 if dtype in ["float16", "uint16"] else 1
583
        self.assertEqual(len(block.ops), num_ops)
Q
Qiao Longfei 已提交
584 585
        init_op = block.ops[0]
        self.assertEqual(init_op.type, 'assign_value')
586
        assert (init_op.attr('fp32_values') == np_array).all()
587 588 589 590 591 592 593
        return block

    def test_numpy_array_initializer_fp16(self):
        """Test the numpy array initializer with float16
        """
        block = self.test_numpy_array_initializer("float16")
        self.assertTrue(block.ops[1])
Q
Qiao Longfei 已提交
594

595 596 597 598 599 600
    def test_numpy_array_initializer_bf16(self):
        """Test the numpy array initializer with bfloat16
        """
        block = self.test_numpy_array_initializer("uint16")
        self.assertTrue(block.ops[1])

Q
Qiao Longfei 已提交
601

602
class TestSetGlobalInitializer(unittest.TestCase):
603

604 605 606 607 608 609 610 611 612 613 614 615 616 617
    def test_set_global_weight_initilizer(self):
        """Test Set Global Param initilizer with UniformInitializer
        """
        main_prog = framework.Program()
        startup_prog = framework.Program()
        fluid.set_global_initializer(initializer.Uniform(low=-0.5, high=0.5))
        with fluid.program_guard(main_prog, startup_prog):
            x = fluid.data(name="x", shape=[1, 3, 32, 32])
            # default initilizer of param in layers.conv2d is NormalInitializer
            conv = fluid.layers.conv2d(x, 5, 3)

        block = startup_prog.global_block()
        self.assertEqual(len(block.ops), 2)

618 619
        # init weight is the first op, and bias is the second
        bias_init_op = block.ops[1]
620 621 622
        self.assertEqual(bias_init_op.type, 'fill_constant')
        self.assertAlmostEqual(bias_init_op.attr('value'), 0.0, delta=DELTA)

623
        param_init_op = block.ops[0]
624 625 626 627 628 629 630 631 632 633 634
        self.assertEqual(param_init_op.type, 'uniform_random')
        self.assertAlmostEqual(param_init_op.attr('min'), -0.5, delta=DELTA)
        self.assertAlmostEqual(param_init_op.attr('max'), 0.5, delta=DELTA)
        self.assertEqual(param_init_op.attr('seed'), 0)
        fluid.set_global_initializer(None)

    def test_set_global_bias_initilizer(self):
        """Test Set Global Bias initilizer with NormalInitializer
        """
        main_prog = framework.Program()
        startup_prog = framework.Program()
635 636 637
        fluid.set_global_initializer(initializer.Uniform(low=-0.5, high=0.5),
                                     bias_init=initializer.Normal(loc=0.0,
                                                                  scale=2.0))
638 639 640 641 642 643 644 645
        with fluid.program_guard(main_prog, startup_prog):
            x = fluid.data(name="x", shape=[1, 3, 32, 32])
            # default initilizer of bias in layers.conv2d is ConstantInitializer
            conv = fluid.layers.conv2d(x, 5, 3)

        block = startup_prog.global_block()
        self.assertEqual(len(block.ops), 2)

646 647
        # init weight is the first op, and bias is the second
        bias_init_op = block.ops[1]
648 649 650 651 652
        self.assertEqual(bias_init_op.type, 'gaussian_random')
        self.assertAlmostEqual(bias_init_op.attr('mean'), 0.0, delta=DELTA)
        self.assertAlmostEqual(bias_init_op.attr('std'), 2.0, delta=DELTA)
        self.assertEqual(bias_init_op.attr('seed'), 0)

653
        param_init_op = block.ops[0]
654 655 656 657 658 659 660
        self.assertEqual(param_init_op.type, 'uniform_random')
        self.assertAlmostEqual(param_init_op.attr('min'), -0.5, delta=DELTA)
        self.assertAlmostEqual(param_init_op.attr('max'), 0.5, delta=DELTA)
        self.assertEqual(param_init_op.attr('seed'), 0)
        fluid.set_global_initializer(None)


661
class TestUniformInitializerDygraph(unittest.TestCase):
662

J
Jiabin Yang 已提交
663
    def func_uniform_initializer(self, dtype="float32"):
664 665 666 667 668
        """
        In dygraph mode, we can use initializer directly to initialize a tensor.
        """
        paddle.disable_static()

L
Leo Chen 已提交
669
        tensor = paddle.zeros([1024, 1024, 16])
670
        tensor.stop_gradient = False
L
Leo Chen 已提交
671
        self.assertTrue(np.allclose(np.zeros((1024, 1024, 16)), tensor.numpy()))
672 673 674 675 676 677 678 679 680

        uniform_ = paddle.nn.initializer.Uniform()
        uniform_(tensor)

        self.assertEqual(tensor.stop_gradient,
                         False)  # stop_gradient is not changed

        hist, prob = output_hist(tensor.numpy())

681 682
        self.assertTrue(np.allclose(hist, prob, rtol=0, atol=1e-3),
                        "hist: " + str(hist))
683 684 685

        paddle.enable_static()

J
Jiabin Yang 已提交
686 687 688 689 690
    def test_uniform_initializer(self, dtype="float32"):
        with framework._test_eager_guard():
            self.func_uniform_initializer()
        self.func_uniform_initializer()

691

692
class TestXavierInitializerDygraph(unittest.TestCase):
693

694 695 696 697 698 699 700 701 702
    def func_xvarier_initializer(self, dtype="float32"):
        """
        In dygraph mode, we can use initializer directly to initialize a tensor.
        """
        paddle.disable_static()

        tensor = paddle.zeros([1024, 1024, 16])
        tensor.stop_gradient = False

703 704 705
        xavier_ = paddle.fluid.initializer.XavierInitializer(uniform=False,
                                                             fan_in=3,
                                                             fan_out=5)
706 707 708 709 710 711 712
        xavier_(tensor)

        hist, _ = output_hist(tensor.numpy())

        hist2, _ = output_hist(
            np.random.normal(0, np.sqrt(2.0 / (3 + 5)), [1024, 1024, 16]))

713 714
        self.assertTrue(np.allclose(hist, hist2, rtol=0, atol=0.01),
                        "hist: " + str(hist) + " hist2: " + str(hist2))
715 716 717 718 719 720 721 722 723
        paddle.enable_static()

    def test_xavier_initializer(self, dtype="float32"):
        with framework._test_eager_guard():
            self.func_xvarier_initializer()
        self.func_xvarier_initializer()


class TestMSRAInitializerDygraph(unittest.TestCase):
724

725 726 727 728 729 730 731 732 733
    def func_msra_initializer(self, dtype="float32"):
        """
        In dygraph mode, we can use initializer directly to initialize a tensor.
        """
        paddle.disable_static()

        tensor = paddle.zeros([1024, 1024, 16])
        tensor.stop_gradient = False

734 735
        msra_ = paddle.fluid.initializer.MSRAInitializer(uniform=False,
                                                         fan_in=4)
736 737 738 739 740 741 742
        msra_(tensor)

        hist, _ = output_hist(tensor.numpy())

        hist2, _ = output_hist(
            np.random.normal(0, np.sqrt(2.0 / (4)), [1024, 1024, 16]))

743 744
        self.assertTrue(np.allclose(hist, hist2, rtol=0, atol=0.01),
                        "hist: " + str(hist) + " hist2: " + str(hist2))
745 746 747 748 749 750 751 752
        paddle.enable_static()

    def test_msra_initializer(self, dtype="float32"):
        with framework._test_eager_guard():
            self.func_msra_initializer()
        self.func_msra_initializer()


753
class TesetconsistencyOfDynamicAndStaticGraph(unittest.TestCase):
754

J
Jiabin Yang 已提交
755
    def func_order(self):
756 757 758 759 760 761 762
        paddle.set_device('cpu')
        SEED = 123
        weight_attr = paddle.framework.ParamAttr(
            name="linear_weight",
            learning_rate=1.0,
            trainable=False,
            regularizer=None,
763 764
            initializer=paddle.nn.initializer.TruncatedNormal(mean=0.0,
                                                              std=2.0))
765 766 767 768 769
        bias_attr = paddle.framework.ParamAttr(
            name="linear_bias",
            learning_rate=1.0,
            trainable=False,
            regularizer=None,
770 771
            initializer=paddle.nn.initializer.TruncatedNormal(mean=0.0,
                                                              std=2.0))
772 773 774 775

        def run_dynamic_graph():
            paddle.disable_static()
            paddle.seed(SEED)
776 777 778 779
            linear = paddle.nn.Linear(1,
                                      1,
                                      weight_attr=weight_attr,
                                      bias_attr=bias_attr)
780 781 782 783 784 785 786
            return linear.weight.numpy(), linear.bias.numpy()
            paddle.enable_static()

        def run_static_graph():
            paddle.enable_static()
            exe = paddle.static.Executor(paddle.CPUPlace())
            paddle.seed(SEED)
787 788 789 790
            linear = paddle.nn.Linear(1,
                                      1,
                                      weight_attr=weight_attr,
                                      bias_attr=bias_attr)
791 792 793 794 795 796 797 798 799 800
            res = exe.run(paddle.static.default_startup_program(),
                          fetch_list=['linear_weight', 'linear_bias'])
            return res[0], res[1]

        dynamic_res = run_dynamic_graph()
        static_res = run_static_graph()

        self.assertTrue(np.array_equal(dynamic_res[0], static_res[0]))
        self.assertTrue(np.array_equal(dynamic_res[1], static_res[1]))

J
Jiabin Yang 已提交
801 802 803 804 805
    def test_order(self):
        with framework._test_eager_guard():
            self.func_order()
        self.func_order()

806

807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824
# 2-D Parameter with shape: [10, 15]
class TestOrthogonalInitializer1(unittest.TestCase):
    """
    case 1
    """

    def config(self):
        self.weight_attr = paddle.ParamAttr(
            initializer=paddle.nn.initializer.Orthogonal(gain=3.0))
        self.dtype = "float64"
        self.in_features = 10
        self.out_features = 15
        self.num_ops = 9

    def check_result(self, a, b):
        self.assertTrue(np.array_equal(a, b))
        self.assertTrue(np.allclose(np.matmul(a, a.T), 9 * np.eye(10)))

J
Jiabin Yang 已提交
825
    def func_orthogonal(self):
826 827 828 829 830
        self.config()
        paddle.set_default_dtype(self.dtype)

        paddle.disable_static()
        paddle.seed(2021)
831 832 833
        linear = paddle.nn.Linear(self.in_features,
                                  self.out_features,
                                  weight_attr=self.weight_attr)
834 835 836 837 838 839 840
        res_dygraph = linear.weight.numpy()

        paddle.enable_static()
        paddle.seed(2021)
        start_prog = paddle.static.Program()
        main_prog = paddle.static.Program()
        with paddle.static.program_guard(main_prog, start_prog):
841 842 843
            linear = paddle.nn.Linear(self.in_features,
                                      self.out_features,
                                      weight_attr=self.weight_attr)
844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859

            block = start_prog.global_block()
            self.assertEqual(len(block.ops), self.num_ops)
            self.assertEqual(block.ops[0].type, 'gaussian_random')
            self.assertEqual(block.ops[1].type, 'qr')
            self.assertEqual(block.ops[2].type, 'diag_v2')
            self.assertEqual(block.ops[3].type, 'sign')
            self.assertEqual(block.ops[4].type, 'elementwise_mul')
            self.assertEqual(block.ops[-3].type, 'reshape2')
            self.assertEqual(block.ops[-2].type, 'scale')

            exe = paddle.static.Executor()
            res_static = exe.run(start_prog, fetch_list=[linear.weight])[0]

        self.check_result(res_dygraph, res_static)

J
Jiabin Yang 已提交
860 861 862 863 864
    def test_orthogonal(self):
        with framework._test_eager_guard():
            self.func_orthogonal()
        self.func_orthogonal()

865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928

# 2-D Parameter with shape: [15, 10]
class TestOrthogonalInitializer2(TestOrthogonalInitializer1):
    """
    case 2
    """

    def config(self):
        self.weight_attr = paddle.ParamAttr(
            initializer=paddle.nn.initializer.Orthogonal(gain=2.0))
        self.dtype = "float64"
        self.in_features = 15
        self.out_features = 10
        self.num_ops = 8

    def check_result(self, a, b):
        self.assertTrue(np.array_equal(a, b))
        self.assertTrue(np.allclose(np.matmul(a.T, a), 4 * np.eye(10)))


# 2-D Parameter with shape: [10, 10]
class TestOrthogonalInitializer3(TestOrthogonalInitializer1):
    """
    case 3
    """

    def config(self):
        self.weight_attr = paddle.ParamAttr(
            initializer=paddle.nn.initializer.Orthogonal())
        self.dtype = "float32"
        self.in_features = 10
        self.out_features = 10
        self.num_ops = 8

    def check_result(self, a, b):
        self.assertTrue(np.array_equal(a, b))
        self.assertTrue(np.allclose(np.matmul(a.T, a), np.eye(10), atol=1.e-6))
        self.assertTrue(np.allclose(np.matmul(a, a.T), np.eye(10), atol=1.e-6))

    def test_error(self):
        self.config()
        with self.assertRaises(AssertionError):
            paddle.nn.Linear(10, 10, bias_attr=self.weight_attr)


# 4-D Parameter with shape: [6, 4, 3, 3]
class TestOrthogonalInitializer4(unittest.TestCase):
    """
    case 4
    """

    def config(self):
        self.weight_attr = paddle.ParamAttr(
            initializer=paddle.nn.initializer.Orthogonal(gain=3.0))
        self.dtype = "float64"
        self.in_features = 4
        self.out_features = 6
        self.kernel_size = (3, 3)

    def check_result(self, a, b):
        self.assertTrue(np.array_equal(a, b))
        a = a.reshape(6, -1)
        self.assertTrue(np.allclose(np.matmul(a, a.T), 9 * np.eye(6)))

J
Jiabin Yang 已提交
929
    def func_orthogonal(self):
930 931 932 933 934
        self.config()
        paddle.set_default_dtype(self.dtype)

        paddle.disable_static()
        paddle.seed(2021)
935 936 937 938
        conv2d = paddle.nn.Conv2D(self.in_features,
                                  self.out_features,
                                  self.kernel_size,
                                  weight_attr=self.weight_attr)
939 940 941 942 943 944 945
        res_dygraph = conv2d.weight.numpy()

        paddle.enable_static()
        paddle.seed(2021)
        start_prog = paddle.static.Program()
        main_prog = paddle.static.Program()
        with paddle.static.program_guard(main_prog, start_prog):
946 947 948 949
            conv2d = paddle.nn.Conv2D(self.in_features,
                                      self.out_features,
                                      self.kernel_size,
                                      weight_attr=self.weight_attr)
950 951 952 953 954
            exe = paddle.static.Executor()
            res_static = exe.run(paddle.static.default_startup_program(),
                                 fetch_list=[conv2d.weight])[0]
        self.check_result(res_dygraph, res_static)

J
Jiabin Yang 已提交
955 956 957 958 959
    def test_orthogonal(self):
        with framework._test_eager_guard():
            self.func_orthogonal()
        self.func_orthogonal()

960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001

# 4-D Parameter with shape: [50, 4, 3, 3]
class TestOrthogonalInitializer5(TestOrthogonalInitializer4):
    """
    case 5
    """

    def config(self):
        self.weight_attr = paddle.ParamAttr(
            initializer=paddle.nn.initializer.Orthogonal(gain=2.0))
        self.dtype = "float64"
        self.in_features = 4
        self.out_features = 50
        self.kernel_size = (3, 3)

    def check_result(self, a, b):
        self.assertTrue(np.array_equal(a, b))
        a = a.reshape(50, -1)
        self.assertTrue(np.allclose(np.matmul(a.T, a), 4 * np.eye(36)))


# 4-D Parameter with shape: [36, 4, 3, 3]
class TestOrthogonalInitializer6(TestOrthogonalInitializer4):
    """
    case 6
    """

    def config(self):
        self.weight_attr = paddle.ParamAttr(
            initializer=paddle.nn.initializer.Orthogonal())
        self.dtype = "float32"
        self.in_features = 4
        self.out_features = 36
        self.kernel_size = (3, 3)

    def check_result(self, a, b):
        self.assertTrue(np.array_equal(a, b))
        a = a.reshape(36, -1)
        self.assertTrue(np.allclose(np.matmul(a.T, a), np.eye(36), atol=1.e-6))
        self.assertTrue(np.allclose(np.matmul(a, a.T), np.eye(36), atol=1.e-6))


1002 1003
# initialize Conv1D weight
class TestDiracInitializer1(unittest.TestCase):
1004

1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019
    def config(self):
        self.weight_attr = paddle.ParamAttr(
            initializer=paddle.nn.initializer.Dirac())
        self.dtype = "float64"
        self.in_channels = 3
        self.out_channels = 2
        self.kernel_size = 3
        self.input_shape = [8, self.in_channels, 10]
        self.conv_layer = paddle.nn.Conv1D
        self.num_ops = 8  #fill_constant*2, reshape*2, assign_value*2, scatter, cast

    def check_result(self, w_dygraph, w_static, conv_in, conv_out):
        self.assertTrue(np.array_equal(w_dygraph, w_static))
        self.assertTrue(np.array_equal(conv_out, conv_in[:, 0:2, 1:9]))

J
Jiabin Yang 已提交
1020
    def func_dirac(self):
1021 1022 1023 1024
        self.config()
        paddle.set_default_dtype(self.dtype)

        paddle.disable_static()
1025 1026 1027 1028
        conv = self.conv_layer(self.in_channels,
                               self.out_channels,
                               self.kernel_size,
                               weight_attr=self.weight_attr)
1029 1030 1031 1032 1033 1034 1035
        weight_dygraph = conv.weight.numpy()

        paddle.enable_static()
        start_prog = paddle.static.Program()
        main_prog = paddle.static.Program()
        with paddle.static.program_guard(main_prog, start_prog):
            inp = paddle.rand(self.input_shape)
1036 1037 1038 1039
            conv = self.conv_layer(self.in_channels,
                                   self.out_channels,
                                   self.kernel_size,
                                   weight_attr=self.weight_attr)
1040 1041 1042 1043 1044

            output = conv(inp)
            block = start_prog.global_block()
            self.assertEqual(len(block.ops), self.num_ops)
            self.assertEqual(block.ops[0].type, 'fill_constant')
1045
            self.assertEqual(block.ops[1].type, 'reshape2')
1046 1047 1048
            self.assertEqual(block.ops[2].type, 'assign_value')
            self.assertEqual(block.ops[3].type, 'assign_value')
            self.assertEqual(block.ops[4].type, 'scatter')
1049
            self.assertEqual(block.ops[5].type, 'reshape2')
1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060

            exe = paddle.static.Executor()
            exe.run(start_prog)
            fetch = exe.run(main_prog, fetch_list=[inp, output, conv.weight])
            conv_input = fetch[0]
            conv_output = fetch[1]
            weight_static = fetch[2]

        self.check_result(weight_dygraph, weight_static, conv_input,
                          conv_output)

J
Jiabin Yang 已提交
1061 1062 1063 1064 1065
    def test_dirac(self):
        with framework._test_eager_guard():
            self.func_dirac()
        self.func_dirac()

1066 1067 1068

# initialize Conv2D weight
class TestDiracInitializer2(TestDiracInitializer1):
1069

1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090
    def config(self):
        self.weight_attr = paddle.ParamAttr(
            initializer=paddle.nn.initializer.Dirac(groups=1))
        self.dtype = "float64"
        self.in_channels = 4
        self.out_channels = 8
        self.kernel_size = (3, 3)
        self.input_shape = [8, self.in_channels, 10, 10]
        self.conv_layer = paddle.nn.Conv2D
        self.num_ops = 8

    def check_result(self, w_dygraph, w_static, conv_in, conv_out):
        self.assertTrue(np.array_equal(w_dygraph, w_static))
        self.assertTrue(
            np.array_equal(conv_out[:, 0:4, :, :], conv_in[:, :, 1:9, 1:9]))
        self.assertTrue(
            np.array_equal(conv_out[:, 4:8, :, :], np.zeros([8, 4, 8, 8])))


# initialize Conv3D weight
class TestDiracInitializer3(TestDiracInitializer1):
1091

1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105
    def config(self):
        self.weight_attr = paddle.ParamAttr(
            initializer=paddle.nn.initializer.Dirac(groups=2))
        self.dtype = "float32"
        self.in_channels = 5
        self.out_channels = 10
        self.kernel_size = (3, 3, 3)
        self.input_shape = [8, self.in_channels, 10, 10, 10]
        self.conv_layer = paddle.nn.Conv3D
        self.num_ops = 7

    def check_result(self, w_dygraph, w_static, conv_in, conv_out):
        self.assertTrue(np.array_equal(w_dygraph, w_static))
        self.assertTrue(
1106 1107
            np.array_equal(conv_out[:, 0:5, :, :, :], conv_in[:, :, 1:9, 1:9,
                                                              1:9]))
1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120
        self.assertTrue(
            np.array_equal(conv_out[:, 5:10, :, :, :], conv_in[:, :, 1:9, 1:9,
                                                               1:9]))

    def test_error(self):
        self.config()
        with self.assertRaises(AssertionError):
            paddle.nn.Linear(10, 10, weight_attr=self.weight_attr)

        with self.assertRaises(AssertionError):
            paddle.nn.Conv2D(5, 9, (3, 3), weight_attr=self.weight_attr)


1121
if __name__ == '__main__':
H
hong 已提交
1122
    paddle.enable_static()
1123
    unittest.main()