forked from vincentfung13/MINE
-
Notifications
You must be signed in to change notification settings - Fork 0
/
train.py
159 lines (129 loc) · 5.98 KB
/
train.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
import os
import sys
import argparse
import yaml
import json
import shutil
import numpy as np
import torch
from torch.utils.data import DataLoader
import torch.distributed as dist
from torch.utils.tensorboard import SummaryWriter
from synthesis_task import SynthesisTask
from utils import run_shell_cmd
parser = argparse.ArgumentParser(description="Training")
parser.add_argument("--config_path", default="./params.yaml", type=str)
parser.add_argument("--workspace", type=str, required=True)
parser.add_argument("--version", type=str, required=True)
parser.add_argument("--extra_config", type=str, default="{}", required=False)
parser.add_argument("--local_rank", default=0, type=int,
help="node rank for distributed training")
args = parser.parse_args()
local_rank = int(args.local_rank)
# Load config yaml file and pre-process params
default_config_path = os.path.join(os.path.dirname(args.config_path), "params_default.yaml")
with open(default_config_path, "r") as f:
config = yaml.safe_load(f)
extra_config = json.loads(args.extra_config)
with open(args.config_path, "r") as f:
dataset_specific_config = yaml.safe_load(f)
for k in dataset_specific_config.keys():
assert k in config, k
config.update(dataset_specific_config)
for k in extra_config.keys():
assert k in config, k
config.update(extra_config)
# Dump tmp config file
tmp_config_path = os.path.join(os.path.dirname(args.config_path), "params_tmp.yaml")
if local_rank == 0:
with open(tmp_config_path, "w") as f:
print("Dumping extra config file...")
yaml.dump(config, f)
# pre-process params
config["training.gpus"] = [int(s) for s in str(config["training.gpus"]).split(",")]
config["lr.decay_steps"] = [int(s) for s in str(config["lr.decay_steps"]).split(",")]
config["current_epoch"] = 0
# Config gpu
gpus = config["training.gpus"][local_rank]
os.environ["CUDA_VISIBLE_DEVICES"] = str(gpus)
# dist env
dist.init_process_group(backend="nccl")
world_size = dist.get_world_size()
global_rank = dist.get_rank()
config["global_rank"] = global_rank
def get_dataset(config, logger):
# Init data loader
assert config["data.name"] in ["llff", "realestate10k", "flowers", "kitti_raw", "dtu"]
if config["data.name"] == "llff":
from input_pipelines.llff.nerf_dataset import NeRFDataset
train_dataset = NeRFDataset(config,
logger,
root=config["data.training_set_path"],
is_validation=False,
img_size=(config["data.img_w"], config["data.img_h"]),
supervision_count=config["data.num_tgt_views"],
visible_points_count=config["data.visible_point_count"],
img_pre_downsample_ratio=config["data.img_pre_downsample_ratio"])
train_sampler = torch.utils.data.distributed.DistributedSampler(train_dataset)
train_data_loader = DataLoader(train_dataset, batch_size=config["data.per_gpu_batch_size"],
drop_last=True, num_workers=0,
sampler=train_sampler,
collate_fn=train_dataset.collate_fn)
val_dataset = NeRFDataset(config,
logger,
root=config["data.training_set_path"],
is_validation=True,
img_size=(config["data.img_w"], config["data.img_h"]),
supervision_count=config["data.num_tgt_views"],
visible_points_count=config["data.visible_point_count"],
img_pre_downsample_ratio=config["data.img_pre_downsample_ratio"])
val_data_loader = DataLoader(val_dataset, batch_size=config["data.per_gpu_batch_size"],
shuffle=False, drop_last=False, num_workers=0,
collate_fn=val_dataset.collate_fn)
else:
raise NotImplementedError
return train_data_loader, val_data_loader
def train():
config["local_rank"] = local_rank
config["world_size"] = world_size
# Enable cudnn benchmark for speed optimization
torch.backends.cudnn.benchmark = True
torch.backends.cudnn.enabled = True
# Config logging and tb writer
logger = None
if global_rank == 0:
import logging
# logging to file and stdout
config["log_file"] = "./training.log" \
if args.workspace.startswith("hdfs") \
else os.path.join(args.workspace, args.version, "training.log")
logger = logging.getLogger("mine")
file_handler = logging.FileHandler(config["log_file"])
stream_handler = logging.StreamHandler(sys.stdout)
formatter = logging.Formatter("[%(asctime)s %(filename)s] %(message)s")
file_handler.setFormatter(formatter)
stream_handler.setFormatter(formatter)
logger.handlers = [file_handler, stream_handler]
logger.setLevel(logging.INFO)
logger.propagate = False
logger.info("Training config: {}".format(config))
# tensorboard summary_writer
config["tb_writer"] = SummaryWriter(log_dir=config["local_workspace"])
config["logger"] = logger
# Init data loader
train_data_loader, val_data_loader = get_dataset(config, logger)
synthesis_task = SynthesisTask(config=config, logger=logger)
synthesis_task.train(train_data_loader, val_data_loader)
def main():
if config["global_rank"] == 0:
# Create sub working dir
workspace = os.path.join(args.workspace, args.version)
if not os.path.exists(workspace):
os.mkdir(workspace)
config["local_workspace"] = workspace
shutil.copy(tmp_config_path, os.path.join(workspace, "params.yaml"))
dist.barrier()
# Start training
train()
if __name__ == "__main__":
main()