model.py 6.93 KB
Newer Older
Chen Sirui's avatar
Chen Sirui committed
1
2
3
4
import numpy as np
import scipy.sparse as sparse
import torch
import torch.nn as nn
5

Chen Sirui's avatar
Chen Sirui committed
6
import dgl
7
import dgl.function as fn
Chen Sirui's avatar
Chen Sirui committed
8
9
10
11
12
13
import dgl.nn as dglnn
from dgl.base import DGLError
from dgl.nn.functional import edge_softmax


class GraphGRUCell(nn.Module):
14
    """Graph GRU unit which can use any message passing
Chen Sirui's avatar
Chen Sirui committed
15
16
17
18
19
20
21
22
23
24
25
    net to replace the linear layer in the original GRU
    Parameter
    ==========
    in_feats : int
        number of input features

    out_feats : int
        number of output features

    net : torch.nn.Module
        message passing network
26
    """
Chen Sirui's avatar
Chen Sirui committed
27
28
29
30
31
32
33

    def __init__(self, in_feats, out_feats, net):
        super(GraphGRUCell, self).__init__()
        self.in_feats = in_feats
        self.out_feats = out_feats
        self.dir = dir
        # net can be any GNN model
34
35
36
        self.r_net = net(in_feats + out_feats, out_feats)
        self.u_net = net(in_feats + out_feats, out_feats)
        self.c_net = net(in_feats + out_feats, out_feats)
Chen Sirui's avatar
Chen Sirui committed
37
38
39
40
41
42
        # Manually add bias Bias
        self.r_bias = nn.Parameter(torch.rand(out_feats))
        self.u_bias = nn.Parameter(torch.rand(out_feats))
        self.c_bias = nn.Parameter(torch.rand(out_feats))

    def forward(self, g, x, h):
43
44
45
46
47
48
49
        r = torch.sigmoid(self.r_net(g, torch.cat([x, h], dim=1)) + self.r_bias)
        u = torch.sigmoid(self.u_net(g, torch.cat([x, h], dim=1)) + self.u_bias)
        h_ = r * h
        c = torch.sigmoid(
            self.c_net(g, torch.cat([x, h_], dim=1)) + self.c_bias
        )
        new_h = u * h + (1 - u) * c
Chen Sirui's avatar
Chen Sirui committed
50
51
52
53
        return new_h


class StackedEncoder(nn.Module):
54
    """One step encoder unit for hidden representation generation
Chen Sirui's avatar
Chen Sirui committed
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
    it can stack multiple vertical layers to increase the depth.

    Parameter
    ==========
    in_feats : int
        number if input features

    out_feats : int
        number of output features

    num_layers : int
        vertical depth of one step encoding unit

    net : torch.nn.Module
        message passing network for graph computation
70
    """
Chen Sirui's avatar
Chen Sirui committed
71
72
73
74
75
76
77
78
79
80

    def __init__(self, in_feats, out_feats, num_layers, net):
        super(StackedEncoder, self).__init__()
        self.in_feats = in_feats
        self.out_feats = out_feats
        self.num_layers = num_layers
        self.net = net
        self.layers = nn.ModuleList()
        if self.num_layers <= 0:
            raise DGLError("Layer Number must be greater than 0! ")
81
82
83
84
85
86
87
        self.layers.append(
            GraphGRUCell(self.in_feats, self.out_feats, self.net)
        )
        for _ in range(self.num_layers - 1):
            self.layers.append(
                GraphGRUCell(self.out_feats, self.out_feats, self.net)
            )
Chen Sirui's avatar
Chen Sirui committed
88
89
90
91
92
93
94
95
96
97
98

    # hidden_states should be a list which for different layer
    def forward(self, g, x, hidden_states):
        hiddens = []
        for i, layer in enumerate(self.layers):
            x = layer(g, x, hidden_states[i])
            hiddens.append(x)
        return x, hiddens


class StackedDecoder(nn.Module):
99
    """One step decoder unit for hidden representation generation
Chen Sirui's avatar
Chen Sirui committed
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
    it can stack multiple vertical layers to increase the depth.

    Parameter
    ==========
    in_feats : int
        number if input features

    hid_feats : int
        number of feature before the linear output layer

    out_feats : int
        number of output features

    num_layers : int
        vertical depth of one step encoding unit

    net : torch.nn.Module
        message passing network for graph computation
118
    """
Chen Sirui's avatar
Chen Sirui committed
119
120
121
122
123
124
125
126
127
128
129
130
131

    def __init__(self, in_feats, hid_feats, out_feats, num_layers, net):
        super(StackedDecoder, self).__init__()
        self.in_feats = in_feats
        self.hid_feats = hid_feats
        self.out_feats = out_feats
        self.num_layers = num_layers
        self.net = net
        self.out_layer = nn.Linear(self.hid_feats, self.out_feats)
        self.layers = nn.ModuleList()
        if self.num_layers <= 0:
            raise DGLError("Layer Number must be greater than 0!")
        self.layers.append(GraphGRUCell(self.in_feats, self.hid_feats, net))
132
133
134
135
        for _ in range(self.num_layers - 1):
            self.layers.append(
                GraphGRUCell(self.hid_feats, self.hid_feats, net)
            )
Chen Sirui's avatar
Chen Sirui committed
136
137
138
139
140
141
142
143
144
145
146

    def forward(self, g, x, hidden_states):
        hiddens = []
        for i, layer in enumerate(self.layers):
            x = layer(g, x, hidden_states[i])
            hiddens.append(x)
        x = self.out_layer(x)
        return x, hiddens


class GraphRNN(nn.Module):
147
    """Graph Sequence to sequence prediction framework
Chen Sirui's avatar
Chen Sirui committed
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
    Support multiple backbone GNN. Mainly used for traffic prediction.

    Parameter
    ==========
    in_feats : int
        number of input features

    out_feats : int
        number of prediction output features

    seq_len : int
        input and predicted sequence length

    num_layers : int
        vertical number of layers in encoder and decoder unit

    net : torch.nn.Module
        Message passing GNN as backbone

    decay_steps : int
        number of steps for the teacher forcing probability to decay
169
170
171
172
173
    """

    def __init__(
        self, in_feats, out_feats, seq_len, num_layers, net, decay_steps
    ):
Chen Sirui's avatar
Chen Sirui committed
174
175
176
177
178
179
180
181
        super(GraphRNN, self).__init__()
        self.in_feats = in_feats
        self.out_feats = out_feats
        self.seq_len = seq_len
        self.num_layers = num_layers
        self.net = net
        self.decay_steps = decay_steps

182
183
184
185
186
187
188
189
190
191
192
        self.encoder = StackedEncoder(
            self.in_feats, self.out_feats, self.num_layers, self.net
        )

        self.decoder = StackedDecoder(
            self.in_feats,
            self.out_feats,
            self.in_feats,
            self.num_layers,
            self.net,
        )
Chen Sirui's avatar
Chen Sirui committed
193
194
195
196

    # Threshold For Teacher Forcing

    def compute_thresh(self, batch_cnt):
197
198
199
        return self.decay_steps / (
            self.decay_steps + np.exp(batch_cnt / self.decay_steps)
        )
Chen Sirui's avatar
Chen Sirui committed
200
201

    def encode(self, g, inputs, device):
202
203
204
205
        hidden_states = [
            torch.zeros(g.num_nodes(), self.out_feats).to(device)
            for _ in range(self.num_layers)
        ]
Chen Sirui's avatar
Chen Sirui committed
206
207
208
209
210
211
212
213
214
        for i in range(self.seq_len):
            _, hidden_states = self.encoder(g, inputs[i], hidden_states)

        return hidden_states

    def decode(self, g, teacher_states, hidden_states, batch_cnt, device):
        outputs = []
        inputs = torch.zeros(g.num_nodes(), self.in_feats).to(device)
        for i in range(self.seq_len):
215
216
217
218
            if (
                np.random.random() < self.compute_thresh(batch_cnt)
                and self.training
            ):
Chen Sirui's avatar
Chen Sirui committed
219
                inputs, hidden_states = self.decoder(
220
221
                    g, teacher_states[i], hidden_states
                )
Chen Sirui's avatar
Chen Sirui committed
222
223
224
225
226
227
228
229
230
231
            else:
                inputs, hidden_states = self.decoder(g, inputs, hidden_states)
            outputs.append(inputs)
        outputs = torch.stack(outputs)
        return outputs

    def forward(self, g, inputs, teacher_states, batch_cnt, device):
        hidden = self.encode(g, inputs, device)
        outputs = self.decode(g, teacher_states, hidden, batch_cnt, device)
        return outputs