-
Notifications
You must be signed in to change notification settings - Fork 0
/
modules.py
executable file
·544 lines (434 loc) · 18.9 KB
/
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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
import numpy as np
import torch
from torch.autograd import Variable
import torch.distributions as tdist
from utils import my_softmax, get_offdiag_indices, gumbel_softmax
_EPS = 1e-10
class MLP(nn.Module):
"""Two-layer fully-connected ELU net with batch norm."""
def __init__(self, n_in, n_hid, n_out, do_prob=0.):
super(MLP, self).__init__()
self.fc1 = nn.Linear(n_in, n_hid)
self.fc2 = nn.Linear(n_hid, n_out)
self.bn = nn.BatchNorm1d(n_out)
self.dropout_prob = do_prob
self.init_weights()
def init_weights(self):
for m in self.modules():
if isinstance(m, nn.Linear):
nn.init.xavier_normal_(m.weight.data)
m.bias.data.fill_(0.1)
elif isinstance(m, nn.BatchNorm1d):
m.weight.data.fill_(1)
m.bias.data.zero_()
def batch_norm(self, inputs):
if len(inputs.shape) > 2:
x = inputs.view(inputs.size(0) * inputs.size(1), -1)
x = self.bn(x)
return x.view(inputs.size(0), inputs.size(1), -1)
elif len(inputs.shape) == 2:
return self.bn(inputs)
else:
raise NotImplementedError(
"Batchnorm for these dimensions not implemented.")
def forward(self, inputs):
# Input shape: [num_sims, num_things, num_features]
x = F.elu(self.fc1(inputs))
x = F.dropout(x, self.dropout_prob, training=self.training)
x = F.elu(self.fc2(x))
return self.batch_norm(x)
class MLP3(nn.Module):
"""Three-layer fully-connected RELU net with batch norm."""
def __init__(self, n_in, n_hid, n_out, do_prob=0.):
super(MLP3, self).__init__()
self.fc1 = nn.Linear(n_in, n_hid)
self.fc2 = nn.Linear(n_hid, 2 * n_hid)
self.fc3 = nn.Linear(2 * n_hid, n_out)
self.dropout_prob = do_prob
def forward(self, inputs):
# Input shape: [num_sims, num_things, num_features]
x = F.dropout(F.relu(self.fc1(inputs)), p=self.dropout_prob)
x = F.dropout(F.relu(self.fc2(x)), p=self.dropout_prob)
return self.fc3(x)
class MLPEncoder(nn.Module):
def __init__(self, n_in, n_hid, n_out, do_prob=0., factor=True):
super(MLPEncoder, self).__init__()
self.factor = factor
self.mlp1 = MLP(n_in, n_hid, n_hid, do_prob)
self.mlp2 = MLP(n_hid * 2, n_hid, n_hid, do_prob)
self.mlp3 = MLP(n_hid, n_hid, n_hid, do_prob)
if self.factor:
self.mlp4 = MLP(n_hid * 3, n_hid, n_hid, do_prob)
#print("Using factor graph MLP encoder.")
else:
self.mlp4 = MLP(n_hid * 2, n_hid, n_hid, do_prob)
#print("Using MLP encoder.")
self.fc_out = nn.Linear(n_hid, n_out)
self.init_weights()
@property
def device(self):
return next(self.parameters()).device
def init_weights(self):
for m in self.modules():
if isinstance(m, nn.Linear):
nn.init.xavier_normal_(m.weight.data)
m.bias.data.fill_(0.1)
def edge2node(self, x, rel_rec, rel_send):
# NOTE: Assumes that we have the same graph across all samples.
incoming = torch.matmul(rel_rec.t(), x)
return incoming / incoming.size(1)
def node2edge(self, x, rel_rec, rel_send):
# NOTE: Assumes that we have the same graph across all samples.
receivers = torch.matmul(rel_rec, x)
senders = torch.matmul(rel_send, x)
edges = torch.cat([receivers, senders], dim=2)
return edges
def forward(self, inputs, rel_rec, rel_send):
# Input shape: [num_sims, num_atoms, num_timesteps, num_dims]
x = inputs.view(inputs.size(0), inputs.size(1), -1)
# New shape: [num_sims, num_atoms, num_timesteps*num_dims]
x = self.mlp1(x) # 2-layer ELU net per node
x = self.node2edge(x, rel_rec, rel_send)
x = self.mlp2(x)
x_skip = x
if self.factor:
x = self.edge2node(x, rel_rec, rel_send)
x = self.mlp3(x)
x = self.node2edge(x, rel_rec, rel_send)
x = torch.cat((x, x_skip), dim=2) # Skip connection
x = self.mlp4(x)
else:
x = self.mlp3(x)
x = torch.cat((x, x_skip), dim=2) # Skip connection
x = self.mlp4(x)
return self.fc_out(x)
class MLPEncoder_multi(nn.Module):
def __init__(self, n_in, n_hid, edge_types_list, do_prob=0., split_point=1,
init_type='xavier_normal', bias_init=0.1):
super(MLPEncoder_multi, self).__init__()
self.edge_types_list = edge_types_list
self.mlp1 = MLP(n_in, n_hid, n_hid, do_prob)
self.mlp2 = MLP(n_hid * 2, n_hid, n_hid, do_prob)
self.init_type = init_type
if self.init_type not in ['xavier_normal', 'orthogonal', 'sparse']:
raise ValueError('This initialization type has not been coded')
self.bias_init = bias_init
self.split_point = split_point
if split_point == 0:
self.mlp3 = MLP(n_hid, n_hid, n_hid, do_prob)
self.mlp4 = MLP(n_hid * 3, n_hid, n_hid, do_prob)
self.fc_out = nn.ModuleList(
[nn.Linear(n_hid, sum(edge_types_list))])
elif split_point == 1:
self.mlp3 = MLP(n_hid, n_hid, n_hid, do_prob)
self.mlp4 = nn.ModuleList(
[MLP(n_hid * 3, n_hid, n_hid, do_prob)
for _ in edge_types_list])
self.fc_out = nn.ModuleList([nn.Linear(n_hid, K)
for K in edge_types_list])
elif split_point == 2:
self.mlp3 = nn.ModuleList(
[MLP(n_hid, n_hid, n_hid, do_prob)
for _ in edge_types_list])
self.mlp4 = nn.ModuleList(
[MLP(n_hid * 3, n_hid, n_hid, do_prob)
for _ in edge_types_list])
self.fc_out = nn.ModuleList(
[nn.Linear(n_hid, K)
for K in edge_types_list])
else:
raise ValueError('Split point is not valid, must be 0, 1, or 2')
self.init_weights()
@property
def device(self):
return next(self.parameters()).device
def init_weights(self):
for m in self.modules():
if isinstance(m, nn.Linear):
if self.init_type == 'orthogonal':
nn.init.orthogonal_(m.weight.data)
elif self.init_type == 'xavier_normal':
nn.init.xavier_normal_(m.weight.data)
elif self.init_type == 'sparse':
nn.init.sparse_(m.weight.data, sparsity=0.1)
if not math.isclose(self.bias_init, 0, rel_tol=1e-9):
m.bias.data.fill_(self.bias_init)
def edge2node(self, x, rel_rec, rel_send):
# NOTE: Assumes that we have the same graph across all samples.
incoming = torch.matmul(rel_rec.t(), x)
return incoming / incoming.size(1)
def node2edge(self, x, rel_rec, rel_send):
# NOTE: Assumes that we have the same graph across all samples.
receivers = torch.matmul(rel_rec, x)
senders = torch.matmul(rel_send, x)
edges = torch.cat([receivers, senders], dim=2)
return edges
def forward(self, inputs, rel_rec, rel_send):
# Input shape: [num_sims, num_atoms, num_timesteps, num_dims]
x = inputs.view(inputs.size(0), inputs.size(1), -1)
# New shape: [num_sims, num_atoms, num_timesteps*num_dims]
x = self.mlp1(x) # 2-layer ELU net per node
x = self.node2edge(x, rel_rec, rel_send)
x = self.mlp2(x)
x_skip = x
x = self.edge2node(x, rel_rec, rel_send)
if self.split_point == 0:
x = self.mlp3(x)
x = self.node2edge(x, rel_rec, rel_send)
x = torch.cat((x, x_skip), dim=2) # Skip connection
x = self.mlp4(x)
return self.fc_out[0](x)
elif self.split_point == 1:
x = self.mlp3(x)
x = self.node2edge(x, rel_rec, rel_send)
x = torch.cat((x, x_skip), dim=2) # Skip connection
y_list = []
for i in range(len(self.edge_types_list)):
y = self.mlp4[i](x)
y_list.append(self.fc_out[i](y))
return torch.cat(y_list, dim=-1)
elif self.split_point == 2:
y_list = []
for i in range(len(self.edge_types_list)):
y = self.mlp3[i](x)
y = self.node2edge(y, rel_rec, rel_send)
y = torch.cat((y, x_skip), dim=2) # Skip connection
y = self.mlp4[i](y)
y_list.append(self.fc_out[i](y))
return torch.cat(y_list, dim=-1)
class MLPEncoder_SD(nn.Module):
def __init__(self, skeleton):
super(MLPEncoder_SD, self).__init__()
self.PA = nn.Parameter(torch.from_numpy(skeleton.astype(np.float32)))
nn.init.constant_(self.PA, 1e-6)
@property
def device(self):
return next(self.parameters()).device
def forward(self, inputs):
x = torch.repeat_interleave(
self.PA[np.newaxis, :, :], inputs.shape[0], dim=0)
return x
class RNNDecoder(nn.Module):
"""Recurrent decoder module."""
def __init__(self, n_in_node, n_atoms, n_clinical, edge_types, n_hid,
cond_hidden, cond_msgs,
do_prob=0., skip_first=False):
super(RNNDecoder, self).__init__()
self.n_atoms = n_atoms
self.cond_hidden = cond_hidden
self.cond_msgs = cond_msgs
self.n_hid = n_hid
self.edge_types = edge_types
self.msg_fc1 = nn.ModuleList(
[nn.Linear(2 * n_hid, n_hid) for _ in range(edge_types)])
self.msg_fc2 = nn.ModuleList(
[nn.Linear(n_hid, n_hid) for _ in range(edge_types)])
self.msg_out_shape = n_hid
self.skip_first_edge_type = skip_first
if self.cond_hidden:
self.clinical_mlp = MLP3(
n_clinical, n_hid, n_atoms * n_hid, do_prob)
if self.cond_msgs:
self.clinical2msg_mlp = MLP3(
n_clinical, n_hid, n_atoms * n_hid, do_prob)
self.in_r = nn.Linear(n_in_node, n_hid)
self.in_z = nn.Linear(n_in_node, n_hid)
self.in_n = nn.Linear(n_in_node, n_hid)
self.hr = nn.Linear(n_hid, n_hid)
self.hz = nn.Linear(n_hid, n_hid)
self.hn = nn.Linear(n_hid, n_hid)
self.out_fc1 = nn.Linear(n_hid, n_hid)
self.out_fc2 = nn.Linear(n_hid, n_hid)
self.out_fc3 = nn.Linear(n_hid, n_in_node)
self.dropout_prob = do_prob
@property
def device(self):
return next(self.parameters()).device
def init_hidden(self, batch_size, clinical_data):
if self.cond_hidden:
hidden = self.clinical_mlp(clinical_data)
hidden = hidden.view(batch_size,
self.n_atoms,
self.msg_out_shape)
else:
hidden = Variable(torch.zeros(batch_size,
self.n_atoms,
self.msg_out_shape))
return hidden
def step(self, inputs, hidden, rel_rec, rel_send, rel_type, clinical_data):
# node2edge
receivers = torch.matmul(rel_rec, hidden)
senders = torch.matmul(rel_send, hidden)
pre_msg = torch.cat([receivers, senders], dim=-1)
all_msgs = Variable(torch.zeros(pre_msg.size(0), pre_msg.size(1),
self.msg_out_shape))
if inputs.is_cuda:
all_msgs = all_msgs.cuda()
if self.skip_first_edge_type:
start_idx = 1
norm = float(len(self.msg_fc2)) - 1.
else:
start_idx = 0
norm = float(len(self.msg_fc2))
# Run separate MLP for every edge type
# NOTE: To exclude one edge type, simply offset range by 1
for i in range(start_idx, len(self.msg_fc2)):
msg = torch.tanh(self.msg_fc1[i](pre_msg))
msg = F.dropout(msg, p=self.dropout_prob)
msg = torch.tanh(self.msg_fc2[i](msg))
msg = msg * rel_type[:, :, i:i + 1]
all_msgs += msg / norm
agg_msgs = all_msgs.transpose(-2, -1).matmul(rel_rec).transpose(-2, -1)
agg_msgs = agg_msgs.contiguous() / inputs.size(2) # Average
if self.cond_msgs:
cln_emb = self.clinical2msg_mlp(clinical_data)
cln_emb = cln_emb.view(inputs.size(0),
inputs.size(1),
self.msg_out_shape)
agg_msgs = agg_msgs + cln_emb
r = torch.sigmoid(self.in_r(inputs) + self.hr(agg_msgs))
z = torch.sigmoid(self.in_z(inputs) + self.hr(agg_msgs))
n = torch.tanh(self.in_n(inputs) + r * self.hn(agg_msgs))
hidden = (1 - z) * n + z * hidden
# Output MLP
pred = F.dropout(F.relu(self.out_fc1(hidden)), p=self.dropout_prob)
pred = F.dropout(F.relu(self.out_fc2(pred)), p=self.dropout_prob)
pred = self.out_fc3(pred)
# Predict position/vlocity difference
pred = inputs + pred
return pred, hidden
def forward(self, data, rel_type, rel_rec, rel_send, clinical):
inputs = data.transpose(1, 2).contiguous()
time_steps = inputs.size(1)
batch_size = inputs.size(0)
# Initializing hidden state with clinical data
hidden = self.init_hidden(batch_size, clinical)
hidden = hidden.to(inputs.device)
pred_all = []
for step in range(0, time_steps-1):
if step == 0:
x = inputs[:, 0, :, :]
pred_all.append(x)
else:
x = pred_all[-1]
pred, hidden = self.step(
x, hidden, rel_rec, rel_send, rel_type, clinical)
pred_all.append(pred)
predictions = torch.stack(pred_all, dim=1)
return predictions.transpose(1, 2).contiguous()
class RNNDecoder_multi(nn.Module):
"""Recurrent decoder module."""
def __init__(self, n_in_node, n_atoms, n_clinical, edge_types,
edge_types_list, n_hid, cond_hidden, cond_msgs,
do_prob=0., skip_first=False):
super(RNNDecoder_multi, self).__init__()
self.n_atoms = n_atoms
self.edge_types = edge_types
self.edge_types_list = edge_types_list
self.cond_hidden = cond_hidden
self.cond_msgs = cond_msgs
self.n_hid = n_hid
self.msg_fc1 = nn.ModuleList(
[nn.Linear(2 * n_hid, n_hid) for _ in range(edge_types)])
self.msg_fc2 = nn.ModuleList(
[nn.Linear(n_hid, n_hid) for _ in range(edge_types)])
self.msg_out_shape = n_hid
self.skip_first_edge_type = skip_first
if self.cond_hidden:
self.clinical_mlp = MLP3(
n_clinical, n_hid, n_atoms * n_hid, do_prob)
if self.cond_msgs:
self.clinical2msg_mlp = MLP3(
n_clinical, n_hid, n_atoms * n_hid, do_prob)
# GRU
self.in_r = nn.Linear(n_in_node, n_hid)
self.in_z = nn.Linear(n_in_node, n_hid)
self.in_n = nn.Linear(n_in_node, n_hid)
self.hr = nn.Linear(n_hid, n_hid)
self.hz = nn.Linear(n_hid, n_hid)
self.hn = nn.Linear(n_hid, n_hid)
self.out_fc1 = nn.Linear(n_hid, n_hid)
self.out_fc2 = nn.Linear(n_hid, n_hid)
self.out_fc3 = nn.Linear(n_hid, n_in_node)
#print('Using learned recurrent interaction net decoder.')
self.dropout_prob = do_prob
@property
def device(self):
return next(self.parameters()).device
def init_hidden(self, batch_size, clinical_data):
if self.cond_hidden:
hidden = self.clinical_mlp(clinical_data)
hidden = hidden.view(batch_size,
self.n_atoms,
self.msg_out_shape)
else:
hidden = Variable(torch.zeros(batch_size,
self.n_atoms,
self.msg_out_shape)
).to(clinical_data.device)
return hidden
def step(self, inputs, hidden, rel_rec, rel_send, rel_type, clinical_data):
# node2edge
receivers = torch.matmul(rel_rec, hidden)
senders = torch.matmul(rel_send, hidden)
pre_msg = torch.cat([receivers, senders], dim=-1)
all_msgs = Variable(torch.zeros(pre_msg.size(0), pre_msg.size(1),
self.msg_out_shape))
if inputs.is_cuda:
all_msgs = all_msgs.cuda()
non_null_idxs = list(range(self.edge_types))
if self.skip_first_edge_type:
edge = 0
for k in self.edge_types_list:
non_null_idxs.remove(edge)
edge += k
# Run separate MLP for every edge type
# NOTE: To exclude one edge type, simply offset range by 1
for i in non_null_idxs:
msg = F.relu(self.msg_fc1[i](pre_msg))
msg = F.dropout(msg, p=self.dropout_prob)
msg = F.relu(self.msg_fc2[i](msg))
msg = msg * rel_type[:, :, i:i + 1]
all_msgs += msg
agg_msgs = all_msgs.transpose(-2, -1).matmul(rel_rec).transpose(-2, -1)
agg_msgs = agg_msgs.contiguous()
if self.cond_msgs:
cln_emb = self.clinical2msg_mlp(clinical_data)
cln_emb = cln_emb.view(inputs.size(0),
inputs.size(1),
self.msg_out_shape)
agg_msgs = agg_msgs + cln_emb
# GRU-style gated aggregation
r = torch.sigmoid(self.in_r(inputs) + self.hr(agg_msgs))
z = torch.sigmoid(self.in_z(inputs) + self.hr(agg_msgs))
n = torch.tanh(self.in_n(inputs) + r * self.hn(agg_msgs))
hidden = (1 - z) * n + z * hidden
# Output MLP
pred = F.dropout(F.relu(self.out_fc1(hidden)), p=self.dropout_prob)
pred = F.dropout(F.relu(self.out_fc2(pred)), p=self.dropout_prob)
pred = self.out_fc3(pred)
# Predict position/velocity difference
pred = inputs + pred
return pred, hidden
def forward(self, data, rel_type, rel_rec, rel_send, clinical):
inputs = data.transpose(1, 2).contiguous()
time_steps = inputs.size(1)
batch_size = inputs.size(0)
# Initializing hidden state with clinical data
hidden = self.init_hidden(batch_size, clinical)
pred_all = []
for step in range(0, time_steps-1):
if step == 0:
x = inputs[:, 0, :, :]
pred_all.append(x)
else:
x = pred_all[-1]
pred, hidden = self.step(
x, hidden, rel_rec, rel_send, rel_type, clinical)
pred_all.append(pred)
predictions = torch.stack(pred_all, dim=1)
return predictions.transpose(1, 2).contiguous()