forked from WeChat-Big-Data-Challenge-2022/challenge
-
Notifications
You must be signed in to change notification settings - Fork 0
/
inference.py
47 lines (39 loc) · 1.56 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
import torch
from torch.utils.data import SequentialSampler, DataLoader
from config import parse_args
from data_helper import MultiModalDataset
from category_id_map import lv2id_to_category_id
from model import MultiModal
def inference():
args = parse_args()
# 1. load data
dataset = MultiModalDataset(args, args.test_annotation, args.test_zip_feats, test_mode=True)
sampler = SequentialSampler(dataset)
dataloader = DataLoader(dataset,
batch_size=args.test_batch_size,
sampler=sampler,
drop_last=False,
pin_memory=True,
num_workers=args.num_workers,
prefetch_factor=args.prefetch)
# 2. load model
model = MultiModal(args)
checkpoint = torch.load(args.ckpt_file, map_location='cpu')
model.load_state_dict(checkpoint['model_state_dict'])
if torch.cuda.is_available():
model = torch.nn.parallel.DataParallel(model.cuda())
model.eval()
# 3. inference
predictions = []
with torch.no_grad():
for batch in dataloader:
pred_label_id = model(batch, inference=True)
predictions.extend(pred_label_id.cpu().numpy())
# 4. dump results
with open(args.test_output_csv, 'w') as f:
for pred_label_id, ann in zip(predictions, dataset.anns):
video_id = ann['id']
category_id = lv2id_to_category_id(pred_label_id)
f.write(f'{video_id},{category_id}\n')
if __name__ == '__main__':
inference()