-
Notifications
You must be signed in to change notification settings - Fork 34
/
train.py
172 lines (133 loc) · 5.86 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
160
161
162
163
164
165
166
167
168
169
170
171
172
import os
import time
import inspect
from termcolor import colored, cprint
from tqdm import tqdm
import torch.backends.cudnn as cudnn
# cudnn.benchmark = True
from options.train_options import TrainOptions
from datasets.dataloader import CreateDataLoader, get_data_generator
from models.base_model import create_model
from utils.distributed import (
get_rank,
synchronize,
reduce_loss_dict,
reduce_sum,
get_world_size,
)
import torch
from utils.visualizer import Visualizer
def train_main_worker(opt, model, train_dl, test_dl, test_dl_for_eval, visualizer, device):
if get_rank() == 0:
cprint('[*] Start training. name: %s' % opt.name, 'blue')
train_dg = get_data_generator(train_dl)
test_dg = get_data_generator(test_dl)
epoch = 0
# get n_epochs here
# opt.total_iters = 100000000
# pbar = tqdm(range(opt.total_iters))
pbar = tqdm(total=opt.total_iters)
iter_start_time = time.time()
for iter_i in range(opt.total_iters):
opt.iter_i = iter_i
iter_ip1 = iter_i + 1
if get_rank() == 0:
visualizer.reset()
data = next(train_dg)
model.set_input(data)
model.optimize_parameters(iter_i)
# nBatches_has_trained += opt.batch_size
if get_rank() == 0:
if iter_i % opt.print_freq == 0:
errors = model.get_current_errors()
t = (time.time() - iter_start_time) / opt.batch_size
epoch_steps = iter_i
visualizer.print_current_errors(iter_i, errors, t)
# if ((nBatches_has_trained % opt.display_freq == 0) or idx == 0):
# if (nBatches_has_trained % opt.display_freq == 0):
# display every n batches
if iter_i % opt.display_freq == 0:
if iter_i == 0 and opt.debug == "1":
pbar.update(1)
continue
# eval
model.inference(data)
visualizer.display_current_results(model.get_current_visuals(), iter_i, phase='train')
# model.set_input(next(test_dg))
test_data = next(test_dg)
model.inference(test_data)
visualizer.display_current_results(model.get_current_visuals(), iter_i, phase='test')
# torch.cuda.empty_cache()
if iter_ip1 % opt.save_latest_freq == 0:
cprint('saving the latest model (current_iter %d)' % (iter_i), 'blue')
latest_name = f'steps-latest'
model.save(latest_name, iter_ip1)
# save every 3000 steps (batches)
if iter_ip1 % opt.save_steps_freq == 0:
cprint('saving the model at iters %d' % iter_ip1, 'blue')
latest_name = f'steps-latest'
model.save(latest_name, iter_ip1)
cur_name = f'steps-{iter_ip1}'
model.save(cur_name, iter_ip1)
# eval every 3000 steps
if iter_ip1 % opt.save_steps_freq == 0:
metrics = model.eval_metrics(test_dl_for_eval, global_step=iter_ip1)
# visualizer.print_current_metrics(epoch, metrics, phase='test')
visualizer.print_current_metrics(iter_ip1, metrics, phase='test')
# print(metrics)
cprint(f'[*] End of steps %d \t Time Taken: %d sec \n%s' %
(
iter_ip1,
time.time() - iter_start_time,
os.path.abspath( os.path.join(opt.logs_dir, opt.name) )
), 'blue', attrs=['bold']
)
# adjust every 10000 steps
if iter_i % opt.save_steps_freq == 0:
model.update_learning_rate()
pbar.update(1)
if __name__ == "__main__":
# this will parse args, setup log_dirs, multi-gpus
opt = TrainOptions().parse_and_setup()
device = opt.device
rank = opt.rank
# CUDA_VISIBLE_DEVICES = int(os.environ["LOCAL_RANK"])
# import pdb; pdb.set_trace()
# get current time, print at terminal. easier to track exp
from datetime import datetime
opt.exp_time = datetime.now().strftime('%Y-%m-%dT%H-%M')
train_dl, test_dl, test_dl_for_eval = CreateDataLoader(opt)
train_ds, test_ds = train_dl.dataset, test_dl.dataset
dataset_size = len(train_ds)
if opt.dataset_mode == 'shapenet_lang':
cprint('[*] # training text snippets = %d' % len(train_ds), 'yellow')
cprint('[*] # testing text snippets = %d' % len(test_ds), 'yellow')
else:
cprint('[*] # training images = %d' % len(train_ds), 'yellow')
cprint('[*] # testing images = %d' % len(test_ds), 'yellow')
# main loop
model = create_model(opt)
cprint(f'[*] "{opt.model}" initialized.', 'cyan')
# visualizer
visualizer = Visualizer(opt)
if get_rank() == 0:
visualizer.setup_io()
# save model and dataset files
if get_rank() == 0:
expr_dir = '%s/%s' % (opt.logs_dir, opt.name)
model_f = inspect.getfile(model.__class__)
dset_f = inspect.getfile(train_ds.__class__)
cprint(f'[*] saving model and dataset files: {model_f}, {dset_f}', 'blue')
modelf_out = os.path.join(expr_dir, os.path.basename(model_f))
dsetf_out = os.path.join(expr_dir, os.path.basename(dset_f))
os.system(f'cp {model_f} {modelf_out}')
os.system(f'cp {dset_f} {dsetf_out}')
if opt.vq_cfg is not None:
vq_cfg = opt.vq_cfg
cfg_out = os.path.join(expr_dir, os.path.basename(vq_cfg))
os.system(f'cp {vq_cfg} {cfg_out}')
if opt.df_cfg is not None:
df_cfg = opt.df_cfg
cfg_out = os.path.join(expr_dir, os.path.basename(df_cfg))
os.system(f'cp {df_cfg} {cfg_out}')
train_main_worker(opt, model, train_dl, test_dl, test_dl_for_eval, visualizer, device)