-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathmain.py
More file actions
348 lines (285 loc) · 12.5 KB
/
main.py
File metadata and controls
348 lines (285 loc) · 12.5 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
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
import logging
import os
import argparse
import sys
import json
import torch
from torch.utils.tensorboard import SummaryWriter
from bridgedepth.config import export_model_config
from bridgedepth.bridgedepth import BridgeDepth
from bridgedepth.dataloader import build_train_loader
from bridgedepth.loss import build_criterion
from bridgedepth.utils import misc
import bridgedepth.utils.dist_utils as comm
from bridgedepth.utils.logger import setup_logger
from bridgedepth.utils.launch import launch
from bridgedepth.utils.eval_disp import eval_disp
from bridgedepth.config import CfgNode
def get_args_parser():
parser = argparse.ArgumentParser(
f"""
Examples:
Run on single machine:
$ {sys.argv[0]} --num-gpus 8
Change some config options:
$ {sys.argv[0]} SOLVER.IMS_PER_BATCH 8
Run on multiple machines:
(machine 0)$ {sys.argv[0]} --machine-rank 0 --num-machines 2 --dist-url <URL> [--other-flags]
(machine 1)$ {sys.argv[1]} --machine-rank 1 --num-machines 2 --dist-url <URL> [--other-flags]
""",
formatter_class=argparse.RawDescriptionHelpFormatter,
)
parser.add_argument("--config-file", default="", metavar="FILE", help="path to config file")
parser.add_argument("--checkpoint-dir", default=None, type=str,
help='where to save the training log and models')
parser.add_argument("--eval-only", action='store_true')
parser.add_argument("--from-pretrained", default=None, help='path to the checkpoint file or model name when eval_only is True')
# distributed training
parser.add_argument("--num-gpus", type=int, default=1, help="number of gpus *per machine*")
parser.add_argument("--num-machines", type=int, default=1, help="total number of machines")
parser.add_argument(
"--machine-rank", type=int, default=0, help="the rank of this machine (unique per machine)"
)
# PyTorch still may leave orphan processes in multi-gpu training.
# Therefore we use a deterministic way to obtain port,
# so that users are aware of orphan processes by seeing the port occupied.
port = 2 ** 15 + 2 ** 14 + hash(os.getuid() if sys.platform != "win32" else 1) % 2 ** 14
parser.add_argument(
"--dist-url",
default="tcp://127.0.0.1:{}".format(port),
help="initialization URL for pytorch distributed backend. See "
"https://pytorch.org/docs/stable/distributed.html for details."
)
parser.add_argument(
"opts",
help="""
Modify config options at the end of the command. For Yacs configs, use
space-separated "PATH.KEY VALUE" pair.
""".strip(),
default=None,
nargs=argparse.REMAINDER
)
return parser
def build_optimizer(model, cfg):
base_lr = cfg.SOLVER.BASE_LR
backbone_weight_decay = cfg.SOLVER.BACKBONE_WEIGHT_DECAY
weight_decay_norm = cfg.SOLVER.WEIGHT_DECAY_NORM
norm_module_types = (
torch.nn.BatchNorm2d,
torch.nn.InstanceNorm2d,
torch.nn.LayerNorm,
)
params = []
params_norm = []
params_backbone = []
memo = set()
for module_name, module in model.named_modules():
for module_param_name, value in module.named_parameters(recurse=False):
if not value.requires_grad:
continue
# Avoid duplicating parameters
if value in memo:
continue
memo.add(value)
if f"{module_name}.{module_param_name}".startswith("stereo_encoder.backbone"):
params_backbone.append(value)
elif isinstance(module, norm_module_types) and weight_decay_norm is not None:
params_norm.append(value)
else:
params.append(value)
ret = []
if len(params) > 0:
ret.append({"params": params, "lr": base_lr})
if len(params_norm) > 0:
ret.append({"params": params_norm, "lr": base_lr, "weight_decay": weight_decay_norm})
if len(params_backbone) > 0:
ret.append({"params": params_backbone, "lr": base_lr, "weight_decay": backbone_weight_decay})
adamw_args = {
"params": ret,
"weight_decay": cfg.SOLVER.WEIGHT_DECAY
}
return torch.optim.AdamW(**adamw_args)
def _setup(cfg, args):
"""
Perform some basic common setups at the beginning of a job, including:
1. Set up the bridgedepth logger
2. Log basic information about environment, cmdline arguments, git commit, and config
3. Backup the config to the output directory
Args:
cfg (CfgNode): the full config to be used
args (argparse.NameSpace): the command line arguments to be logged
"""
checkpoint_dir = args.checkpoint_dir
if comm.is_main_process() and checkpoint_dir:
misc.check_path(checkpoint_dir)
rank = comm.get_rank()
logger = setup_logger(checkpoint_dir, distributed_rank=rank, name='bridgedepth')
logger.info("Rank of current process: {}. World size: {}".format(rank, comm.get_world_size()))
logger.info("Environment info:\n" + misc.collect_env_info())
logger.info("git:\n {}\n".format(misc.get_sha()))
logger.info("Command line arguments: " + str(args))
if comm.is_main_process() and checkpoint_dir:
path = os.path.join(checkpoint_dir, "config.yaml")
with open(path, 'w') as f:
f.write(cfg.dump())
logger.info("Full config saved to {}".format(path))
# make sure each worker has a different, yet deterministic seed if specified
misc.seed_all_rng(None if cfg.SEED < 0 else cfg.SEED + rank)
# cudnn benchmark has large overhead. It shouldn't be used considering the small size of
# typical validation set.
if not (hasattr(args, "eval_only") and args.eval_only):
torch.backends.cudnn.benchmark = cfg.CUDNN_BENCHMARK
def setup(args):
"""
Create config and perform basic setups.
"""
from bridgedepth.config import get_cfg
cfg = get_cfg()
if len(args.config_file) > 0:
cfg.merge_from_file(args.config_file)
cfg.merge_from_list(args.opts)
cfg.freeze()
_setup(cfg, args)
comm.setup_for_distributed(comm.is_main_process())
return cfg
def main(args):
# torch.backends.cudnn.benchmark = False
cfg = setup(args)
if args.eval_only:
model = BridgeDepth.from_pretrained(args.from_pretrained)
else:
model = BridgeDepth(cfg, mono_pretrained=True)
model = model.to(torch.device("cuda"))
if comm.get_world_size() > 1:
model = torch.nn.parallel.DistributedDataParallel(
model,
device_ids=[comm.get_local_rank()],
find_unused_parameters=True,
)
model_without_ddp = model.module
else:
model_without_ddp = model
# evaluate
if args.eval_only:
eval_disp(model, cfg)
return
num_params = sum(p.numel() for p in model_without_ddp.parameters())
logger = logging.getLogger("bridgedepth")
logger.info('Number of params:' + str(num_params))
logger.info(
"params:\n" + json.dumps({n: p.numel() for n, p in model_without_ddp.named_parameters() if p.requires_grad},
indent=2))
optimizer = build_optimizer(model_without_ddp, cfg)
criterion = build_criterion(cfg)
# resume checkpoints
start_epoch = 0
start_step = 0
resume = cfg.SOLVER.RESUME
strict_resume = cfg.SOLVER.STRICT_RESUME
no_resume_optimizer = cfg.SOLVER.NO_RESUME_OPTIMIZER
if resume:
logger.info('Load checkpoint: %s' % resume)
torch.serialization.add_safe_globals([CfgNode])
checkpoint = torch.load(resume, map_location='cpu')
weights = checkpoint['model'] if 'model' in checkpoint else checkpoint
model_without_ddp.load_state_dict(weights, strict=strict_resume)
if 'optimizer' in checkpoint and 'step' in checkpoint and 'epoch' in checkpoint and not no_resume_optimizer:
logger.info('Load optimizer')
optimizer.load_state_dict(checkpoint['optimizer'])
start_epoch = checkpoint['epoch']
start_step = checkpoint['step']
# training dataset
train_loader, train_sampler = build_train_loader(cfg)
# training scheduler
last_epoch = start_step if resume and start_step > 0 else -1
lr_scheduler = torch.optim.lr_scheduler.OneCycleLR(
optimizer, cfg.SOLVER.BASE_LR,
cfg.SOLVER.MAX_ITER + 100,
pct_start=0.05,
cycle_momentum=False,
anneal_strategy='cos',
last_epoch=last_epoch
)
if comm.is_main_process():
writer = SummaryWriter(args.checkpoint_dir)
total_steps = start_step
epoch = start_epoch
logger.info('Start training')
print_freq = 20
metric_logger = misc.MetricLogger(delimiter=" ")
metric_logger.add_meter('lr', misc.SmoothedValue(window_size=1, fmt='{value:.7f}'))
while total_steps < cfg.SOLVER.MAX_ITER:
model.train()
# manual change random seed for shuffling every epoch
if comm.get_world_size() > 1:
train_sampler.set_epoch(epoch)
if hasattr(train_loader.dataset, "set_epoch"):
train_loader.dataset.set_epoch(epoch)
header = 'Epoch: [{}]'.format(epoch)
for sample in metric_logger.log_every(train_loader, print_freq, header, logger=logger):
result_dict = model(sample)
loss_dict = criterion(result_dict, sample, log=True)
weight_dict = criterion.weight_dict
losses = sum(loss_dict[k] * weight_dict[k] for k in loss_dict.keys() if k in weight_dict)
# more efficient zero_grad
for param in model_without_ddp.parameters():
param.grad = None
losses.backward()
# Gradient clipping
torch.nn.utils.clip_grad_norm_(model.parameters(), cfg.SOLVER.GRAD_CLIP)
optimizer.step()
# for training status print
metric_logger.update(lr=lr_scheduler.get_last_lr()[0])
metric_logger.update(**{k: v for k, v in loss_dict.items() if not k.endswith('_aux')})
lr_scheduler.step()
if comm.is_main_process():
for k, v in loss_dict.items():
writer.add_scalar(f"train/{k}", v, total_steps)
total_steps += 1
if total_steps % cfg.SOLVER.CHECKPOINT_PERIOD == 0 or total_steps == cfg.SOLVER.MAX_ITER:
if comm.is_main_process():
checkpoint_path = os.path.join(args.checkpoint_dir, 'step_%06d.pth' % total_steps)
torch.save({
'model': model_without_ddp.state_dict(),
'model_config': export_model_config(cfg),
}, checkpoint_path)
if total_steps % cfg.SOLVER.LATEST_CHECKPOINT_PERIOD == 0:
checkpoint_path = os.path.join(args.checkpoint_dir, 'checkpoint_latest.pth')
if comm.is_main_process():
torch.save({
'model': model_without_ddp.state_dict(),
'model_config': export_model_config(cfg),
'optimizer': optimizer.state_dict(),
'step': total_steps,
'epoch': epoch,
}, checkpoint_path)
if cfg.TEST.EVAL_PERIOD > 0 and total_steps % cfg.TEST.EVAL_PERIOD == 0:
logger.info('Start validation')
result_dict = eval_disp(model, cfg)
if comm.is_main_process():
for k, v in result_dict.items():
if isinstance(v, dict):
for _k, _v in v.items():
if isinstance(_v, dict):
for __k, __v in _v.items():
writer.add_scalar(f"val/{k}.{_k}.{__k}", __v, total_steps)
else:
writer.add_scalar(f"val/{k}.{_k}", _v, total_steps)
else:
writer.add_scalar(f"val/{k}", v, total_steps)
model.train()
if total_steps >= cfg.SOLVER.MAX_ITER:
logger.info('Training done')
return
epoch += 1
if __name__ == '__main__':
args = get_args_parser().parse_args()
print("Command Line Args:", args)
launch(
main,
args.num_gpus,
num_machines=args.num_machines,
machine_rank=args.machine_rank,
dist_url=args.dist_url,
args=(args,)
)