forked from nnzhan/Graph-WaveNet
-
Notifications
You must be signed in to change notification settings - Fork 24
/
model.py
191 lines (163 loc) · 8.15 KB
/
model.py
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
import torch
import torch.nn as nn
from torch.nn import BatchNorm2d, Conv1d, Conv2d, ModuleList, Parameter
import torch.nn.functional as F
def nconv(x, A):
"""Multiply x by adjacency matrix along source node axis"""
return torch.einsum('ncvl,vw->ncwl', (x, A)).contiguous()
class GraphConvNet(nn.Module):
def __init__(self, c_in, c_out, dropout, support_len=3, order=2):
super().__init__()
c_in = (order * support_len + 1) * c_in
self.final_conv = Conv2d(c_in, c_out, (1, 1), padding=(0, 0), stride=(1, 1), bias=True)
self.dropout = dropout
self.order = order
def forward(self, x, support: list):
out = [x]
for a in support:
x1 = nconv(x, a)
out.append(x1)
for k in range(2, self.order + 1):
x2 = nconv(x1, a)
out.append(x2)
x1 = x2
h = torch.cat(out, dim=1)
h = self.final_conv(h)
h = F.dropout(h, self.dropout, training=self.training)
return h
class GWNet(nn.Module):
def __init__(self, device, num_nodes, dropout=0.3, supports=None, do_graph_conv=True,
addaptadj=True, aptinit=None, in_dim=2, out_dim=12,
residual_channels=32, dilation_channels=32, cat_feat_gc=False,
skip_channels=256, end_channels=512, kernel_size=2, blocks=4, layers=2,
apt_size=10):
super().__init__()
self.dropout = dropout
self.blocks = blocks
self.layers = layers
self.do_graph_conv = do_graph_conv
self.cat_feat_gc = cat_feat_gc
self.addaptadj = addaptadj
if self.cat_feat_gc:
self.start_conv = nn.Conv2d(in_channels=1, # hard code to avoid errors
out_channels=residual_channels,
kernel_size=(1, 1))
self.cat_feature_conv = nn.Conv2d(in_channels=in_dim - 1,
out_channels=residual_channels,
kernel_size=(1, 1))
else:
self.start_conv = nn.Conv2d(in_channels=in_dim,
out_channels=residual_channels,
kernel_size=(1, 1))
self.fixed_supports = supports or []
receptive_field = 1
self.supports_len = len(self.fixed_supports)
if do_graph_conv and addaptadj:
if aptinit is None:
nodevecs = torch.randn(num_nodes, apt_size), torch.randn(apt_size, num_nodes)
else:
nodevecs = self.svd_init(apt_size, aptinit)
self.supports_len += 1
self.nodevec1, self.nodevec2 = [Parameter(n.to(device), requires_grad=True) for n in nodevecs]
depth = list(range(blocks * layers))
# 1x1 convolution for residual and skip connections (slightly different see docstring)
self.residual_convs = ModuleList([Conv1d(dilation_channels, residual_channels, (1, 1)) for _ in depth])
self.skip_convs = ModuleList([Conv1d(dilation_channels, skip_channels, (1, 1)) for _ in depth])
self.bn = ModuleList([BatchNorm2d(residual_channels) for _ in depth])
self.graph_convs = ModuleList([GraphConvNet(dilation_channels, residual_channels, dropout, support_len=self.supports_len)
for _ in depth])
self.filter_convs = ModuleList()
self.gate_convs = ModuleList()
for b in range(blocks):
additional_scope = kernel_size - 1
D = 1 # dilation
for i in range(layers):
# dilated convolutions
self.filter_convs.append(Conv2d(residual_channels, dilation_channels, (1, kernel_size), dilation=D))
self.gate_convs.append(Conv1d(residual_channels, dilation_channels, (1, kernel_size), dilation=D))
D *= 2
receptive_field += additional_scope
additional_scope *= 2
self.receptive_field = receptive_field
self.end_conv_1 = Conv2d(skip_channels, end_channels, (1, 1), bias=True)
self.end_conv_2 = Conv2d(end_channels, out_dim, (1, 1), bias=True)
@staticmethod
def svd_init(apt_size, aptinit):
m, p, n = torch.svd(aptinit)
nodevec1 = torch.mm(m[:, :apt_size], torch.diag(p[:apt_size] ** 0.5))
nodevec2 = torch.mm(torch.diag(p[:apt_size] ** 0.5), n[:, :apt_size].t())
return nodevec1, nodevec2
@classmethod
def from_args(cls, args, device, supports, aptinit, **kwargs):
defaults = dict(dropout=args.dropout, supports=supports,
do_graph_conv=args.do_graph_conv, addaptadj=args.addaptadj, aptinit=aptinit,
in_dim=args.in_dim, apt_size=args.apt_size, out_dim=args.seq_length,
residual_channels=args.nhid, dilation_channels=args.nhid,
skip_channels=args.nhid * 8, end_channels=args.nhid * 16,
cat_feat_gc=args.cat_feat_gc)
defaults.update(**kwargs)
model = cls(device, args.num_nodes, **defaults)
return model
def load_checkpoint(self, state_dict):
"""It is assumed that ckpt was trained to predict a subset of timesteps."""
bk, wk = ['end_conv_2.bias', 'end_conv_2.weight'] # only weights that depend on seq_length
b, w = state_dict.pop(bk), state_dict.pop(wk)
self.load_state_dict(state_dict, strict=False)
cur_state_dict = self.state_dict()
cur_state_dict[bk][:b.shape[0]] = b
cur_state_dict[wk][:w.shape[0]] = w
self.load_state_dict(cur_state_dict)
def forward(self, x):
# Input shape is (bs, features, n_nodes, n_timesteps)
in_len = x.size(3)
if in_len < self.receptive_field:
x = nn.functional.pad(x, (self.receptive_field - in_len, 0, 0, 0))
if self.cat_feat_gc:
f1, f2 = x[:, [0]], x[:, 1:]
x1 = self.start_conv(f1)
x2 = F.leaky_relu(self.cat_feature_conv(f2))
x = x1 + x2
else:
x = self.start_conv(x)
skip = 0
adjacency_matrices = self.fixed_supports
# calculate the current adaptive adj matrix once per iteration
if self.addaptadj:
adp = F.softmax(F.relu(torch.mm(self.nodevec1, self.nodevec2)), dim=1)
adjacency_matrices = self.fixed_supports + [adp]
# WaveNet layers
for i in range(self.blocks * self.layers):
# EACH BLOCK
# |----------------------------------------| *residual*
# | |
# | |-dil_conv -- tanh --| |
# ---| * ----|-- 1x1 -- + --> *x_in*
# |-dil_conv -- sigm --| |
# 1x1
# |
# ---------------------------------------> + -------------> *skip*
residual = x
# dilated convolution
filter = torch.tanh(self.filter_convs[i](residual))
gate = torch.sigmoid(self.gate_convs[i](residual))
x = filter * gate
# parametrized skip connection
s = self.skip_convs[i](x) # what are we skipping??
try: # if i > 0 this works
skip = skip[:, :, :, -s.size(3):] # TODO(SS): Mean/Max Pool?
except:
skip = 0
skip = s + skip
if i == (self.blocks * self.layers - 1): # last X getting ignored anyway
break
if self.do_graph_conv:
graph_out = self.graph_convs[i](x, adjacency_matrices)
x = x + graph_out if self.cat_feat_gc else graph_out
else:
x = self.residual_convs[i](x)
x = x + residual[:, :, :, -x.size(3):] # TODO(SS): Mean/Max Pool?
x = self.bn[i](x)
x = F.relu(skip) # ignore last X?
x = F.relu(self.end_conv_1(x))
x = self.end_conv_2(x) # downsample to (bs, seq_length, 207, nfeatures)
return x