-
Notifications
You must be signed in to change notification settings - Fork 0
/
continuous_sol_training.py
184 lines (143 loc) · 6.35 KB
/
continuous_sol_training.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
import torch
from torch.utils.data import DataLoader
from torch.autograd import Variable
import sol
from sol import sol_dataset
from sol.start_of_line_finder import StartOfLineFinder
from sol.alignment_loss import alignment_loss
from sol.sol_dataset import SolDataset
from sol.crop_transform import CropTransform
from lf.line_follower import LineFollower
from hw import cnn_lstm
from utils.dataset_wrapper import DatasetWrapper
from utils import safe_load, transformation_utils
import numpy as np
import cv2
import json
import sys
import os
import time
import random
import yaml
from utils.continuous_state import init_model
from utils.dataset_parse import load_file_list
def training_step(config):
train_config = config['training']
allowed_training_time = train_config['sol']['reset_interval']
init_training_time = time.time()
training_set_list = load_file_list(train_config['training_set'])
print("Len", len(training_set_list))
train_dataset = SolDataset(training_set_list,
rescale_range=train_config['sol']['training_rescale_range'],
transform=CropTransform(train_config['sol']['crop_params']))
train_dataloader = DataLoader(train_dataset,
batch_size=train_config['sol']['batch_size'],
shuffle=True, num_workers=0,
collate_fn=sol_dataset.collate)
batches_per_epoch = int(train_config['sol']['images_per_epoch']/train_config['sol']['batch_size'])
print("batches", batches_per_epoch)
train_dataloader = DatasetWrapper(train_dataloader, batches_per_epoch)
test_set_list = load_file_list(train_config['validation_set'])
test_dataset = SolDataset(test_set_list,
rescale_range=train_config['sol']['validation_rescale_range'],
random_subset_size=train_config['sol']['validation_subset_size'],
transform=None)
test_dataloader = DataLoader(test_dataset, batch_size=1, shuffle=False, num_workers=0, collate_fn=sol_dataset.collate)
print("Test", len(list(test_dataloader)))
alpha_alignment = train_config['sol']['alpha_alignment']
alpha_backprop = train_config['sol']['alpha_backprop']
sol, lf, hw = init_model(config, only_load='sol')
dtype = torch.cuda.FloatTensor
lowest_loss = np.inf
lowest_loss_i = 0
epoch = -1
while True:#This ends on a break based on the current itme
epoch += 1
print("Train Time:",(time.time() - init_training_time), "Allowed Time:", allowed_training_time)
sol.eval()
sum_loss = 0.0
steps = 0.0
start_time = time.time()
for step_i, x in enumerate(test_dataloader):
img = Variable(x['img'].type(dtype), requires_grad=False)
sol_gt = None
if x['sol_gt'] is not None:
sol_gt = Variable(x['sol_gt'].type(dtype), requires_grad=False)
predictions = sol(img)
predictions = transformation_utils.pt_xyrs_2_xyxy(predictions)
loss = alignment_loss(predictions, sol_gt, x['label_sizes'], alpha_alignment, alpha_backprop)
sum_loss += loss.data#[0]
steps += 1
if epoch == 0:
print("First Validation Step Complete")
print("Benchmark Validation CER:", sum_loss/steps)
lowest_loss = sum_loss/steps
sol, lf, hw = init_model(config, sol_dir='current', only_load='sol')
optimizer = torch.optim.Adam(sol.parameters(), lr=train_config['sol']['learning_rate'])
optim_path = os.path.join(train_config['snapshot']['current'], "sol_optim.pt")
if os.path.exists(optim_path):
print("Loading Optim Settings")
optimizer.load_state_dict(safe_load.torch_state(optim_path))
else:
print("Failed to load Optim Settings")
elif lowest_loss > sum_loss/steps:
lowest_loss = sum_loss/steps
print("Saving Best")
dirname = train_config['snapshot']['best_validation']
if not len(dirname) != 0 and os.path.exists(dirname):
os.makedirs(dirname)
save_path = os.path.join(dirname, "sol.pt")
torch.save(sol.state_dict(), save_path)
lowest_loss_i = epoch
print("Test Loss", sum_loss/steps, lowest_loss)
print("Time:", time.time() - start_time)
print("")
print("Epoch", epoch)
# print(allowed_training_time)
# print(time.time() - init_training_time)
if allowed_training_time < (time.time() - init_training_time):
print("---")
print("Out of time. Saving current state and exiting...")
dirname = train_config['snapshot']['current']
if not len(dirname) != 0 and os.path.exists(dirname):
os.makedirs(dirname)
save_path = os.path.join(dirname, "sol.pt")
torch.save(sol.state_dict(), save_path)
optim_path = os.path.join(dirname, "sol_optim.pt")
torch.save(optimizer.state_dict(), optim_path)
break
sol.train()
sum_loss = 0.0
steps = 0.0
start_time = time.time()
for step_i, x in enumerate(train_dataloader):
# print(x)
print(step_i)
img = Variable(x['img'].type(dtype), requires_grad=False)
sol_gt = None
if x['sol_gt'] is not None:
sol_gt = Variable(x['sol_gt'].type(dtype), requires_grad=False)
predictions = sol(img)
predictions = transformation_utils.pt_xyrs_2_xyxy(predictions)
loss = alignment_loss(predictions, sol_gt, x['label_sizes'], alpha_alignment, alpha_backprop)
optimizer.zero_grad()
loss.backward()
optimizer.step()
sum_loss += loss.item()#[0]
steps += 1
print("Train Loss", sum_loss/steps)
print("Real Epoch", train_dataloader.epoch)
print("Time:", time.time() - start_time)
# sys.exit()
if __name__ == "__main__":
config_path = "sample_config.yaml"
with open(config_path) as f:
config = yaml.safe_load(f)
cnt = 0
if True:
print("")
print("SOL Full Step", cnt)
print("")
cnt += 1
training_step(config)
# sys.exit()