-
Notifications
You must be signed in to change notification settings - Fork 24
/
main.py
208 lines (175 loc) · 7.73 KB
/
main.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
"""
Utilities for training, testing and caching results
for HICO-DET and V-COCO evaluations.
Fred Zhang <frederic.zhang@anu.edu.au>
The Australian National University
Australian Centre for Robotic Vision
"""
import os
import sys
import torch
import random
import warnings
import argparse
import numpy as np
import torch.distributed as dist
import torch.multiprocessing as mp
from torch.utils.data import DataLoader, DistributedSampler
from upt import build_detector
from utils import custom_collate, CustomisedDLE, DataFactory
warnings.filterwarnings("ignore")
def main(rank, args):
dist.init_process_group(
backend="nccl",
init_method="env://",
world_size=args.world_size,
rank=rank
)
# Fix seed
seed = args.seed + dist.get_rank()
torch.manual_seed(seed)
np.random.seed(seed)
random.seed(seed)
torch.cuda.set_device(rank)
trainset = DataFactory(name=args.dataset, partition=args.partitions[0], data_root=args.data_root)
testset = DataFactory(name=args.dataset, partition=args.partitions[1], data_root=args.data_root)
train_loader = DataLoader(
dataset=trainset,
collate_fn=custom_collate, batch_size=args.batch_size,
num_workers=args.num_workers, pin_memory=True, drop_last=True,
sampler=DistributedSampler(
trainset,
num_replicas=args.world_size,
rank=rank)
)
test_loader = DataLoader(
dataset=testset,
collate_fn=custom_collate, batch_size=1,
num_workers=args.num_workers, pin_memory=True, drop_last=False,
sampler=torch.utils.data.SequentialSampler(testset)
)
args.human_idx = 0
if args.dataset == 'hicodet':
object_to_target = train_loader.dataset.dataset.object_to_verb
args.num_classes = 117
elif args.dataset == 'vcoco':
object_to_target = list(train_loader.dataset.dataset.object_to_action.values())
args.num_classes = 24
upt = build_detector(args, object_to_target)
if os.path.exists(args.resume):
print(f"=> Rank {rank}: continue from saved checkpoint {args.resume}")
checkpoint = torch.load(args.resume, map_location='cpu')
upt.load_state_dict(checkpoint['model_state_dict'])
else:
print(f"=> Rank {rank}: start from a randomly initialised model")
engine = CustomisedDLE(
upt, train_loader,
max_norm=args.clip_max_norm,
num_classes=args.num_classes,
print_interval=args.print_interval,
find_unused_parameters=True,
cache_dir=args.output_dir
)
if args.cache:
if args.dataset == 'hicodet':
engine.cache_hico(test_loader, args.output_dir)
elif args.dataset == 'vcoco':
engine.cache_vcoco(test_loader, args.output_dir)
return
if args.eval:
if args.dataset == 'vcoco':
raise NotImplementedError(f"Evaluation on V-COCO has not been implemented.")
ap = engine.test_hico(test_loader)
# Fetch indices for rare and non-rare classes
num_anno = torch.as_tensor(trainset.dataset.anno_interaction)
rare = torch.nonzero(num_anno < 10).squeeze(1)
non_rare = torch.nonzero(num_anno >= 10).squeeze(1)
print(
f"The mAP is {ap.mean():.4f},"
f" rare: {ap[rare].mean():.4f},"
f" none-rare: {ap[non_rare].mean():.4f}"
)
return
for p in upt.detector.parameters():
p.requires_grad = False
param_dicts = [{
"params": [p for n, p in upt.named_parameters()
if "interaction_head" in n and p.requires_grad]
}]
optim = torch.optim.AdamW(
param_dicts, lr=args.lr_head,
weight_decay=args.weight_decay
)
lr_scheduler = torch.optim.lr_scheduler.StepLR(optim, args.lr_drop)
# Override optimiser and learning rate scheduler
engine.update_state_key(optimizer=optim, lr_scheduler=lr_scheduler)
engine(args.epochs)
@torch.no_grad()
def sanity_check(args):
dataset = DataFactory(name='hicodet', partition=args.partitions[0], data_root=args.data_root)
args.human_idx = 0; args.num_classes = 117
object_to_target = dataset.dataset.object_to_verb
upt = build_detector(args, object_to_target)
if args.eval:
upt.eval()
image, target = dataset[0]
outputs = upt([image], [target])
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--lr-head', default=1e-4, type=float)
parser.add_argument('--batch-size', default=2, type=int)
parser.add_argument('--weight-decay', default=1e-4, type=float)
parser.add_argument('--epochs', default=20, type=int)
parser.add_argument('--lr-drop', default=10, type=int)
parser.add_argument('--clip-max-norm', default=0.1, type=float)
parser.add_argument('--backbone', default='resnet50', type=str)
parser.add_argument('--dilation', action='store_true')
parser.add_argument('--position-embedding', default='sine', type=str, choices=('sine', 'learned'))
parser.add_argument('--repr-dim', default=512, type=int)
parser.add_argument('--hidden-dim', default=256, type=int)
parser.add_argument('--enc-layers', default=6, type=int)
parser.add_argument('--dec-layers', default=6, type=int)
parser.add_argument('--dim-feedforward', default=2048, type=int)
parser.add_argument('--dropout', default=0.1, type=float)
parser.add_argument('--nheads', default=8, type=int)
parser.add_argument('--num-queries', default=100, type=int)
parser.add_argument('--pre-norm', action='store_true')
parser.add_argument('--no-aux-loss', dest='aux_loss', action='store_false')
parser.add_argument('--set-cost-class', default=1, type=float)
parser.add_argument('--set-cost-bbox', default=5, type=float)
parser.add_argument('--set-cost-giou', default=2, type=float)
parser.add_argument('--bbox-loss-coef', default=5, type=float)
parser.add_argument('--giou-loss-coef', default=2, type=float)
parser.add_argument('--eos-coef', default=0.1, type=float,
help="Relative classification weight of the no-object class")
parser.add_argument('--alpha', default=0.5, type=float)
parser.add_argument('--gamma', default=0.2, type=float)
parser.add_argument('--dataset', default='hicodet', type=str)
parser.add_argument('--partitions', nargs='+', default=['train2015', 'test2015'], type=str)
parser.add_argument('--num-workers', default=2, type=int)
parser.add_argument('--data-root', default='./hicodet')
# training parameters
parser.add_argument('--device', default='cuda',
help='device to use for training / testing')
parser.add_argument('--port', default='1234', type=str)
parser.add_argument('--seed', default=66, type=int)
parser.add_argument('--pretrained', default='', help='Path to a pretrained detector')
parser.add_argument('--resume', default='', help='Resume from a model')
parser.add_argument('--output-dir', default='checkpoints')
parser.add_argument('--print-interval', default=500, type=int)
parser.add_argument('--world-size', default=1, type=int)
parser.add_argument('--eval', action='store_true')
parser.add_argument('--cache', action='store_true')
parser.add_argument('--sanity', action='store_true')
parser.add_argument('--box-score-thresh', default=0.2, type=float)
parser.add_argument('--fg-iou-thresh', default=0.5, type=float)
parser.add_argument('--min-instances', default=3, type=int)
parser.add_argument('--max-instances', default=15, type=int)
args = parser.parse_args()
print(args)
if args.sanity:
sanity_check(args)
sys.exit()
os.environ["MASTER_ADDR"] = "localhost"
os.environ["MASTER_PORT"] = args.port
mp.spawn(main, nprocs=args.world_size, args=(args,))