-
Notifications
You must be signed in to change notification settings - Fork 0
/
train.py
214 lines (181 loc) · 7.3 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
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
import argparse
import pathlib
from conf import default, general, paths
import os
from utils.ops import count_parameters
from utils.dataloader import TrainDataSet
import torch
import logging, sys
from torch.multiprocessing import Process, freeze_support
import importlib
from torch.utils.data import DataLoader, RandomSampler
from torch import nn
from utils.trainer import train_loop, val_loop, EarlyStop
import time
from torch.optim.lr_scheduler import ExponentialLR
from torch.utils.tensorboard import SummaryWriter
parser = argparse.ArgumentParser(
description='Train NUMBER_MODELS models based in the same parameters'
)
parser.add_argument( # Experiment number
'-e', '--experiment',
type = int,
default = 14,
help = 'The number of the experiment'
)
parser.add_argument( # referent year
'-y', '--year',
type = int,
default = 2019,
help = "Reference year to use in the training step. The deforestation considered: (year-1)-(year)"
)
parser.add_argument( # batch size
'-b', '--batch-size',
type = int,
default = default.BATCH_SIZE,
help = 'The number of samples of each batch'
)
parser.add_argument( # Number of models to be trained
'-n', '--number-models',
type = int,
default = default.N_MODELS,
help = 'The number models to be trained from the scratch'
)
parser.add_argument( # Experiment path
'-x', '--experiments-path',
type = pathlib.Path,
default = paths.EXPERIMENTS_PATH,
help = 'The patch to data generated by all experiments'
)
parser.add_argument( # Number of train samples per epoch
'-t', '--number-train-samples',
type = int,
default = default.N_TRAIN_SAMPLES_PER_EPOCH,
help = 'The number of samples of each train epoch'
)
parser.add_argument( # Number of validation samples per epoch
'-v', '--number-val-samples',
type = int,
default = default.N_VAL_SAMPLES_PER_EPOCH,
help = 'The number of samples of each validation epoch'
)
parser.add_argument( # Numbe of threads
'-r', '--threads',
type = int,
default = default.N_THREADS,
help = "Number of threads"
)
args = parser.parse_args()
exp_path = os.path.join(str(args.experiments_path), f'exp_{args.experiment}')
if not os.path.exists(exp_path):
os.mkdir(exp_path)
logs_path = os.path.join(exp_path, f'logs')
if not os.path.exists(logs_path):
os.mkdir(logs_path)
models_path = os.path.join(exp_path, f'models')
if not os.path.exists(models_path):
os.mkdir(models_path)
visual_path = os.path.join(exp_path, f'visual')
if not os.path.exists(visual_path):
os.mkdir(visual_path)
predicted_path = os.path.join(exp_path, f'predicted')
if not os.path.exists(predicted_path):
os.mkdir(predicted_path)
results_path = os.path.join(exp_path, f'results')
if not os.path.exists(results_path):
os.mkdir(results_path)
def run(model_idx):
outfile = os.path.join(logs_path, f'train_{args.experiment}_{model_idx}.txt')
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s:%(levelname)s:%(name)s:%(message)s',
filename=outfile,
filemode='w'
)
log = logging.getLogger('training')
device = "cuda" if torch.cuda.is_available() else "cpu"
model_m =importlib.import_module(f'conf.exp_{args.experiment}')
model = model_m.get_model(log)
log.info('Loading data...')
ds_train = TrainDataSet(ds_prefix = general.TRAIN_PREFIX, year = args.year, device = device)
ds_val = TrainDataSet(ds_prefix = general.VAL_PREFIX, year = args.year, device = device)
if args.number_train_samples > 0:
train_sampler = RandomSampler(ds_train, num_samples=args.number_train_samples)
else:
train_sampler = None
if args.number_val_samples > 0:
val_sampler = RandomSampler(ds_val, num_samples=args.number_val_samples)
else:
val_sampler = None
dataloader_train = DataLoader(ds_train, batch_size=args.batch_size, shuffle = (train_sampler is None), sampler=train_sampler, num_workers=1, persistent_workers =True )
dataloader_val = DataLoader(ds_val, batch_size=args.batch_size, sampler = val_sampler)
log.info('Data loaded.')
model.to(device)
log.info(f'Model trainable parameters: {count_parameters(model)}')
torch.set_num_threads(args.threads)
loss_fn = nn.CrossEntropyLoss(ignore_index=2, weight=torch.tensor(general.CLASSES_WEIGHTS).to(device))
optimizer = torch.optim.Adam(model.parameters(), lr=general.LEARNING_RATE)
model_path = os.path.join(models_path, f'model_{model_idx}.pth')
early_stop = EarlyStop(
train_patience=general.EARLY_STOP_PATIENCE,
path_to_save = model_path,
min_delta = general.EARLY_STOP_MIN_DELTA,
min_epochs = general.EARLY_STOP_MIN_EPOCHS
)
t0 = time.perf_counter()
log.info(f'Model: {model}')
log.info(f'Train batch size: {args.batch_size}')
log.info(f'Loss fn: {loss_fn}')
log.info(f'Classes Weights :{general.CLASSES_WEIGHTS}')
log.info(f'Optmizer :{optimizer}')
log.info(f'Train samples: {args.number_train_samples}')
log.info(f'Val samples: {args.number_val_samples}')
log.info(f'Paticence :{general.EARLY_STOP_PATIENCE}')
log.info(f'Early Stop Min Delta :{general.EARLY_STOP_MIN_DELTA}')
log.info(f'Early Stop Min Epochs :{general.EARLY_STOP_MIN_EPOCHS}')
log.info(f'Scheduler Gamma :{general.LEARNING_RATE_SCHEDULER_GAMMA}')
#log.info(f'LR Milestones :{general.LEARNING_RATE_SCHEDULER_MILESTONES}')
'''scheduler = MultiStepLR(
optimizer,
milestones = general.LEARNING_RATE_SCHEDULER_MILESTONES,
gamma=general.LEARNING_RATE_SCHEDULER_GAMMA,
verbose = True
)'''
scheduler = ExponentialLR(
optimizer,
gamma=general.LEARNING_RATE_SCHEDULER_GAMMA,
verbose = True
)
train_tb_logdir_path = os.path.join(logs_path, f'train_model_{model_idx}')
val_tb_logdir_path = os.path.join(logs_path, f'val_model_{model_idx}')
#if not os.path.exists(tb_logdir_path):
# os.mkdir(tb_logdir_path)
train_writer = SummaryWriter(log_dir=train_tb_logdir_path)
val_writer = SummaryWriter(log_dir=val_tb_logdir_path)
for t in range(general.MAX_EPOCHS):
epoch = t+1
print(f"-------------------------------\nEpoch {epoch}")
model.train()
loss, f1 = train_loop(dataloader_train, model, loss_fn, optimizer)
train_writer.add_scalar('Loss', loss, t)
train_writer.add_scalar('F1Score', f1, t)
#summary_writer.add_scalar('Loss/Train', loss)
#summary_writer.add_scalar('F1Score/Train', f1)
model.eval()
val_loss, val_f1 = val_loop(dataloader_val, model, loss_fn)
val_writer.add_scalar('Loss', val_loss, t)
val_writer.add_scalar('F1Score', val_f1, t)
#summary_writer.add_scalar('Loss/Validation', loss)
#summary_writer.add_scalar('F1Score/Validation', f1)
#val_sample_image(dataloader_val, model, visual_path, t)
if early_stop.testEpoch(model = model, val_value = val_loss):
break
scheduler.step()
t_time = (time.perf_counter() - t0)/60
log.info(f'Training time: {t_time} mins, for {t} epochs, Avg Training Time per epoch:{t_time/t}')
if __name__=="__main__":
freeze_support()
for model_idx in range(args.number_models):
p = Process(target=run, args=(model_idx,))
p.start()
p.join()