test_initializer.py 41.8 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 math
16 17
import unittest

18 19
import numpy as np

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

DELTA = 0.00001


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


38 39 40 41 42 43 44 45
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


46
class TestConstantInitializer(unittest.TestCase):
47 48 49 50 51
    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)
52 53 54 55 56 57
        self.assertEqual(
            paddle.nn.initializer.calculate_gain('relu'), math.sqrt(2.0)
        )
        self.assertEqual(
            paddle.nn.initializer.calculate_gain('leaky_relu', 1), 1
        )
58 59
        self.assertEqual(paddle.nn.initializer.calculate_gain('selu'), 3.0 / 4)

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

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

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

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

110 111

class TestUniformInitializer(unittest.TestCase):
112
    def test_uniform_initializer_default_value(self, dtype="float32"):
113
        """Test the uniform initializer with default value"""
114 115
        program = framework.Program()
        block = program.global_block()
116
        for _ in range(2):
117 118 119 120 121 122 123
            block.create_parameter(
                dtype=dtype,
                shape=[5, 10],
                lod_level=0,
                name="param",
                initializer=initializer.UniformInitializer(),
            )
124
        num_ops = 2 if dtype == "float16" else 1
125
        self.assertEqual(len(block.ops), num_ops)
126 127 128 129 130
        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)
131
        return block
132

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

158
    def test_uniform_initializer(self, dtype="float32"):
159
        """Test uniform initializer with supplied attributes"""
160 161
        program = framework.Program()
        block = program.global_block()
162
        for _ in range(2):
163 164 165 166 167 168 169
            block.create_parameter(
                dtype=dtype,
                shape=[5, 10],
                lod_level=0,
                name="param",
                initializer=initializer.UniformInitializer(-4.2, 3.1, 123),
            )
170
        num_ops = 2 if dtype == "float16" else 1
171
        self.assertEqual(len(block.ops), num_ops)
172 173 174 175 176
        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)
177
        return block
178

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

    def test_uniform_initializer_fp16(self):
201
        """Test uniform initializer with float16"""
202 203 204 205 206 207
        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]))
208

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

217 218 219

class TestNormalInitializer(unittest.TestCase):
    def test_normal_initializer_default_value(self):
220
        """Test the normal initializer with default value"""
221 222
        program = framework.Program()
        block = program.global_block()
223
        for _ in range(2):
224 225 226 227 228 229 230
            block.create_parameter(
                dtype="float32",
                shape=[5, 10],
                lod_level=0,
                name="param",
                initializer=initializer.NormalInitializer(),
            )
231 232 233 234 235 236 237
        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)

238
    def test_normal_initializer(self, dtype="float32"):
239
        """Test normal initializer with supplied attributes"""
240 241
        program = framework.Program()
        block = program.global_block()
242
        for _ in range(2):
243 244 245 246 247 248 249
            block.create_parameter(
                dtype=dtype,
                shape=[5, 10],
                lod_level=0,
                name="param",
                initializer=initializer.NormalInitializer(2.3, 1.9, 123),
            )
250
        num_ops = 1
251
        self.assertEqual(len(block.ops), num_ops)
252 253 254 255 256
        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)
257 258 259
        return block

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

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

267

268 269 270
class TestXavierInitializer(unittest.TestCase):
    def test_uniform_xavier_initializer(self):
        """Test Xavier initializer with uniform distribution on
271
        for matrix multiply.
272 273 274
        """
        program = framework.Program()
        block = program.global_block()
275 276 277 278 279 280
        for _ in range(2):
            param = block.create_parameter(
                dtype="float32",
                shape=[5, 10],
                lod_level=0,
                name="param",
281 282
                initializer=initializer.XavierInitializer(),
            )
283 284 285 286 287 288 289 290 291 292
        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
293
        for convolutions.
294 295 296
        """
        program = framework.Program()
        block = program.global_block()
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",
303 304
                initializer=initializer.XavierInitializer(),
            )
305 306 307 308
        self.assertEqual(len(block.ops), 1)
        init_op = block.ops[0]
        self.assertEqual(init_op.type, 'uniform_random')
        receptive_field_size = float(15 * 20)
309
        limit = np.sqrt(
310 311
            6.0 / ((param.shape[0] + param.shape[1]) * receptive_field_size)
        )
312 313 314 315 316 317
        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
318
        for matrix multiply.
319 320 321
        """
        program = framework.Program()
        block = program.global_block()
322 323 324 325 326 327
        for _ in range(2):
            param = block.create_parameter(
                dtype="float32",
                shape=[5, 10],
                lod_level=0,
                name="param",
328 329
                initializer=initializer.XavierInitializer(uniform=False),
            )
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
340
        for convolutions.
341 342 343
        """
        program = framework.Program()
        block = program.global_block()
344 345 346 347 348 349
        for _ in range(2):
            param = block.create_parameter(
                dtype="float32",
                shape=[5, 10, 15, 20],
                lod_level=0,
                name="param",
350 351
                initializer=initializer.XavierInitializer(uniform=False),
            )
352 353 354 355
        self.assertEqual(len(block.ops), 1)
        init_op = block.ops[0]
        self.assertEqual(init_op.type, 'gaussian_random')
        receptive_field_size = float(15 * 20)
356
        std = np.sqrt(
357 358
            2.0 / ((param.shape[0] + param.shape[1]) * receptive_field_size)
        )
359 360 361 362
        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)

363 364 365 366
    def test_xavier_initializer_supplied_arguments(
        self, dtype="float32", uniform=True
    ):
        """Test the Xavier initializer with supplied arguments"""
367 368
        program = framework.Program()
        block = program.global_block()
369
        for _ in range(2):
370 371 372 373 374 375 376 377 378 379 380 381 382 383
            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
        )
384
        self.assertEqual(len(block.ops), num_ops)
385
        init_op = block.ops[0]
386 387 388 389 390 391 392
        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')
393
        self.assertEqual(init_op.attr('seed'), 134)
394 395 396
        return block

    def test_xavier_initializer_fp16(self):
397
        """Test the Xavier initializer with float16"""
398
        block = self.test_xavier_initializer_supplied_arguments("float16")
399

400
    def test_xavier_initializer_bf16(self):
401
        """Test the Xavier initializer with bfloat16"""
402
        block_uniform = self.test_xavier_initializer_supplied_arguments(
403 404
            "uint16"
        )
405 406
        self.assertEqual(len(block_uniform.ops), 1)
        block_gaussian = self.test_xavier_initializer_supplied_arguments(
407 408
            "uint16", False
        )
409

410

411 412 413
class TestMSRAInitializer(unittest.TestCase):
    def test_uniform_msra_initializer(self):
        """Test MSRA initializer with uniform distribution on
414
        for matrix multiply.
415 416 417
        """
        program = framework.Program()
        block = program.global_block()
418 419 420 421 422 423
        for _ in range(2):
            param = block.create_parameter(
                dtype="float32",
                shape=[5, 10],
                lod_level=0,
                name="param",
424 425
                initializer=initializer.MSRAInitializer(),
            )
426 427 428 429 430 431 432 433 434 435
        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
436
        for convolutions.
437 438 439
        """
        program = framework.Program()
        block = program.global_block()
440 441 442 443 444 445
        for _ in range(2):
            param = block.create_parameter(
                dtype="float32",
                shape=[5, 10, 15, 20],
                lod_level=0,
                name="param",
446 447
                initializer=initializer.MSRAInitializer(),
            )
448 449 450 451 452 453 454 455 456 457 458
        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
459
        for matrix multiply.
460 461 462
        """
        program = framework.Program()
        block = program.global_block()
463 464 465 466 467 468
        for _ in range(2):
            param = block.create_parameter(
                dtype="float32",
                shape=[5, 10],
                lod_level=0,
                name="param",
469 470
                initializer=initializer.MSRAInitializer(uniform=False),
            )
471 472 473 474 475 476 477 478 479 480
        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
481
        for convolutions.
482 483 484
        """
        program = framework.Program()
        block = program.global_block()
485 486 487 488 489 490
        for _ in range(2):
            param = block.create_parameter(
                dtype="float32",
                shape=[5, 10, 15, 20],
                lod_level=0,
                name="param",
491 492
                initializer=initializer.MSRAInitializer(uniform=False),
            )
493 494 495 496 497 498 499 500 501
        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)

502
    def test_msra_initializer_supplied_arguments(self, dtype="float32"):
503
        """Test the MSRA initializer with supplied arguments"""
504 505
        program = framework.Program()
        block = program.global_block()
506
        for _ in range(2):
507 508 509 510 511 512 513
            block.create_parameter(
                dtype=dtype,
                shape=[5, 10],
                lod_level=0,
                name="param",
                initializer=initializer.MSRAInitializer(fan_in=12, seed=134),
            )
514
        num_ops = 2 if dtype == "float16" else 1
515
        self.assertEqual(len(block.ops), num_ops)
516 517 518 519 520 521
        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)
522
        return block
523

524
    def test_msra_initializer_fp16(self):
525
        """Test the MSRA initializer with float16"""
526 527
        block = self.test_msra_initializer_supplied_arguments("float16")
        self.assertTrue(check_cast_op(block.ops[1]))
528

529
    def test_msra_initializer_bf16(self):
530
        """Test the MSRA initializer with bfloat16"""
531 532
        block = self.test_msra_initializer_supplied_arguments("uint16")

533 534 535

class TestBilinearInitializer(unittest.TestCase):
    def test_bilinear_initializer(self, dtype="float32"):
536
        """Test the bilinear initializer with supplied arguments"""
537 538
        program = framework.Program()
        block = program.global_block()
539 540
        for _ in range(2):
            block.create_parameter(
541
                dtype=dtype,
542 543 544
                shape=[8, 1, 3, 3],
                lod_level=0,
                name="param",
545 546
                initializer=initializer.BilinearInitializer(),
            )
547
        num_ops = 2 if dtype in ["float16", "uint16", "float64"] else 1
548
        self.assertEqual(len(block.ops), num_ops)
549 550
        init_op = block.ops[0]
        self.assertEqual(init_op.type, 'assign_value')
551 552
        return block

553 554 555
    def test_bilinear_initializer_fp64(self):
        self.test_bilinear_initializer(dtype='float64')

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

561
    def test_bilinear_initializer_bf16(self):
562
        """Test the bilinear initializer with supplied arguments"""
563 564 565
        block = self.test_bilinear_initializer("uint16")
        self.assertTrue(check_cast_op(block.ops[1]))

566 567 568
    def test_type_error(self):
        self.assertRaises(TypeError, self.test_bilinear_initializer, 'int32')

569

570 571 572 573 574 575
class TestBilinearInitializerDygraphAPI(unittest.TestCase):
    def func_test_case(self):
        factor = 2
        C = 2
        B = 8
        H = W = 32
576 577 578 579 580
        w_attr = paddle.ParamAttr(
            learning_rate=0.0,
            regularizer=L2Decay(0.0),
            initializer=initializer.BilinearInitializer(),
        )
581
        data = paddle.rand([B, 3, H, W], dtype='float32')
582 583 584 585 586 587 588 589 590
        conv_up = paddle.nn.Conv2DTranspose(
            3,
            out_channels=C,
            kernel_size=2 * factor - factor % 2,
            padding=int(math.ceil((factor - 1) / 2.0)),
            stride=factor,
            weight_attr=w_attr,
            bias_attr=False,
        )
591 592 593 594 595 596
        x = conv_up(data)
        return x

    def func_test_case_fp16(self):
        paddle.set_default_dtype("float16")
        paddle.seed(1234)
597 598 599 600 601
        w_attr = paddle.ParamAttr(
            learning_rate=0.0,
            regularizer=L2Decay(0.0),
            initializer=initializer.BilinearInitializer(),
        )
602 603 604 605 606 607
        conv2d = paddle.nn.Conv2D(1, 2, 3, weight_attr=w_attr)
        paddle.set_default_dtype("float32")
        return conv2d.weight

    def test_bilinear_initializer(self):
        paddle.disable_static()
608
        eager_x = self.func_test_case()
609 610 611 612 613 614
        legacy_x = self.func_test_case()
        self.assertEqual(eager_x.numpy().all(), legacy_x.numpy().all())
        paddle.enable_static()

    def test_bilinear_initializer_fp16(self):
        paddle.disable_static()
615
        eager_x = self.func_test_case_fp16()
616 617 618 619 620
        legacy_x = self.func_test_case_fp16()
        self.assertEqual(eager_x.numpy().all(), legacy_x.numpy().all())
        paddle.enable_static()


Q
Qiao Longfei 已提交
621
class TestNumpyArrayInitializer(unittest.TestCase):
622
    def test_numpy_array_initializer(self, dtype="float32"):
623
        """Test the numpy array initializer with supplied arguments"""
Q
Qiao Longfei 已提交
624
        import numpy
625

Q
Qiao Longfei 已提交
626 627
        program = framework.Program()
        block = program.global_block()
628
        np_array = numpy.random.random((10000)).astype(dtype)
Q
Qiao Longfei 已提交
629 630 631 632 633 634
        for _ in range(2):
            block.create_parameter(
                dtype=np_array.dtype,
                shape=np_array.shape,
                lod_level=0,
                name="param",
635 636
                initializer=initializer.NumpyArrayInitializer(np_array),
            )
637
        num_ops = 2 if dtype in ["float16", "uint16"] else 1
638
        self.assertEqual(len(block.ops), num_ops)
Q
Qiao Longfei 已提交
639 640
        init_op = block.ops[0]
        self.assertEqual(init_op.type, 'assign_value')
641
        assert (init_op.attr('fp32_values') == np_array).all()
642 643 644
        return block

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

649
    def test_numpy_array_initializer_bf16(self):
650
        """Test the numpy array initializer with bfloat16"""
651 652 653
        block = self.test_numpy_array_initializer("uint16")
        self.assertTrue(block.ops[1])

Q
Qiao Longfei 已提交
654

655 656
class TestSetGlobalInitializer(unittest.TestCase):
    def test_set_global_weight_initilizer(self):
657
        """Test Set Global Param initilizer with UniformInitializer"""
658 659 660 661 662 663
        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
664
            conv = paddle.static.nn.conv2d(x, 5, 3)
665 666 667 668

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

669 670
        # init weight is the first op, and bias is the second
        bias_init_op = block.ops[1]
671 672 673
        self.assertEqual(bias_init_op.type, 'fill_constant')
        self.assertAlmostEqual(bias_init_op.attr('value'), 0.0, delta=DELTA)

674
        param_init_op = block.ops[0]
675 676 677 678 679 680 681
        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):
682
        """Test Set Global Bias initilizer with NormalInitializer"""
683 684
        main_prog = framework.Program()
        startup_prog = framework.Program()
685 686 687 688
        fluid.set_global_initializer(
            initializer.Uniform(low=-0.5, high=0.5),
            bias_init=initializer.Normal(loc=0.0, scale=2.0),
        )
689 690 691
        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
692
            conv = paddle.static.nn.conv2d(x, 5, 3)
693 694 695 696

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

697 698
        # init weight is the first op, and bias is the second
        bias_init_op = block.ops[1]
699 700 701 702 703
        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)

704
        param_init_op = block.ops[0]
705 706 707 708 709 710 711
        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)


712
class TestUniformInitializerDygraph(unittest.TestCase):
713
    def test_uniform_initializer(self, dtype="float32"):
714 715 716 717 718
        """
        In dygraph mode, we can use initializer directly to initialize a tensor.
        """
        paddle.disable_static()

L
Leo Chen 已提交
719
        tensor = paddle.zeros([1024, 1024, 16])
720
        tensor.stop_gradient = False
721 722 723
        np.testing.assert_allclose(
            np.zeros((1024, 1024, 16)), tensor.numpy(), rtol=1e-05
        )
724 725 726 727

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

728 729 730
        self.assertEqual(
            tensor.stop_gradient, False
        )  # stop_gradient is not changed
731 732 733

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

734
        np.testing.assert_allclose(hist, prob, rtol=0, atol=0.001)
735 736 737 738

        paddle.enable_static()


739
class TestXavierInitializerDygraph(unittest.TestCase):
740
    def test_xvarier_initializer(self, dtype="float32"):
741 742 743 744 745 746 747 748
        """
        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

749 750 751
        xavier_ = paddle.fluid.initializer.XavierInitializer(
            uniform=False, fan_in=3, fan_out=5
        )
752 753 754 755 756
        xavier_(tensor)

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

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

760
        np.testing.assert_allclose(hist, hist2, rtol=0, atol=0.01)
761 762 763 764
        paddle.enable_static()


class TestMSRAInitializerDygraph(unittest.TestCase):
765
    def test_msra_initializer(self, dtype="float32"):
766 767 768 769 770 771 772 773
        """
        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

774 775 776
        msra_ = paddle.fluid.initializer.MSRAInitializer(
            uniform=False, fan_in=4
        )
777 778 779 780 781
        msra_(tensor)

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

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

785
        np.testing.assert_allclose(hist, hist2, rtol=0, atol=0.01)
786 787 788
        paddle.enable_static()


789
class TesetconsistencyOfDynamicAndStaticGraph(unittest.TestCase):
790
    def test_order(self):
791 792 793 794 795 796 797
        paddle.set_device('cpu')
        SEED = 123
        weight_attr = paddle.framework.ParamAttr(
            name="linear_weight",
            learning_rate=1.0,
            trainable=False,
            regularizer=None,
798 799 800 801
            initializer=paddle.nn.initializer.TruncatedNormal(
                mean=0.0, std=2.0
            ),
        )
802 803 804 805 806
        bias_attr = paddle.framework.ParamAttr(
            name="linear_bias",
            learning_rate=1.0,
            trainable=False,
            regularizer=None,
807 808 809 810
            initializer=paddle.nn.initializer.TruncatedNormal(
                mean=0.0, std=2.0
            ),
        )
811 812 813 814

        def run_dynamic_graph():
            paddle.disable_static()
            paddle.seed(SEED)
815 816 817
            linear = paddle.nn.Linear(
                1, 1, weight_attr=weight_attr, bias_attr=bias_attr
            )
818 819 820 821 822 823 824
            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)
825 826 827 828 829 830 831
            linear = paddle.nn.Linear(
                1, 1, weight_attr=weight_attr, bias_attr=bias_attr
            )
            res = exe.run(
                paddle.static.default_startup_program(),
                fetch_list=['linear_weight', 'linear_bias'],
            )
832 833 834 835 836
            return res[0], res[1]

        dynamic_res = run_dynamic_graph()
        static_res = run_static_graph()

837 838
        np.testing.assert_array_equal(dynamic_res[0], static_res[0])
        np.testing.assert_array_equal(dynamic_res[1], static_res[1])
839 840


841 842 843 844 845 846 847 848
# 2-D Parameter with shape: [10, 15]
class TestOrthogonalInitializer1(unittest.TestCase):
    """
    case 1
    """

    def config(self):
        self.weight_attr = paddle.ParamAttr(
849 850
            initializer=paddle.nn.initializer.Orthogonal(gain=3.0)
        )
851 852 853 854 855 856
        self.dtype = "float64"
        self.in_features = 10
        self.out_features = 15
        self.num_ops = 9

    def check_result(self, a, b):
857
        np.testing.assert_array_equal(a, b)
858 859 860
        np.testing.assert_allclose(
            np.matmul(a, a.T), 9 * np.eye(10), rtol=1e-5, atol=1e-8
        )
861

862
    def test_orthogonal(self):
863 864 865 866 867
        self.config()
        paddle.set_default_dtype(self.dtype)

        paddle.disable_static()
        paddle.seed(2021)
868 869 870
        linear = paddle.nn.Linear(
            self.in_features, self.out_features, weight_attr=self.weight_attr
        )
871 872 873 874 875 876 877
        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):
878 879 880 881 882
            linear = paddle.nn.Linear(
                self.in_features,
                self.out_features,
                weight_attr=self.weight_attr,
            )
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

            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)


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

    def config(self):
        self.weight_attr = paddle.ParamAttr(
908 909
            initializer=paddle.nn.initializer.Orthogonal(gain=2.0)
        )
910 911 912 913 914 915
        self.dtype = "float64"
        self.in_features = 15
        self.out_features = 10
        self.num_ops = 8

    def check_result(self, a, b):
916
        np.testing.assert_array_equal(a, b)
917 918 919
        np.testing.assert_allclose(
            np.matmul(a.T, a), 4 * np.eye(10), rtol=1e-5, atol=1e-8
        )
920 921 922 923 924 925 926 927 928 929


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

    def config(self):
        self.weight_attr = paddle.ParamAttr(
930 931
            initializer=paddle.nn.initializer.Orthogonal()
        )
932 933 934 935 936 937
        self.dtype = "float32"
        self.in_features = 10
        self.out_features = 10
        self.num_ops = 8

    def check_result(self, a, b):
938
        np.testing.assert_array_equal(a, b)
939 940 941 942 943 944
        np.testing.assert_allclose(
            np.matmul(a.T, a), np.eye(10), rtol=1e-05, atol=1e-06
        )
        np.testing.assert_allclose(
            np.matmul(a, a.T), np.eye(10), rtol=1e-05, atol=1e-06
        )
945 946 947 948 949 950 951 952 953 954 955 956 957 958 959

    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(
960 961
            initializer=paddle.nn.initializer.Orthogonal(gain=3.0)
        )
962 963 964 965 966 967
        self.dtype = "float64"
        self.in_features = 4
        self.out_features = 6
        self.kernel_size = (3, 3)

    def check_result(self, a, b):
968
        np.testing.assert_array_equal(a, b)
969
        a = a.reshape(6, -1)
970 971 972
        np.testing.assert_allclose(
            np.matmul(a, a.T), 9 * np.eye(6), rtol=1e-5, atol=1e-8
        )
973

974
    def test_orthogonal(self):
975 976 977 978 979
        self.config()
        paddle.set_default_dtype(self.dtype)

        paddle.disable_static()
        paddle.seed(2021)
980 981 982 983 984 985
        conv2d = paddle.nn.Conv2D(
            self.in_features,
            self.out_features,
            self.kernel_size,
            weight_attr=self.weight_attr,
        )
986 987 988 989 990 991 992
        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):
993 994 995 996 997 998
            conv2d = paddle.nn.Conv2D(
                self.in_features,
                self.out_features,
                self.kernel_size,
                weight_attr=self.weight_attr,
            )
999
            exe = paddle.static.Executor()
1000 1001 1002 1003
            res_static = exe.run(
                paddle.static.default_startup_program(),
                fetch_list=[conv2d.weight],
            )[0]
1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014
        self.check_result(res_dygraph, res_static)


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

    def config(self):
        self.weight_attr = paddle.ParamAttr(
1015 1016
            initializer=paddle.nn.initializer.Orthogonal(gain=2.0)
        )
1017 1018 1019 1020 1021 1022
        self.dtype = "float64"
        self.in_features = 4
        self.out_features = 50
        self.kernel_size = (3, 3)

    def check_result(self, a, b):
1023
        np.testing.assert_array_equal(a, b)
1024
        a = a.reshape(50, -1)
1025 1026 1027
        np.testing.assert_allclose(
            np.matmul(a.T, a), 4 * np.eye(36), rtol=1e-5, atol=1e-8
        )
1028 1029 1030 1031 1032 1033 1034 1035 1036 1037


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

    def config(self):
        self.weight_attr = paddle.ParamAttr(
1038 1039
            initializer=paddle.nn.initializer.Orthogonal()
        )
1040 1041 1042 1043 1044 1045
        self.dtype = "float32"
        self.in_features = 4
        self.out_features = 36
        self.kernel_size = (3, 3)

    def check_result(self, a, b):
1046
        np.testing.assert_array_equal(a, b)
1047
        a = a.reshape(36, -1)
1048 1049 1050 1051 1052 1053
        np.testing.assert_allclose(
            np.matmul(a.T, a), np.eye(36), rtol=1e-05, atol=1e-06
        )
        np.testing.assert_allclose(
            np.matmul(a, a.T), np.eye(36), rtol=1e-05, atol=1e-06
        )
1054 1055


1056 1057 1058 1059
# initialize Conv1D weight
class TestDiracInitializer1(unittest.TestCase):
    def config(self):
        self.weight_attr = paddle.ParamAttr(
1060 1061
            initializer=paddle.nn.initializer.Dirac()
        )
1062 1063 1064 1065 1066 1067
        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
1068 1069 1070
        self.num_ops = (
            8  # fill_constant*2, reshape*2, assign_value*2, scatter, cast
        )
1071 1072

    def check_result(self, w_dygraph, w_static, conv_in, conv_out):
1073 1074
        np.testing.assert_array_equal(w_dygraph, w_static)
        np.testing.assert_array_equal(conv_out, conv_in[:, 0:2, 1:9])
1075

1076
    def test_dirac(self):
1077 1078 1079 1080
        self.config()
        paddle.set_default_dtype(self.dtype)

        paddle.disable_static()
1081 1082 1083 1084 1085 1086
        conv = self.conv_layer(
            self.in_channels,
            self.out_channels,
            self.kernel_size,
            weight_attr=self.weight_attr,
        )
1087 1088 1089 1090 1091 1092 1093
        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)
1094 1095 1096 1097 1098 1099
            conv = self.conv_layer(
                self.in_channels,
                self.out_channels,
                self.kernel_size,
                weight_attr=self.weight_attr,
            )
1100 1101 1102 1103 1104

            output = conv(inp)
            block = start_prog.global_block()
            self.assertEqual(len(block.ops), self.num_ops)
            self.assertEqual(block.ops[0].type, 'fill_constant')
1105
            self.assertEqual(block.ops[1].type, 'reshape2')
1106 1107 1108
            self.assertEqual(block.ops[2].type, 'assign_value')
            self.assertEqual(block.ops[3].type, 'assign_value')
            self.assertEqual(block.ops[4].type, 'scatter')
1109
            self.assertEqual(block.ops[5].type, 'reshape2')
1110 1111 1112 1113 1114 1115 1116 1117

            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]

1118 1119 1120
        self.check_result(
            weight_dygraph, weight_static, conv_input, conv_output
        )
1121 1122 1123 1124 1125 1126


# initialize Conv2D weight
class TestDiracInitializer2(TestDiracInitializer1):
    def config(self):
        self.weight_attr = paddle.ParamAttr(
1127 1128
            initializer=paddle.nn.initializer.Dirac(groups=1)
        )
1129 1130 1131 1132 1133 1134 1135 1136 1137
        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):
1138
        np.testing.assert_array_equal(w_dygraph, w_static)
1139 1140 1141 1142 1143 1144
        np.testing.assert_array_equal(
            conv_out[:, 0:4, :, :], conv_in[:, :, 1:9, 1:9]
        )
        np.testing.assert_array_equal(
            conv_out[:, 4:8, :, :], np.zeros([8, 4, 8, 8])
        )
1145 1146 1147 1148 1149 1150


# initialize Conv3D weight
class TestDiracInitializer3(TestDiracInitializer1):
    def config(self):
        self.weight_attr = paddle.ParamAttr(
1151 1152
            initializer=paddle.nn.initializer.Dirac(groups=2)
        )
1153 1154 1155 1156 1157 1158 1159 1160 1161
        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):
1162
        np.testing.assert_array_equal(w_dygraph, w_static)
1163 1164 1165 1166 1167 1168
        np.testing.assert_array_equal(
            conv_out[:, 0:5, :, :, :], conv_in[:, :, 1:9, 1:9, 1:9]
        )
        np.testing.assert_array_equal(
            conv_out[:, 5:10, :, :, :], conv_in[:, :, 1:9, 1:9, 1:9]
        )
1169 1170 1171 1172 1173 1174 1175 1176 1177 1178

    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)


1179
if __name__ == '__main__':
H
hong 已提交
1180
    paddle.enable_static()
1181
    unittest.main()