-
Notifications
You must be signed in to change notification settings - Fork 7
/
pgcn_models.py
348 lines (277 loc) · 14 KB
/
pgcn_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
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
import torch
from torch import nn
import torch.nn.functional as F
from torch.nn.parameter import Parameter
import math
class GraphConvolution(nn.Module):
"""
Simple GCN layer, similar to https://arxiv.org/abs/1609.02907
"""
def __init__(self, in_features, out_features, bias=True):
super(GraphConvolution, self).__init__()
self.in_features = in_features
self.out_features = out_features
self.weight = Parameter(torch.Tensor(in_features, out_features))
if bias:
self.bias = Parameter(torch.Tensor(out_features))
else:
self.register_parameter('bias', None)
self.reset_parameters()
def reset_parameters(self):
stdv = 1. / math.sqrt(self.weight.size(1))
self.weight.data.uniform_(-stdv, stdv)
if self.bias is not None:
self.bias.data.uniform_(-stdv, stdv)
def forward(self, input, adj):
support = torch.mm(input, self.weight)
output = torch.mm(adj, support)
#output = SparseMM(adj)(support)
if self.bias is not None:
return output + self.bias
else:
return output
def __repr__(self):
return self.__class__.__name__ + ' (' \
+ str(self.in_features) + ' -> ' \
+ str(self.out_features) + ')'
class GCN(nn.Module):
def __init__(self, nfeat, nhid, nclass, dropout):
super(GCN, self).__init__()
self.gc1 = GraphConvolution(nfeat, nhid)
self.gc2 = GraphConvolution(nhid, nclass)
self.dropout = dropout
def forward(self, x, adj):
x = F.relu(self.gc1(x, adj))
x = F.dropout(x, self.dropout, training=self.training)
x = self.gc2(x, adj)
# x = F.relu(self.gc2(x, adj))
# x = F.dropout(x, self.dropout, training=self.training)
return x
class PGCN(torch.nn.Module):
def __init__(self, model_configs, graph_configs, test_mode=False):
super(PGCN, self).__init__()
self.num_class = model_configs['num_class']
self.adj_num = graph_configs['adj_num']
self.child_num = graph_configs['child_num']
self.child_iou_num = graph_configs['iou_num']
self.child_dis_num = graph_configs['dis_num']
self.dropout = model_configs['dropout']
self.test_mode = test_mode
self.act_feat_dim = model_configs['act_feat_dim']
self.comp_feat_dim = model_configs['comp_feat_dim']
self._prepare_pgcn()
self.Act_GCN = GCN(self.act_feat_dim, 512, self.act_feat_dim, dropout=model_configs['gcn_dropout'])
self.Comp_GCN = GCN(self.comp_feat_dim, 512, self.comp_feat_dim, dropout=model_configs['gcn_dropout'])
self.dropout_layer = nn.Dropout(p=self.dropout)
self.U_v512 = nn.Sequential(
nn.Linear(512, 512),
nn.Tanh(),
nn.Linear(512, 512),
)
self.U_a512 = nn.Sequential(
nn.Linear(512, 512),
nn.Tanh(),
nn.Linear(512, 512),
)
self.U_v1536 = nn.Sequential(
nn.Linear(1536, 1536),
nn.Tanh(),
nn.Linear(1536, 1536),
)
self.U_a1536 = nn.Sequential(
nn.Linear(1536, 1536),
nn.Tanh(),
nn.Linear(1536, 1536),
)
def _prepare_pgcn(self):
self.activity_fc = nn.Linear(self.act_feat_dim * 2, self.num_class + 1)
self.completeness_fc = nn.Linear(self.comp_feat_dim * 2, self.num_class)
self.regressor_fc = nn.Linear(self.comp_feat_dim * 2, 2 * self.num_class)
nn.init.normal_(self.activity_fc.weight.data, 0, 0.001)
nn.init.constant_(self.activity_fc.bias.data, 0)
nn.init.normal_(self.completeness_fc.weight.data, 0, 0.001)
nn.init.constant_(self.completeness_fc.bias.data, 0)
nn.init.normal_(self.regressor_fc.weight.data, 0, 0.001)
nn.init.constant_(self.regressor_fc.bias.data, 0)
def train(self, mode=True):
super(PGCN, self).train(mode)
def get_optim_policies(self):
normal_weight = []
normal_bias = []
for m in self.modules():
if isinstance(m, torch.nn.Linear):
ps = list(m.parameters())
normal_weight.append(ps[0])
if len(ps) == 2:
normal_bias.append(ps[1])
elif isinstance(m, GraphConvolution):
ps = list(m.parameters())
normal_weight.append(ps[0])
if len(ps) == 2:
normal_bias.append(ps[1])
elif len(m._modules) == 0:
if len(list(m.parameters())) > 0:
raise ValueError("New atomic module type: {}. Need to give it a learning policy".format(type(m)))
return [
{'params': normal_weight, 'lr_mult': 1, 'decay_mult': 1,
'name': "normal_weight"},
{'params': normal_bias, 'lr_mult': 2, 'decay_mult': 0,
'name': "normal_bias"},
]
def forward(self, input, target, reg_target, prop_type):
if not self.test_mode:
return self.train_forward(input, target, reg_target, prop_type)
else:
return self.test_forward(input)
# RM attention fusion
def TBMRF_block(self, audio, video, nb_block, typee=1):
for i in range(nb_block):
video_residual = video
if typee == 1:
v = self.U_v512(video)
else:
v = self.U_v1536(video)
audio_residual = audio
if typee == 1:
a = self.U_a512(audio)
else:
a = self.U_a1536(audio)
merged = torch.mul(v + a, 0.5)
a_trans = audio_residual
v_trans = video_residual
video = nn.Tanh()(a_trans + merged)
audio = nn.Tanh()(v_trans + merged)
return torch.mul(video + audio, 0.5)
def train_forward(self, input, target, reg_target, prop_type):
activity_fts = input[0]
completeness_fts = input[1]
batch_size = activity_fts.size()[0]
# Attention on activity_fts
audioF = torch.zeros(batch_size, activity_fts.shape[1], 512).cuda()
audioF[:, :, :128] = activity_fts[:, :, 512:].cuda()
videoF = activity_fts[:, :, :512].cuda()
activity_fts = self.TBMRF_block(audioF, videoF, 1)
# Attention on completeness_fts
audioF = torch.zeros(batch_size, completeness_fts.shape[1], 1536).cuda()
audioF[:, :, :128] = completeness_fts[:, :, 512:512 + 128].cuda()
audioF[:, :, 128:128*2] = completeness_fts[:, :, 640 + 512:640 + 512 + 128].cuda()
audioF[:, :, 128*2:128*3] = completeness_fts[:, :, 1280 + 512:1280 + 512 + 128].cuda()
audioF = torch.zeros(batch_size, completeness_fts.shape[1], 1536).cuda()
videoF = completeness_fts[:, :, :1536].cuda()
videoF[:, :, :512] = completeness_fts[:, :, :512].cuda()
videoF[:, :, 512:512*2] = completeness_fts[:, :, 640:640 + 512].cuda()
videoF[:, :, 512*2:512*3] = completeness_fts[:, :, 1280:1280 + 512].cuda()
completeness_fts = self.TBMRF_block(audioF, videoF, 1, typee=2)
# construct feature matrix
act_ft_mat = activity_fts.view(-1, self.act_feat_dim).contiguous()
comp_ft_mat = completeness_fts.view(-1, self.comp_feat_dim).contiguous()
# act cosine similarity
dot_product_mat = torch.mm(act_ft_mat, torch.transpose(act_ft_mat, 0, 1))
len_vec = torch.unsqueeze(torch.sqrt(torch.sum(act_ft_mat * act_ft_mat, dim=1)), dim=0)
len_mat = torch.mm(torch.transpose(len_vec, 0, 1), len_vec)
act_cos_sim_mat = dot_product_mat / len_mat
# comp cosine similarity
dot_product_mat = torch.mm(comp_ft_mat, torch.transpose(comp_ft_mat, 0, 1))
len_vec = torch.unsqueeze(torch.sqrt(torch.sum(comp_ft_mat * comp_ft_mat, dim=1)), dim=0)
len_mat = torch.mm(torch.transpose(len_vec, 0, 1), len_vec)
comp_cos_sim_mat = dot_product_mat / len_mat
mask = act_ft_mat.new_zeros(self.adj_num, self.adj_num)
for stage_cnt in range(self.child_num + 1):
ind_list = list(range(1 + stage_cnt * self.child_num, 1 + (stage_cnt + 1) * self.child_num))
for i, ind in enumerate(ind_list):
mask[stage_cnt, ind] = 1 / self.child_num
mask[stage_cnt, stage_cnt] = 1
mask_mat_var = act_ft_mat.new_zeros(act_ft_mat.size()[0], act_ft_mat.size()[0])
for row in range(int(act_ft_mat.size(0)/ self.adj_num)):
mask_mat_var[row * self.adj_num : (row + 1) * self.adj_num, row * self.adj_num : (row + 1) * self.adj_num] \
= mask
act_adj_mat = mask_mat_var * act_cos_sim_mat
comp_adj_mat = mask_mat_var * comp_cos_sim_mat
# normalized by the number of nodes
act_adj_mat = F.relu(act_adj_mat)
comp_adj_mat = F.relu(comp_adj_mat)
act_gcn_ft = self.Act_GCN(act_ft_mat, act_adj_mat)
comp_gcn_ft = self.Comp_GCN(comp_ft_mat, comp_adj_mat)
out_act_fts = torch.cat((act_gcn_ft, act_ft_mat), dim=-1)
act_fts = out_act_fts[:-1: self.adj_num, :]
act_fts = self.dropout_layer(act_fts)
out_comp_fts = torch.cat((comp_gcn_ft, comp_ft_mat), dim=-1)
comp_fts = out_comp_fts[:-1: self.adj_num, :]
raw_act_fc = self.activity_fc(act_fts)
raw_comp_fc = self.completeness_fc(comp_fts)
# keep 7 proposal to calculate completeness
raw_comp_fc = raw_comp_fc.view(batch_size, -1, raw_comp_fc.size()[-1])[:, :-1, :].contiguous()
raw_comp_fc = raw_comp_fc.view(-1, raw_comp_fc.size()[-1])
comp_target = target.view(batch_size, -1, self.adj_num)[:, :-1, :].contiguous().view(-1).data
comp_target = comp_target[0: -1: self.adj_num].contiguous()
# keep the target proposal
type_data = prop_type.view(-1).data
type_data = type_data[0: -1: self.adj_num]
target = target.view(-1)
target = target[0: -1: self.adj_num]
act_indexer = ((type_data == 0) + (type_data == 2)).nonzero().squeeze()
reg_target = reg_target.view(-1, 2)
reg_target = reg_target[0: -1: self.adj_num]
reg_indexer = (type_data == 0).nonzero().squeeze()
raw_regress_fc = self.regressor_fc(comp_fts).view(-1, self.completeness_fc.out_features, 2).contiguous()
return raw_act_fc[act_indexer, :], target[act_indexer], type_data[act_indexer], \
raw_comp_fc, comp_target, \
raw_regress_fc[reg_indexer, :, :], target[reg_indexer], reg_target[reg_indexer, :]
def test_forward(self, input):
activity_fts = input[0]
completeness_fts = input[1]
batch_size = activity_fts.size()[0]
# Attention on activity_fts
audioF = torch.zeros(batch_size, activity_fts.shape[1], 512).cuda()
audioF[:, :, :128] = activity_fts[:, :, 512:].cuda()
videoF = activity_fts[:, :, :512].cuda()
activity_fts = self.TBMRF_block(audioF, videoF, 1)
# Attention on completeness_fts
audioF = torch.zeros(batch_size, completeness_fts.shape[1], 1536).cuda()
audioF[:, :, :128] = completeness_fts[:, :, 512:512 + 128].cuda()
audioF[:, :, 128:128*2] = completeness_fts[:, :, 640 + 512:640 + 512 + 128].cuda()
audioF[:, :, 128*2:128*3] = completeness_fts[:, :, 1280 + 512:1280 + 512 + 128].cuda()
audioF = torch.zeros(batch_size, completeness_fts.shape[1], 1536).cuda()
videoF = completeness_fts[:, :, :1536].cuda()
videoF[:, :, :512] = completeness_fts[:, :, :512].cuda()
videoF[:, :, 512:512*2] = completeness_fts[:, :, 640:640 + 512].cuda()
videoF[:, :, 512*2:512*3] = completeness_fts[:, :, 1280:1280 + 512].cuda()
completeness_fts = self.TBMRF_block(audioF, videoF, 1, typee=2)
# construct feature matrix
act_ft_mat = activity_fts.view(-1, self.act_feat_dim).contiguous()
comp_ft_mat = completeness_fts.view(-1, self.comp_feat_dim).contiguous()
# act cosine similarity
dot_product_mat = torch.mm(act_ft_mat, torch.transpose(act_ft_mat, 0, 1))
len_vec = torch.unsqueeze(torch.sqrt(torch.sum(act_ft_mat * act_ft_mat, dim=1)), dim=0)
len_mat = torch.mm(torch.transpose(len_vec, 0, 1), len_vec)
act_cos_sim_mat = dot_product_mat / len_mat
# comp cosine similarity
dot_product_mat = torch.mm(comp_ft_mat, torch.transpose(comp_ft_mat, 0, 1))
len_vec = torch.unsqueeze(torch.sqrt(torch.sum(comp_ft_mat * comp_ft_mat, dim=1)), dim=0)
len_mat = torch.mm(torch.transpose(len_vec, 0, 1), len_vec)
comp_cos_sim_mat = dot_product_mat / len_mat
mask = act_ft_mat.new_zeros(self.adj_num, self.adj_num)
for stage_cnt in range(self.child_num + 1):
ind_list = list(range(1 + stage_cnt * self.child_num, 1 + (stage_cnt + 1) * self.child_num))
for i, ind in enumerate(ind_list):
mask[stage_cnt, ind] = 1 / self.child_num
mask[stage_cnt, stage_cnt] = 1
mask_mat_var = act_ft_mat.new_zeros(act_ft_mat.size()[0], act_ft_mat.size()[0])
for row in range(int(act_ft_mat.size(0)/ self.adj_num)):
mask_mat_var[row * self.adj_num: (row + 1) * self.adj_num, row * self.adj_num: (row + 1) * self.adj_num] \
= mask
act_adj_mat = mask_mat_var * act_cos_sim_mat
comp_adj_mat = mask_mat_var * comp_cos_sim_mat
# normalized by the number of nodes
act_adj_mat = F.relu(act_adj_mat)
comp_adj_mat = F.relu(comp_adj_mat)
act_gcn_ft = self.Act_GCN(act_ft_mat, act_adj_mat)
comp_gcn_ft = self.Comp_GCN(comp_ft_mat, comp_adj_mat)
out_act_fts = torch.cat((act_gcn_ft, act_ft_mat), dim=-1)
act_fts = out_act_fts[:-1: self.adj_num, :]
out_comp_fts = torch.cat((comp_gcn_ft, comp_ft_mat), dim=-1)
comp_fts = out_comp_fts[:-1: self.adj_num, :]
raw_act_fc = self.activity_fc(act_fts)
raw_comp_fc = self.completeness_fc(comp_fts)
raw_regress_fc = self.regressor_fc(comp_fts).view(-1, self.completeness_fc.out_features * 2).contiguous()
return raw_act_fc, raw_comp_fc, raw_regress_fc