test_imperative_named_members.py 5.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import unittest
16

17
import numpy as np
18

19
import paddle
20
import paddle.fluid as fluid
21
from paddle.fluid.framework import _test_eager_guard
22 23 24 25


class MyLayer(fluid.Layer):
    def __init__(self, num_channel, dim, num_filter=5):
26
        super().__init__()
27
        self.fc = paddle.nn.Linear(dim, dim)
28
        self.conv = paddle.nn.Conv2D(num_channel, num_channel, num_filter)
29 30 31 32 33 34 35 36

    def forward(self, x):
        x = self.fc(x)
        x = self.conv(x)
        return x


class TestImperativeNamedSubLayers(unittest.TestCase):
37
    def func_test_named_sublayers(self):
38
        with fluid.dygraph.guard():
39 40
            fc1 = paddle.nn.Linear(10, 3)
            fc2 = paddle.nn.Linear(3, 10, bias_attr=False)
41
            custom = MyLayer(3, 10)
42
            model = paddle.nn.Sequential(fc1, fc2, custom)
43 44 45 46 47
            named_sublayers = model.named_sublayers()
            list_named_sublayers = list(named_sublayers)

            expected_sublayers = [fc1, fc2, custom, custom.fc, custom.conv]
            self.assertEqual(len(list_named_sublayers), len(expected_sublayers))
48 49 50
            for (name, sublayer), expected_sublayer in zip(
                list_named_sublayers, expected_sublayers
            ):
51 52 53 54
                self.assertEqual(sublayer, expected_sublayer)

            list_sublayers = list(model.sublayers())
            self.assertEqual(len(list_named_sublayers), len(list_sublayers))
55 56 57
            for (name, sublayer), expected_sublayer in zip(
                list_named_sublayers, list_sublayers
            ):
58 59 60 61
                self.assertEqual(sublayer, expected_sublayer)

            self.assertListEqual(
                [l for _, l in list(model.named_sublayers(include_self=True))],
62 63
                [model] + expected_sublayers,
            )
64

65 66 67 68 69
    def test_named_sublayers(self):
        with _test_eager_guard():
            self.func_test_named_sublayers()
        self.func_test_named_sublayers()

70 71

class TestImperativeNamedParameters(unittest.TestCase):
72
    def func_test_named_parameters(self):
73
        with fluid.dygraph.guard():
74 75
            fc1 = paddle.nn.Linear(10, 3)
            fc2 = paddle.nn.Linear(3, 10, bias_attr=False)
76
            custom = MyLayer(3, 10)
H
hong 已提交
77
            model = paddle.nn.Sequential(fc1, fc2, custom)
78 79 80

            named_parameters = list(model.named_parameters())
            expected_named_parameters = list()
J
Jiabin Yang 已提交
81
            for prefix, layer in model.named_sublayers():
82
                for name, param in layer.named_parameters(
83 84
                    include_sublayers=False
                ):
85 86 87 88 89
                    full_name = prefix + ('.' if prefix else '') + name
                    expected_named_parameters.append((full_name, param))

            self.assertListEqual(expected_named_parameters, named_parameters)

90 91 92 93 94 95
    def test_named_parameters(self):
        with _test_eager_guard():
            self.func_test_named_parameters()
        self.func_test_named_parameters()

    def func_test_dir_layer(self):
96 97 98 99
        with fluid.dygraph.guard():

            class Mymodel(fluid.dygraph.Layer):
                def __init__(self):
100
                    super().__init__()
101 102
                    self.linear1 = paddle.nn.Linear(10, 10)
                    self.linear2 = paddle.nn.Linear(5, 5)
103
                    self.conv2d = paddle.nn.Conv2D(3, 2, 3)
104 105
                    self.embedding = fluid.dygraph.Embedding(size=[128, 16])
                    self.h_0 = fluid.dygraph.to_variable(
106 107 108 109 110 111 112 113
                        np.zeros([10, 10]).astype('float32')
                    )
                    self.weight = self.create_parameter(
                        shape=[2, 3],
                        attr=fluid.ParamAttr(),
                        dtype="float32",
                        is_bias=False,
                    )
114 115 116 117 118

            model = Mymodel()

            expected_members = dir(model)

119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
            self.assertTrue(
                "linear1" in expected_members,
                "model should contain Layer: linear1",
            )
            self.assertTrue(
                "linear2" in expected_members,
                "model should contain Layer: linear2",
            )
            self.assertTrue(
                "conv2d" in expected_members,
                "model should contain Layer: conv2d",
            )
            self.assertTrue(
                "embedding" in expected_members,
                "model should contain Layer: embedding",
            )
            self.assertTrue(
                "h_0" in expected_members, "model should contain buffer: h_0"
            )
            self.assertTrue(
                "weight" in expected_members,
                "model should contain parameter: weight",
            )
142

143 144 145 146 147
    def test_dir_layer(self):
        with _test_eager_guard():
            self.func_test_dir_layer()
        self.func_test_dir_layer()

148 149 150

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