forked from rwth-i6/returnn
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rnn.py
executable file
·539 lines (489 loc) · 22.6 KB
/
rnn.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
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
#!/usr/bin/env python2.7
"""
Main entry point
================
This is the main entry point. You can execute this file.
See :func:`rnn.initConfig` for some arguments, or just run ``./rnn.py --help``.
See :ref:`tech_overview` for a technical overview.
"""
from __future__ import print_function
__author__ = "Patrick Doetsch"
__copyright__ = "Copyright 2014"
__credits__ = ["Patrick Doetsch", "Paul Voigtlaender" ]
__license__ = "RWTHOCR"
__maintainer__ = "Patrick Doetsch"
__email__ = "doetsch@i6.informatik.rwth-aachen.de"
import os
import sys
import time
import numpy
from optparse import OptionParser
from Log import log
from Device import Device, TheanoFlags, getDevicesInitArgs
from Config import Config
from Engine import Engine
from Dataset import Dataset, init_dataset, init_dataset_via_str
from HDFDataset import HDFDataset
from Debug import initIPythonKernel, initBetterExchook, initFaulthandler, initCudaNotInMainProcCheck
from Util import initThreadJoinHack, describe_crnn_version, describe_theano_version, \
describe_tensorflow_version, BackendEngine, get_tensorflow_version_tuple
try:
import Server
except ImportError:
Server = None
config = None; """ :type: Config """
engine = None; """ :type: TFEngine.Engine | Engine """
train_data = None; """ :type: Dataset """
dev_data = None; """ :type: Dataset """
eval_data = None; """ :type: Dataset """
quit = False
server = None; """:type: Server"""
def initConfig(configFilename=None, commandLineOptions=()):
"""
:type configFilename: str
:type commandLineOptions: list[str]
Initializes the global config.
"""
global config
config = Config()
if configFilename:
assert os.path.isfile(configFilename), "config file not found"
config.load_file(configFilename)
if commandLineOptions and commandLineOptions[0][:1] not in ["-", "+"]:
# Assume that this is a config filename.
config.load_file(commandLineOptions[0])
commandLineOptions = commandLineOptions[1:]
parser = OptionParser()
parser.add_option("-a", "--activation", dest = "activation", help = "[STRING/LIST] Activation functions: logistic, tanh, softsign, relu, identity, zero, one, maxout.")
parser.add_option("-b", "--batch_size", dest = "batch_size", help = "[INTEGER/TUPLE] Maximal number of frames per batch (optional: shift of batching window).")
parser.add_option("-c", "--chunking", dest = "chunking", help = "[INTEGER/TUPLE] Maximal number of frames per sequence (optional: shift of chunking window).")
parser.add_option("-d", "--description", dest = "description", help = "[STRING] Description of experiment.")
parser.add_option("-e", "--epoch", dest = "epoch", help = "[INTEGER] Starting epoch.")
parser.add_option("-E", "--eval", dest = "eval", help = "[STRING] eval file path")
parser.add_option("-f", "--gate_factors", dest = "gate_factors", help = "[none/local/global] Enables pooled (local) or separate (global) coefficients on gates.")
parser.add_option("-g", "--lreg", dest = "lreg", help = "[FLOAT] L1 or L2 regularization.")
parser.add_option("-i", "--save_interval", dest = "save_interval", help = "[INTEGER] Number of epochs until a new model will be saved.")
parser.add_option("-j", "--dropout", dest = "dropout", help = "[FLOAT] Dropout probability (0 to disable).")
#parser.add_option("-k", "--multiprocessing", dest = "multiprocessing", help = "[BOOLEAN] Enable multi threaded processing (required when using multiple devices).")
parser.add_option("-k", "--output_file", dest = "output_file", help = "[STRING] Path to target file for network output.")
parser.add_option("-l", "--log", dest = "log", help = "[STRING] Log file path.")
parser.add_option("-L", "--load", dest = "load", help = "[STRING] load model file path.")
parser.add_option("-m", "--momentum", dest = "momentum", help = "[FLOAT] Momentum term in gradient descent optimization.")
parser.add_option("-n", "--num_epochs", dest = "num_epochs", help = "[INTEGER] Number of epochs that should be trained.")
parser.add_option("-o", "--order", dest = "order", help = "[default/sorted/random] Ordering of sequences.")
parser.add_option("-p", "--loss", dest = "loss", help = "[loglik/sse/ctc] Objective function to be optimized.")
parser.add_option("-q", "--cache", dest = "cache", help = "[INTEGER] Cache size in bytes (supports notation for kilo (K), mega (M) and gigabtye (G)).")
parser.add_option("-r", "--learning_rate", dest = "learning_rate", help = "[FLOAT] Learning rate in gradient descent optimization.")
parser.add_option("-s", "--hidden_sizes", dest = "hidden_sizes", help = "[INTEGER/LIST] Number of units in hidden layers.")
parser.add_option("-t", "--truncate", dest = "truncate", help = "[INTEGER] Truncates sequence in BPTT routine after specified number of timesteps (-1 to disable).")
parser.add_option("-u", "--device", dest = "device", help = "[STRING/LIST] CPU and GPU devices that should be used (example: gpu0,cpu[1-6] or gpu,cpu*).")
parser.add_option("-v", "--verbose", dest = "log_verbosity", help = "[INTEGER] Verbosity level from 0 - 5.")
parser.add_option("-w", "--window", dest = "window", help = "[INTEGER] Width of sliding window over sequence.")
parser.add_option("-x", "--task", dest = "task", help = "[train/forward/analyze] Task of the current program call.")
parser.add_option("-y", "--hidden_type", dest = "hidden_type", help = "[VALUE/LIST] Hidden layer types: forward, recurrent, lstm.")
parser.add_option("-z", "--max_sequences", dest = "max_seqs", help = "[INTEGER] Maximal number of sequences per batch.")
parser.add_option("--config", dest="load_config", help="[STRING] load config")
(options, args) = parser.parse_args(list(commandLineOptions))
options = vars(options)
for opt in options.keys():
if options[opt] is not None:
if opt == "load_config":
config.load_file(options[opt])
else:
config.add_line(opt, options[opt])
assert len(args) % 2 == 0, "expect (++key, value) config tuples in remaining args: %r" % args
for i in range(0, len(args), 2):
key, value = args[i:i+2]
assert key[0:2] == "++", "expect key prefixed with '++' in (%r, %r)" % (key, value)
if value[:2] == "+-": value = value[1:] # otherwise we never could specify things like "++threshold -0.1"
config.add_line(key=key[2:], value=value)
# I really don't know where to put this otherwise:
if config.bool("EnableAutoNumpySharedMemPickling", False):
import TaskSystem
TaskSystem.SharedMemNumpyConfig["enabled"] = True
#Server default options
if config.value('task', 'train') == 'server':
config.set('num_inputs', 2)
config.set('num_outputs', 1)
#config.set('network', [{'out': {'loss': 'ce', 'class': 'softmax', 'target': 'classes'}}])
def initLog():
logs = config.list('log', [])
log_verbosity = config.int_list('log_verbosity', [])
log_format = config.list('log_format', [])
log.initialize(logs = logs, verbosity = log_verbosity, formatter = log_format)
def initConfigJsonNetwork():
# initialize postprocess config file
if config.has('initialize_from_json'):
json_file = config.value('initialize_from_json', '')
assert os.path.isfile(json_file), "json file not found: " + json_file
print("loading network topology from json:", json_file, file=log.v5)
config.network_topology_json = open(json_file).read().encode('utf8')
def initDevices():
"""
:rtype: list[Device]
"""
oldDeviceConfig = ",".join(config.list('device', ['default']))
if BackendEngine.is_tensorflow_selected():
if os.environ.get("TF_DEVICE"):
config.set("device", os.environ.get("TF_DEVICE"))
print("Devices: Use %s via TF_DEVICE instead of %s." %
(os.environ.get("TF_DEVICE"), oldDeviceConfig), file=log.v4)
if not BackendEngine.is_theano_selected():
return None
if config.value("task", "train") == "nop":
return []
if "device" in TheanoFlags:
# This is important because Theano likely already has initialized that device.
config.set("device", TheanoFlags["device"])
print("Devices: Use %s via THEANO_FLAGS instead of %s." % \
(TheanoFlags["device"], oldDeviceConfig), file=log.v4)
devArgs = getDevicesInitArgs(config)
assert len(devArgs) > 0
devices = [Device(**kwargs) for kwargs in devArgs]
for device in devices:
while not device.initialized:
time.sleep(0.25)
if devices[0].blocking:
print("Devices: Used in blocking / single proc mode.", file=log.v4)
else:
print("Devices: Used in multiprocessing mode.", file=log.v4)
return devices
def getCacheByteSizes():
"""
:rtype: (int,int,int)
:returns cache size in bytes for (train,dev,eval)
"""
import Util
cache_sizes_user = config.list('cache_size', ["%iG" % Util.defaultCacheSizeInGBytes()])
num_datasets = 1 + config.has('dev') + config.has('eval')
cache_factor = 1.0
if len(cache_sizes_user) == 1:
cache_sizes_user *= 3
cache_factor /= float(num_datasets)
elif len(cache_sizes_user) == 2:
cache_sizes_user.append('0')
assert len(cache_sizes_user) == 3, "invalid amount of cache sizes specified"
cache_sizes = []
for cache_size_user in cache_sizes_user:
cache_size = cache_factor * float(cache_size_user.replace('G', '').replace('M', '').replace('K', ''))
assert len(cache_size_user) - len(str(cache_size)) <= 1, "invalid cache size specified"
if cache_size_user.find('G') > 0:
cache_size *= 1024 * 1024 * 1024
elif cache_size_user.find('M') > 0:
cache_size *= 1024 * 1024
elif cache_size_user.find('K') > 0:
cache_size *= 1024
cache_size = int(cache_size) + 1 if int(cache_size) > 0 else 0
cache_sizes.append(cache_size)
return cache_sizes
def load_data(config, cache_byte_size, files_config_key, **kwargs):
"""
:param Config config:
:param int cache_byte_size:
:param str files_config_key: such as "train" or "dev"
:param kwargs: passed on to init_dataset() or init_dataset_via_str()
:rtype: (Dataset,int)
:returns the dataset, and the cache byte size left over if we cache the whole dataset.
"""
if not config.has(files_config_key):
return None, 0
kwargs = kwargs.copy()
kwargs.setdefault("name", files_config_key)
if config.is_typed(files_config_key) and isinstance(config.typed_value(files_config_key), dict):
config_opts = config.typed_value(files_config_key)
assert isinstance(config_opts, dict)
kwargs.update(config_opts)
if 'cache_byte_size' not in config_opts:
if kwargs.get('class', None) == 'HDFDataset':
kwargs["cache_byte_size"] = cache_byte_size
Dataset.kwargs_update_from_config(config, kwargs)
data = init_dataset(kwargs)
else:
config_str = config.value(files_config_key, "")
data = init_dataset_via_str(config_str, config=config, cache_byte_size=cache_byte_size, **kwargs)
cache_leftover = 0
if isinstance(data, HDFDataset):
cache_leftover = data.definite_cache_leftover
return data, cache_leftover
def initData():
"""
Initializes the globals train,dev,eval of type Dataset.
"""
cache_byte_sizes = getCacheByteSizes()
chunking = "0"
if config.value("on_size_limit", "ignore") == "chunk":
chunking = config.value("batch_size", "0")
elif config.value('chunking', "0") == "1": # MLP mode
chunking = "1"
global train_data, dev_data, eval_data
dev_data, extra_cache_bytes_dev = load_data(
config, cache_byte_sizes[1], 'dev', chunking=chunking, seq_ordering="sorted", shuffle_frames_of_nseqs=0)
eval_data, extra_cache_bytes_eval = load_data(
config, cache_byte_sizes[2], 'eval', chunking=chunking, seq_ordering="sorted", shuffle_frames_of_nseqs=0)
train_cache_bytes = cache_byte_sizes[0]
if train_cache_bytes >= 0:
# Maybe we have left over cache from dev/eval if dev/eval have cached everything.
train_cache_bytes += extra_cache_bytes_dev + extra_cache_bytes_eval
train_data, extra_train = load_data(config, train_cache_bytes, 'train')
def printTaskProperties(devices=None):
"""
:type devices: list[Device]
"""
if train_data:
print("Train data:", file=log.v2)
print(" input:", train_data.num_inputs, "x", train_data.window, file=log.v2)
print(" output:", train_data.num_outputs, file=log.v2)
print(" ", train_data.len_info() or "no info", file=log.v2)
if dev_data:
print("Dev data:", file=log.v2)
print(" ", dev_data.len_info() or "no info", file=log.v2)
if eval_data:
print("Eval data:", file=log.v2)
print(" ", eval_data.len_info() or "no info", file=log.v2)
if devices:
print("Devices:", file=log.v3)
for device in devices:
print(" %s: %s" % (device.name, device.device_name), end=' ', file=log.v3)
print("(units:", device.get_device_shaders(),
"clock: %.02fGhz" % (device.get_device_clock() / 1024.0),
"memory: %.01f" % (device.get_device_memory() / float(1024 * 1024 * 1024)) + "GB)", end=' ', file=log.v3)
print("working on", device.num_batches, "batches" if device.num_batches > 1 else "batch", end=' ', file=log.v3)
print("(update on device)" if device.update_specs['update_rule'] != 'none' else "(update on host)", file=log.v3)
def initEngine(devices):
"""
:type devices: list[Device]
Initializes global engine.
"""
global engine
if BackendEngine.is_theano_selected():
engine = Engine(devices)
elif BackendEngine.is_tensorflow_selected():
import TFEngine
engine = TFEngine.Engine(config=config)
else:
raise NotImplementedError
def crnnGreeting(configFilename=None, commandLineOptions=None):
print("CRNN starting up, version %s, pid %i, cwd %s" % (
describe_crnn_version(), os.getpid(), os.getcwd()), file=log.v3)
if configFilename:
print("CRNN config: %s" % configFilename, file=log.v4)
if os.path.islink(configFilename):
print("CRNN config is symlink to: %s" % os.readlink(configFilename), file=log.v4)
if commandLineOptions is not None:
print("CRNN command line options: %s" % (commandLineOptions,), file=log.v4)
def initBackendEngine():
BackendEngine.select_engine(config=config)
if BackendEngine.is_theano_selected():
print("Theano:", describe_theano_version(), file=log.v3)
elif BackendEngine.is_tensorflow_selected():
print("TensorFlow:", describe_tensorflow_version(), file=log.v3)
if get_tensorflow_version_tuple()[0] == 0:
print("Warning: TF <1.0 is not supported and likely broken.", file=log.v2)
from TFUtil import debugRegisterBetterRepr, setup_tf_thread_pools
setup_tf_thread_pools(log_file=log.v2)
debugRegisterBetterRepr()
else:
raise NotImplementedError
def init(configFilename=None, commandLineOptions=(), config_updates=None, extra_greeting=None):
"""
:param str|None configFilename:
:param tuple[str]|list[str]|None commandLineOptions:
:param dict[str]|None config_updates:
:param str|None extra_greeting:
"""
initBetterExchook()
initThreadJoinHack()
initConfig(configFilename=configFilename, commandLineOptions=commandLineOptions)
if config_updates:
config.update(config_updates)
initLog()
if extra_greeting:
print(extra_greeting, file=log.v1)
crnnGreeting(configFilename=configFilename, commandLineOptions=commandLineOptions)
initBackendEngine()
initFaulthandler()
if BackendEngine.is_theano_selected():
if config.value('task', 'train') == "theano_graph":
config.set("multiprocessing", False)
if config.bool('multiprocessing', True):
initCudaNotInMainProcCheck()
if config.bool('ipython', False):
initIPythonKernel()
initConfigJsonNetwork()
devices = initDevices()
if needData():
initData()
printTaskProperties(devices)
if config.value('task', 'train') == 'server':
server = Server.Server(config)
else:
initEngine(devices)
def finalize():
print("Quitting", file=getattr(log, "v4", sys.stderr))
global quit
quit = True
sys.exited = True
if BackendEngine.is_theano_selected():
if engine:
for device in engine.devices:
device.terminate()
elif BackendEngine.is_tensorflow_selected():
if engine:
engine.finalize()
def needData():
if config.has("need_data") and not config.bool("need_data", True):
return False
task = config.value('task', 'train')
if task in ['theano_graph', "nop"]:
return False
return True
def executeMainTask():
st = time.time()
task = config.value('task', 'train')
if task == 'train':
assert train_data.have_seqs(), "no train files specified, check train option: %s" % config.value('train', None)
engine.init_train_from_config(config, train_data, dev_data, eval_data)
engine.train()
elif task == "eval":
engine.init_train_from_config(config, train_data, dev_data, eval_data)
engine.epoch = config.int("epoch", None)
assert engine.epoch
print("Evaluate epoch", engine.epoch, file=log.v4)
engine.eval_model()
elif task == 'forward':
assert eval_data is not None, 'no eval data provided'
assert config.has('output_file'), 'no output file provided'
combine_labels = config.value('combine_labels', '')
output_file = config.value('output_file', '')
engine.init_network_from_config(config)
engine.forward_to_hdf(
data=eval_data, output_file=output_file, combine_labels=combine_labels,
batch_size=config.int('forward_batch_size', 0))
elif task == "search":
engine.use_search_flag = True
engine.init_network_from_config(config)
if config.value("search_data", "eval") in ["train", "dev", "eval"]:
data = {"train": train_data, "dev": dev_data, "eval": eval_data}[config.value("search_data", "eval")]
assert data, "set search_data"
else:
data = init_dataset(config.typed_value("search_data"))
engine.search(data, output_layer_name=config.value("search_output_layer", "output"))
elif task == 'compute_priors':
assert train_data is not None, 'train data for priors should be provided'
engine.init_network_from_config(config)
engine.compute_priors(dataset=train_data, config=config)
elif task == 'theano_graph':
import theano.printing
import theano.compile.io
import theano.compile.function_module
engine.start_epoch = 1
engine.init_network_from_config(config)
for task in config.list('theano_graph.task', ['train']):
func = engine.devices[-1].get_compute_func(task)
prefix = config.value("theano_graph.prefix", "current") + ".task"
print("dumping to %s.* ..." % prefix, file=log.v1)
theano.printing.debugprint(func, file=open("%s.optimized_func.txt" % prefix, "w"))
assert isinstance(func.maker, theano.compile.function_module.FunctionMaker)
for inp in func.maker.inputs:
assert isinstance(inp, theano.compile.io.In)
if inp.update:
theano.printing.debugprint(inp.update, file=open("%s.unoptimized.var_%s_update.txt" % (prefix, inp.name), "w"))
theano.printing.pydotprint(func, format='png', var_with_name_simple=True,
outfile = "%s.png" % prefix)
elif task == 'analyze': # anything based on the network + Device
statistics = config.list('statistics', None)
engine.init_network_from_config(config)
engine.analyze(data=eval_data or dev_data, statistics=statistics)
elif task == "analyze_data": # anything just based on the data
analyze_data(config)
elif task == "classify":
assert eval_data is not None, 'no eval data provided'
assert config.has('label_file'), 'no output file provided'
label_file = config.value('label_file', '')
engine.init_network_from_config(config)
engine.classify(engine.devices[0], eval_data, label_file)
elif task == "daemon":
engine.init_network_from_config(config)
engine.daemon(config)
elif task == "server":
print("Server Initiating", file=log.v1)
elif task.startswith("config:"):
action = config.typed_dict[task[len("config:"):]]
print("Task: %r" % action, file=log.v1)
assert callable(action)
action()
elif task.startswith("optional-config:"):
action = config.typed_dict.get(task[len("optional-config:"):], None)
if action is None:
print("No task found for %r, so just quitting." % task, file=log.v1)
else:
print("Task: %r" % action, file=log.v1)
assert callable(action)
action()
elif task == "nop":
print("Task: No-operation", file=log.v1)
else:
assert False, "unknown task: %s" % task
print(("elapsed: %f" % (time.time() - st)), file=log.v3)
def analyze_data(config):
dss = config.value('analyze_dataset', 'train')
ds = {"train": train_data, "dev": dev_data, "eval": eval_data}[dss]
epoch = config.int('epoch', 1)
print("Analyze dataset", dss, "epoch", epoch, file=log.v1)
ds.init_seq_order(epoch=epoch)
stat_prefix = config.value('statistics_save_prefix', 'statistics')
dtype = config.value('statistics_dtype', 'float64')
target = config.value('target', 'classes')
data_key = config.value('data_key', 'data')
assert ds.is_data_sparse(target), "need for prior calculation"
assert not ds.is_data_sparse(data_key), "needed for mean/var estimation"
from Util import inplace_increment, progress_bar_with_time, NumbersDict
priors = numpy.zeros((ds.get_data_dim(target),), dtype=dtype)
mean = numpy.zeros((ds.get_data_dim(data_key),), dtype=dtype)
mean_sq = numpy.zeros((ds.get_data_dim(data_key),), dtype=dtype)
total_targets_len = 0
total_data_len = 0
seq_idx = 0
while ds.is_less_than_num_seqs(seq_idx):
progress_bar_with_time(ds.get_complete_frac(seq_idx))
ds.load_seqs(seq_idx, seq_idx + 1)
targets = ds.get_data(seq_idx, target)
inplace_increment(priors, targets, 1)
total_targets_len += targets.shape[0]
data = ds.get_data(seq_idx, data_key)
new_total_data_len = total_data_len + data.shape[0]
f = float(total_data_len) / new_total_data_len
mean = mean * f + numpy.sum(data, axis=0) * (1.0 - f)
mean_sq = mean_sq * f + numpy.sum(data * data, axis=0) * (1.0 - f)
total_data_len = new_total_data_len
seq_idx += 1
log_priors = numpy.log(priors)
log_priors -= numpy.log(NumbersDict(ds.get_num_timesteps())[target])
var = numpy.sqrt(mean_sq - mean * mean)
print("Finished. %i total target frames, %i total data frames" % (total_targets_len, total_data_len), file=log.v1)
priors_fn = stat_prefix + ".log_priors.txt"
mean_fn = stat_prefix + ".mean.txt"
var_fn = stat_prefix + ".var.txt"
print("Dump priors to", priors_fn, file=log.v1)
numpy.savetxt(priors_fn, log_priors)
print("Dump mean to", mean_fn, file=log.v1)
numpy.savetxt(mean_fn, mean)
print("Dump var to", var_fn, file=log.v1)
numpy.savetxt(var_fn, var)
print("Done.", file=log.v1)
def main(argv):
return_code = 0
try:
assert len(argv) >= 2, "usage: %s <config>" % argv[0]
init(commandLineOptions=argv[1:])
executeMainTask()
except KeyboardInterrupt:
return_code = 1
print("KeyboardInterrupt", file=getattr(log, "v3", sys.stderr))
if getattr(log, "verbose", [False] * 6)[5]:
sys.excepthook(*sys.exc_info())
finalize()
if return_code:
sys.exit(return_code)
if __name__ == '__main__':
main(sys.argv)