-
Notifications
You must be signed in to change notification settings - Fork 5
/
model.py
executable file
·393 lines (338 loc) · 16.8 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
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
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
import model
import torch.nn.init as torch_init
torch.set_default_tensor_type('torch.cuda.FloatTensor')
import utils.wsad_utils as utils
from torch.nn import init
from multiprocessing.dummy import Pool as ThreadPool
def weights_init(m):
classname = m.__class__.__name__
if classname.find('Conv') != -1 or classname.find('Linear') != -1:
# torch_init.xavier_uniform_(m.weight)
# import pdb
# pdb.set_trace()
torch_init.kaiming_uniform_(m.weight)
if type(m.bias)!=type(None):
m.bias.data.fill_(0)
class BWA_fusion_dropout_feat_v2(torch.nn.Module):
def __init__(self, n_feature, n_class,**args):
super().__init__()
embed_dim = 1024
self.bit_wise_attn = nn.Sequential(
nn.Conv1d(n_feature, embed_dim, 3, padding=1),nn.LeakyReLU(0.2),nn.Dropout(0.5))
self.channel_conv = nn.Sequential(
nn.Conv1d(n_feature, embed_dim, 3, padding=1),nn.LeakyReLU(0.2),nn.Dropout(0.5))
self.attention = nn.Sequential(nn.Conv1d(embed_dim, 512, 3, padding=1),
nn.LeakyReLU(0.2),
nn.Dropout(0.5),
nn.Conv1d(512, 512, 3, padding=1),
nn.LeakyReLU(0.2), nn.Conv1d(512, 1, 1),
nn.Dropout(0.5),
nn.Sigmoid())
self.channel_avg=nn.AdaptiveAvgPool1d(1)
def forward(self,vfeat,ffeat):
channelfeat = self.channel_avg(vfeat)
channel_attn = self.channel_conv(channelfeat)
bit_wise_attn = self.bit_wise_attn(ffeat)
filter_feat = torch.sigmoid(bit_wise_attn*channel_attn)*vfeat
x_atn = self.attention(filter_feat)
return x_atn,filter_feat
#fusion split modal single+ bit_wise_atten dropout+ contrastive + mutual learning +fusion feat(cat)
#------TOP!!!!!!!!!!
class CO2(torch.nn.Module):
def __init__(self, n_feature, n_class,**args):
super().__init__()
embed_dim=2048
mid_dim=1024
dropout_ratio=args['opt'].dropout_ratio
reduce_ratio=args['opt'].reduce_ratio
self.vAttn = getattr(model,args['opt'].AWM)(1024,args)
self.fAttn = getattr(model,args['opt'].AWM)(1024,args)
self.feat_encoder = nn.Sequential(
nn.Conv1d(n_feature, embed_dim, 3, padding=1),nn.LeakyReLU(0.2),nn.Dropout(dropout_ratio))
self.fusion = nn.Sequential(
nn.Conv1d(n_feature, n_feature, 1, padding=0),nn.LeakyReLU(0.2),nn.Dropout(dropout_ratio))
self.classifier = nn.Sequential(
nn.Dropout(dropout_ratio),
nn.Conv1d(embed_dim, embed_dim, 3, padding=1),nn.LeakyReLU(0.2),
nn.Dropout(0.7), nn.Conv1d(embed_dim, n_class+1, 1))
# self.cadl = CADL()
# self.attention = Non_Local_Block(embed_dim,mid_dim,dropout_ratio)
self.channel_avg=nn.AdaptiveAvgPool1d(1)
self.batch_avg=nn.AdaptiveAvgPool1d(1)
self.ce_criterion = nn.BCELoss()
self.apply(weights_init)
def forward(self, inputs, is_training=True, **args):
feat = inputs.transpose(-1, -2)
b,c,n=feat.size()
# feat = self.feat_encoder(x)
v_atn,vfeat = self.vAttn(feat[:,:1024,:],feat[:,1024:,:])
f_atn,ffeat = self.fAttn(feat[:,1024:,:],feat[:,:1024,:])
x_atn = (f_atn+v_atn)/2
nfeat = torch.cat((vfeat,ffeat),1)
nfeat = self.fusion(nfeat)
x_cls = self.classifier(nfeat)
# fg_mask, bg_mask,dropped_fg_mask = self.cadl(x_cls, x_atn, include_min=True)
return {'feat':nfeat.transpose(-1, -2), 'cas':x_cls.transpose(-1, -2), 'attn':x_atn.transpose(-1, -2), 'v_atn':v_atn.transpose(-1, -2),'f_atn':f_atn.transpose(-1, -2)}
#,fg_mask.transpose(-1, -2), bg_mask.transpose(-1, -2),dropped_fg_mask.transpose(-1, -2)
# return att_sigmoid,att_logit, feat_emb, bag_logit, instance_logit
def _multiply(self, x, atn, dim=-1, include_min=False):
if include_min:
_min = x.min(dim=dim, keepdim=True)[0]
else:
_min = 0
return atn * (x - _min) + _min
def criterion(self, outputs, labels, **args):
feat, element_logits, element_atn= outputs['feat'],outputs['cas'],outputs['attn']
v_atn = outputs['v_atn']
f_atn = outputs['f_atn']
mutual_loss=0.5*F.mse_loss(v_atn,f_atn.detach())+0.5*F.mse_loss(f_atn,v_atn.detach())
#learning weight dynamic, lambda1 (1-lambda1)
b,n,c = element_logits.shape
element_logits_supp = self._multiply(element_logits, element_atn,include_min=True)
loss_mil_orig, _ = self.topkloss(element_logits,
labels,
is_back=True,
rat=args['opt'].k,
reduce=None)
# SAL
loss_mil_supp, _ = self.topkloss(element_logits_supp,
labels,
is_back=False,
rat=args['opt'].k,
reduce=None)
loss_3_supp_Contrastive = self.Contrastive(feat,element_logits_supp,labels,is_back=False)
loss_norm = element_atn.mean()
# guide loss
loss_guide = (1 - element_atn -
element_logits.softmax(-1)[..., [-1]]).abs().mean()
v_loss_norm = v_atn.mean()
# guide loss
v_loss_guide = (1 - v_atn -
element_logits.softmax(-1)[..., [-1]]).abs().mean()
f_loss_norm = f_atn.mean()
# guide loss
f_loss_guide = (1 - f_atn -
element_logits.softmax(-1)[..., [-1]]).abs().mean()
# total loss
total_loss = (loss_mil_orig.mean() + loss_mil_supp.mean() +
args['opt'].alpha3*loss_3_supp_Contrastive+
args['opt'].alpha4*mutual_loss+
args['opt'].alpha1*(loss_norm+v_loss_norm+f_loss_norm)/3 +
args['opt'].alpha2*(loss_guide+v_loss_guide+f_loss_guide)/3)
# output = torch.cosine_similarity(dropped_fg_feat, fg_feat, dim=1)
# pdb.set_trace()
return total_loss
def topkloss(self,
element_logits,
labels,
is_back=True,
lab_rand=None,
rat=8,
reduce=None):
if is_back:
labels_with_back = torch.cat(
(labels, torch.ones_like(labels[:, [0]])), dim=-1)
else:
labels_with_back = torch.cat(
(labels, torch.zeros_like(labels[:, [0]])), dim=-1)
if lab_rand is not None:
labels_with_back = torch.cat((labels, lab_rand), dim=-1)
topk_val, topk_ind = torch.topk(
element_logits,
k=max(1, int(element_logits.shape[-2] // rat)),
dim=-2)
instance_logits = torch.mean(
topk_val,
dim=-2,
)
labels_with_back = labels_with_back / (
torch.sum(labels_with_back, dim=1, keepdim=True) + 1e-4)
milloss = (-(labels_with_back *
F.log_softmax(instance_logits, dim=-1)).sum(dim=-1))
if reduce is not None:
milloss = milloss.mean()
return milloss, topk_ind
def Contrastive(self,x,element_logits,labels,is_back=False):
if is_back:
labels = torch.cat(
(labels, torch.ones_like(labels[:, [0]])), dim=-1)
else:
labels = torch.cat(
(labels, torch.zeros_like(labels[:, [0]])), dim=-1)
sim_loss = 0.
n_tmp = 0.
_, n, c = element_logits.shape
for i in range(0, 3*2, 2):
atn1 = F.softmax(element_logits[i], dim=0)
atn2 = F.softmax(element_logits[i+1], dim=0)
n1 = torch.FloatTensor([np.maximum(n-1, 1)]).cuda()
n2 = torch.FloatTensor([np.maximum(n-1, 1)]).cuda()
Hf1 = torch.mm(torch.transpose(x[i], 1, 0), atn1) # (n_feature, n_class)
Hf2 = torch.mm(torch.transpose(x[i+1], 1, 0), atn2)
Lf1 = torch.mm(torch.transpose(x[i], 1, 0), (1 - atn1)/n1)
Lf2 = torch.mm(torch.transpose(x[i+1], 1, 0), (1 - atn2)/n2)
d1 = 1 - torch.sum(Hf1*Hf2, dim=0) / (torch.norm(Hf1, 2, dim=0) * torch.norm(Hf2, 2, dim=0)) # 1-similarity
d2 = 1 - torch.sum(Hf1*Lf2, dim=0) / (torch.norm(Hf1, 2, dim=0) * torch.norm(Lf2, 2, dim=0))
d3 = 1 - torch.sum(Hf2*Lf1, dim=0) / (torch.norm(Hf2, 2, dim=0) * torch.norm(Lf1, 2, dim=0))
sim_loss = sim_loss + 0.5*torch.sum(torch.max(d1-d2+0.5, torch.FloatTensor([0.]).cuda())*labels[i,:]*labels[i+1,:])
sim_loss = sim_loss + 0.5*torch.sum(torch.max(d1-d3+0.5, torch.FloatTensor([0.]).cuda())*labels[i,:]*labels[i+1,:])
n_tmp = n_tmp + torch.sum(labels[i,:]*labels[i+1,:])
sim_loss = sim_loss / n_tmp
return sim_loss
def decompose(self, outputs, **args):
feat, element_logits, atn_supp, atn_drop, element_atn = outputs
return element_logits,element_atn
class ANT_CO2(torch.nn.Module):
def __init__(self, n_feature, n_class,**args):
super().__init__()
embed_dim=2048
mid_dim=1024
dropout_ratio=args['opt'].dropout_ratio
reduce_ratio=args['opt'].reduce_ratio
self.vAttn = getattr(model,args['opt'].AWM)(1024,args)
self.fAttn = getattr(model,args['opt'].AWM)(1024,args)
self.feat_encoder = nn.Sequential(
nn.Conv1d(n_feature, embed_dim, 3, padding=1),nn.LeakyReLU(0.2),nn.Dropout(dropout_ratio))
self.fusion = nn.Sequential(
nn.Conv1d(n_feature, n_feature, 1, padding=0),nn.LeakyReLU(0.2),nn.Dropout(dropout_ratio))
self.classifier = nn.Sequential(
nn.Dropout(dropout_ratio),
nn.Conv1d(embed_dim, embed_dim, 3, padding=1),nn.LeakyReLU(0.2),
nn.Dropout(0.7), nn.Conv1d(embed_dim, n_class+1, 1))
# self.cadl = CADL()
# self.attention = Non_Local_Block(embed_dim,mid_dim,dropout_ratio)
self.channel_avg=nn.AdaptiveAvgPool1d(1)
self.batch_avg=nn.AdaptiveAvgPool1d(1)
self.ce_criterion = nn.BCELoss()
_kernel = ((args['opt'].max_seqlen // args['opt'].t) // 2 * 2 + 1)
self.pool=nn.AvgPool1d(_kernel, 1, padding=_kernel // 2, count_include_pad=True) \
if _kernel is not None else nn.Identity()
self.apply(weights_init)
def forward(self, inputs, is_training=True, **args):
feat = inputs.transpose(-1, -2)
b,c,n=feat.size()
# feat = self.feat_encoder(x)
v_atn,vfeat = self.vAttn(feat[:,:1024,:],feat[:,1024:,:])
f_atn,ffeat = self.fAttn(feat[:,1024:,:],feat[:,:1024,:])
x_atn = (f_atn+v_atn)/2
nfeat = torch.cat((vfeat,ffeat),1)
nfeat = self.fusion(nfeat)
x_cls = self.classifier(nfeat)
x_cls=self.pool(x_cls)
x_atn=self.pool(x_atn)
f_atn=self.pool(f_atn)
v_atn=self.pool(v_atn)
# fg_mask, bg_mask,dropped_fg_mask = self.cadl(x_cls, x_atn, include_min=True)
return {'feat':nfeat.transpose(-1, -2), 'cas':x_cls.transpose(-1, -2), 'attn':x_atn.transpose(-1, -2), 'v_atn':v_atn.transpose(-1, -2),'f_atn':f_atn.transpose(-1, -2)}
#,fg_mask.transpose(-1, -2), bg_mask.transpose(-1, -2),dropped_fg_mask.transpose(-1, -2)
# return att_sigmoid,att_logit, feat_emb, bag_logit, instance_logit
def _multiply(self, x, atn, dim=-1, include_min=False):
if include_min:
_min = x.min(dim=dim, keepdim=True)[0]
else:
_min = 0
return atn * (x - _min) + _min
def criterion(self, outputs, labels, **args):
feat, element_logits, element_atn= outputs['feat'],outputs['cas'],outputs['attn']
v_atn = outputs['v_atn']
f_atn = outputs['f_atn']
mutual_loss=0.5*F.mse_loss(v_atn,f_atn.detach())+0.5*F.mse_loss(f_atn,v_atn.detach())
#learning weight dynamic, lambda1 (1-lambda1)
b,n,c = element_logits.shape
element_logits_supp = self._multiply(element_logits, element_atn,include_min=True)
loss_mil_orig, _ = self.topkloss(element_logits,
labels,
is_back=True,
rat=args['opt'].k,
reduce=None)
# SAL
loss_mil_supp, _ = self.topkloss(element_logits_supp,
labels,
is_back=False,
rat=args['opt'].k,
reduce=None)
loss_3_supp_Contrastive = self.Contrastive(feat,element_logits_supp,labels,is_back=False)
loss_norm = element_atn.mean()
# guide loss
loss_guide = (1 - element_atn -
element_logits.softmax(-1)[..., [-1]]).abs().mean()
v_loss_norm = v_atn.mean()
# guide loss
v_loss_guide = (1 - v_atn -
element_logits.softmax(-1)[..., [-1]]).abs().mean()
f_loss_norm = f_atn.mean()
# guide loss
f_loss_guide = (1 - f_atn -
element_logits.softmax(-1)[..., [-1]]).abs().mean()
# total loss
total_loss = (loss_mil_orig.mean() + loss_mil_supp.mean() + args['opt'].alpha3*loss_3_supp_Contrastive +mutual_loss+
args['opt'].alpha1*(loss_norm+v_loss_norm+f_loss_norm)/3 +
args['opt'].alpha2*(loss_guide+v_loss_guide+f_loss_guide)/3)
# output = torch.cosine_similarity(dropped_fg_feat, fg_feat, dim=1)
# pdb.set_trace()
return total_loss
def topkloss(self,
element_logits,
labels,
is_back=True,
lab_rand=None,
rat=8,
reduce=None):
if is_back:
labels_with_back = torch.cat(
(labels, torch.ones_like(labels[:, [0]])), dim=-1)
else:
labels_with_back = torch.cat(
(labels, torch.zeros_like(labels[:, [0]])), dim=-1)
if lab_rand is not None:
labels_with_back = torch.cat((labels, lab_rand), dim=-1)
topk_val, topk_ind = torch.topk(
element_logits,
k=max(1, int(element_logits.shape[-2] // rat)),
dim=-2)
instance_logits = torch.mean(
topk_val,
dim=-2,
)
labels_with_back = labels_with_back / (
torch.sum(labels_with_back, dim=1, keepdim=True) + 1e-4)
milloss = (-(labels_with_back *
F.log_softmax(instance_logits, dim=-1)).sum(dim=-1))
if reduce is not None:
milloss = milloss.mean()
return milloss, topk_ind
def Contrastive(self,x,element_logits,labels,is_back=False):
if is_back:
labels = torch.cat(
(labels, torch.ones_like(labels[:, [0]])), dim=-1)
else:
labels = torch.cat(
(labels, torch.zeros_like(labels[:, [0]])), dim=-1)
sim_loss = 0.
n_tmp = 0.
_, n, c = element_logits.shape
for i in range(0, 3*2, 2):
atn1 = F.softmax(element_logits[i], dim=0)
atn2 = F.softmax(element_logits[i+1], dim=0)
n1 = torch.FloatTensor([np.maximum(n-1, 1)]).cuda()
n2 = torch.FloatTensor([np.maximum(n-1, 1)]).cuda()
Hf1 = torch.mm(torch.transpose(x[i], 1, 0), atn1) # (n_feature, n_class)
Hf2 = torch.mm(torch.transpose(x[i+1], 1, 0), atn2)
Lf1 = torch.mm(torch.transpose(x[i], 1, 0), (1 - atn1)/n1)
Lf2 = torch.mm(torch.transpose(x[i+1], 1, 0), (1 - atn2)/n2)
d1 = 1 - torch.sum(Hf1*Hf2, dim=0) / (torch.norm(Hf1, 2, dim=0) * torch.norm(Hf2, 2, dim=0)) # 1-similarity
d2 = 1 - torch.sum(Hf1*Lf2, dim=0) / (torch.norm(Hf1, 2, dim=0) * torch.norm(Lf2, 2, dim=0))
d3 = 1 - torch.sum(Hf2*Lf1, dim=0) / (torch.norm(Hf2, 2, dim=0) * torch.norm(Lf1, 2, dim=0))
sim_loss = sim_loss + 0.5*torch.sum(torch.max(d1-d2+0.5, torch.FloatTensor([0.]).cuda())*labels[i,:]*labels[i+1,:])
sim_loss = sim_loss + 0.5*torch.sum(torch.max(d1-d3+0.5, torch.FloatTensor([0.]).cuda())*labels[i,:]*labels[i+1,:])
n_tmp = n_tmp + torch.sum(labels[i,:]*labels[i+1,:])
sim_loss = sim_loss / n_tmp
return sim_loss
def decompose(self, outputs, **args):
feat, element_logits, atn_supp, atn_drop, element_atn = outputs
return element_logits,element_atn