test_imperative_gnn.py 6.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14
# Copyright (c) 2018 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.

15
import sys
16
import unittest
17

18
import numpy as np
19
from test_imperative_base import new_program_scope
20 21 22 23

import paddle
import paddle.fluid as fluid
import paddle.fluid.core as core
24
import paddle.nn.functional as F
L
lujun 已提交
25
from paddle.fluid.dygraph.base import to_variable
26
from paddle.fluid.framework import _test_eager_guard
27
from paddle.fluid.optimizer import AdamOptimizer
28 29 30 31 32 33


def gen_data():
    pass


34
class GraphConv(fluid.Layer):
35
    def __init__(self, name_scope, in_features, out_features):
36
        super().__init__(name_scope)
37 38 39 40 41 42

        self._in_features = in_features
        self._out_features = out_features
        self.weight = self.create_parameter(
            attr=None,
            dtype='float32',
43 44 45 46 47
            shape=[self._in_features, self._out_features],
        )
        self.bias = self.create_parameter(
            attr=None, dtype='float32', shape=[self._out_features]
        )
48 49

    def forward(self, features, adj):
K
kangguangli 已提交
50
        support = paddle.matmul(features, self.weight)
51
        # TODO(panyx0718): sparse matmul?
K
kangguangli 已提交
52
        return paddle.matmul(adj, support) + self.bias
53 54


55
class GCN(fluid.Layer):
56
    def __init__(self, name_scope, num_hidden):
57
        super().__init__(name_scope)
58 59 60 61
        self.gc = GraphConv(self.full_name(), num_hidden, 32)
        self.gc2 = GraphConv(self.full_name(), 32, 10)

    def forward(self, x, adj):
62
        x = F.relu(self.gc(x, adj))
63 64 65
        return self.gc2(x, adj)


L
lujun 已提交
66
class TestDygraphGNN(unittest.TestCase):
67
    def func_gnn_float32(self):
C
cnn 已提交
68
        paddle.seed(90)
L
Leo Chen 已提交
69
        paddle.framework.random._manual_program_seed(90)
X
polish  
Xin Pan 已提交
70 71 72 73 74
        startup = fluid.Program()
        main = fluid.Program()

        scope = fluid.core.Scope()
        with new_program_scope(main=main, startup=startup, scope=scope):
75 76 77 78 79 80
            features = fluid.layers.data(
                name='features',
                shape=[1, 100, 50],
                dtype='float32',
                append_batch_size=False,
            )
X
polish  
Xin Pan 已提交
81
            # Use selected rows when it's supported.
82 83 84 85 86 87 88 89 90 91 92 93
            adj = fluid.layers.data(
                name='adj',
                shape=[1, 100, 100],
                dtype='float32',
                append_batch_size=False,
            )
            labels = fluid.layers.data(
                name='labels',
                shape=[100, 1],
                dtype='int64',
                append_batch_size=False,
            )
X
polish  
Xin Pan 已提交
94 95 96

            model = GCN('test_gcn', 50)
            logits = model(features, adj)
97
            logits = paddle.reshape(logits, logits.shape[1:])
X
polish  
Xin Pan 已提交
98 99
            # In other example, it's nll with log_softmax. However, paddle's
            # log_loss only supports binary classification now.
100 101 102
            loss = paddle.nn.functional.softmax_with_cross_entropy(
                logits, labels
            )
103
            loss = paddle.sum(loss)
X
polish  
Xin Pan 已提交
104 105 106

            adam = AdamOptimizer(learning_rate=1e-3)
            adam.minimize(loss)
107 108 109 110 111
            exe = fluid.Executor(
                fluid.CPUPlace()
                if not core.is_compiled_with_cuda()
                else fluid.CUDAPlace(0)
            )
X
polish  
Xin Pan 已提交
112
            exe.run(startup)
113 114 115 116 117 118 119 120
            static_loss = exe.run(
                feed={
                    'features': np.ones([1, 100, 50], dtype=np.float32),
                    'adj': np.ones([1, 100, 100], dtype=np.float32),
                    'labels': np.ones([100, 1], dtype=np.int64),
                },
                fetch_list=[loss],
            )[0]
X
polish  
Xin Pan 已提交
121 122

            static_weight = np.array(
123 124
                scope.find_var(model.gc.weight.name).get_tensor()
            )
X
polish  
Xin Pan 已提交
125

L
lujun 已提交
126
        with fluid.dygraph.guard():
C
cnn 已提交
127
            paddle.seed(90)
L
Leo Chen 已提交
128
            paddle.framework.random._manual_program_seed(90)
129

130
            features = np.ones([1, 100, 50], dtype=np.float32)
X
polish  
Xin Pan 已提交
131
            # Use selected rows when it's supported.
132 133
            adj = np.ones([1, 100, 100], dtype=np.float32)
            labels = np.ones([100, 1], dtype=np.int64)
134 135 136

            model = GCN('test_gcn', 50)
            logits = model(to_variable(features), to_variable(adj))
137
            logits = paddle.reshape(logits, logits.shape[1:])
138 139
            # In other example, it's nll with log_softmax. However, paddle's
            # log_loss only supports binary classification now.
140
            loss = paddle.nn.functional.softmax_with_cross_entropy(
141 142
                logits, to_variable(labels)
            )
143
            loss = paddle.sum(loss)
144
            loss.backward()
145 146 147
            adam = AdamOptimizer(
                learning_rate=1e-3, parameter_list=model.parameters()
            )
148

X
polish  
Xin Pan 已提交
149
            adam.minimize(loss)
150
            model.clear_gradients()
151 152
            loss_value = loss.numpy()
            model_gc_weight_value = model.gc.weight.numpy()
153 154

        with fluid.dygraph.guard():
C
cnn 已提交
155
            paddle.seed(90)
L
Leo Chen 已提交
156
            paddle.framework.random._manual_program_seed(90)
157

158
            features2 = np.ones([1, 100, 50], dtype=np.float32)
159
            # Use selected rows when it's supported.
160 161
            adj2 = np.ones([1, 100, 100], dtype=np.float32)
            labels2 = np.ones([100, 1], dtype=np.int64)
162 163 164

            model2 = GCN('test_gcn', 50)
            logits2 = model2(to_variable(features2), to_variable(adj2))
165
            logits2 = paddle.reshape(logits2, logits2.shape[1:])
166 167
            # In other example, it's nll with log_softmax. However, paddle's
            # log_loss only supports binary classification now.
168
            loss2 = paddle.nn.functional.softmax_with_cross_entropy(
169 170
                logits2, to_variable(labels2)
            )
171
            loss2 = paddle.sum(loss2)
172
            loss2.backward()
173 174 175
            adam2 = AdamOptimizer(
                learning_rate=1e-3, parameter_list=model2.parameters()
            )
176
            adam2.minimize(loss2)
177
            model2.clear_gradients()
178 179 180 181
            loss2_value = loss2.numpy()
            model2_gc_weight_value = model2.gc.weight.numpy()

        self.assertEqual(static_loss, loss_value)
182 183 184
        np.testing.assert_allclose(
            static_weight, model_gc_weight_value, rtol=1e-05
        )
185
        self.assertEqual(static_loss, loss2_value)
186 187 188
        np.testing.assert_allclose(
            static_weight, model2_gc_weight_value, rtol=1e-05
        )
189
        sys.stderr.write('%s %s\n' % (static_loss, loss_value))
190

191 192 193 194 195
    def test_gnn_float32(self):
        with _test_eager_guard():
            self.func_gnn_float32()
        self.func_gnn_float32()

196 197

if __name__ == '__main__':
198
    paddle.enable_static()
199
    unittest.main()