-
Notifications
You must be signed in to change notification settings - Fork 30
/
nn_modules.py
330 lines (248 loc) · 10.6 KB
/
nn_modules.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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
#!/usr/bin/env python
"""
nn_modules.py
"""
import torch
from torch import nn
from torch.nn import functional as F
from torch.autograd import Variable
import numpy as np
from scipy import sparse
from helpers import to_numpy
# --
# Samplers
class UniformNeighborSampler(object):
"""
Samples from a "dense 2D edgelist", which looks like
[
[1, 2, 3, ..., 1],
[1, 3, 3, ..., 3],
...
]
stored as torch.LongTensor.
This relies on a preprocessing step where we sample _exactly_ K neighbors
for each node -- if the node has less than K neighbors, we upsample w/ replacement
and if the node has more than K neighbors, we downsample w/o replacement.
This seems like a "definitely wrong" thing to do -- but it runs pretty fast, and
I don't know what kind of degradation it causes in practice.
"""
def __init__(self, adj):
self.adj = adj
def __call__(self, ids, n_samples=-1):
tmp = self.adj[ids]
perm = torch.randperm(tmp.size(1))
if ids.is_cuda:
perm = perm.cuda()
tmp = tmp[:,perm]
return tmp[:,:n_samples]
class SparseUniformNeighborSampler(object):
"""
Samples from "sparse 2D edgelist", which looks like
[
[0, 0, 0, 0, ..., 0],
[1, 2, 3, 0, ..., 0],
[1, 3, 0, 0, ..., 0],
...
]
stored as a scipy.sparse.csr_matrix.
The first row is a "dummy node", so there's an "off-by-one" issue vs `feats`.
Have to increment/decrement by 1 in a couple of places. In the regular
uniform sampler, this "dummy node" is at the end.
Ideally, obviously, we'd be doing this sampling on the GPU. But it does not
appear that torch.sparse.LongTensor can support this ATM.
"""
def __init__(self, adj,):
assert sparse.issparse(adj), "SparseUniformNeighborSampler: not sparse.issparse(adj)"
self.adj = adj
idx, partial_degrees = np.unique(adj.nonzero()[0], return_counts=True)
self.degrees = np.zeros(adj.shape[0]).astype(int)
self.degrees[idx] = partial_degrees
def __call__(self, ids, n_samples=128):
assert n_samples > 0, 'SparseUniformNeighborSampler: n_samples must be set explicitly'
is_cuda = ids.is_cuda
ids = to_numpy(ids)
tmp = self.adj[ids]
sel = np.random.choice(self.adj.shape[1], (ids.shape[0], n_samples))
sel = sel % self.degrees[ids].reshape(-1, 1)
tmp = tmp[
np.arange(ids.shape[0]).repeat(n_samples).reshape(-1),
np.array(sel).reshape(-1)
]
tmp = np.asarray(tmp).squeeze()
tmp = Variable(torch.LongTensor(tmp))
if is_cuda:
tmp = tmp.cuda()
return tmp
sampler_lookup = {
"uniform_neighbor_sampler" : UniformNeighborSampler,
"sparse_uniform_neighbor_sampler" : SparseUniformNeighborSampler,
}
# --
# Preprocessers
class IdentityPrep(nn.Module):
def __init__(self, input_dim, n_nodes=None):
""" Example of preprocessor -- doesn't do anything """
super(IdentityPrep, self).__init__()
self.input_dim = input_dim
@property
def output_dim(self):
return self.input_dim
def forward(self, ids, feats, layer_idx=0):
return feats
class NodeEmbeddingPrep(nn.Module):
def __init__(self, input_dim, n_nodes, embedding_dim=64):
""" adds node embedding """
super(NodeEmbeddingPrep, self).__init__()
self.n_nodes = n_nodes
self.input_dim = input_dim
self.embedding_dim = embedding_dim
self.embedding = nn.Embedding(num_embeddings=n_nodes + 1, embedding_dim=embedding_dim)
self.fc = nn.Linear(embedding_dim, embedding_dim) # Affine transform, for changing scale + location
@property
def output_dim(self):
if self.input_dim:
return self.input_dim + self.embedding_dim
else:
return self.embedding_dim
def forward(self, ids, feats, layer_idx=0):
if layer_idx > 0:
embs = self.embedding(ids)
else:
# Don't look at node's own embedding for prediction, or you'll probably overfit a lot
embs = self.embedding(Variable(ids.clone().data.zero_() + self.n_nodes))
embs = self.fc(embs)
if self.input_dim:
return torch.cat([feats, embs], dim=1)
else:
return embs
class LinearPrep(nn.Module):
def __init__(self, input_dim, n_nodes, output_dim=32):
""" adds node embedding """
super(LinearPrep, self).__init__()
self.fc = nn.Linear(input_dim, output_dim, bias=False)
self.output_dim = output_dim
def forward(self, ids, feats, layer_idx=0):
return self.fc(feats)
prep_lookup = {
"identity" : IdentityPrep,
"node_embedding" : NodeEmbeddingPrep,
"linear" : LinearPrep,
}
# --
# Aggregators
class AggregatorMixin(object):
@property
def output_dim(self):
tmp = torch.zeros((1, self.output_dim_))
return self.combine_fn([tmp, tmp]).size(1)
class MeanAggregator(nn.Module, AggregatorMixin):
def __init__(self, input_dim, output_dim, activation, combine_fn=lambda x: torch.cat(x, dim=1)):
super(MeanAggregator, self).__init__()
self.fc_x = nn.Linear(input_dim, output_dim, bias=False)
self.fc_neib = nn.Linear(input_dim, output_dim, bias=False)
self.output_dim_ = output_dim
self.activation = activation
self.combine_fn = combine_fn
def forward(self, x, neibs):
agg_neib = neibs.view(x.size(0), -1, neibs.size(1)) # !! Careful
agg_neib = agg_neib.mean(dim=1) # Careful
out = self.combine_fn([self.fc_x(x), self.fc_neib(agg_neib)])
if self.activation:
out = self.activation(out)
return out
class PoolAggregator(nn.Module, AggregatorMixin):
def __init__(self, input_dim, output_dim, pool_fn, activation, hidden_dim=512, combine_fn=lambda x: torch.cat(x, dim=1)):
super(PoolAggregator, self).__init__()
self.mlp = nn.Sequential(*[
nn.Linear(input_dim, hidden_dim, bias=True),
nn.ReLU()
])
self.fc_x = nn.Linear(input_dim, output_dim, bias=False)
self.fc_neib = nn.Linear(hidden_dim, output_dim, bias=False)
self.output_dim_ = output_dim
self.activation = activation
self.pool_fn = pool_fn
self.combine_fn = combine_fn
def forward(self, x, neibs):
h_neibs = self.mlp(neibs)
agg_neib = h_neibs.view(x.size(0), -1, h_neibs.size(1))
agg_neib = self.pool_fn(agg_neib)
out = self.combine_fn([self.fc_x(x), self.fc_neib(agg_neib)])
if self.activation:
out = self.activation(out)
return out
class MaxPoolAggregator(PoolAggregator):
def __init__(self, input_dim, output_dim, activation, hidden_dim=512, combine_fn=lambda x: torch.cat(x, dim=1)):
super(MaxPoolAggregator, self).__init__(**{
"input_dim" : input_dim,
"output_dim" : output_dim,
"pool_fn" : lambda x: x.max(dim=1)[0],
"activation" : activation,
"hidden_dim" : hidden_dim,
"combine_fn" : combine_fn,
})
class MeanPoolAggregator(PoolAggregator):
def __init__(self, input_dim, output_dim, activation, hidden_dim=512, combine_fn=lambda x: torch.cat(x, dim=1)):
super(MeanPoolAggregator, self).__init__(**{
"input_dim" : input_dim,
"output_dim" : output_dim,
"pool_fn" : lambda x: x.mean(dim=1),
"activation" : activation,
"hidden_dim" : hidden_dim,
"combine_fn" : combine_fn,
})
class LSTMAggregator(nn.Module, AggregatorMixin):
def __init__(self, input_dim, output_dim, activation,
hidden_dim=512, bidirectional=False, combine_fn=lambda x: torch.cat(x, dim=1)):
super(LSTMAggregator, self).__init__()
assert not hidden_dim % 2, "LSTMAggregator: hiddem_dim % 2 != 0"
self.lstm = nn.LSTM(input_dim, hidden_dim // (1 + bidirectional), bidirectional=bidirectional, batch_first=True)
self.fc_x = nn.Linear(input_dim, output_dim, bias=False)
self.fc_neib = nn.Linear(hidden_dim, output_dim, bias=False)
self.output_dim_ = output_dim
self.activation = activation
self.combine_fn = combine_fn
def forward(self, x, neibs):
x_emb = self.fc_x(x)
agg_neib = neibs.view(x.size(0), -1, neibs.size(1))
agg_neib, _ = self.lstm(agg_neib)
agg_neib = agg_neib[:,-1,:] # !! Taking final state, but could do something better (eg attention)
neib_emb = self.fc_neib(agg_neib)
out = self.combine_fn([x_emb, neib_emb])
if self.activation:
out = self.activation(out)
return out
class AttentionAggregator(nn.Module, AggregatorMixin):
def __init__(self, input_dim, output_dim, activation, hidden_dim=32, combine_fn=lambda x: torch.cat(x, dim=1)):
super(AttentionAggregator, self).__init__()
self.att = nn.Sequential(*[
nn.Linear(input_dim, hidden_dim, bias=False),
nn.Tanh(),
nn.Linear(hidden_dim, hidden_dim, bias=False),
])
self.fc_x = nn.Linear(input_dim, output_dim, bias=False)
self.fc_neib = nn.Linear(input_dim, output_dim, bias=False)
self.output_dim_ = output_dim
self.activation = activation
self.combine_fn = combine_fn
def forward(self, x, neibs):
# Compute attention weights
neib_att = self.att(neibs)
x_att = self.att(x)
neib_att = neib_att.view(x.size(0), -1, neib_att.size(1))
x_att = x_att.view(x_att.size(0), x_att.size(1), 1)
ws = F.softmax(torch.bmm(neib_att, x_att).squeeze())
# Weighted average of neighbors
agg_neib = neibs.view(x.size(0), -1, neibs.size(1))
agg_neib = torch.sum(agg_neib * ws.unsqueeze(-1), dim=1)
out = self.combine_fn([self.fc_x(x), self.fc_neib(agg_neib)])
if self.activation:
out = self.activation(out)
return out
aggregator_lookup = {
"mean" : MeanAggregator,
"max_pool" : MaxPoolAggregator,
"mean_pool" : MeanPoolAggregator,
"lstm" : LSTMAggregator,
"attention" : AttentionAggregator,
}