-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathattention_model.py
322 lines (248 loc) · 9.63 KB
/
attention_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
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
""" Attention-based Deep Multiple Instance Learning (ABMIL) models based on Ilse et el. paper [1] for experiments with one and three GPUs, for QMNIST and Imagenette datasets. "Attention1GPU" corresponds to original "Attenion" model that can be found in https://github.com/AMLab-Amsterdam/AttentionDeepMIL.
[1] Ilse, Maximilian, Jakub Tomczak, and Max Welling. "Attention-based deep multiple instance learning." International conference on machine learning. PMLR, 2018.
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision.models.resnet import ResNet, Bottleneck
class Attention3GPUs(nn.Module):
def __init__(self):
super(Attention3GPUs, self).__init__()
self.L = 500
self.D = 128
self.K = 1
self.feature_extractor_part1_0 = nn.Sequential(
nn.Conv2d(1, 20, kernel_size=5),
).to('cuda:2')
self.feature_extractor_part1_1 = nn.Sequential(
nn.ReLU(),
nn.MaxPool2d(2, stride=2),
nn.Conv2d(20, 50, kernel_size=5),
).to('cuda:0')
self.feature_extractor_part1_2 = nn.Sequential(
nn.ReLU(),
nn.MaxPool2d(2, stride=2)
).to('cuda:1')
self.feature_extractor_part2 = nn.Sequential(
nn.Linear(50 * 4 * 4, self.L),
nn.ReLU(),
).to('cuda:1')
self.attention = nn.Sequential(
nn.Linear(self.L, self.D),
nn.Tanh(),
nn.Linear(self.D, self.K)
).to('cuda:1')
self.classifier = nn.Sequential(
nn.Linear(self.L*self.K, 1),
nn.Sigmoid()
).to('cuda:1')
def forward(self, x):
x = x.squeeze(0)
H = self.feature_extractor_part1_0(x.to('cuda:2'))
H = self.feature_extractor_part1_1(H.to('cuda:0'))
H = self.feature_extractor_part1_2(H.to('cuda:1'))
H = H.view(-1, 50 * 4 * 4)
H = self.feature_extractor_part2(H).to('cuda:1') # NxL
A = self.attention(H).to('cuda:1') # NxK
A = torch.transpose(A.to('cuda:1'), 1, 0) # KxN
# print('A.shape', A.shape)
A = F.softmax(A.to('cuda:1'), dim=1) # softmax over N
# print('A.shape,soft', A.shape)
M = torch.mm(A.to('cuda:1'), H) # KxL
Y_prob = self.classifier(M.to('cuda:1'))
Y_hat = torch.ge(Y_prob.to('cuda:1'), 0.5).float()
return Y_prob, Y_hat, A
# AUXILIARY METHODS
def calculate_classification_error(self, X, Y):
Y = Y.float()
_, Y_hat, _ = self.forward(X)
error = 1. - Y_hat.eq(Y).cpu().float().mean().item()#.data[0]
# print('error:', error, 'Y_hat', Y_hat)
return error, Y_hat
def calculate_objective(self, X, Y):
Y = Y.float()
Y_prob, _, A = self.forward(X)
Y_prob = torch.clamp(Y_prob, min=1e-5, max=1. - 1e-5)
neg_log_likelihood = -1. * (Y * torch.log(Y_prob) + (1. - Y) * torch.log(1. - Y_prob)) # negative log bernoulli
return neg_log_likelihood, A
class Attention1GPU(nn.Module):
def __init__(self):
super(Attention1GPU, self).__init__()
self.L = 500
self.D = 128
self.K = 1
self.feature_extractor_part1_0 = nn.Sequential(
nn.Conv2d(1, 20, kernel_size=5),
)
self.feature_extractor_part1_1 = nn.Sequential(
nn.ReLU(),
nn.MaxPool2d(2, stride=2),
nn.Conv2d(20, 50, kernel_size=5),
)
self.feature_extractor_part1_2 = nn.Sequential(
nn.ReLU(),
nn.MaxPool2d(2, stride=2)
)
self.feature_extractor_part2 = nn.Sequential(
nn.Linear(50 * 4 * 4, self.L),
nn.ReLU(),
)
self.attention = nn.Sequential(
nn.Linear(self.L, self.D),
nn.Tanh(),
nn.Linear(self.D, self.K)
)
self.classifier = nn.Sequential(
nn.Linear(self.L*self.K, 1),
nn.Sigmoid()
)
def forward(self, x):
x = x.squeeze(0)
H = self.feature_extractor_part1_0(x)
H = self.feature_extractor_part1_1(H)
H = self.feature_extractor_part1_2(H)
H = H.view(-1, 50 * 4 * 4)
H = self.feature_extractor_part2(H) # NxL
A = self.attention(H) # NxK
A = torch.transpose(A, 1, 0) # KxN
A = F.softmax(A, dim=1) # softmax over N
M = torch.mm(A, H) # KxL
Y_prob = self.classifier(M)
Y_hat = torch.ge(Y_prob, 0.5).float()
return Y_prob, Y_hat, A
# AUXILIARY METHODS
def calculate_classification_error(self, X, Y):
Y = Y.float()
_, Y_hat, _ = self.forward(X)
error = 1. - Y_hat.eq(Y).cpu().float().mean().item()#.data[0]
# print('error:', error, 'Y_hat', Y_hat)
return error, Y_hat
def calculate_objective(self, X, Y):
Y = Y.float()
Y_prob, _, A = self.forward(X)
Y_prob = torch.clamp(Y_prob, min=1e-5, max=1. - 1e-5)
neg_log_likelihood = -1. * (Y * torch.log(Y_prob) + (1. - Y) * torch.log(1. - Y_prob)) # negative log bernoulli
return neg_log_likelihood, A
num_classes = 2
class ModelParallelResNet18(ResNet):
def __init__(self, *args, **kwargs):
super(ModelParallelResNet18, self).__init__(
Bottleneck, [2, 2, 2, 2], num_classes=num_classes, *args, **kwargs)
self.seq1 = nn.Sequential(
self.conv1,
self.bn1,
self.relu,
self.maxpool,
self.layer1
).to('cuda:2')
self.seq2 = nn.Sequential(
self.layer2
).to('cuda:0')
self.seq3 = nn.Sequential(
self.layer3,
self.layer4,
self.avgpool
).to('cuda:1')
def forward(self, x):
x = self.seq2(self.seq1(x).to('cuda:0'))
x = self.seq3(x.to('cuda:1'))
return x.view(x.size(0), -1)
class Attention_Imagenette_bags_3GPUs(nn.Module):
def __init__(self):
super(Attention_Imagenette_bags_3GPUs, self).__init__()
self.L = 2048
self.D = 524
self.K = 1
self.feature_extractor = ModelParallelResNet18()
self.attention = nn.Sequential(
nn.Linear(self.L, self.D),
nn.Tanh(),
nn.Linear(self.D, self.K)
).to('cuda:1')
self.classifier = nn.Sequential(
nn.Linear(self.L*self.K, 1),
nn.Sigmoid()
).to('cuda:1')
def forward(self, x):
x = x.squeeze(0)
H = self.feature_extractor(x).to('cuda:1')
A = self.attention(H.to('cuda:1')) # NxK
A = torch.transpose(A.to('cuda:1'), 1, 0) # KxN
A = F.softmax(A.to('cuda:1'), dim=1) # softmax over N
M = torch.mm(A.to('cuda:1'), H) # KxL
Y_prob = self.classifier(M.to('cuda:1'))
Y_hat = torch.ge(Y_prob.to('cuda:1'), 0.5).float()
return Y_prob, Y_hat, A
# AUXILIARY METHODS
def calculate_classification_error(self, X, Y):
Y = Y.float()
_, Y_hat, _ = self.forward(X)
error = 1. - Y_hat.eq(Y).cpu().float().mean().item()#.data[0]
return error, Y_hat
def calculate_objective(self, X, Y):
Y = Y.float()
Y_prob, _, A = self.forward(X)
Y_prob = torch.clamp(Y_prob, min=1e-5, max=1. - 1e-5)
neg_log_likelihood = -1. * (Y * torch.log(Y_prob) + (1. - Y) * torch.log(1. - Y_prob)) # negative log bernoulli
return neg_log_likelihood, A
class ModelParallelResNet18_1GPU(ResNet):
def __init__(self, *args, **kwargs):
super(ModelParallelResNet18_1GPU, self).__init__(
Bottleneck, [2, 2, 2, 2], num_classes=num_classes, *args, **kwargs)
self.seq1 = nn.Sequential(
self.conv1,
self.bn1,
self.relu,
self.maxpool,
self.layer1
)
self.seq2 = nn.Sequential(
self.layer2
)
self.seq3 = nn.Sequential(
self.layer3,
self.layer4,
self.avgpool
)
def forward(self, x):
x = self.seq2(self.seq1(x))
x = self.seq3(x)
return x.view(x.size(0), -1)
class Attention_Imagenette_bags_1GPU(nn.Module):
def __init__(self):
super(Attention_Imagenette_bags_1GPU, self).__init__()
self.L = 2048
self.D = 524
self.K = 1
self.feature_extractor = ModelParallelResNet18_1GPU()
self.attention = nn.Sequential(
nn.Linear(self.L, self.D),
nn.Tanh(),
nn.Linear(self.D, self.K)
)
self.classifier = nn.Sequential(
nn.Linear(self.L*self.K, 1),
nn.Sigmoid()
)
def forward(self, x):
x = x.squeeze(0)
H = self.feature_extractor(x)
A = self.attention(H) # NxK
A = torch.transpose(A, 1, 0) # KxN
A = F.softmax(A, dim=1) # softmax over N
M = torch.mm(A, H) # KxL
Y_prob = self.classifier(M)
Y_hat = torch.ge(Y_prob, 0.5).float()
return Y_prob, Y_hat, A
# AUXILIARY METHODS
def calculate_classification_error(self, X, Y):
Y = Y.float()
_, Y_hat, _ = self.forward(X)
error = 1. - Y_hat.eq(Y).cpu().float().mean().item()#.data[0]
return error, Y_hat
def calculate_objective(self, X, Y):
Y = Y.float()
Y_prob, _, A = self.forward(X)
Y_prob = torch.clamp(Y_prob, min=1e-5, max=1. - 1e-5)
neg_log_likelihood = -1. * (Y * torch.log(Y_prob) + (1. - Y) * torch.log(1. - Y_prob)) # negative log bernoulli
return neg_log_likelihood, A