-
Notifications
You must be signed in to change notification settings - Fork 23
/
eval.py
194 lines (167 loc) · 6.91 KB
/
eval.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
# try:
# from vis import save_occ
# except:
# print('Load Occupancy Visualization Tools Failed.')
import time, argparse, os.path as osp, os
import torch, numpy as np
import torch.distributed as dist
from mmengine import Config
from mmengine.runner import set_random_seed
from mmengine.logging import MMLogger
from mmseg.models import build_segmentor
import warnings
warnings.filterwarnings("ignore")
def pass_print(*args, **kwargs):
pass
def main(local_rank, args):
# global settings
set_random_seed(args.seed)
torch.backends.cudnn.deterministic = False
torch.backends.cudnn.benchmark = True
# load config
cfg = Config.fromfile(args.py_config)
cfg.work_dir = args.work_dir
# init DDP
if args.gpus > 1:
distributed = True
ip = os.environ.get("MASTER_ADDR", "127.0.0.1")
port = os.environ.get("MASTER_PORT", "20507")
hosts = int(os.environ.get("WORLD_SIZE", 1)) # number of nodes
rank = int(os.environ.get("RANK", 0)) # node id
gpus = torch.cuda.device_count() # gpus per node
print(f"tcp://{ip}:{port}")
dist.init_process_group(
backend="nccl", init_method=f"tcp://{ip}:{port}",
world_size=hosts * gpus, rank=rank * gpus + local_rank)
world_size = dist.get_world_size()
cfg.gpu_ids = range(world_size)
torch.cuda.set_device(local_rank)
if local_rank != 0:
import builtins
builtins.print = pass_print
else:
distributed = False
world_size = 1
writer = None
timestamp = time.strftime('%Y%m%d_%H%M%S', time.localtime())
log_file = osp.join(args.work_dir, f'{timestamp}.log')
logger = MMLogger('selfocc', log_file=log_file)
MMLogger._instance_dict['selfocc'] = logger
logger.info(f'Config:\n{cfg.pretty_text}')
# build model
import model
from dataset import get_dataloader
my_model = build_segmentor(cfg.model)
my_model.init_weights()
n_parameters = sum(p.numel() for p in my_model.parameters() if p.requires_grad)
logger.info(f'Number of params: {n_parameters}')
if distributed:
if cfg.get('syncBN', True):
my_model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(my_model)
logger.info('converted sync bn.')
find_unused_parameters = cfg.get('find_unused_parameters', False)
ddp_model_module = torch.nn.parallel.DistributedDataParallel
my_model = ddp_model_module(
my_model.cuda(),
device_ids=[torch.cuda.current_device()],
broadcast_buffers=False,
find_unused_parameters=find_unused_parameters)
raw_model = my_model.module
else:
my_model = my_model.cuda()
raw_model = my_model
logger.info('done ddp model')
train_dataset_loader, val_dataset_loader = get_dataloader(
cfg.train_dataset_config,
cfg.val_dataset_config,
cfg.train_loader,
cfg.val_loader,
dist=distributed,
val_only=True)
# resume and load
cfg.resume_from = ''
if osp.exists(osp.join(args.work_dir, 'latest.pth')):
cfg.resume_from = osp.join(args.work_dir, 'latest.pth')
if args.resume_from:
cfg.resume_from = args.resume_from
logger.info('resume from: ' + cfg.resume_from)
logger.info('work dir: ' + args.work_dir)
if cfg.resume_from and osp.exists(cfg.resume_from):
map_location = 'cpu'
ckpt = torch.load(cfg.resume_from, map_location=map_location)
raw_model.load_state_dict(ckpt.get("state_dict", ckpt), strict=True)
print(f'successfully resumed.')
elif cfg.load_from:
ckpt = torch.load(cfg.load_from, map_location='cpu')
if 'state_dict' in ckpt:
state_dict = ckpt['state_dict']
else:
state_dict = ckpt
try:
print(raw_model.load_state_dict(state_dict, strict=False))
except:
from misc.checkpoint_util import refine_load_from_sd
print(raw_model.load_state_dict(
refine_load_from_sd(state_dict), strict=False))
print_freq = cfg.print_freq
from misc.metric_util import MeanIoU
miou_metric = MeanIoU(
list(range(1, 17)),
17, #17,
['barrier', 'bicycle', 'bus', 'car', 'construction_vehicle',
'motorcycle', 'pedestrian', 'traffic_cone', 'trailer', 'truck',
'driveable_surface', 'other_flat', 'sidewalk', 'terrain', 'manmade',
'vegetation'],
True, 17, filter_minmax=False)
miou_metric.reset()
my_model.eval()
os.environ['eval'] = 'true'
with torch.no_grad():
for i_iter_val, data in enumerate(val_dataset_loader):
for k in list(data.keys()):
if isinstance(data[k], torch.Tensor):
data[k] = data[k].cuda()
input_imgs = data.pop('img')
result_dict = my_model(imgs=input_imgs, metas=data)
if 'final_occ' in result_dict:
for idx, pred in enumerate(result_dict['final_occ']):
pred_occ = pred
gt_occ = result_dict['sampled_label'][idx]
occ_mask = result_dict['occ_mask'][idx].flatten()
# if args.vis_occ:
# os.makedirs(os.path.join(args.work_dir, 'vis'), exist_ok=True)
# save_occ(
# os.path.join(args.work_dir, 'vis'),
# pred_occ.reshape(1, 200, 200, 16),
# f'val_{i_iter_val}_pred',
# True, 0)
# save_occ(
# os.path.join(args.work_dir, 'vis'),
# gt_occ.reshape(1, 200, 200, 16),
# f'val_{i_iter_val}_gt',
# True, 0)
miou_metric._after_step(pred_occ, gt_occ, occ_mask)
# breakpoint()
if i_iter_val % print_freq == 0 and local_rank == 0:
logger.info('[EVAL] Iter %5d'%(i_iter_val))
miou, iou2 = miou_metric._after_epoch()
logger.info(f'mIoU: {miou}, iou2: {iou2}')
miou_metric.reset()
if writer is not None:
writer.close()
if __name__ == '__main__':
# Training settings
parser = argparse.ArgumentParser(description='')
parser.add_argument('--py-config', default='config/tpv_lidarseg.py')
parser.add_argument('--work-dir', type=str, default='./out/tpv_lidarseg')
parser.add_argument('--resume-from', type=str, default='')
parser.add_argument('--seed', type=int, default=42)
parser.add_argument('--vis-occ', action='store_true', default=False)
args = parser.parse_args()
ngpus = torch.cuda.device_count()
args.gpus = ngpus
print(args)
if ngpus > 1:
torch.multiprocessing.spawn(main, args=(args,), nprocs=args.gpus)
else:
main(0, args)