gat.py 6.66 KB
Newer Older
Lingfan Yu's avatar
Lingfan Yu committed
1
2
3
4
5
6
"""
Graph Attention Networks
Paper: https://arxiv.org/abs/1710.10903
Code: https://github.com/PetarV-/GAT
"""

Lingfan Yu's avatar
Lingfan Yu committed
7
8
9
10
11
12
13
14
15
import networkx as nx
from dgl.graph import DGLGraph
import torch
import torch.nn as nn
import torch.nn.functional as F
import argparse
from dataset import load_data, preprocess_features
import numpy as np

Lingfan Yu's avatar
Lingfan Yu committed
16
17
18
19
class NodeReduceModule(nn.Module):
    def __init__(self, input_dim, num_hidden, num_heads=3, input_dropout=None,
            attention_dropout=None):
        super(NodeReduceModule, self).__init__()
Lingfan Yu's avatar
Lingfan Yu committed
20
        self.num_heads = num_heads
Lingfan Yu's avatar
Lingfan Yu committed
21
22
        self.input_dropout = input_dropout
        self.attention_dropout = attention_dropout
Lingfan Yu's avatar
Lingfan Yu committed
23
24
25
26
27
28
        self.fc = nn.ModuleList(
                [nn.Linear(input_dim, num_hidden, bias=False)
                    for _ in range(num_heads)])
        self.attention = nn.ModuleList(
                [nn.Linear(num_hidden * 2, 1, bias=False) for _ in range(num_heads)])

Lingfan Yu's avatar
Lingfan Yu committed
29
30
31
32
    def forward(self, msgs):
        src, dst = zip(*msgs)
        hu = torch.cat(src, dim=0) # neighbor repr
        hv = torch.cat(dst, dim=0)
Lingfan Yu's avatar
Lingfan Yu committed
33

Lingfan Yu's avatar
Lingfan Yu committed
34
        msgs_repr = []
Lingfan Yu's avatar
Lingfan Yu committed
35

Lingfan Yu's avatar
Lingfan Yu committed
36
        # iterate for each head
Lingfan Yu's avatar
Lingfan Yu committed
37
38
39
40
41
        for i in range(self.num_heads):
            # calc W*hself and W*hneigh
            hvv = self.fc[i](hv)
            huu = self.fc[i](hu)
            # calculate W*hself||W*hneigh
Lingfan Yu's avatar
Lingfan Yu committed
42
            h = torch.cat((hvv, huu), dim=1)
Lingfan Yu's avatar
Lingfan Yu committed
43
44
45
46
47
48
49
            a = F.leaky_relu(self.attention[i](h))
            a = F.softmax(a, dim=0)
            if self.attention_dropout is not None:
                a = F.dropout(a, self.attention_dropout)
            if self.input_dropout is not None:
                hvv = F.dropout(hvv, self.input_dropout)
            h = torch.sum(a * hvv, 0, keepdim=True)
Lingfan Yu's avatar
Lingfan Yu committed
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
            msgs_repr.append(h)

        return msgs_repr


class NodeUpdateModule(nn.Module):
    def __init__(self, residual, fc, act, aggregator):
        super(NodeUpdateModule, self).__init__()
        self.residual = residual
        self.fc = fc
        self.act = act
        self.aggregator = aggregator

    def forward(self, node, msgs_repr):
        # apply residual connection and activation for each head
        for i in range(len(msgs_repr)):
Lingfan Yu's avatar
Lingfan Yu committed
66
            if self.residual:
Lingfan Yu's avatar
Lingfan Yu committed
67
68
                h = self.fc[i](node['h'])
                msgs_repr[i] = msgs_repr[i] + h
Lingfan Yu's avatar
Lingfan Yu committed
69
            if self.act is not None:
Lingfan Yu's avatar
Lingfan Yu committed
70
                msgs_repr[i] = self.act(msgs_repr[i])
Lingfan Yu's avatar
Lingfan Yu committed
71
72

        # aggregate multi-head results
Lingfan Yu's avatar
Lingfan Yu committed
73
        h = self.aggregator(msgs_repr)
Lingfan Yu's avatar
Lingfan Yu committed
74
75
76
77
78
        return {'h': h}


class GAT(nn.Module):
    def __init__(self, num_layers, in_dim, num_hidden, num_classes, num_heads,
Lingfan Yu's avatar
Lingfan Yu committed
79
            activation, input_dropout, attention_dropout, use_residual=False):
Lingfan Yu's avatar
Lingfan Yu committed
80
        super(GAT, self).__init__()
Lingfan Yu's avatar
Lingfan Yu committed
81
82
83
84
        self.input_dropout = input_dropout
        self.reduce_layers = nn.ModuleList()
        self.update_layers = nn.ModuleList()
        # hidden layers
Lingfan Yu's avatar
Lingfan Yu committed
85
86
87
88
89
90
91
        for i in range(num_layers):
            if i == 0:
                last_dim = in_dim
                residual = False
            else:
                last_dim = num_hidden * num_heads # because of concat heads
                residual = use_residual
Lingfan Yu's avatar
Lingfan Yu committed
92
93
94
95
96
97
98
99
100
101
102
103
            self.reduce_layers.append(
                    NodeReduceModule(last_dim, num_hidden, num_heads, input_dropout,
                        attention_dropout))
            self.update_layers.append(
                    NodeUpdateModule(residual, self.reduce_layers[-1].fc, activation,
                        lambda x: torch.cat(x, 1)))
        # projection
        self.reduce_layers.append(
            NodeReduceModule(num_hidden * num_heads, num_classes, 1, input_dropout,
                attention_dropout))
        self.update_layers.append(
            NodeUpdateModule(False, self.reduce_layers[-1].fc, None, sum))
Lingfan Yu's avatar
Lingfan Yu committed
104
105

    def forward(self, g):
Lingfan Yu's avatar
Lingfan Yu committed
106
107
108
109
110
111
112
113
114
115
        g.register_message_func(lambda src, dst, edge: (src['h'], dst['h']))
        for reduce_func, update_func in zip(self.reduce_layers, self.update_layers):
            # apply dropout
            if self.input_dropout is not None:
                # TODO (lingfan): use batched dropout once we have better api
                #                 for global manipulation
                for n in g.nodes():
                    g.node[n]['h'] = F.dropout(g.node[n]['h'], p=self.input_dropout)
            g.register_reduce_func(reduce_func)
            g.register_update_func(update_func)
Lingfan Yu's avatar
Lingfan Yu committed
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
            g.update_all()
        logits = [g.node[n]['h'] for n in g.nodes()]
        logits = torch.cat(logits, dim=0)
        return logits


def main(args):
    # dropout parameters
    input_dropout = 0.2
    attention_dropout = 0.2

    # load and preprocess dataset
    adj, features, y_train, y_val, y_test, train_mask, val_mask, test_mask = load_data(args.dataset)
    features = preprocess_features(features)

    # initialize graph
    g = DGLGraph(adj)

    # create model
    model = GAT(args.num_layers,
                features.shape[1],
                args.num_hidden,
                y_train.shape[1],
                args.num_heads,
                F.elu,
                input_dropout,
Lingfan Yu's avatar
Lingfan Yu committed
142
                attention_dropout,
Lingfan Yu's avatar
Lingfan Yu committed
143
144
145
146
147
148
149
150
                args.residual)

    # use optimizer
    optimizer = torch.optim.Adam(model.parameters(), lr=args.lr)

    # convert labels and masks to tensor
    labels = torch.FloatTensor(y_train)
    mask = torch.FloatTensor(train_mask.astype(np.float32))
Lingfan Yu's avatar
Lingfan Yu committed
151
    n_train = torch.sum(mask)
Lingfan Yu's avatar
Lingfan Yu committed
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166

    for epoch in range(args.epochs):
        # reset grad
        optimizer.zero_grad()

        # reset graph states
        for n in g.nodes():
            g.node[n]['h'] = torch.FloatTensor(features[n].toarray())

        # forward
        logits = model.forward(g)

        # masked cross entropy loss
        # TODO: (lingfan) use gather to speed up
        logp = F.log_softmax(logits, 1)
Lingfan Yu's avatar
Lingfan Yu committed
167
        loss = -torch.sum(logp * labels * mask.view(-1, 1)) / n_train
Lingfan Yu's avatar
Lingfan Yu committed
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
        print("epoch {} loss: {}".format(epoch, loss.item()))

        loss.backward()
        optimizer.step()

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='GAT')
    parser.add_argument("--dataset", type=str, required=True,
            help="dataset name")
    parser.add_argument("--epochs", type=int, default=10,
            help="training epoch")
    parser.add_argument("--num-heads", type=int, default=3,
            help="number of attentional heads to use")
    parser.add_argument("--num-layers", type=int, default=1,
            help="number of hidden layers")
    parser.add_argument("--num-hidden", type=int, default=8,
            help="size of hidden units")
    parser.add_argument("--residual", action="store_true",
            help="use residual connection")
    parser.add_argument("--lr", type=float, default=0.001,
            help="learning rate")
    args = parser.parse_args()
    print(args)

    main(args)