test_batch_graph_wrapper.py 4.3 KB
Newer Older
Y
Yelrose 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
# 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.
"""
    This file is for testing gin layer.
"""
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import unittest
import numpy as np

import paddle.fluid as F
import paddle.fluid.layers as L

Y
Yelrose 已提交
27
from pgl.layers.conv import gcn 
Y
Yelrose 已提交
28 29 30 31 32 33 34 35
from pgl import graph
from pgl import graph_wrapper


class BatchedGraphWrapper(unittest.TestCase):
    """BatchedGraphWrapper
    """
    def test_batched_graph_wrapper(self):
Y
Yelrose 已提交
36
        """test_batch_graph_wrapper
Y
Yelrose 已提交
37 38 39 40 41
        """
        np.random.seed(1)

        graph_list = []
      
Y
Yelrose 已提交
42
        num_graph = 5 
Y
Yelrose 已提交
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
        feed_num_nodes = []
        feed_num_edges = []
        feed_edges = []
        feed_node_feats = []
        
        for _ in range(num_graph):
            num_nodes = np.random.randint(5, 20) 
            edges = np.random.randint(low=0, high=num_nodes, size=(10, 2))
            node_feat = {"feature": np.random.rand(num_nodes, 4).astype("float32")}
            single_graph  = graph.Graph(num_nodes=num_nodes, edges=edges, node_feat=node_feat)
            feed_num_nodes.append(num_nodes)
            feed_num_edges.append(len(edges))
            feed_edges.append(edges)
            feed_node_feats.append(node_feat["feature"])
            graph_list.append(single_graph)

        multi_graph = graph.MultiGraph(graph_list)
 
        np.random.seed(1)
        hidden_size = 8
        num_nodes = 10

        place = F.CUDAPlace(0)# if use_cuda else F.CPUPlace()
        prog = F.Program()
        startup_prog = F.Program()
        
        with F.program_guard(prog, startup_prog):
            with F.unique_name.guard():
                # Standard Graph Wrapper
                gw = graph_wrapper.GraphWrapper(
                    name='graph',
                    place=place,
                    node_feat=[("feature", [-1, 4], "float32")])

Y
Yelrose 已提交
77
                output = gcn(gw,
Y
Yelrose 已提交
78 79 80
                    gw.node_feat['feature'],
                    hidden_size=hidden_size,
                    activation='relu',
Y
Yelrose 已提交
81 82
                    name='gcn')

Y
Yelrose 已提交
83 84 85 86 87 88 89 90 91 92
                # BatchGraphWrapper
                num_nodes = L.data(name="num_nodes", shape=[-1], dtype="int32")
                num_edges= L.data(name="num_edges", shape=[-1], dtype="int32")
                edges = L.data(name="edges", shape=[-1, 2], dtype="int32")
                node_feat = L.data(name="node_feats", shape=[-1, 4], dtype="float32")
                batch_gw = graph_wrapper.BatchGraphWrapper(num_nodes=num_nodes,
                                                 num_edges=num_edges,
                                                 edges=edges,
                                                 node_feats={"feature": node_feat})

Y
Yelrose 已提交
93
                output2 = gcn(batch_gw,
Y
Yelrose 已提交
94 95 96
                    batch_gw.node_feat['feature'],
                    hidden_size=hidden_size,
                    activation='relu',
Y
Yelrose 已提交
97
                    name='gcn')
Y
Yelrose 已提交
98 99 100 101 102 103 104 105 106 107 108
    

        exe = F.Executor(place)
        exe.run(startup_prog)
        feed_dict = gw.to_feed(multi_graph)
        feed_dict["num_nodes"] = np.array(feed_num_nodes, dtype="int32")
        feed_dict["num_edges"] = np.array(feed_num_edges, dtype="int32")
        feed_dict["edges"] = np.array(np.concatenate(feed_edges, 0), dtype="int32").reshape([-1, 2])
        feed_dict["node_feats"] = np.array(np.concatenate(feed_node_feats, 0), dtype="float32").reshape([-1, 4])
        
        # Run
Y
Yelrose 已提交
109
        O1, O2 = exe.run(prog, feed=feed_dict, fetch_list=[output, output2])
Y
Yelrose 已提交
110 111

        # The output from two kind of models should be same.
Y
Yelrose 已提交
112 113 114
        for o1, o2 in zip(O1, O2):
            dist = np.sum((o1 - o2) ** 2)
            self.assertLess(dist, 1e-15)
Y
Yelrose 已提交
115 116 117 118


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