-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathupstream.py
180 lines (171 loc) · 7.04 KB
/
upstream.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
import os
import argparse
import torch
import numpy as np
import random
import src.config
import src.datasets
import src.models
import pytorch_lightning as pl
import wandb
from datetime import datetime
from pytorch_lightning.loggers import WandbLogger
from pytorch_lightning.callbacks import ModelCheckpoint, EarlyStopping
def upstream(config, ds_path=None):
"""Starts upstream training with the given config and dataset path
The upstream task is defined in the given config
"""
# Set all seeds:
torch.manual_seed(config.SEED)
torch.cuda.manual_seed(config.SEED)
torch.cuda.manual_seed_all(config.SEED)
np.random.seed(config.SEED)
random.seed(config.SEED)
torch.backends.cudnn.benchmark = False
torch.backends.cudnn.deterministic = True
ds_path = config.TRAIN_DATA if ds_path is None else ds_path
# Iterate over all model configs if given
for args in src.utils.grid_search(config.ALGORITHM_ARGS):
for ds_args in src.utils.grid_search(config.DATASET_ARGS):
print(f'Dataset arguments: {ds_args}', flush=True)
######### Train with given args ##########
print(f'Evaluating arguments: {args}', flush=True)
# Create the datasets
valid_dataset = src.datasets.get_dataset(
dataset_name=config.DATASET,
dataset_args=ds_args,
root_dir=ds_path,
config_path=config.CONFIG_PATH,
test_mode=False,
valid_mode=True,
skip_files=[]
)
test_dataset = src.datasets.get_dataset(
dataset_name=config.DATASET,
dataset_args=ds_args,
root_dir=ds_path,
config_path=config.CONFIG_PATH,
test_mode=True, valid_mode=False,
skip_files=valid_dataset.used_files
)
skip_files = valid_dataset.used_files+test_dataset.used_files
train_dataset = src.datasets.get_dataset(
dataset_name=config.DATASET,
dataset_args=ds_args,
root_dir=ds_path,
config_path=config.CONFIG_PATH,
test_mode=False, valid_mode=False,
skip_files=skip_files
)
# Create the dataloaders
collate_fn = train_dataset.collate_fn if hasattr(train_dataset, 'collate_fn') else None
valid_dl = torch.utils.data.DataLoader(
dataset=valid_dataset,
batch_size=args['batch_size'],
shuffle=False,
num_workers=config.NUM_WORKERS,
collate_fn=collate_fn
)
train_dl = torch.utils.data.DataLoader(
dataset=train_dataset,
batch_size=args['batch_size'],
shuffle=True,
num_workers=config.NUM_WORKERS,
collate_fn=collate_fn
)
test_dl = torch.utils.data.DataLoader(
dataset=test_dataset,
batch_size=args['batch_size'],
shuffle=False,
num_workers=1,
collate_fn=collate_fn
)
_epochs = args['epochs']
total_step_count = len(train_dl)*_epochs
val_after_nth_step = len(train_dl)/4 # 4 times valid per epoch
val_check_interval = val_after_nth_step/len(train_dl)
if val_check_interval <= 1:
check_val_every_n_epoch = 1
else:
check_val_every_n_epoch = int(val_check_interval)
val_check_interval = 1.0
print(f'Epochs: {_epochs}, ',
f'Steps: {total_step_count}, ',
f'val_check_interval: {val_check_interval}',
f'check_val_every_n_epoch: {check_val_every_n_epoch}'
)
#######################
args.update({'input_dim': train_dataset.input_shape,
'output_dim': train_dataset.output_shapes,
'total_step_count': total_step_count,
'_epochs': _epochs})
print('Create the model')
model = src.models.get_model(
algorithm_name=config.ALGORITHM,
algorithm_args=args
)
loggers = []
if config.WANDB:
if type(ds_path)==list:
ds_name = 'Combined'
else:
ds_name = os.path.realpath(ds_path).split('/')[-1]
proj_name = 'harth_plus_dl_upstream_'+config.PROJ_NAME+'_'+ds_name
wandb_logger = WandbLogger(project=proj_name)
wandb_logger.watch(model, log_graph=False)
loggers.append(wandb_logger)
callbacks = []
cp_path = config.CONFIG_PATH
cp_name = str(
datetime.today()
).replace(':','_').replace(' ','__').replace('.','_')
checkpoint_callback = ModelCheckpoint(
monitor='val_loss' if len(valid_dataset)!=0 else None,
dirpath=cp_path,
filename=cp_name,
verbose=True
)
callbacks.append(checkpoint_callback)
early_stopping = EarlyStopping(
monitor='val_loss',
min_delta=0.0,
patience=total_step_count*0.10, # 10% of total steps
verbose=True
)
callbacks.append(early_stopping)
trainer = pl.Trainer(
gpus=config.NUM_GPUS,
logger=loggers,
callbacks=callbacks,
max_epochs=_epochs,
num_sanity_val_steps=1,
log_every_n_steps=1,
check_val_every_n_epoch=check_val_every_n_epoch,
val_check_interval=val_check_interval,
accelerator="gpu",
strategy='ddp'
)
trainer.fit(model, train_dl, valid_dl)
##### Final testing #####
if len(test_dataset) != 0:
model_cls = src.models.get_model_class(config.ALGORITHM)
best_model = model_cls.load_from_checkpoint(
os.path.join(cp_path,cp_name+'.ckpt')
)
best_model.eval() # eval mode
trainer.test(best_model, dataloaders=test_dl)
if config.WANDB: wandb.finish()
torch.cuda.empty_cache()
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Start Upstream training.')
parser.add_argument('-p', '--params_path', required=False, type=str,
help='params path with config.yml file',
default='/param/config.yml')
parser.add_argument('-d', '--dataset_path', required=False, type=str,
help='path to dataset.', default=None)
args = parser.parse_args()
config_path = args.params_path
# Read config
config = src.config.UpstreamConfig(config_path)
ds_path = args.dataset_path
upstream(config, ds_path)