-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathavobject.py
270 lines (207 loc) · 10.1 KB
/
avobject.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
import torch
import torch.nn as nn
import torch.optim as optim
from torch.nn import functional as F
import time
import sys
from model import SyncNetModel
import os
from tqdm import tqdm
class avobject_model(nn.Module):
def __init__(self, learning_rate=0.0001, nOut=1024, n_neg=20):
super(avobject_model, self).__init__();
self.n_neg = n_neg
self.__S__ = SyncNetModel(nOut=nOut).cuda();
self.__optimizer__ = torch.optim.SGD(self.parameters(), lr = learning_rate);
self.cos = nn.CosineSimilarity(dim=1).cuda()
self.logits_scale = nn.Linear(1, 1, bias=False).cuda()
torch.nn.init.ones_(self.logits_scale.weight)
def train_network(self,loader=None,evalmode=None):
if evalmode:
self.eval();
else:
self.train();
loss = 0
counter = 0
index = 0
stepsize = loader.batch_size
criterion = ContrastiveLoss()
for data in loader:
self.__optimizer__.zero_grad();
video, audio = data['video'], data['audio']
# padding for cover all image
pad_len = 4
video = torch.nn.ConstantPad3d([pad_len, pad_len, pad_len, pad_len],
0)(video)
if evalmode:
with torch.no_grad():
out_vid = self.__S__.forward_vid(video.cuda(), return_feat=False)
out_aud = self.__S__.forward_aud(audio.cuda())
else:
out_vid = self.__S__.forward_vid(video.cuda(), return_feat=False)
out_aud = self.__S__.forward_aud(audio.cuda())
norm_vid = F.normalize(out_vid, p=2, dim=1)
norm_aud = F.normalize(out_aud, p=2, dim=1)
norm_aud = norm_aud.permute(0, 3, 1, 2)
vid_sync, aud_sync, label = self.create_online_sync_negatives(norm_vid, norm_aud)
score, _ = self.calc_av_scores(vid_sync, aud_sync)
nloss = criterion(score, label)
if not evalmode:
nloss.backward()
self.__optimizer__.step();
counter+=1
loss += nloss.detach().cpu();
sys.stdout.write("\r progress: %d / %d , Loss %.5f"%(counter*stepsize, len(loader)*stepsize, loss/counter))
sys.stdout.flush();
sys.stdout.write("\n");
return loss/counter
def train_network_with_random(self,loader=None,evalmode=None):
if evalmode:
self.eval();
else:
self.train();
loss = 0
counter = 0
index = 0
stepsize = loader.batch_size
criterion = ContrastiveLoss()
for data in loader:
self.__optimizer__.zero_grad();
video, audio, false_audio = data['video'], data['audio'], data['false_audio']
# padding for cover all image
pad_len = 4
video = torch.nn.ConstantPad3d([pad_len, pad_len, pad_len, pad_len],
0)(video)
if evalmode:
with torch.no_grad():
out_vid = self.__S__.forward_vid(video.cuda(), return_feat=False)
out_aud = self.__S__.forward_aud(audio.cuda())
out_false_aud = self.__S__.forward_aud(false_audio.cuda())
else:
out_vid = self.__S__.forward_vid(video.cuda(), return_feat=False)
out_aud = self.__S__.forward_aud(audio.cuda())
out_false_aud = self.__S__.forward_aud(false_audio.cuda())
norm_vid = F.normalize(out_vid, p=2, dim=1)
norm_aud = F.normalize(out_aud, p=2, dim=1)
norm_aud = norm_aud.permute(0, 3, 1, 2)
norm_false_aud = F.normalize(out_false_aud, p=2, dim=1)
norm_false_aud = norm_false_aud.permute(0, 3, 1, 2)
vid_sync, aud_sync, label = self.create_online_sync_negatives_random_sample(norm_vid, norm_aud, norm_false_aud)
score, _ = self.calc_av_scores(vid_sync, aud_sync)
nloss = criterion(score, label)
if not evalmode:
nloss.backward()
self.__optimizer__.step();
counter+=1
loss += nloss.detach().cpu();
sys.stdout.write("\r progress: %d / %d , Loss %.5f"%(counter*stepsize, len(loader)*stepsize, loss/counter))
sys.stdout.flush();
sys.stdout.write("\n");
return loss/counter
def predict(self, data):
video, audio = data['video'], data['audio']
pad_len = 4
video = torch.nn.ConstantPad3d([pad_len, pad_len, pad_len, pad_len],
0)(video)
with torch.no_grad():
out_vid = self.__S__.forward_vid(video.cuda(), return_feat=False)
out_aud = self.__S__.forward_aud(audio.cuda())
norm_vid = F.normalize(out_vid, p=2, dim=1)
norm_aud = F.normalize(out_aud, p=2, dim=1)
norm_aud = norm_aud.permute(0, 3, 1, 2)
vid_sync, aud_sync, label = self.create_online_sync_negatives(norm_vid, norm_aud)
score, att_map = self.calc_av_scores(vid_sync, aud_sync)
return score, att_map, vid_sync, aud_sync, label
def create_online_sync_negatives(self, vid_emb, aud_emb):
assert self.n_neg % 2 == 0
ww = self.n_neg // 2
fr_trunc, to_trunc = ww, aud_emb.shape[-1] - ww
vid_emb_pos = vid_emb[:, :, fr_trunc:to_trunc]
slice_size = to_trunc - fr_trunc
aud_emb_posneg = aud_emb.squeeze(1).unfold(-1, slice_size, 1)
aud_emb_posneg = aud_emb_posneg.permute([0, 2, 1, 3])
# this is the index of the positive samples within the posneg bundle
pos_idx = self.n_neg // 2
aud_emb_pos = aud_emb[:, 0, :, fr_trunc:to_trunc]
# make sure that we got the indices correctly
assert torch.all(aud_emb_posneg[:, pos_idx] == aud_emb_pos)
# Shuffle negative samples and positive samples
idx = torch.randperm(aud_emb_posneg.shape[1])
aud_emb_posneg = aud_emb_posneg[:, idx].view(aud_emb_posneg.size())
pos_idx = (idx == pos_idx).nonzero(as_tuple=True)[0].item()
# Note, Torch don't allow pythonic swap like a, b = b, a
# Once more, Check that we got the indices correctly
assert torch.all(aud_emb_posneg[:, pos_idx] == aud_emb_pos)
return vid_emb_pos, aud_emb_posneg, pos_idx
def create_online_sync_negatives_random_sample(self, vid_emb, aud_emb, false_aud_emb):
assert self.n_neg % 2 == 0
ww = self.n_neg // 2
fr_trunc, to_trunc = ww, false_aud_emb.shape[-1] - ww
vid_emb_pos = vid_emb[:, :, fr_trunc:to_trunc]
slice_size = to_trunc - fr_trunc
aud_emb_posneg = false_aud_emb.squeeze(1).unfold(-1, slice_size, 1)
aud_emb_posneg = aud_emb_posneg.permute([0, 2, 1, 3])
# this is the index of the positive samples within the posneg bundle
pos_idx = self.n_neg // 2
aud_emb_pos = aud_emb[:, 0, :, fr_trunc:to_trunc]
# Shuffle negative samples and positive samples
idx = torch.randperm(aud_emb_posneg.shape[1])
aud_emb_posneg = aud_emb_posneg[:, idx].view(aud_emb_posneg.size())
pos_idx = (idx == pos_idx).nonzero(as_tuple=True)[0].item()
aud_emb_posneg[:, pos_idx] = aud_emb_pos
# Check that we got the indices correctly
assert torch.all(aud_emb_posneg[:, pos_idx] == aud_emb_pos)
return vid_emb_pos, aud_emb_posneg, pos_idx
def calc_av_scores(self, vid, aud):
"""
:return: aggregated scores over T, h, w
"""
vid = vid[:, :, None]
aud = aud.transpose(1, 2)[..., None, None]
cos_similarity = self.cos(vid, aud)
scores = self.logits_scale(cos_similarity[..., None]).squeeze(-1)
att_map = self.logsoftmax_2d(scores)
scores = torch.nn.MaxPool3d(kernel_size=(1, scores.shape[-2],
scores.shape[-1]))(scores)
scores = scores.squeeze()
return scores, att_map
def logsoftmax_2d(self, logits):
# Log softmax on last 2 dims because torch won't allow multiple dims
orig_shape = logits.shape
logprobs = torch.nn.LogSoftmax(dim=-1)(
logits.reshape(list(logits.shape[:-2]) + [-1])).reshape(orig_shape)
return logprobs
def updateLearningRate(self, alpha):
learning_rate = []
for param_group in self.__optimizer__.param_groups:
param_group['lr'] = param_group['lr']*alpha
learning_rate.append(param_group['lr'])
return learning_rate;
def saveParameters(self, path):
torch.save(self.state_dict(), path);
## ===== ===== ===== ===== ===== ===== ===== =====
## Load parameters
## ===== ===== ===== ===== ===== ===== ===== =====
def loadParameters(self, path):
self_state = self.state_dict();
loaded_state = torch.load(path);
for name, param in loaded_state.items():
origname = name;
if name not in self_state:
name = name.replace("module.", "");
if name not in self_state:
print("%s is not in the model."%origname);
continue;
if self_state[name].size() != loaded_state[origname].size():
print("Wrong parameter length: %s, model: %s, loaded: %s"%(origname, self_state[name].size(), loaded_state[origname].size()));
continue;
self_state[name].copy_(param);
class ContrastiveLoss(torch.nn.Module):
"""
Contrastive loss function.
"""
def __init__(self):
super(ContrastiveLoss, self).__init__()
def forward(self, scores, label):
loss_contrastive = -torch.log(torch.exp(scores[:, label].sum()) / torch.exp(scores.sum(2).sum(0)).sum())
return loss_contrastive