-
Notifications
You must be signed in to change notification settings - Fork 43
/
Copy pathtrain.py
204 lines (174 loc) · 7.08 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
#!/usr/bin/env python
from data_iterator import *
from state import *
from session_encdec import *
from utils import *
import time
import traceback
import os.path
import sys
import argparse
import cPickle
import logging
import search
import pprint
import numpy
import collections
import signal
class Unbuffered:
def __init__(self, stream):
self.stream = stream
def write(self, data):
self.stream.write(data)
self.stream.flush()
def __getattr__(self, attr):
return getattr(self.stream, attr)
sys.stdout = Unbuffered(sys.stdout)
logger = logging.getLogger(__name__)
### Unique RUN_ID for this execution
RUN_ID = str(time.time())
### Additional measures can be set here
measures = ["train", "valid"]
def init_timings():
timings = {}
for m in measures:
timings[m] = []
return timings
def save(model, timings):
print "Saving the model..."
# ignore keyboard interrupt while saving
start = time.time()
s = signal.signal(signal.SIGINT, signal.SIG_IGN)
model.save(model.state['save_dir'] + '/' + model.state['run_id'] + "_" + model.state['prefix'] + '_model.npz')
cPickle.dump(model.state, open(model.state['save_dir'] + '/' + model.state['run_id'] + "_" + model.state['prefix'] + '_state.pkl', 'w'))
numpy.savez(model.state['save_dir'] + '/' + model.state['run_id'] + "_" + model.state['prefix'] + '_timing.npz', **timings)
signal.signal(signal.SIGINT, s)
print "Model saved, took {}".format(time.time() - start)
def load(model, filename):
print "Loading the model..."
# ignore keyboard interrupt while saving
start = time.time()
s = signal.signal(signal.SIGINT, signal.SIG_IGN)
model.load(filename)
signal.signal(signal.SIGINT, s)
print "Model loaded, took {}".format(time.time() - start)
def main(args):
logging.basicConfig(
level = logging.INFO,
format = "%(asctime)s: %(name)s: %(levelname)s: %(message)s")
state = eval(args.prototype)()
timings = init_timings()
if args.resume != "":
logger.debug("Resuming %s" % args.resume)
state_file = args.resume + '_state.pkl'
timings_file = args.resume + '_timing.npz'
if os.path.isfile(state_file) and os.path.isfile(timings_file):
logger.debug("Loading previous state")
state = cPickle.load(open(state_file, 'r'))
timings = dict(numpy.load(open(timings_file, 'r')))
for x, y in timings.items():
timings[x] = list(y)
else:
raise Exception("Cannot resume, cannot find files!")
logger.info("State:\n{}".format(pprint.pformat(state)))
logger.info("Timings:\n{}".format(pprint.pformat(timings)))
model = SessionEncoderDecoder(state)
rng = model.rng
if args.resume != "":
filename = args.resume + '_model.npz'
if os.path.isfile(filename):
logger.info("Loading previous model")
load(model, filename)
else:
raise Exception("Cannot resume, cannot find model file!")
else:
# assign new run_id key
model.state['run_id'] = RUN_ID
logger.info("Compile trainer")
train_batch = model.build_train_function()
eval_batch = model.build_eval_function()
random_sampler = search.RandomSampler(model)
logger.info("Load data")
train_data, valid_data = get_batch_iterator(rng, state)
train_data.start()
# Start looping through the dataset
step = 0
patience = state['patience']
start_time = time.time()
train_cost = 0
train_done = 0
ex_done = 0
while step < state['loop_iters'] and patience >= 0:
# Sample stuff
if step % 200 == 0:
for param in model.params:
print "%s = %.4f" % (param.name,
numpy.sum(param.get_value() ** 2) ** 0.5)
samples, costs = random_sampler.sample([[]], n_samples=1, n_turns=3)
print "Sampled : {}".format(samples[0])
# Training phase
batch = train_data.next()
# Train finished
if not batch:
# Restart training
logger.debug("Got None...")
break
c = train_batch(
batch['x'], batch['y'], batch['max_length'], batch['x_mask'])
if numpy.isinf(c) or numpy.isnan(c):
logger.warn("Got NaN cost .. skipping")
continue
train_cost += c
train_done += batch['num_preds']
this_time = time.time()
if step % state['train_freq'] == 0:
elapsed = this_time - start_time
h, m, s = ConvertTimedelta(this_time - start_time)
print ".. %.2d:%.2d:%.2d %4d mb # %d bs %d maxl %d acc_cost = %.4f" % (h, m, s,\
state['time_stop'] - (time.time() - start_time)/60.,\
step, \
batch['x'].shape[1], \
batch['max_length'], \
float(train_cost/train_done))
if valid_data is not None and\
step % state['valid_freq'] == 0 and step > 1:
valid_data.start()
valid_cost = 0
valid_done = 0
logger.debug("[VALIDATION START]")
while True:
batch = valid_data.next()
# Train finished
if not batch:
break
if numpy.isinf(c) or numpy.isnan(c):
continue
c = eval_batch(
batch['x'], batch['y'], batch['max_length'], batch['x_mask'])
valid_cost += c
valid_done += batch['num_preds']
logger.debug("[VALIDATION END]")
valid_cost /= valid_done
if len(timings["valid"]) == 0 or valid_cost < numpy.min(numpy.array(timings["valid"])):
patience = state['patience']
# Saving model if decrease in validation cost
save(model, timings)
elif valid_cost >= timings["valid"][-1] * state['cost_threshold']:
patience -= 1
print "** validation error = %.4f, patience = %d" % (float(valid_cost), patience)
timings["train"].append(train_cost/train_done)
timings["valid"].append(valid_cost)
# Reset train cost and train done
train_cost = 0
train_done = 0
step += 1
logger.debug("All done, exiting...")
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument("--resume", type=str, default="", help="Resume training from that state")
parser.add_argument("--prototype", type=str, help="Use the prototype", default='prototype_state')
args = parser.parse_args()
return args
if __name__ == "__main__":
args = parse_args()
main(args)