forked from zalandoresearch/SWARM
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodels.py
221 lines (159 loc) · 6.4 KB
/
models.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
import torch
from torch import nn
import torch.nn.functional as F
from torch.nn.modules.dropout import _DropoutNd
from swarmlayer import SwarmLayer
from set_transformer import InducedSetAttentionBlock, RFF
nonlinearities = {}
nonlinearities['relu'] = nn.ReLU()
nonlinearities['elu'] = nn.ELU()
nonlinearities['lrelu'] = nn.LeakyReLU()
class MaskedSequential(nn.Module):
"""
Build a sequential module out of modules that take a mask parameter in their forward() method. Known modules that
don't take a mask argument (e.g. non-linearities) can be seamlessly included.
"""
def __init__(self, *mods):
super().__init__()
self.mods = nn.ModuleList([*mods])
def forward(self, x, mask):
for m in self.mods:
if type(m) in [type(nl) for nl in nonlinearities.values()] + \
[nn.Linear] + [Dropout2dChannelsLast] + [nn.LSTM]:
x = m(x)
else:
x = m(x, mask)
return x
class SetLinear(nn.Module):
def __init__(self,
n_in,
n_out,
pooling='MEAN'):
super().__init__()
self.pooling = pooling
self.ffwd1 = nn.Linear(n_in, n_out)
self.ffwd2 = nn.Linear(n_in, n_out)
def forward(self, x, mask=None):
# x is (N, n_samp, n_in)
N, n_samp, n_in = x.size()
local = self.ffwd1(x)
glob = self.ffwd2(x)
if mask is not None:
mask = mask.unsqueeze(2).float()
if self.pooling=='MEAN':
pool = (glob * mask).sum(dim=1, keepdim=True) / mask.sum(dim=1, keepdim=True)
else:
pool = torch.max(glob+torch.log(mask), dim=1, keepdim=True)[0]
else:
if self.pooling=='MEAN':
pool = glob.mean(dim=1, keepdim=True)
else:
pool = torch.max(glob, dim=1, keepdim=True)[0]
return local + pool
class Dropout2dChannelsLast(_DropoutNd):
def forward(self, x, input):
e = torch.ones_like((input[:,:1,:]))
return input * F.dropout(e, self.p, self.training, self.inplace)
def create_model( opt):
nonlinearity = nonlinearities[opt.non_lin]
if opt.type == 'Swarm':
# uses opt. ...
# n_layers
# n_in
# n_out
# n_hidden
# n_iter
# dropout
if opt.n_layers == 1:
model = SwarmLayer( n_in = opt.n_in,
n_out = opt.n_out,
n_hidden = opt.n_hidden,
n_iter = opt.n_iter,
dropout = opt.dropout,
n_dim=1, pooling='MEAN', channel_first=False, cache=True)
else:
assert opt.n_layers>1
layers = []
n_out_last = opt.n_in
for i in range(opt.n_layers-1):
layers.append( SwarmLayer(n_in = n_out_last,
n_out = opt.n_hidden,
n_hidden = opt.n_hidden,
n_iter = opt.n_iter,
dropout=opt.dropout,
n_dim=1, pooling='MEAN', channel_first=False, cache=True) )
layers.append( nonlinearity)
n_out_last = opt.n_hidden
layers.append( SwarmLayer(n_in = n_out_last,
n_out = opt.n_out,
n_hidden = opt.n_hidden,
n_iter = opt.n_iter,
dropout=opt.dropout,
n_dim=1, pooling='MEAN', channel_first=False, cache=True) )
model = MaskedSequential(*layers)
elif opt.type == 'SetLinear' or opt.type == 'SetLinearMax':
# uses opt. ...
# n_layers
# n_in
# n_out
# n_hidden
pooling = 'MEAN' if opt.type == 'SetLinear' else 'MAX'
layers = []
n_out_last = opt.n_in
for i in range(opt.n_layers - 1):
layers.append(SetLinear(n_in=n_out_last,
n_out=opt.n_hidden,
pooling=pooling) )
n_out_last = opt.n_hidden
layers.append(nonlinearity)
layers.append(SetLinear(n_in=n_out_last,
n_out=opt.n_out,
pooling=pooling) )
model = MaskedSequential(*layers)
elif opt.type == 'SetTransformer':
# uses opt. ...
# n_layers
# n_in
# n_out
# n_hidden
# n_heads
# n_ind_points
d = opt.n_hidden
h = opt.n_heads
m = opt.n_ind_points
layers = [nn.Linear( opt.n_in, opt.n_hidden)]
for _ in range(opt.n_layers):
layers.append( InducedSetAttentionBlock(d=d, m=m, h=h,first_rff=RFF(d=d),second_rff=RFF(d=d)) )
if opt.dropout>0.0:
layers.append(Dropout2dChannelsLast( p=opt.dropout))
layers.append(nn.Linear(opt.n_hidden, opt.n_out))
model = MaskedSequential(*layers)
elif opt.type == 'LSTM' or opt.type == 'LSTMS':
# uses opt. ...
# n_layers
# n_in
# n_out
# n_hidden
# LSTMS is LSTM made set equivariant by sorting
class LSTMModel(nn.Module):
def __init__(self, opt):
super().__init__()
self.lstm = nn.LSTM( opt.n_in, opt.n_hidden, opt.n_layers,
batch_first=True, bidirectional=True)
self.lin = nn.Linear(opt.n_hidden*2 , opt.n_out)
def forward(self, x, mask):
if opt.type == 'LSTMS':
i = torch.argsort(x[:, :, 0], dim=1)
ix = i.unsqueeze(2).expand_as(x)
x = torch.gather(x, dim=1, index=ix)
#ask = torch.gather(mask, dim=1, index=i)
tmp,_ = self.lstm(x)
out = self.lin(tmp)
if opt.type == 'LSTMS':
iout = i.unsqueeze(2).expand_as(out)
out = torch.zeros_like(out).scatter_(1, iout, out)
return out
model = LSTMModel(opt)
else:
raise ValueError("Unknown model type {}".format(opt.type))
return model