forked from rwth-i6/returnn
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TFEngine.py
2010 lines (1845 loc) · 87.8 KB
/
TFEngine.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
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
TensorFlow engine
=================
The basic engine for the TensorFlow backend is implemented here,
i.e. the high-level logic to train, i.e. looping over epochs,
holding the network instance, creating the TensorFlow session,
managing the data pipeline, etc.
See :ref:`tech_overview` for an overview how it fits all together.
"""
from __future__ import print_function
import os
import sys
import time
try:
# noinspection PyCompatibility
from Queue import Queue
except ImportError:
# noinspection PyCompatibility
from queue import Queue
import numpy
import tensorflow as tf
from tensorflow.python.client import timeline
from Dataset import Dataset, Batch, BatchSetGenerator
from Engine import Engine as TheanoEngine
from LearningRateControl import loadLearningRateControlFromConfig, LearningRateControl
from Log import log
from Network import LayerNetwork
from Pretrain import pretrainFromConfig
from TFNetwork import TFNetwork, ExternData, help_on_tf_exception
from TFUpdater import Updater
from Util import hms, NumbersDict, PY3, BackendEngine
from pprint import pprint
class CancelTrainingException(Exception):
pass
class Runner(object):
def __init__(self, engine, dataset, batches, train, eval=True, extra_fetches=None, extra_fetches_callback=None):
"""
:param Engine engine:
:param Dataset.Dataset dataset:
:param BatchSetGenerator batches:
:param bool train: whether to do updates on the model
:param bool eval: whether to evaluate (i.e. calculate loss/error)
:param dict[str,tf.Tensor|TFUtil.Data|TFNetworkLayer.LayerBase]|None extra_fetches: additional fetches per step.
`extra_fetches_callback` will be called with these. In case of Data/LayerBase, it will return a list,
where each item corresponds to the batch-seq.
It might also be useful to add `network.get_extern_data("seq_idx")` and `network.get_extern_data("seq_tag")`.
:param (**dict[str,numpy.ndarray|str|list[numpy.ndarray|str])->None extra_fetches_callback: called if extra_fetches
"""
from TFDataPipeline import FeedDictDataProvider, DataProviderBase
engine.network.extern_data.check_matched_dataset(
dataset=dataset, used_data_keys=engine.network.used_data_keys)
self.engine = engine
self.data_provider = FeedDictDataProvider(
tf_session=engine.tf_session, extern_data=engine.network.extern_data,
data_keys=engine.network.used_data_keys,
dataset=dataset, batches=batches)
assert isinstance(self.data_provider, DataProviderBase)
self._should_train = train
self._should_eval = eval
self.store_metadata_mod_step = engine.config.int("store_metadata_mod_step", 0)
self.reset_updater_vars_mod_step = engine.config.int("reset_updater_vars_mod_step", 0)
self.finalized = False
self.cancel_flag = False
self.run_exception = None
self.num_steps = None
self.device_crash_batch = None # type: int|None
self.start_time = None
self.elapsed = None
self._results_accumulated = {} # type: dict[str,float] # entries like "cost:output" or "loss"
self.num_frames_accumulated = NumbersDict() # for each result key, the corresponding number of frames
self.results = {} # type: dict[str,float] # entries like "cost:output" or "loss"
self.score = {} # type: dict[str,float] # entries like "cost:output"
self.error = {} # type: dict[str,float] # entries like "error:output"
self.stats = {} # type: dict[str,float|numpy.ndarray|Util.Stats] # entries like "stats:..."
self.extra_fetches = extra_fetches
if extra_fetches is not None:
assert extra_fetches_callback
self.extra_fetches_callback = extra_fetches_callback
from Util import terminal_size
terminal_width, _ = terminal_size()
self._show_interactive_process_bar = (log.verbose[3] and (not log.verbose[5]) and terminal_width >= 0)
def _get_fetches_dict(self):
"""
:return: values and actions which should be calculated and executed in self.run() by the TF session for each step
:rtype: dict[str,tf.Tensor|tf.Operation]
"""
# Note that it is important that we do not recreate graph nodes for every call to this function.
# Thus everything which we access here should be cached.
d = {}
for key in self.data_provider.data_keys:
data = self.data_provider.extern_data.get_data(key)
for dim, v in data.size_placeholder.items():
d["size:%s:%i" % (key, dim)] = v
if self._should_train or self._should_eval:
# These values are cached internally and the graph nodes are created on the first call.
loss = self.engine.network.get_objective()
if loss is 0:
loss = self.engine.get_const_tensor(key="zero_loss", value=0.0)
d["loss"] = loss
for layer_name, loss in self.engine.network.loss_by_layer.items():
if self.engine.network.get_layer(layer_name).only_on_eval and self._should_train:
continue
d["cost:%s" % layer_name] = loss
for layer_name, error in self.engine.network.error_by_layer.items():
if self.engine.network.get_layer(layer_name).only_on_eval and self._should_train:
continue
d["error:%s" % layer_name] = error
for layer in self.engine.network.layers.values():
if layer.target and layer.target.startswith("layer:"):
target_data = layer.loss.target
for dim, v in target_data.size_placeholder.items():
d["size:%s:%i" % (layer.target, dim)] = v
for layer in self.engine.network.layers.values():
for k, v in layer.stats.items():
d["stats:%s:%s" % (layer.name, k)] = v
if self._should_train:
assert self.engine.updater
def callback_on_new():
# Force a new check.
self.engine._checked_uninitialized_vars = False
self.engine.updater.init_optimizer_vars(session=self.engine.tf_session)
d["optim_op"] = self.engine.updater.get_optim_op(callback_on_new=callback_on_new)
if self.engine.updater.optim_meta_losses:
d.update(self.engine.updater.optim_meta_losses)
if self.extra_fetches is not None:
from TFNetworkLayer import LayerBase
from TFUtil import Data
for k, v in self.extra_fetches.items():
if v is None:
continue
if isinstance(v, tf.Tensor):
d["extra:%s" % k] = v
continue
if isinstance(v, LayerBase):
v = v.output
assert isinstance(v, Data)
d["extra:%s" % k] = v.placeholder # see _maybe_handle_extra_fetches, it will transform to batch-major there
for i, s in v.size_placeholder.items():
d["extra:%s:size_%i" % (k, i)] = s
if self.engine.get_all_merged_summaries() is not None:
d["summary"] = self.engine.get_all_merged_summaries()
if self.engine.config.bool("tf_log_memory_usage", False):
from TFUtil import mem_usage_for_dev
for dev in self.engine.tf_session.list_devices():
if dev.device_type != "GPU":
# mem_usage_for_dev currently only works for GPU
continue
d["mem_usage:%s" % os.path.basename(dev.name.replace("/device:", "/"))] = mem_usage_for_dev(dev.name)
if self.engine.network.get_post_control_dependencies():
d["post_control_dependencies"] = self.engine.network.get_post_control_dependencies()
return d
def _print_process(self, report_prefix, step, step_duration, eval_info):
"""
:param str report_prefix:
:param int step:
:param float step_duration: in secs
:param dict[str] eval_info: via :func:`_collect_eval_info`
:return: nothing, will be printed to log
"""
if not self._show_interactive_process_bar and not log.v[5]:
return
start_elapsed = time.time() - self.start_time
complete = self.data_provider.get_complete_frac()
assert complete > 0
total_time_estimated = start_elapsed / complete
remaining_estimated = total_time_estimated - start_elapsed
if log.verbose[5]:
info = [
report_prefix,
"step %i" % step]
if eval_info: # Such as score.
info += ["%s %s" % item for item in sorted(eval_info.items())]
info += [
"%.3f sec/step" % step_duration,
"elapsed %s" % hms(start_elapsed),
"exp. remaining %s" % hms(remaining_estimated),
"complete %.02f%%" % (complete * 100)]
print(", ".join(filter(None, info)), file=log.v5)
elif self._show_interactive_process_bar:
from Util import progress_bar
progress_bar(complete, hms(remaining_estimated))
def _print_finish_process(self):
if self._show_interactive_process_bar:
from Util import progress_bar
progress_bar()
def _get_target_for_key(self, key):
"""
:param str key: e.g. "cost:output" where the last part is the layer name. or "loss"
:return: target name which is the data-key in the dataset, e.g. "classes"
:rtype: str
"""
if ":" in key:
layer = self.engine.network.get_layer(key[key.find(":") + 1:])
if layer.target:
return layer.target
return self.engine.network.extern_data.default_target
def _epoch_norm_factor_for_result(self, key):
"""
:param str key: e.g. "cost:output"
:return: factor to multiply with such accumulated values for the final epoch stats
:rtype: float
"""
# Default: Normalize by number of frames.
return 1.0 / self.num_frames_accumulated[key]
def _finalize(self, num_steps):
"""
Called at the end of an epoch.
:param int num_steps: number of steps we did for this epoch
"""
assert not self.data_provider.have_more_data(session=self.engine.tf_session)
results = {key: value * self._epoch_norm_factor_for_result(key)
for (key, value) in self._results_accumulated.items()}
self.results = results
self.score = {key: value for (key, value) in results.items() if key.startswith("cost:")}
if self.engine.config.bool("calculate_exp_loss", False):
self.score.update({key + ":exp": numpy.exp(value) for (key, value) in results.items() if key.startswith("cost:")})
self.error = {key: value for (key, value) in results.items() if key.startswith("error:")}
self.num_steps = num_steps
self.finalized = True
def _get_batch_dim_from_fetches(self, fetches_results):
"""
:param dict[str,numpy.ndarray|None] fetches_results: results of calculations, see self._get_fetches_dict()
:rtype: int
"""
default_target = self.engine.network.extern_data.default_target
if "size:%s:0" % default_target in fetches_results:
return len(fetches_results["size:%s:0" % default_target])
for k, v in sorted(fetches_results.items()):
if not k.startswith("size:"):
continue
if not k.endswith(":0"):
continue
return len(v)
assert False, "batch-dim not found in %r" % fetches_results
def _step_seq_len(self, fetches_results, data_key):
"""
:param dict[str,numpy.ndarray|None] fetches_results: results of calculations, see self._get_fetches_dict()
:param str data_key: e.g. "classes"
:return: the seq length of this batch
:rtype: int
"""
seq_len_key = "size:%s:0" % data_key
if seq_len_key in fetches_results:
return numpy.sum(fetches_results[seq_len_key])
else:
# We assume that this data-key has no time axis. Use the batch-dim instead.
return self._get_batch_dim_from_fetches(fetches_results)
def _collect_eval_info(self, fetches_results):
"""
:param dict[str,numpy.ndarray|None] fetches_results: results of calculations, see self._get_fetches_dict()
:return: dict for printing the step stats, see self._print_process(), e.g. {"cost:output": 2.3}
:rtype: dict[str,float]
"""
# See see self._get_fetches_dict() for the keys.
keys = [k for k in fetches_results.keys() if k.startswith("cost:") or k.startswith("error:") or k == "loss"]
step_seq_lens = {} # key -> int
for key in keys:
target = self._get_target_for_key(key)
step_seq_lens[key] = self._step_seq_len(
fetches_results=fetches_results, data_key=target)
# Accumulate for epoch stats.
self.num_frames_accumulated += NumbersDict(step_seq_lens)
for key in keys:
value = fetches_results[key]
if key not in self._results_accumulated:
self._results_accumulated[key] = value
else:
self._results_accumulated[key] += value
# Prepare eval info stats for this batch run.
eval_info = {}
for key in keys:
value = fetches_results[key]
if value:
value /= float(step_seq_lens[key])
eval_info[key] = value
if self.engine.config.bool("calculate_exp_loss", False) and key.startswith("cost:"):
eval_info[key + ":exp"] = numpy.exp(value)
# Add batch size info.
if self.engine.config.bool("log_batch_size", False):
for k, v in sorted(fetches_results.items()):
if not k.startswith("size:"):
continue
if not k.endswith(":0"):
continue
eval_info["num_seqs"] = len(v)
eval_info["max_size:%s" % k[len("size:"):-len(":0")]] = max(v)
# Add raw stats.
for k, v in fetches_results.items():
if k.startswith("stats:"):
if v.ndim == 1:
v = list(v) # looks nicer in logs
eval_info[k] = v
self.stats[k] = v # Always just store latest value.
if k.startswith("mem_usage:"):
from Util import human_bytes_size, Stats
self.stats.setdefault(k, Stats(format_str=human_bytes_size))
self.stats[k].collect([v])
eval_info[k] = human_bytes_size(v)
return eval_info
def _maybe_handle_extra_fetches(self, fetches_results):
"""
:param dict[str,numpy.ndarray|str] fetches_results: results of calculations, see self._get_fetches_dict()
"""
if self.extra_fetches is None:
return
d = {}
from TFNetworkLayer import LayerBase
from TFUtil import Data
for k, v in self.extra_fetches.items():
if v is None:
d[k] = None
continue
r = fetches_results["extra:%s" % k]
if isinstance(v, tf.Tensor):
d[k] = r
continue
if isinstance(v, LayerBase):
v = v.output
assert isinstance(v, Data)
if v.batch_dim_axis != 0:
r = numpy.moveaxis(r, v.batch_dim_axis, 0)
if v.have_time_axis():
assert v.time_dim_axis_excluding_batch == 0
assert list(v.size_placeholder.keys()) == [0]
seq_lens = fetches_results["extra:%s:size_0" % k] # shape: (batch,)
assert seq_lens.shape == (r.shape[0],)
d[k] = [r[i, :seq_lens[i]] for i in range(seq_lens.shape[0])]
else:
d[k] = list(r)
self.extra_fetches_callback(**d)
def run(self, report_prefix):
"""
:param str report_prefix: prefix for logging, e.g. "train"
"""
sess = self.engine.tf_session
if self.engine.config.has("tf_log_dir"):
logdir = self.engine.config.value("tf_log_dir", None)
elif self.engine.model_filename:
logdir = os.path.dirname(self.engine.model_filename)
elif log.filename:
logdir = os.path.dirname(log.filename)
else:
logdir = os.getcwd()
if logdir:
from Util import log_runtime_info_to_dir, get_utc_start_time_filename_part
logdir += "/%s" % self.data_provider.get_dataset_name()
if not self._should_train: # like eval
logdir += "-%i" % self.engine.epoch
if self.engine.use_search_flag:
logdir += "-search"
logdir += "-%s" % get_utc_start_time_filename_part()
log_runtime_info_to_dir(logdir, config=self.engine.config)
writer = tf.summary.FileWriter(logdir)
else:
writer = None
print("TF: log_dir: %s" % logdir, file=log.v5)
run_metadata = tf.RunMetadata()
debug_shell_in_runner = self.engine.config.bool("debug_shell_in_runner", False)
debug_shell_in_runner_step = self.engine.config.int("debug_shell_in_runner_step", 1)
# Not sure if this is the best thing to do for an evaluation but it's ok for now.
# We could also set it to 0 for non train epochs.
step_offset = self.engine.network.get_global_train_step(session=sess)
coord = self.data_provider.coord
threads = tf.train.start_queue_runners(sess=sess, coord=coord)
self.data_provider.start_threads()
self.start_time = time.time()
elapsed_time_tf = 0.0
step = None
fetches_dict = None
feed_dict = None
meta_step_info = None
try:
# step is like mini-batch in our usual terminology
step = 0
fetches_dict = self._get_fetches_dict()
# After get_fetches_dict, maybe some new uninitialized vars. Last check.
self.engine.check_uninitialized_vars()
# Also, add graph to summary here because the updater/optimizer might not have been created before.
if writer:
writer.add_graph(sess.graph)
while self.data_provider.have_more_data(session=sess):
feed_dict, meta_step_info = self.data_provider.get_feed_dict()
if isinstance(self.engine.network.train_flag, tf.Tensor):
feed_dict[self.engine.network.train_flag] = self._should_train
if isinstance(self.engine.network.epoch_step, tf.Tensor):
feed_dict[self.engine.network.epoch_step] = step
start_time = time.time()
if self._should_train and self.reset_updater_vars_mod_step and step % self.reset_updater_vars_mod_step == 0:
print("Reset updater vars in step %i." % step, file=log.v5)
self.engine.updater.init_optimizer_vars(session=sess)
if step == 0:
if self.engine.config.bool("check_unsupported_device", False) and self.engine.is_requesting_for_gpu():
from TFUtil import find_unsupported_devices_in_graph
ops = find_unsupported_devices_in_graph(graph=sess.graph, dev_name="GPU")
if not ops:
print("All ops in graph can be run on GPU.")
else:
print("The following ops do not have a GPU kernel:")
pprint(ops)
if debug_shell_in_runner and debug_shell_in_runner_step == step:
print("debug_shell_in_runner, step %i" % step, file=log.v1)
import Debug
Debug.debug_shell(user_ns=locals(), user_global_ns=globals(), exit_afterwards=False)
# Now do one calculation step. Optionally with metadata.
try:
if self.store_metadata_mod_step and step % self.store_metadata_mod_step == 0:
# Slow run that stores extra information for debugging.
print('Storing metadata', file=log.v5)
run_options = tf.RunOptions(
trace_level=tf.RunOptions.FULL_TRACE)
# We could use tfdbg.add_debug_tensor_watch here.
session_run_start_time = time.time()
fetches_results = sess.run(
fetches_dict,
feed_dict=feed_dict,
options=run_options,
run_metadata=run_metadata) # type: dict[str,numpy.ndarray|str]
elapsed_time_tf += time.time() - session_run_start_time
writer.add_summary(fetches_results["summary"], step + step_offset)
writer.add_run_metadata(run_metadata, 'step_{:04d}'.format(step + step_offset))
tl = timeline.Timeline(run_metadata.step_stats)
timeline_path = os.path.join(logdir, 'timeline.trace')
with open(timeline_path, 'w') as f:
f.write(tl.generate_chrome_trace_format(show_memory=True))
else:
session_run_start_time = time.time()
fetches_results = sess.run(fetches_dict, feed_dict=feed_dict) # type: dict[str,numpy.ndarray|str]
elapsed_time_tf += time.time() - session_run_start_time
if writer and "summary" in fetches_results:
writer.add_summary(fetches_results["summary"], step + step_offset)
except tf.errors.OpError as exc:
print("TensorFlow exception:", exc, file=log.v1)
# Extra info will be printed below.
raise
eval_info = self._collect_eval_info(fetches_results=fetches_results)
self._maybe_handle_extra_fetches(fetches_results)
duration = time.time() - start_time
self._print_process(report_prefix=report_prefix, step=step, step_duration=duration, eval_info=eval_info)
if step <= 10 and writer:
writer.flush()
if PY3:
os.sync()
step += 1
if self.cancel_flag:
raise CancelTrainingException("cancel_flag is set")
self._print_finish_process()
if not self.data_provider.have_reached_end():
raise Exception("Did not successfully reached the end of the dataset.")
if self._should_train:
final_global_train_step = self.engine.network.get_global_train_step(session=sess)
assert step + step_offset == final_global_train_step
self._finalize(num_steps=step)
if self.stats:
print("Stats:", file=log.v1)
for k, v in sorted(self.stats.items()):
print(" %s:" % k, v, file=log.v1)
elapsed = time.time() - self.start_time
elapsed_tf_percentage = (elapsed_time_tf / elapsed) if (elapsed > 0) else 0.0
print("%s, finished after %i steps, %s elapsed (%.1f%% computing time)" % (
report_prefix, step, hms(elapsed), (elapsed_tf_percentage * 100.)), file=log.v3)
except KeyboardInterrupt as exc:
print("KeyboardInterrupt in step %r." % step)
self.run_exception = exc
except BaseException as exc:
print("Exception %r in step %r." % (exc, step), file=log.v1)
if not isinstance(exc, CancelTrainingException):
help_on_tf_exception(
exception=exc, feed_dict=feed_dict, meta_step_info=meta_step_info,
extern_data=self.data_provider.extern_data, file=log.v2)
sys.excepthook(*sys.exc_info())
self.device_crash_batch = step
self.run_exception = exc
finally:
from Util import try_and_ignore_exception
from TFUtil import stop_event_writer_thread
if writer:
try_and_ignore_exception(writer.close)
try_and_ignore_exception(lambda: stop_event_writer_thread(writer.event_writer))
try_and_ignore_exception(coord.request_stop)
try_and_ignore_exception(lambda: coord.join(threads))
try_and_ignore_exception(self.data_provider.stop_threads)
self.elapsed = time.time() - self.start_time
class Engine(object):
def __init__(self, config=None):
"""
:param Config.Config|None config:
"""
if config is None:
from Config import get_global_config
config = get_global_config(auto_create=True)
if not log.initialized:
log.init_by_config(config)
if BackendEngine.selectedEngine is None:
BackendEngine.select_engine(engine=BackendEngine.TensorFlow)
assert BackendEngine.is_tensorflow_selected()
self.config = config
self.orig_config = {} # see _maybe_update_config
self.devices_config = self._get_devices_config()
self._check_devices()
self.tf_session = None # type: tf.Session
self.network = None # type: TFNetwork
self.updater = None # type: Updater
self.learning_rate_control = None # type: LearningRateControl
self._checked_uninitialized_vars = False
self._merge_all_summaries = None
self.dataset_batches = {} # type: dict[str,BatchSetGenerator]
self.train_data = None # type: Dataset
self.start_epoch = None
self.use_dynamic_train_flag = False
self.use_search_flag = config.value("task", None) == "search"
self.use_eval_flag = config.value("task", None) != "forward"
self._const_cache = {} # type: dict[str,tf.Tensor]
def finalize(self):
self._close_tf_session()
tf.reset_default_graph()
self.network = None
self.updater = None
self._merge_all_summaries = None
def get_const_tensor(self, key, value):
if key not in self._const_cache:
self._const_cache[key] = tf.constant(value=value, name="const_%s" % key)
return self._const_cache[key]
def _get_devices_config(self):
"""
:rtype: list[dict[str]]
"""
from Device import getDevicesInitArgs
if not self.config.value("device", None):
# Better default: Use GPU if available.
from TFUtil import is_gpu_available
if is_gpu_available():
print("Device not set explicitly, and we found a GPU, which we will use.", file=log.v2)
self.config.set("device", "gpu")
else:
print("Device not set explicitly, and no GPU found.", file=log.v2)
return getDevicesInitArgs(self.config)
def is_requesting_for_gpu(self):
return any([d["device"].startswith("gpu") for d in self.devices_config])
def _check_devices(self):
from TFUtil import print_available_devices, is_gpu_available
print_available_devices(file=log.v2)
assert len(self.devices_config) == 1, "multiple devices not supported yet for TF"
if self.is_requesting_for_gpu():
assert is_gpu_available(), "no GPU available"
else:
if is_gpu_available():
print("Note: There is a GPU available but you have set device=cpu.", file=log.v2)
def _close_tf_session(self):
if self.tf_session:
self.tf_session.close()
self.tf_session = None
def _make_tf_session(self):
self._close_tf_session()
opts = self.config.typed_value("tf_session_opts", {})
assert isinstance(opts, dict)
opts = opts.copy()
# See options here:
# https://github.com/tensorflow/tensorflow/blob/master/tensorflow/core/protobuf/config.proto
opts.setdefault("log_device_placement", False)
opts.setdefault("device_count", {}).setdefault("GPU", 1 if self.is_requesting_for_gpu() else 0)
# Note: We don't set intra_op_parallelism_threads and inter_op_parallelism_threads here anymore
# because it is saver to do it via setup_tf_thread_pools() which we call very early.
print("Setup tf.Session with options %r ..." % opts, file=log.v2)
config = tf.ConfigProto(**opts)
# config.gpu_options.allow_growth=True
# For debugging, see tfdbg.LocalCLIDebugWrapperSession.
self.tf_session = tf.Session(config=config)
def _reset_graph(self):
"""
Resets the default graph (of the current thread),
and clears up any cached tensors created in it.
"""
tf.reset_default_graph()
self._checked_uninitialized_vars = False
self._merge_all_summaries = None
self._const_cache.clear()
get_train_start_epoch_batch = TheanoEngine.get_train_start_epoch_batch
config_get_final_epoch = TheanoEngine.config_get_final_epoch
get_epoch_model = TheanoEngine.get_epoch_model
epoch_model_filename = TheanoEngine.epoch_model_filename
def get_epoch_model_filename(self, epoch=None):
if not epoch:
epoch = self.epoch
return self.epoch_model_filename(self.model_filename, epoch, self.is_pretrain_epoch(epoch=epoch))
def get_epoch_str(self):
return ("pretrain " if self.is_pretrain_epoch() else "") + "epoch %s" % self.epoch
def is_pretrain_epoch(self, epoch=None):
if not epoch:
epoch = self.epoch
return self.pretrain and epoch <= self.pretrain.get_train_num_epochs()
def is_first_epoch_after_pretrain(self):
return self.pretrain and self.epoch == self.pretrain.get_train_num_epochs() + 1
def get_eval_datasets(self):
eval_datasets = {}; """ :type: dict[str,Dataset.Dataset] """
for name, dataset in [("dev", self.dev_data), ("eval", self.eval_data)]:
if not dataset: continue
eval_datasets[name] = dataset
return eval_datasets
def load_model(self, epoch=None, filename=None):
"""
:param int epoch:
:param str filename:
"""
assert epoch or filename
if epoch:
assert not filename
filename = self.get_epoch_model_filename(epoch=epoch)
print("Load model %s" % (filename,), file=log.v4)
self.network.load_params_from_file(filename, session=self.tf_session)
def save_model(self, filename=None):
"""
:param str filename: full filename for model
"""
if not filename:
filename = self.get_epoch_model_filename()
print("Save model under %s" % (filename,), file=log.v4)
self.network.save_params_to_file(filename, session=self.tf_session)
@staticmethod
def delete_model(filename):
"""
:param str filename:
:return: accumulated file-size in bytes of deleted files
:rtype: int
"""
# This assumes TensorFlow models here.
# They consists of multiple files with the extensions ".index", ".meta" and ".data*".
from glob import glob
count_bytes = 0
assert os.path.exists(filename + ".index")
for fn in glob(filename + "*"):
fn_ext = os.path.splitext(fn)[1]
if fn_ext not in [".index", ".meta"] and not fn_ext.startswith(".data"):
continue
count_bytes += os.stat(fn).st_size
os.remove(fn)
assert count_bytes > 0
return count_bytes
def init_train_from_config(self, config=None, train_data=None, dev_data=None, eval_data=None):
"""
:param Config.Config|None config:
:param Dataset.Dataset|None train_data:
:param Dataset.Dataset|None dev_data:
:param Dataset.Dataset|None eval_data:
"""
if not config:
config = self.config
if not config.has("num_inputs") and not config.has("num_outputs") and (train_data or dev_data or eval_data):
from Dataset import set_config_num_inputs_outputs_from_dataset
set_config_num_inputs_outputs_from_dataset(config=config, dataset=train_data or dev_data or eval_data)
self.use_dynamic_train_flag = True
self.train_data = train_data
self.dev_data = dev_data
self.eval_data = eval_data
self.start_epoch, self.start_batch = self.get_train_start_epoch_batch(config)
self.batch_size = config.int('batch_size', 1)
self.shuffle_batches = config.bool('shuffle_batches', True)
self.update_batch_size = config.int('update_batch_size', 0)
self.save_model_epoch_interval = config.int('save_interval', 1)
self.save_epoch1_initial_model = config.bool('save_epoch1_initial_model', False)
self.learning_rate_control = loadLearningRateControlFromConfig(config)
self.learning_rate = self.learning_rate_control.defaultLearningRate
self.initial_learning_rate = self.learning_rate
self.pretrain_learning_rate = config.float('pretrain_learning_rate', self.learning_rate)
self.final_epoch = self.config_get_final_epoch(config) # Inclusive.
self.max_seqs = config.int('max_seqs', -1)
self.ctc_prior_file = config.value('ctc_prior_file', None)
self.exclude = config.int_list('exclude', [])
self.init_train_epoch_posthook = config.value('init_train_epoch_posthook', None)
self.share_batches = config.bool('share_batches', False)
self.seq_drop = config.float('seq_drop', 0.0)
self.seq_drop_freq = config.float('seq_drop_freq', 10)
self.max_seq_length = config.typed_value('max_seq_length', None) or config.float('max_seq_length', 0)
self.inc_seq_length = config.float('inc_seq_length', 0)
if not self.max_seq_length:
self.max_seq_length = sys.maxsize # type: int|float|dict[str,int]|NumbersDict
if isinstance(self.max_seq_length, dict):
self.max_seq_length = NumbersDict(self.max_seq_length)
assert isinstance(self.max_seq_length, (int, float, NumbersDict))
# And also initialize the network. That depends on some vars here such as pretrain.
self.init_network_from_config(config)
def init_network_from_config(self, config=None):
"""
:param Config.Config|None config:
"""
if not config:
config = self.config
self.model_filename = config.value('model', None)
self.preload_from_files = config.typed_value('preload_from_files', {})
self.pretrain = pretrainFromConfig(config)
self.max_seqs = config.int('max_seqs', -1)
epoch, model_epoch_filename = self.get_epoch_model(config)
if not model_epoch_filename and not self.start_epoch:
if self.config.bool("allow_random_model_init", False):
print("No model will be loaded. Randomly initializing model.", file=log.v2)
epoch = 1
else:
raise Exception(
"You are not using training, otherwise start_epoch would be set via self.init_train_from_config(). "
"There was also no model found which we could load. Set one via 'load'.")
self.epoch = epoch or self.start_epoch
assert self.epoch
if self.pretrain:
# This would be obsolete if we don't want to load an existing model.
# In self.init_train_epoch(), we initialize a new model.
net_dict = self.pretrain.get_network_json_for_epoch(self.epoch)
else:
net_dict = LayerNetwork.json_from_config(config)
self._init_network(net_desc=net_dict, epoch=self.epoch)
if self.preload_from_files:
# This option is to be replaced by a load_on_init option for each layer in the future.
print("WARNING: Option 'preload_from_files' is currently not compatible with 'load_on_init' in SubnetworkLayer", file=log.v2)
print("Start pre-loading weights...", file=log.v2)
for model_name in self.preload_from_files.keys():
model_filename = self.preload_from_files.get(model_name)['filename']
print("loading weights from", model_filename, file=log.v2)
self_prefix = self.network.get_absolute_name_scope_prefix() # with "/" at end
load_if_prefix = self.preload_from_files.get(model_name)['prefix'] # prefix to identify the variables to be restored from the file
from TFNetwork import CustomCheckpointLoader
loader = CustomCheckpointLoader(
filename=model_filename, saveable_params=self.network.get_trainable_params(), params_prefix=self_prefix, load_if_prefix=load_if_prefix)
loader.set_as_custom_init()
self.network.initialize_params(session=self.tf_session)
if model_epoch_filename:
print("loading weights from", model_epoch_filename, file=log.v2)
try:
self.network.load_params_from_file(model_epoch_filename, session=self.tf_session)
except tf.errors.NotFoundError:
print("Exiting now because model cannot be loaded.", file=log.v1)
sys.exit(1)
def _maybe_update_config(self, net_desc, epoch):
"""
This is a slightly hacky way to overwrite entries in the config, via the network description.
This can e.g. be used in pretraining to overwrite certain settings such as batch_size.
:param dict[str,dict[str]] net_desc:
:param int epoch:
"""
def set_value(key, value):
"""
:param str key:
:param value:
"""
assert key in self.config.typed_dict
self.config.typed_dict[key] = value
# Some entries need specific handling, e.g. to update our attribs.
if key == "max_seq_length":
# See init_train_from_config.
if not value:
value = sys.maxsize
if isinstance(value, dict):
value = NumbersDict(value)
assert isinstance(value, (int, float, NumbersDict))
if key in ["batch_size", "max_seq_length", "max_seqs", "inc_seq_length", "seq_drop", "seq_drop_freq"]:
# To be sure, never keep the batch order.
self.dataset_batches.clear()
setattr(self, key, value)
if self.orig_config:
# We have updated the config before. Now, first, recover all entries.
for key, value in self.orig_config.items():
set_value(key, value)
self.orig_config.clear()
if "#config" not in net_desc:
return
config_overwrites = net_desc["#config"]
for key, value in config_overwrites.items():
if key == "learning_rate":
if not self.learning_rate_control:
print("No lr control, ignore learning rate %r for epoch %i" % (value, epoch), file=log.v3)
continue
old_lr = self.learning_rate_control.getLearningRateForEpoch(epoch)
print("Overwrite learning rate for epoch %i: %r -> %r" % (epoch, old_lr, value), file=log.v3)
assert self.config.is_true("use_learning_rate_control_always")
self.learning_rate_control.epochData[epoch].learningRate = value
continue
assert key in self.config.typed_dict, "config update key %r -> %r expected to be in orig. config" % (key, value)
orig_value = self.config.typed_dict[key]
print("Update config key %r for epoch %i: %r -> %r" % (key, epoch, orig_value, value), file=log.v3)
self.orig_config[key] = orig_value
set_value(key, value)
def _init_network(self, net_desc, epoch=None):
"""
:param dict[str,dict[str]] net_desc: layer name -> layer description dict
:param int|None epoch: if not given, uses self.epoch. used for the random seed
"""
if epoch is None:
epoch = self.epoch
self._close_tf_session()
self._reset_graph()
self._maybe_update_config(net_desc=net_desc, epoch=epoch)
# The new session will by default use the newly created default graph.
self._make_tf_session()
tf_random_seed = 42
net_random_seed = epoch
if self.config.opt_typed_value("random_seed", None):
seed = self.config.int("random_seed", None)
net_random_seed = (epoch * 3 + seed * 5 + 7) % (2 ** 31)
tf_random_seed = (net_random_seed * 2 + 3) % (2 ** 31)
tf.set_random_seed(tf_random_seed)
from TFUtil import get_global_train_flag_placeholder
if self.use_dynamic_train_flag:
train_flag = get_global_train_flag_placeholder()
else:
train_flag = False
if False: # TODO ...
extern_data = ExternData()
extern_data.init_from_config(self.config)
# TODO...
self.network, self.updater = self.create_network(
config=self.config,
rnd_seed=net_random_seed,
train_flag=train_flag, eval_flag=self.use_eval_flag, search_flag=self.use_search_flag,
initial_learning_rate=getattr(self, "initial_learning_rate", None),
net_dict=net_desc)
self.network.initialize_params(session=self.tf_session)
@classmethod
def create_network(cls, config, rnd_seed, train_flag, eval_flag, search_flag, net_dict, initial_learning_rate=1.0):
"""
:param Config.Config config:
:param int rnd_seed:
:param bool|tf.Tensor train_flag:
:param float initial_learning_rate:
:param bool eval_flag:
:param bool search_flag:
:param dict[str,dict[str]] net_dict:
:return: network, updater
:rtype: (TFNetwork, Updater|None)
"""
network = TFNetwork(
name="root",
config=config,
rnd_seed=rnd_seed,
train_flag=train_flag,
eval_flag=eval_flag,
search_flag=search_flag)
network.construct_from_dict(net_dict)
if train_flag is not False and config.list("search_train_network_layers"):
network.construct_extra_net(
net_dict, layer_list=config.list("search_train_network_layers"), search_flag=True)
print("search train network layers:")
for layer_name, layer in sorted(network.extra_net.layers.items()):
print(" layer %s %r #: %s" % (layer.layer_class, layer_name, layer.output.dim), file=log.v2)
if not network.extra_net.layers:
print(" (no layers)", file=log.v2)
# We don't expect any new params (for now). Check that.
net_params = network.get_params_list()
for extra_param in network.extra_net.get_params_list():
assert extra_param in net_params
network.layers_desc = net_dict
updater = None
if train_flag is not False:
# Need to create new Updater because it has the learning_rate var which must be in the current graph.
updater = Updater(
config=config, network=network,
initial_learning_rate=initial_learning_rate)
updater.set_trainable_vars(network.get_trainable_params())
network.print_network_info()
return network, updater
def maybe_init_new_network(self, net_desc):
"""
:param dict[str,dict[str]] net_desc: layer name -> layer description dict
"""
if self.network.layers_desc == net_desc:
return
from Util import dict_diff_str
print("reinit because network description differs. Diff:",
dict_diff_str(self.network.layers_desc, net_desc), file=log.v3)
old_network_params = self.network.get_params_serialized(self.tf_session)
self._init_network(net_desc)
if self.is_pretrain_epoch() and not self.pretrain.copy_output_layer:
# "ifpossible" logic handled below. copy_output_layer=True is currently not enforced.
for l in self.network.get_output_layers():
if l.name in old_network_params.values_dict:
print("suspend copying of output layer: " + l.name, file=log.v2)
old_network_params.values_dict.pop(l.name)
# This copy will copy the old params over and leave the rest randomly initialized.
# This also works if the old network has just the same topology,
# e.g. if it is the initial model from self.init_network_from_config().
# In pretraining it can happen, that the dimension of output parameters of the previous epoch is
# not equal to the dimension in the current epoch, due to difference in layer size.
# In that case initialize output parameters randomly.
self.network.set_params_by_serialized(
old_network_params, session=self.tf_session,
ignore_wrong_shape=self.is_pretrain_epoch(),
copy_param_mode=self.pretrain.copy_param_mode if self.is_pretrain_epoch() else None,
ignore_non_existing=self.is_pretrain_epoch())
def train(self):
print("start training at epoch %i and step %i" % (self.start_epoch, self.start_batch), file=log.v3)
print("using batch size: %i, max seqs: %i" % (self.batch_size, self.max_seqs), file=log.v4)
print("learning rate control:", self.learning_rate_control, file=log.v4)
print("pretrain:", self.pretrain, file=log.v4)
self.dataset_batches.clear()
assert self.start_epoch >= 1, "Epochs start at 1."
final_epoch = self.final_epoch if self.final_epoch != 0 else sys.maxsize
if self.start_epoch > final_epoch:
print("No epochs to train, start_epoch: %i, final_epoch: %i" %
(self.start_epoch, self.final_epoch), file=log.v1)
self.check_last_epoch()
if isinstance(self.max_seq_length, (int, float)):
self.max_seq_length += (self.start_epoch - 1) * self.inc_seq_length
epoch = self.start_epoch # Epochs start at 1.
while epoch <= final_epoch:
self.epoch = epoch # type: int
if isinstance(self.max_seq_length, int) and self.max_seq_length != sys.maxsize:
if int(self.max_seq_length + self.inc_seq_length) != int(self.max_seq_length):
print("increasing sequence lengths to", int(self.max_seq_length + self.inc_seq_length), file=log.v3)
self.dataset_batches.pop("train", None)
self.max_seq_length += self.inc_seq_length
if self.epoch % self.seq_drop_freq == 0:
if self.seq_drop > 0.0:
self.dataset_batches.pop("train", None)
# In case of random seq ordering, we want to reorder each epoch.
if self.train_data.init_seq_order(epoch=self.epoch):
self.dataset_batches.pop("train", None)
for dataset_name, dataset in self.get_eval_datasets().items():
if dataset.init_seq_order(epoch=self.epoch):
self.dataset_batches.pop(dataset_name, None)
self.init_train_epoch()
self.train_epoch()
epoch += 1