test_imperative_gnn.py 6.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
# 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.

import unittest
import numpy as np
import sys

import paddle
import paddle.fluid as fluid
import paddle.fluid.core as core
X
polish  
Xin Pan 已提交
22
from paddle.fluid.optimizer import AdamOptimizer
23
from test_imperative_base import new_program_scope
L
lujun 已提交
24
from paddle.fluid.dygraph.base import to_variable
25
from paddle.fluid.framework import _test_eager_guard
26 27 28 29 30 31


def gen_data():
    pass


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

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

    def forward(self, features, adj):
        support = fluid.layers.matmul(features, self.weight)
        # TODO(panyx0718): sparse matmul?
        return fluid.layers.matmul(adj, support) + self.bias


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

    def forward(self, x, adj):
        x = fluid.layers.relu(self.gc(x, adj))
        return self.gc2(x, adj)


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

        scope = fluid.core.Scope()
        with new_program_scope(main=main, startup=startup, scope=scope):
73 74 75 76 77 78
            features = fluid.layers.data(
                name='features',
                shape=[1, 100, 50],
                dtype='float32',
                append_batch_size=False,
            )
X
polish  
Xin Pan 已提交
79
            # Use selected rows when it's supported.
80 81 82 83 84 85 86 87 88 89 90 91
            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 已提交
92 93 94 95 96 97 98 99 100 101 102

            model = GCN('test_gcn', 50)
            logits = model(features, adj)
            logits = fluid.layers.reshape(logits, logits.shape[1:])
            # In other example, it's nll with log_softmax. However, paddle's
            # log_loss only supports binary classification now.
            loss = fluid.layers.softmax_with_cross_entropy(logits, labels)
            loss = fluid.layers.reduce_sum(loss)

            adam = AdamOptimizer(learning_rate=1e-3)
            adam.minimize(loss)
103 104 105 106 107
            exe = fluid.Executor(
                fluid.CPUPlace()
                if not core.is_compiled_with_cuda()
                else fluid.CUDAPlace(0)
            )
X
polish  
Xin Pan 已提交
108
            exe.run(startup)
109 110 111 112 113 114 115 116
            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 已提交
117 118

            static_weight = np.array(
119 120
                scope.find_var(model.gc.weight.name).get_tensor()
            )
X
polish  
Xin Pan 已提交
121

L
lujun 已提交
122
        with fluid.dygraph.guard():
C
cnn 已提交
123
            paddle.seed(90)
L
Leo Chen 已提交
124
            paddle.framework.random._manual_program_seed(90)
125

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

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

X
polish  
Xin Pan 已提交
145
            adam.minimize(loss)
146
            model.clear_gradients()
147 148
            loss_value = loss.numpy()
            model_gc_weight_value = model.gc.weight.numpy()
149 150

        with fluid.dygraph.guard():
C
cnn 已提交
151
            paddle.seed(90)
L
Leo Chen 已提交
152
            paddle.framework.random._manual_program_seed(90)
153

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

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

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

187 188 189 190 191
    def test_gnn_float32(self):
        with _test_eager_guard():
            self.func_gnn_float32()
        self.func_gnn_float32()

192 193

if __name__ == '__main__':
194
    paddle.enable_static()
195
    unittest.main()