-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.py
430 lines (385 loc) · 16.6 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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
# Copyright (c) Chris Choy ([email protected]). All Rights Reserved.
#
# Please cite "4D Spatio-Temporal ConvNets: Minkowski Convolutional Neural
# Networks", CVPR'19 (https://arxiv.org/abs/1904.08755) if you use any part of
# the code.
# Change dataloader multiprocess start method to anything not fork
import torch.multiprocessing as mp
try:
mp.set_start_method('forkserver') # Reuse process created
except RuntimeError:
pass
import os
import sys
import json
import logging
from easydict import EasyDict as edict
import random
import numpy as np
# Torch packages
import torch
# Train deps
from config import get_config
import shutil
from lib.test import test
from lib.train import train
from lib.multitrain import train as train_mp
from lib.check_data import check_data
from lib.utils import load_state_with_same_shape, get_torch_device, count_parameters
from lib.dataset import initialize_data_loader, _init_fn
from lib.datasets import load_dataset
from lib.datasets.semantic_kitti import SemanticKITTI
from lib.datasets.Indoor3DSemSegLoader import S3DIS
from lib.datasets.nuscenes import Nuscenes
from lib.dataloader import InfSampler
import lib.transforms as t
from models import load_model
import MinkowskiEngine as ME # force loadding
def setup_seed(seed):
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
np.random.seed(seed)
random.seed(seed)
torch.backends.cudnn.deterministic = True
def main():
config = get_config()
ch = logging.StreamHandler(sys.stdout)
logging.getLogger().setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
file_handler = logging.FileHandler(os.path.join(config.log_dir, './model.log'))
file_handler.setLevel(logging.INFO)
file_handler.setFormatter(formatter)
logging.basicConfig(
format=os.uname()[1].split('.')[0] + ' %(asctime)s %(message)s',
datefmt='%m/%d %H:%M:%S',
handlers=[ch, file_handler])
if config.test_config:
# When using the test_config, reload and overwrite it, so should keep some configs
val_bs = config.val_batch_size
is_export = config.is_export
json_config = json.load(open(config.test_config, 'r'))
json_config['is_train'] = False
json_config['weights'] = config.weights
json_config['multiprocess'] = False
json_config['log_dir'] = config.log_dir
json_config['val_threads'] = config.val_threads
json_config['submit'] = config.submit
config = edict(json_config)
config.val_batch_size = val_bs
config.is_export = is_export
config.is_train = False
sys.path.append(config.log_dir)
# from local_models import load_model
else:
'''bakup files'''
if not os.path.exists(os.path.join(config.log_dir,'models')):
os.mkdir(os.path.join(config.log_dir,'models'))
for filename in os.listdir('./models'):
if ".py" in filename: # donnot cp the init file since it will raise import error
shutil.copy(os.path.join("./models", filename), os.path.join(config.log_dir,'models'))
elif 'modules' in filename:
# copy the moduls folder also
if os.path.exists(os.path.join(config.log_dir,'models/modules')):
shutil.rmtree(os.path.join(config.log_dir,'models/modules'))
shutil.copytree(os.path.join('./models',filename), os.path.join(config.log_dir,'models/modules'))
shutil.copy('./main.py', config.log_dir)
shutil.copy('./config.py', config.log_dir)
shutil.copy('./lib/train.py', config.log_dir)
shutil.copy('./lib/test.py', config.log_dir)
if config.resume == 'True':
new_iter_size = config.max_iter
new_bs = config.batch_size
config.resume = config.log_dir
json_config = json.load(open(config.resume + '/config.json', 'r'))
json_config['resume'] = config.resume
config = edict(json_config)
config.weights = os.path.join(config.log_dir, 'weights.pth') # use the pre-trained weights
logging.info('==== resuming from {}, Total {} ======'.format(config.max_iter, new_iter_size))
config.max_iter = new_iter_size
config.batch_size = new_bs
else:
config.resume = None
if config.is_cuda and not torch.cuda.is_available():
raise Exception("No GPU found")
gpu_list = range(config.num_gpu)
device = get_torch_device(config.is_cuda)
# torch.set_num_threads(config.threads)
# torch.manual_seed(config.seed)
# if config.is_cuda:
# torch.cuda.manual_seed(config.seed)
logging.info('===> Configurations')
dconfig = vars(config)
for k in dconfig:
logging.info(' {}: {}'.format(k, dconfig[k]))
DatasetClass = load_dataset(config.dataset)
logging.info('===> Initializing dataloader')
setup_seed(2021)
"""
---- Setting up train, val, test dataloaders ----
Supported datasets:
- ScannetSparseVoxelizationDataset
- ScannetDataset
- SemanticKITTI
"""
if config.is_train:
if config.dataset == 'ScannetSparseVoxelizationDataset':
train_data_loader = initialize_data_loader(
DatasetClass,
config,
phase=config.train_phase,
threads=config.threads,
augment_data=True,
elastic_distortion=config.train_elastic_distortion,
shuffle=True,
repeat=True,
batch_size=config.batch_size,
limit_numpoints=config.train_limit_numpoints)
val_data_loader = initialize_data_loader(
DatasetClass,
config,
threads=config.val_threads,
phase=config.val_phase,
augment_data=False,
elastic_distortion=config.test_elastic_distortion,
shuffle=False,
repeat=False,
batch_size=config.val_batch_size,
limit_numpoints=False)
elif config.dataset == "SemanticKITTI":
dataset = SemanticKITTI(root=config.semantic_kitti_path,
num_points = None,
voxel_size=config.voxel_size,
sample_stride=config.sample_stride,
submit=False)
collate_fn_factory = t.cfl_collate_fn_factory
train_data_loader = torch.utils.data.DataLoader(
dataset['train'],
batch_size=config.batch_size,
sampler=InfSampler(dataset['train'], shuffle=True), # shuffle=true, repeat=true
num_workers=config.threads,
pin_memory=True,
collate_fn=collate_fn_factory(config.train_limit_numpoints)
)
val_data_loader = torch.utils.data.DataLoader( # shuffle=false, repeat=false
dataset['test'],
batch_size=config.batch_size,
num_workers=config.val_threads,
pin_memory=True,
collate_fn=t.cfl_collate_fn_factory(False)
)
elif config.dataset == "S3DIS":
trainset = S3DIS(
config,
train=True,
)
valset = S3DIS(
config,
train=False,
)
train_data_loader = torch.utils.data.DataLoader(
trainset,
batch_size=config.batch_size,
sampler=InfSampler(trainset, shuffle=True), # shuffle=true, repeat=true
num_workers=config.threads,
pin_memory=True,
collate_fn=t.cfl_collate_fn_factory(config.train_limit_numpoints)
)
val_data_loader = torch.utils.data.DataLoader( # shuffle=false, repeat=false
valset,
batch_size=config.batch_size,
num_workers=config.val_threads,
pin_memory=True,
collate_fn=t.cfl_collate_fn_factory(False)
)
elif config.dataset == 'Nuscenes':
config.xyz_input=False
trainset = Nuscenes(
config,
train=True,
)
valset = Nuscenes(
config,
train=False,
)
train_data_loader = torch.utils.data.DataLoader(
trainset,
batch_size=config.batch_size,
sampler=InfSampler(trainset, shuffle=True), # shuffle=true, repeat=true
num_workers=config.threads,
pin_memory=True,
collate_fn=t.cfl_collate_fn_factory(False)
)
val_data_loader = torch.utils.data.DataLoader( # shuffle=false, repeat=false
valset,
batch_size=config.batch_size,
num_workers=config.val_threads,
pin_memory=True,
collate_fn=t.cfl_collate_fn_factory(False)
)
else:
print('Dataset {} not supported').format(config.dataset)
raise NotImplementedError
# Setting up num_in_channel and num_labels
if train_data_loader.dataset.NUM_IN_CHANNEL is not None:
num_in_channel = train_data_loader.dataset.NUM_IN_CHANNEL
else:
num_in_channel = 3
num_labels = train_data_loader.dataset.NUM_LABELS
else: # not config.is_train
val_DatasetClass = load_dataset('ScannetDatasetWholeScene_evaluation')
if config.dataset == 'ScannetSparseVoxelizationDataset':
if config.is_export: # when export, we need to export the train results too
train_data_loader = initialize_data_loader(
DatasetClass,
config,
phase=config.train_phase,
threads=config.threads,
augment_data=True,
elastic_distortion=config.train_elastic_distortion, # DEBUG: not sure about this
shuffle=False,
repeat=False,
batch_size=config.batch_size,
limit_numpoints=config.train_limit_numpoints)
val_data_loader = initialize_data_loader(
DatasetClass,
config,
threads=config.val_threads,
phase=config.val_phase,
augment_data=False,
elastic_distortion=config.test_elastic_distortion,
shuffle=False,
repeat=False,
batch_size=config.val_batch_size,
limit_numpoints=False)
if val_data_loader.dataset.NUM_IN_CHANNEL is not None:
num_in_channel = val_data_loader.dataset.NUM_IN_CHANNEL
else:
num_in_channel = 3
num_labels = val_data_loader.dataset.NUM_LABELS
elif config.dataset == "SemanticKITTI":
dataset = SemanticKITTI(root=config.semantic_kitti_path,
num_points = None,
voxel_size=config.voxel_size,
submit=config.submit)
val_data_loader = torch.utils.data.DataLoader( # shuffle=false, repeat=false
dataset['test'],
batch_size=config.val_batch_size,
num_workers=config.val_threads,
pin_memory=True,
collate_fn=t.cfl_collate_fn_factory(False)
)
num_in_channel = 4
num_labels = 19
elif config.dataset == 'S3DIS':
config.xyz_input = False
trainset = S3DIS(
config,
train=True,
)
valset = S3DIS(
config,
train=False,
)
train_data_loader = torch.utils.data.DataLoader(
trainset,
batch_size=config.batch_size,
sampler=InfSampler(trainset, shuffle=True), # shuffle=true, repeat=true
num_workers=config.threads,
pin_memory=True,
collate_fn=t.cfl_collate_fn_factory(config.train_limit_numpoints)
)
val_data_loader = torch.utils.data.DataLoader( # shuffle=false, repeat=false
valset,
batch_size=config.batch_size,
num_workers=config.val_threads,
pin_memory=True,
collate_fn=t.cfl_collate_fn_factory(False)
)
num_in_channel = 9
num_labels = 13
elif config.dataset == 'Nuscenes':
config.xyz_input = False
trainset = Nuscenes(
config,
train=True,
)
valset = Nuscenes(
config,
train-False,
)
train_data_loader = torch.utils.data.DataLoader(
trainset,
batch_size=config.batch_size,
sampler=InfSampler(trainset, shuffle=True), # shuffle=true, repeat=true
num_workers=config.threads,
pin_memory=True,
collate_fn=t.cfl_collate_fn_factory(False)
)
val_data_loader = torch.utils.data.DataLoader( # shuffle=false, repeat=false
valset,
batch_size=config.batch_size,
num_workers=config.val_threads,
pin_memory=True,
collate_fn=t.cfl_collate_fn_factory(False)
)
num_in_channel = 5
num_labels = 16
else:
print('Dataset {} not supported').format(config.dataset)
raise NotImplementedError
logging.info('===> Building model')
NetClass = load_model(config.model)
model = NetClass(num_in_channel, num_labels, config)
logging.info('===> Number of trainable parameters: {}: {}M'.format(NetClass.__name__,count_parameters(model)/1e6))
logging.info(model)
# Set the number of threads
# ME.initialize_nthreads(12, D=3)
model = model.to(device)
if config.weights == 'modelzoo': # Load modelzoo weights if possible.
logging.info('===> Loading modelzoo weights')
model.preload_modelzoo()
# Load weights if specified by the parameter.
elif config.weights.lower() != 'none':
logging.info('===> Loading weights: ' + config.weights)
state = torch.load(config.weights)
# delete the keys containing the 'attn' since it raises size mismatch
d_ = {k:v for k,v in state['state_dict'].items() if '_map' not in k } # debug: sometiems model conmtains 'map_qk' which is not right for naming a module, since 'map' are always buffers
d = {}
for k in d_.keys():
if 'module.' in k:
d[k.replace('module.','')] = d_[k]
else:
d[k] = d_[k]
# del d_
if config.weights_for_inner_model:
model.model.load_state_dict(d)
else:
if config.lenient_weight_loading:
matched_weights = load_state_with_same_shape(model, state['state_dict'])
model_dict = model.state_dict()
model_dict.update(matched_weights)
model.load_state_dict(model_dict)
else:
model.load_state_dict(d, strict=True)
if config.is_debug:
check_data(model, train_data_loader, val_data_loader, config)
return None
elif config.is_train:
if config.multiprocess:
train_mp(NetClass, train_data_loader, val_data_loader, config)
else:
train(model, train_data_loader, val_data_loader, config)
elif config.is_export:
test(model, train_data_loader, config, save_pred=True, split='train')
test(model, val_data_loader, config, save_pred=True, split='val')
else:
assert config.multiprocess == False
# if test for submission, make a submit directory at current directory
submit_dir = os.path.join(os.getcwd(), 'submit', 'sequences')
if config.submit and not os.path.exists(submit_dir):
os.makedirs(submit_dir)
print("Made submission directory: " + submit_dir)
test(model, val_data_loader, config, submit_dir=submit_dir)
if __name__ == '__main__':
__spec__ = None
main()