-
Notifications
You must be signed in to change notification settings - Fork 14
/
pygrid.py
382 lines (299 loc) · 10.9 KB
/
pygrid.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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
import os
import logging
import shutil
import datetime
import sys
import csv
import queue
import threading
import concurrent.futures
import multiprocessing
#import multiprocessing.dummy as multiprocessing
import tensorflow.compat.v2 as tf
def init_mp(tf2=True):
if tf2:
multiprocessing.set_start_method('spawn')
def copy_source(file, output_dir):
with tf.io.gfile.GFile(os.path.join(output_dir, os.path.basename(file)), mode='wb') as f:
with tf.io.gfile.GFile(file, mode='rb') as f0:
shutil.copyfileobj(f0, f)
from logging import StreamHandler, getLevelName, Handler
class FileHandler(StreamHandler):
"""
A handler class which writes formatted logging records to disk files.
"""
def __init__(self, filename, mode='a', encoding=None, delay=False):
"""
Open the specified file and use it as the stream for logging.
"""
# Issue #27493: add support for Path objects to be passed in
# keep the absolute path, otherwise derived classes which use this
# may come a cropper when the current directory changes
self.baseFilename = os.path.abspath(filename)
self.mode = mode
self.encoding = encoding
self.delay = delay
if delay:
# We don't open the stream, but we still need to call the
# Handler constructor to set level, formatter, lock etc.
Handler.__init__(self)
self.stream = None
else:
StreamHandler.__init__(self, self._open())
with tf.io.gfile.GFile(self.baseFilename, 'w') as f:
f.write('Logging ........\n')
def close(self):
"""
Closes the stream.
"""
self.acquire()
try:
try:
if self.stream:
try:
self.flush()
finally:
stream = self.stream
self.stream = None
if hasattr(stream, "close"):
stream.close()
finally:
# Issue #19523: call unconditionally to
# prevent a handler leak when delay is set
StreamHandler.close(self)
finally:
self.release()
def _open(self):
"""
Open the current base file with the (original) mode and encoding.
Return the resulting stream.
"""
return tf.io.gfile.GFile(self.baseFilename, self.mode)
def emit(self, record):
"""
Emit a record.
If the stream was not opened because 'delay' was specified in the
constructor, open it before calling the superclass's emit.
"""
if self.stream is None:
self.stream = self._open()
StreamHandler.emit(self, record)
def __repr__(self):
level = getLevelName(self.level)
return '<%s %s (%s)>' % (self.__class__.__name__, self.baseFilename, level)
def setup_logging_file(name, f, console=True):
log_format = logging.Formatter("%(asctime)s : %(message)s")
logger = logging.getLogger(name)
logger.handlers = []
file_handler = FileHandler(f)
file_handler.setFormatter(log_format)
logger.addHandler(file_handler)
if console:
console_handler = logging.StreamHandler(sys.stdout)
console_handler.setFormatter(log_format)
logger.addHandler(console_handler)
logger.setLevel(logging.INFO)
return logger
def setup_logging(name, output_dir, console=True):
log_format = logging.Formatter("%(asctime)s : %(message)s")
logger = logging.getLogger(name)
logger.handlers = []
output_file = os.path.join(output_dir, 'output.log')
file_handler = FileHandler(output_file)
file_handler.setFormatter(log_format)
logger.addHandler(file_handler)
if console:
console_handler = logging.StreamHandler(sys.stdout)
console_handler.setFormatter(log_format)
logger.addHandler(console_handler)
logger.setLevel(logging.INFO)
return logger
def get_argv():
argv = sys.argv
for i in range(1, len(argv)):
if argv[i] == '--ckpt_load':
argv.pop(i)
argv.pop(i)
break
for i in range(1, len(argv)):
if argv[i].startswith('--ckpt_load='):
argv.pop(i)
break
for i in range(1, len(argv)):
if argv[i] == '--device':
argv.pop(i)
argv.pop(i)
break
for i in range(1, len(argv)):
if argv[i].startswith('--device='):
argv.pop(i)
break
return ''.join(argv[1:])
def get_output_filename(file):
file_name = get_exp_id(file)
if len(sys.argv) > 1:
file_name = file_name + get_argv()
return file_name
def get_output_dir(exp_id, rootdir):
t = datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S')
output_dir = os.path.join(rootdir, 'output/' + exp_id, t)
if len(sys.argv) > 1:
output_dir = output_dir + get_argv()
if not os.path.exists(output_dir):
os.makedirs(output_dir)
return output_dir
free_devices_lock = threading.Lock()
free_devices = queue.Queue()
def fill_queue(device_ids):
[free_devices.put_nowait(device_id) for device_id in device_ids]
def allocate_device():
try:
free_devices_lock.acquire()
return free_devices.get()
finally:
free_devices_lock.release()
def free_device(device):
try:
free_devices_lock.acquire()
return free_devices.put_nowait(device)
finally:
free_devices_lock.release()
job_file_lock = threading.Lock()
def update_job_status(job_id, job_status, read_opts, write_opts):
try:
job_file_lock.acquire()
opts = read_opts()
opt = next(opt for opt in opts if opt['job_id'] == job_id)
opt['status'] = job_status
write_opts(opts)
except Exception:
logging.exception('exception in update_job_status()')
finally:
job_file_lock.release()
def update_job_result_file(update_job_result, job_opt, job_stats, read_opts, write_opts):
try:
job_file_lock.acquire()
opts = read_opts()
target_opt = next(opt for opt in opts if opt['job_id'] == job_opt['job_id'])
update_job_result(target_opt, job_stats)
write_opts(opts)
finally:
job_file_lock.release()
run_job_lock = threading.Lock()
def run_job(logger, opt, output_dir, output_dir_ckpt, train):
device_id = allocate_device()
opt_override = {'device': device_id}
def merge(a, b):
d = {}
d.update(a)
d.update(b)
return d
# opt = {**opt, **opt_override}
opt = merge(opt, opt_override)
logger.info('new job: job_id={}, device_id={}'.format(opt['job_id'], opt['device']))
try:
logger.info("spawning process: job_id={}, device_id={}".format(opt['job_id'], opt['device']))
try:
output_dir_thread = os.path.join(output_dir, str(opt['job_id']))
os.makedirs(output_dir_thread, exist_ok=True)
output_dir_thread_ckpt = os.path.join(output_dir_ckpt, str(opt['job_id']))
os.makedirs(output_dir_thread_ckpt, exist_ok=True)
# logger_thread = setup_logging('job{}'.format(opt['job_id']), output_dir_thread, console=True)
run_job_lock.acquire()
manager = multiprocessing.Manager()
return_dict = manager.dict()
p = multiprocessing.Process(target=train, args=(opt, output_dir, output_dir_thread, output_dir_thread_ckpt, return_dict))
p.start()
# return_dict = {}
# train(opt, output_dir_thread, logger_thread, return_dict)
finally:
run_job_lock.release()
p.join()
logger.info('finished process: job_id={}, device_id={}'.format(opt['job_id'], opt['device']))
return return_dict['stats']
finally:
free_device(device_id)
def run_jobs(logger, exp_id, output_dir, output_dir_ckpt, workers, train_job, read_opts, write_opts, update_job_result):
opt_list = read_opts()
opt_open = [opt for opt in opt_list if opt['status'] == 'open']
logger.info('scheduling {} open of {} total jobs'.format(len(opt_open), len(opt_list)))
logger.info('starting thread pool with {} workers'.format(workers))
with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as executor:
def adjust_opt(opt):
opt_override = {'exp_id': '{}_{}'.format(exp_id, opt['job_id'])}
def merge(a, b):
d = {}
d.update(a)
d.update(b)
return d
# return {**opt, **opt_override}
return merge(opt, opt_override)
def do_run_job(opt):
update_job_status(opt['job_id'], 'running', read_opts, write_opts)
return run_job(logger, adjust_opt(opt), output_dir, output_dir_ckpt, train_job)
futures = {executor.submit(do_run_job, opt): opt for opt in opt_open}
# do_run_job(opt_open[0])
# futures = []
for future in concurrent.futures.as_completed(futures):
opt = futures[future]
try:
stats = future.result()
logger.info('finished job future: job_id={}'.format(opt['job_id']))
update_job_result_file(update_job_result, opt, stats, read_opts, write_opts)
update_job_status(opt['job_id'], 'finished', read_opts, write_opts)
except Exception:
logger.exception('exception in run_jobs()')
update_job_status(opt['job_id'], 'fail', read_opts, write_opts)
def is_int(value):
try:
int(value)
return True
except ValueError:
return False
def is_float(value):
try:
float(value)
return not is_int(value)
except ValueError:
return False
def is_bool(value):
return value.upper() in ['TRUE', 'FALSE']
def is_array(value):
return '[' in value
def cast_str(value):
if is_int(value):
return int(value)
if is_float(value):
return float(value)
if is_bool(value):
return value.upper() == 'TRUE'
if is_array(value):
return eval(value)
return value
def get_exp_id(file):
return os.path.splitext(os.path.basename(file))[0]
def overwrite_opt(opt, opt_override):
for (k, v) in opt_override.items():
setattr(opt, k, v)
return opt
def write_opts(opt_list, f):
writer = csv.writer(f(), delimiter=',')
header = [key for key in opt_list[0]]
writer.writerow(header)
for opt in opt_list:
writer.writerow([opt[k] for k in header])
def read_opts(f):
opt_list = []
reader = csv.reader(f(), delimiter=',')
header = next(reader)
for values in reader:
opt = {}
for i, field in enumerate(header):
opt[field] = cast_str(values[i])
opt_list += [opt]
return opt_list
def reset_job_status(opts_list):
for opt in opts_list:
if opt['status'] == 'running':
opt['status'] = 'open'
return opts_list