-
Notifications
You must be signed in to change notification settings - Fork 13
/
dist_test.py
executable file
·186 lines (158 loc) · 5.48 KB
/
dist_test.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
import argparse
import json
import os
import sys
import gorilla
import numpy as np
import torch
import torch.nn as nn
import yaml
from det3d import __version__, 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 warnings
warnings.filterwarnings("ignore")
def parse_args():
parser = argparse.ArgumentParser(description="Train a detector")
parser.add_argument("config", help="train config file path")
parser.add_argument("--work_dir", 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("--local_rank", type=int, default=0)
parser.add_argument("--test", type=bool, default=0)
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)
num_params_str = gorilla.parameter_count_table(model, max_depth=2)
logger.info("Number of Parameters: \n %s \n" %
(num_params_str))
if args.test:
cfg.data.val.info_path = "/data/dataset/nuscenes_test/infos_test_10sweeps_repeat_withvelo.pkl"
cfg.data.val.ann_file = None
cfg.data.val.root_path = '/data/dataset/nuscenes_test'
dataset = build_dataset(cfg.data.val)
if args.test:
dataset.version = 'v1.0-test'
data_loader = build_dataloader(
dataset,
batch_size=cfg.data.samples_per_gpu,
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 = torch.nn.SyncBatchNorm.convert_sync_batchnorm(model)
model = DistributedDataParallel(
model.cuda(cfg.local_rank),
device_ids=[cfg.local_rank],
output_device=cfg.local_rank,
# broadcast_buffers=False,
find_unused_parameters=False,
)
else:
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")
for i, data_batch in enumerate(data_loader):
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)
if args.local_rank != 0:
return
predictions = {}
for p in all_predictions:
predictions.update(p)
try:
print(type(predictions), dataset.evaluation, args.work_dir, args.test)
result_dict, _ = dataset.evaluation(
predictions, output_dir=args.work_dir, testset=args.test)
except:
print(type(predictions), dataset.evaluation, args.work_dir)
result_dict, _ = dataset.evaluation(
predictions, output_dir=args.work_dir)
if not args.test:
for k, v in result_dict["results"].items():
print(f"Evaluation {k}: {v}")
if __name__ == "__main__":
main()