forked from tianweiy/CenterPoint
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdist_test.py
More file actions
211 lines (170 loc) · 5.77 KB
/
Copy pathdist_test.py
File metadata and controls
211 lines (170 loc) · 5.77 KB
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
import argparse
import copy
import json
import os
import sys
try:
import apex
except:
print("No APEX!")
import numpy as np
import torch
import yaml
from det3d import torchie
from det3d.datasets import build_dataloader, build_dataset
from det3d.models import build_detector
from det3d.torchie import Config
from det3d.torchie.apis import (
batch_processor,
build_optimizer,
get_root_logger,
init_dist,
set_random_seed,
train_detector,
)
from det3d.torchie.trainer import get_dist_info, load_checkpoint
from det3d.torchie.trainer.utils import all_gather, synchronize
from torch.nn.parallel import DistributedDataParallel
import pickle
import time
def save_pred(pred, root):
with open(os.path.join(root, "prediction.pkl"), "wb") as f:
pickle.dump(pred, f)
def parse_args():
parser = argparse.ArgumentParser(description="Train a detector")
parser.add_argument("config", help="train config file path")
parser.add_argument("--work_dir", required=True, help="the dir to save logs and models")
parser.add_argument(
"--checkpoint", help="the dir to checkpoint which the model read from"
)
parser.add_argument(
"--txt_result",
type=bool,
default=False,
help="whether to save results to standard KITTI format of txt type",
)
parser.add_argument(
"--gpus",
type=int,
default=1,
help="number of gpus to use " "(only applicable to non-distributed training)",
)
parser.add_argument(
"--launcher",
choices=["none", "pytorch", "slurm", "mpi"],
default="none",
help="job launcher",
)
parser.add_argument("--speed_test", action="store_true")
parser.add_argument("--local_rank", type=int, default=0)
parser.add_argument("--testset", action="store_true")
args = parser.parse_args()
if "LOCAL_RANK" not in os.environ:
os.environ["LOCAL_RANK"] = str(args.local_rank)
return args
def main():
# torch.manual_seed(0)
# torch.backends.cudnn.deterministic = True
# torch.backends.cudnn.benchmark = False
# np.random.seed(0)
args = parse_args()
cfg = Config.fromfile(args.config)
cfg.local_rank = args.local_rank
# update configs according to CLI args
if args.work_dir is not None:
cfg.work_dir = args.work_dir
distributed = False
if "WORLD_SIZE" in os.environ:
distributed = int(os.environ["WORLD_SIZE"]) > 1
if distributed:
torch.cuda.set_device(args.local_rank)
torch.distributed.init_process_group(backend="nccl", init_method="env://")
cfg.gpus = torch.distributed.get_world_size()
else:
cfg.gpus = args.gpus
# init logger before other steps
logger = get_root_logger(cfg.log_level)
logger.info("Distributed testing: {}".format(distributed))
logger.info(f"torch.backends.cudnn.benchmark: {torch.backends.cudnn.benchmark}")
model = build_detector(cfg.model, train_cfg=None, test_cfg=cfg.test_cfg)
if args.testset:
print("Use Test Set")
dataset = build_dataset(cfg.data.test)
else:
print("Use Val Set")
dataset = build_dataset(cfg.data.val)
data_loader = build_dataloader(
dataset,
batch_size=cfg.data.samples_per_gpu if not args.speed_test else 1,
workers_per_gpu=cfg.data.workers_per_gpu,
dist=distributed,
shuffle=False,
)
checkpoint = load_checkpoint(model, args.checkpoint, map_location="cpu")
# put model on gpus
if distributed:
model = apex.parallel.convert_syncbn_model(model)
model = DistributedDataParallel(
model.cuda(cfg.local_rank),
device_ids=[cfg.local_rank],
output_device=cfg.local_rank,
# broadcast_buffers=False,
find_unused_parameters=True,
)
else:
# model = fuse_bn_recursively(model)
model = model.cuda()
model.eval()
mode = "val"
logger.info(f"work dir: {args.work_dir}")
if cfg.local_rank == 0:
prog_bar = torchie.ProgressBar(len(data_loader.dataset) // cfg.gpus)
detections = {}
cpu_device = torch.device("cpu")
start = time.time()
start = int(len(dataset) / 3)
end = int(len(dataset) * 2 /3)
time_start = 0
time_end = 0
for i, data_batch in enumerate(data_loader):
if i == start:
torch.cuda.synchronize()
time_start = time.time()
if i == end:
torch.cuda.synchronize()
time_end = time.time()
with torch.no_grad():
outputs = batch_processor(
model, data_batch, train_mode=False, local_rank=args.local_rank,
)
for output in outputs:
token = output["metadata"]["token"]
for k, v in output.items():
if k not in [
"metadata",
]:
output[k] = v.to(cpu_device)
detections.update(
{token: output,}
)
if args.local_rank == 0:
prog_bar.update()
synchronize()
all_predictions = all_gather(detections)
print("\n Total time per frame: ", (time_end - time_start) / (end - start))
if args.local_rank != 0:
return
predictions = {}
for p in all_predictions:
predictions.update(p)
if not os.path.exists(args.work_dir):
os.makedirs(args.work_dir)
save_pred(predictions, args.work_dir)
result_dict, _ = dataset.evaluation(copy.deepcopy(predictions), output_dir=args.work_dir, testset=args.testset)
if result_dict is not None:
for k, v in result_dict["results"].items():
print(f"Evaluation {k}: {v}")
if args.txt_result:
assert False, "No longer support kitti"
if __name__ == "__main__":
main()