-
Notifications
You must be signed in to change notification settings - Fork 2
/
inference.py
359 lines (316 loc) · 12.8 KB
/
inference.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
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import logging
import h5py
import torch
import json
from tqdm import tqdm
from time import sleep
from config import cfg
from utils.utils import Timer
from dataloader import get_dataloader
from sklearn.metrics import f1_score
from collections import defaultdict
from torch.nn import functional as F
def to_list(tensor):
return tensor.cpu().numpy().tolist()
def compute_on_dataset(model, data_loader, local_rank, device, timer=None, output_file='debug.h5'):
model.eval()
results_dict = {}
gt_dict = {}
cpu_device = torch.device("cpu")
text = "GPU {}".format(local_rank)
pbar = tqdm(
total=len(data_loader),
position=local_rank,
desc=text,
)
with h5py.File(output_file, 'w') as f:
box_feat_ds = f.create_dataset(
'bbox_features', shape=(len(data_loader), 150, 1024)
)
box_ds = f.create_dataset(
'bboxes', shape=(len(data_loader), 150, 4)
)
num_boxes_ds = f.create_dataset(
'num_boxes', shape=(len(data_loader), 1)
)
img_size_ds = f.create_dataset(
'image_size', shape=(len(data_loader), 2)
)
info_dict = {}
for e, out_dict in enumerate(data_loader):
images = out_dict['images']
targets = out_dict['gt_bboxes']
image_ids = out_dict['image_ids']
info = out_dict['info']
images = [image.to(device) for image in images]
targets = [target.to(device) for target in targets]
if timer:
timer.tic()
x, _, output = model(images, targets)
if timer:
if not cfg.MODEL.DEVICE == 'cpu':
torch.cuda.synchronize()
timer.toc()
assert (x.shape[0] == len(targets[0].bbox))
output = [o.to(cpu_device) for o in output]
info_dict[image_ids[0]] = {}
info_dict[image_ids[0]]['idx'] = e
info_dict[image_ids[0]]['objects'] = {}
bboxes = targets[0].bbox
num_boxes = len(targets[0].bbox)
for i in range(num_boxes):
tmp = {}
tmp = info[0][i]
tmp['idx'] = i
info_dict[image_ids[0]]['objects'][info[0][i]['object_id']] = tmp
'''
for i in range(5):
fpn_feat_ds[i][e] = output[i].numpy()
'''
box_feat_ds[e, :num_boxes, :] = x.cpu().numpy()
box_ds[e, :num_boxes, :] = bboxes.cpu().numpy()
num_boxes_ds[e] = num_boxes
img_size_ds[e] = targets[0].size
pbar.update(1)
sleep(0.001)
with open(output_file.replace('.h5', '_map.json'), 'w') as fp:
json.dump(info_dict, fp)
def inference_step(model, out_dict, device=torch.device('cuda')):
images = torch.stack(out_dict['images'])
obj_labels = torch.cat(out_dict['object_labels'], -1)
attr_labels = torch.cat(out_dict['attribute_labels'], -1)
cropped_image = torch.stack(out_dict['cropped_image'])
images = images.to(device)
obj_labels = obj_labels.to(device)
attr_labels = attr_labels.to(device)
cropped_image = cropped_image.to(device)
# loss_dict = model(images, targets)
ret_dict = model(bbox_images=cropped_image, spatial_feat=None,
attr_labels=attr_labels, obj_labels=obj_labels,
images=images)
attr_score, obj_score = ret_dict.get('attr_score', None), \
ret_dict.get('obj_score', None)
if attr_score is not None:
attr_score_norm = F.softmax(attr_score, -1)
ret_dict['pred_attr_prob'], ret_dict['pred_attr'] = attr_score_norm.max(-1)
if obj_score is not None:
obj_score_norm = F.softmax(obj_score, -1)
ret_dict['pred_obj_prob'], ret_dict['pred_obj'] = obj_score_norm.max(-1)
ret_dict['obj_labels'], ret_dict['attr_labels'] = obj_labels, attr_labels
return ret_dict
def inference(
model,
current_epoch,
current_iter,
local_rank,
data_loader,
dataset_name,
device="cuda",
max_instance=3200,
mute=False,
verbose_return=False
):
model.train(False)
# convert to a torch.device for efficiency
device = torch.device(device)
if not mute:
logger = logging.getLogger("maskrcnn_benchmark.inference")
logger.info("Start evaluation")
total_timer = Timer()
total_timer.tic()
torch.cuda.empty_cache()
if not mute:
pbar = tqdm(
total=len(data_loader),
desc="Validation in progress"
)
def to_list(tensor):
return tensor.cpu().numpy().tolist()
with torch.no_grad():
all_pred_obj, all_truth_obj, all_pred_attr, all_truth_attr = [], [], [], []
all_image_ids, all_boxes = [], []
all_pred_attr_prob = []
all_raws = []
obj_loss_all, attr_loss_all = 0, 0
cnt = 0
for iteration, out_dict in enumerate(data_loader):
if type(max_instance) is int:
if iteration == max_instance // model.cfg.EXTERNAL.BATCH_SIZE: break
if type(max_instance) is float:
if iteration > max_instance * len(data_loader) // model.cfg.EXTERNAL.BATCH_SIZE: break
# print(iteration)
if verbose_return:
all_image_ids.extend(out_dict['image_ids'])
all_boxes.extend(out_dict['gt_bboxes'])
all_raws.extend(out_dict['raw'])
ret_dict = inference_step(model, out_dict, device)
loss_attr, loss_obj, attr_score, obj_score = ret_dict.get('attr_loss', None), \
ret_dict.get('obj_loss', None), \
ret_dict.get('attr_score', None), \
ret_dict.get('obj_score', None)
if loss_attr is not None:
attr_loss_all += loss_attr.item()
pred_attr_prob, pred_attr = ret_dict['pred_attr_prob'], ret_dict['pred_attr']
all_pred_attr.extend(to_list(pred_attr))
all_truth_attr.extend(to_list(ret_dict['attr_labels']))
all_pred_attr_prob.extend(to_list(pred_attr_prob))
if loss_obj is not None:
obj_loss_all += loss_obj.item()
_, pred_obj = obj_score.max(-1)
all_pred_obj.extend(to_list(pred_obj))
all_truth_obj.extend(to_list(ret_dict['obj_labels']))
cnt += 1
if not mute:
pbar.update(1)
obj_f1 = f1_score(all_truth_obj, all_pred_obj, average='micro')
attr_f1 = f1_score(all_truth_attr, all_pred_attr, average='micro')
obj_loss_all /= (cnt + 1e-10)
attr_loss_all /= (cnt + 1e-10)
if not mute:
logger.info('Epoch: {}\tIteration: {}\tObject f1: {}\tAttr f1:{}\tObject loss:{}\tAttr loss:{}'.
format(current_epoch, current_iter, obj_f1, attr_f1, obj_loss_all, attr_loss_all))
#compute_on_dataset(model, data_loader, local_rank, device, inference_timer, output_file)
# wait for all processes to complete before measuring the time
total_time = total_timer.toc()
model.train(True)
if not verbose_return:
return obj_f1, attr_f1, len(all_truth_attr)
else:
return obj_f1, attr_f1, all_pred_attr, all_truth_attr, all_pred_obj, all_truth_obj, all_image_ids, all_boxes, \
all_pred_attr_prob, all_raws
def run_forget_metrics(metric_dict, finished_tasks, all_tasks, key, forget_dict):
for task in all_tasks:
if len(metric_dict[key][task]) <= 1 or task not in finished_tasks:
forget_dict[task].append(-1)
else:
forget_dict[task].append(max(metric_dict[key][task][:-1]) - metric_dict[key][task][-1])
def run_forward_transfer_metrics(metric_dict, seen_tasks, all_tasks, key, ft_dict):
for task in all_tasks:
if task not in seen_tasks:
ft_dict[task].append(metric_dict[key][task][-1])
else:
ft_dict[task].append(-1)
def numericalize_metric_scores(metric_dict):
result_dict = defaultdict(list)
for t in range(metric_dict['length']):
for key in ['attr_acc', 'forget_dict', 'obj_acc']:
total_inst = 0
total_score = 0
for attr in metric_dict[key]:
inst_num = metric_dict['inst_num'][attr][t]
score = metric_dict[key][attr][t]
if score != -1:
total_inst += inst_num
total_score += score * inst_num
avg_score = total_score / (total_inst + 1e-10)
result_dict[key].append(avg_score)
return result_dict
def inference_ocl_attr(
model,
current_epoch,
current_iter,
dataset_name,
prev_metric_dict,
seen_objects,
finished_objects,
all_objects,
max_instance
):
"""
:param model:
:param current_epoch:
:param current_iter:
:param prev_metric_dict: {attr_acc: <attr>: [acc1, acc2]}
:param filter_objects:
:param filter_attrs:
:return:
"""
model.train(False)
device = torch.device('cuda')
if not prev_metric_dict:
prev_metric_dict = {
'attr_acc': defaultdict(list),
'inst_num': defaultdict(list),
'ft_dict': defaultdict(list),
'forget_dict': defaultdict(list),
'obj_acc': defaultdict(list),
'length': 0
}
pbar = tqdm(
total=len(all_objects),
desc="Validation in progress"
)
# only seen objects by this time
for obj in all_objects:
dataloader = get_dataloader(model.cfg, 'val',False,False,filter_obj=[obj])
obj_acc, attr_acc, inst_num = inference(model, current_epoch, current_iter, 0, dataloader, dataset_name,
max_instance=max_instance, mute=True)
prev_metric_dict['attr_acc'][obj].append(attr_acc)
prev_metric_dict['inst_num'][obj].append(inst_num)
prev_metric_dict['obj_acc'][obj].append(obj_acc)
pbar.update(1)
metric_dict = prev_metric_dict
#run_forward_transfer_metrics(metric_dict, seen_objects, all_objects, 'attr_acc', metric_dict['ft_dict'])
run_forget_metrics(metric_dict, finished_objects, all_objects, 'attr_acc', metric_dict['forget_dict'])
metric_dict['length'] += 1
numerical_metric_dict = numericalize_metric_scores(metric_dict)
return metric_dict, numerical_metric_dict
def inference_mean_exemplar(
model,
current_epoch,
current_iter,
local_rank,
data_loader,
dataset_name,
device="cuda",
max_instance=3200,
mute=False,
):
model.train(False)
# convert to a torch.device for efficiency
device = torch.device(device)
if not mute:
logger = logging.getLogger("maskrcnn_benchmark.inference")
logger.info("Start evaluation")
total_timer = Timer()
inference_timer = Timer()
total_timer.tic()
torch.cuda.empty_cache()
if not mute:
pbar = tqdm(
total=len(data_loader),
desc="Validation in progress"
)
with torch.no_grad():
all_pred_obj, all_truth_obj, all_pred_attr, all_truth_attr = [], [], [], []
obj_loss_all, attr_loss_all = 0, 0
cnt = 0
for iteration, out_dict in enumerate(data_loader):
if type(max_instance) is int:
if iteration == max_instance // model.cfg.EXTERNAL.BATCH_SIZE: break
if type(max_instance) is float:
if iteration > max_instance * len(data_loader) // model.cfg.EXTERNAL.BATCH_SIZE: break
# print(iteration)
images = torch.stack(out_dict['images'])
obj_labels = torch.cat(out_dict['object_labels'], -1)
attr_labels = torch.cat(out_dict['attribute_labels'], -1)
cropped_image = torch.stack(out_dict['cropped_image'])
images = images.to(device)
obj_labels = obj_labels.to(device)
attr_labels = attr_labels.to(device)
cropped_image = cropped_image.to(device)
# loss_dict = model(images, targets)
pred_obj = model.mean_of_exemplar_classify(cropped_image)
all_pred_obj.extend(to_list(pred_obj))
all_truth_obj.extend(to_list(obj_labels))
cnt += 1
if not mute:
pbar.update(1)
obj_f1 = f1_score(all_truth_obj, all_pred_obj, average='micro')
#attr_f1 = f1_score(all_truth_attr, all_pred_attr, average='micro')
obj_loss_all /= (cnt + 1e-10)
# wait for all processes to complete before measuring the time
total_time = total_timer.toc()
model.train(True)
return obj_f1, 0, len(all_truth_obj)