forked from rwth-i6/returnn
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TFEngine.py
2219 lines (2041 loc) · 96.9 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 = self.engine._get_new_data_provider(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 = NumbersDict() # entries like "cost:output" or "loss"
self._inv_norm_accumulated = NumbersDict() # entries like "output"
self.num_frames_accumulated = NumbersDict() # for each data key (eg. "classes"), 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
self._horovod_stopped_runner = False
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.
def reduce_sum(x, name, average=False):
if not self.engine.config.is_true("use_horovod"):
return x
from TFUtil import global_tensor
import horovod.tensorflow as hvd
return global_tensor(
lambda: hvd.allreduce(x, average=average),
name="fetch_reduce_sum__" + name.replace(":", "__").replace("/", "_"))
def inv_reduce_sum(x, name):
if not self.engine.config.is_true("use_horovod"):
return x
from TFUtil import global_tensor
return global_tensor(
lambda: tf.reciprocal(reduce_sum(tf.reciprocal(x), name=name)),
name="fetch_inv_reduce_sum__" + name.replace(":", "__").replace("/", "_"))
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)
else: # non-constant-zero loss
assert self.engine.network.losses_dict
d["loss"] = reduce_sum(loss, name="loss", average=True)
for loss_name, loss in self.engine.network.losses_dict.items():
if loss.get_only_on_eval() and self._should_train:
continue
if loss.get_loss_value_for_fetch() is not None:
d["cost:%s" % loss_name] = reduce_sum(loss.get_loss_value_for_fetch(), name="cost:%s" % loss_name)
if loss.get_error_value() is not None:
d["error:%s" % loss_name] = reduce_sum(loss.get_error_value(), name="error:%s" % loss_name)
d["loss_norm_factor:%s" % loss_name] = inv_reduce_sum(
loss.get_norm_factor(), name="loss_norm_factor:%s" % loss_name)
for layer in self.engine.network.layers.values():
if layer.only_on_eval and self._should_train:
continue
# Maybe store additional size info of layer targets.
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 _finalize(self, num_steps):
"""
Called at the end of an epoch.
:param int num_steps: number of steps we did for this epoch
"""
results = {key: self._normalize_loss(value, key, self._inv_norm_accumulated)
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 _normalize_loss(self, value, key, inv_loss_norm_factors):
"""
:param T value:
:param str key: e.g. "cost:output", "error:output" or "loss"
:param NumbersDict inv_loss_norm_factors: keys e.g. e.g. "output" (layer names)
:return: normalized value
:rtype: T
"""
if not value:
return value
if key == "loss":
# This is a special case. This is the total loss.
# Do not normalize this, as it is also used as-is for the gradient.
# You can use the `use_normalized_loss` for a flag if you want to have this normalized.
return value
loss_norm_keys = inv_loss_norm_factors.keys()
assert len(loss_norm_keys) > 0
# Assume "cost:output" or "error:output" or so.
assert ":" in key
loss_norm_key = key[key.find(":") + 1:]
assert loss_norm_key in loss_norm_keys, "unexpected key %r" % key
value = value / inv_loss_norm_factors[loss_norm_key]
return value
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 are e.g. "cost:output", "error:output" or "loss".
keys = [k for k in fetches_results.keys() if k.startswith("cost:") or k.startswith("error:") or k == "loss"]
# step_seq_lens keys are e.g. "data" or "classes".
step_seq_lens = {
k[len("size:"):-2]: numpy.sum(v)
for (k, v) in fetches_results.items()
if k.startswith("size:") and k.endswith(":0")}
# loss_norm_factors keys are e.g. "output" (layer names).
loss_norm_factors = {
k[len("loss_norm_factor:"):]: v for (k, v) in fetches_results.items() if k.startswith("loss_norm_factor:")}
inv_loss_norm_factors = NumbersDict({k: 1.0 / v for (k, v) in loss_norm_factors.items()})
# Accumulate for epoch stats.
self._results_accumulated += NumbersDict({key: fetches_results[key] for key in keys})
self._inv_norm_accumulated += inv_loss_norm_factors
self.num_frames_accumulated += NumbersDict(step_seq_lens)
# Prepare eval info stats for this batch run.
eval_info = {}
for key in keys:
value = fetches_results[key]
value = self._normalize_loss(value, key, inv_loss_norm_factors)
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 _horovod_finish_data(self):
self._horovod_signal_broadcast(have_more_data=False)
def _horovod_signal_error(self):
self._horovod_signal_broadcast(have_more_data=False, error=True)
def _horovod_signal_have_more_data(self):
"""
:return: whether to stop (because some other instance stopped), whether an error occured
:rtype: (bool, bool)
"""
return self._horovod_signal_broadcast(have_more_data=True)
def _horovod_signal_broadcast(self, have_more_data=True, error=False):
"""
:param bool have_more_data: whether we have more data in this instance
:param bool error: whether some error occured here
:return: whether to stop (because some other instance stopped), whether an error occured
:rtype: (bool, bool)
"""
if not self.engine.config.is_true("use_horovod"):
return False, False
# Stopped before? Keep in sync -> Don't send anything anymore, other peers do not expect it.
if self._horovod_stopped_runner:
return True, False
import horovod.tensorflow as hvd
from TFUtil import global_tensor
have_more_data_placeholder = global_tensor(
lambda: tf.placeholder(tf.int32, shape=(), name="horovod_have_more_data_placeholder"),
name="horovod_have_more_data_placeholder") # 0 or 1
sum_have_data_t = global_tensor(
lambda: hvd.allreduce(have_more_data_placeholder, average=False),
name="horovod_sum_have_data") # 0..size
have_error_placeholder = global_tensor(
lambda: tf.placeholder(tf.int32, shape=(), name="horovod_have_error_placeholder"),
name="horovod_have_error_placeholder") # 0 or 1
sum_have_error_t = global_tensor(
lambda: hvd.allreduce(have_error_placeholder, average=False),
name="horovod_sum_have_error") # 0..size
sum_have_data, sum_have_error = self.engine.tf_session.run(
(sum_have_data_t, sum_have_error_t),
feed_dict={
have_more_data_placeholder: 1 if have_more_data else 0,
have_error_placeholder: 1 if error else 0})
stop = False
if sum_have_data < hvd.size() or sum_have_error > 0:
# Some of the peers do not have data anymore. Or some peer had an error.
# This means we should stop. Other peers will not expect further signals.
stop = True
self._horovod_stopped_runner = True
error_occured = sum_have_error > 0
return stop, error_occured
def _horovod_sync_params(self, local_step, is_final=False):
"""
Horovod reduce type 'param', i.e. each node (rank) does update independently,
but after N steps, we average params.
:param int local_step: step of this epoch
:param bool is_final:
:return: TF runtime
:rtype: float
"""
if not self.engine.config.is_true("use_horovod"):
return 0.0
if self.engine.config.value("horovod_reduce_type", "") != "param":
return 0.0
if not self._should_train:
return 0.0
sync_step = self.engine.config.int("horovod_param_sync_step", 1)
assert sync_step >= 1
if not is_final and local_step % sync_step != sync_step - 1:
return 0.0
from TFUtil import global_tensor
import horovod.tensorflow as hvd
def assign_avg_var(var):
"""
:param tf.Variable var:
:rtype: tf.Tensor
"""
return tf.assign(var, hvd.allreduce(var.read_value(), average=True))
assign_ops = []
for var in self.engine.updater.trainable_vars:
assign_ops.append(global_tensor(
lambda: assign_avg_var(var),
name="horovod_sync_params__var_%s" % var.name[:-2].replace("/", "_")).op)
start_time = time.time()
self.engine.tf_session.run(assign_ops)
return time.time() - start_time
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()
if self.engine._do_save():
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)
hvd_stop = hvd_error = False
while self.data_provider.have_more_data(session=sess):
hvd_stop, hvd_error = self._horovod_signal_have_more_data()
if hvd_error:
raise Exception("Some other Horovod peer failed.")
if hvd_stop:
# Some other peer does not have data anymore, but no error occurred.
break
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)
elapsed_time_tf += self._horovod_sync_params(local_step=step)
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 hvd_stop and 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)
self._horovod_finish_data()
self._horovod_sync_params(local_step=step, is_final=True)
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:
# Try and ignore certain exceptions as we anyway should try to clean up as much as possible.
from Util import try_and_ignore_exception
from TFUtil import stop_event_writer_thread
try_and_ignore_exception(self._horovod_signal_error) # ignored if _horovod_finish_data was called before
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 is_gpu_available
assert len(self.devices_config) == 1, "multiple devices not supported yet for TF"
if self.is_requesting_for_gpu():
assert tf.test.is_built_with_cuda(), "You use a CPU-only TF version. Use tensorflow-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", {})
if self.is_requesting_for_gpu():
opts["device_count"].setdefault("GPU", 1)
else:
opts["device_count"].setdefault("GPU", 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 self._do_save():
return
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)
# Note that model_epoch_filename could be set but epoch could be None or 0.
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.start_epoch is used as the start epoch in training.
# If there is an existing model, it might be higher than 1.
# In that case, epoch == self.start_epoch - 1.
is_training = config.value('task', 'train') == 'train'
is_first_train_epoch = is_training and not epoch
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:
# Notes for related options:
# - import_model_train_epoch1. This however requires all params to exist in the checkpoint.
# - SubnetworkLayer also has a load_on_init option.
# - LayerBase has custom_param_importer which is quite flexible.
print("Start pre-loading weights...", file=log.v2)
for model_name, opts in sorted(self.preload_from_files.items()):
assert isinstance(opts, dict)
if opts.get("init_for_train", False):
if not is_first_train_epoch:
continue
else: # default: init for recog
if is_training:
continue
model_filename = opts['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 = opts.get('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():