-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtensor_tracer.py
2313 lines (2037 loc) · 96.3 KB
/
tensor_tracer.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
# Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ========================================================================
"""A utility to trace tensor values on TPU."""
import collections
import hashlib
import operator
import os
import os.path
import sys
import numpy as np
from tensorflow.core.framework import summary_pb2
from tensorflow.python.eager import monitoring
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import func_graph
from tensorflow.python.framework import function
from tensorflow.python.framework import graph_io
from tensorflow.python.framework import ops
from tensorflow.python.framework import tensor_util
from tensorflow.python.lib.io import file_io
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import array_ops_stack
from tensorflow.python.ops import cond
from tensorflow.python.ops import control_flow_case
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import control_flow_util
from tensorflow.python.ops import gen_math_ops
from tensorflow.python.ops import init_ops
from tensorflow.python.ops import linalg_ops
from tensorflow.python.ops import logging_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import nn_impl
from tensorflow.python.ops import state_ops
from tensorflow.python.ops import string_ops
from tensorflow.python.ops import summary_ops_v2 as summary
from tensorflow.python.ops import variable_scope
from tensorflow.python.platform import analytics
from tensorflow.python.platform import gfile
from tensorflow.python.platform import remote_utils
from tensorflow.python.platform import tf_logging as logging
from tensorflow.python.summary import summary_iterator
from tensorflow.python.tpu import tensor_tracer_flags
from tensorflow.python.tpu import tensor_tracer_report
from tensorflow.python.tpu import tpu_replication
from tensorflow.python.tpu.ops import tpu_ops
from tensorflow.python.training import training_util
_DEVICE_TYPE_TPU = 'tpu'
_DEVICE_TYPE_CPU = 'cpu'
_TRACE_MODE_PART_TENSOR_SIZE = 3
_REASON_OUTSIDE_OP_RANGE = 'not-traced-outside-op-range'
_REASON_UNSAFE_OP = 'not-traced-unsafe-op'
_REASON_WHILELOOP_OP = 'not-traced-special-whileloop-op'
_REASON_CONTROLFLOW_OP = 'not-traced-control-flow-op'
_REASON_IN_CONTROL_FLOW = 'not-traced-in-control-flow'
_REASON_UNSAFE_SCALAR = 'not-traced-unsafe-scalar'
_REASON_SKIP_SCALAR = 'not-traced-scalar'
_REASON_LESS_INTERESTING_OP = 'not-traced-less-interesting-op'
_REASON_DEVICE_MISMATCH = 'not-traced-device-mismatch'
_REASON_DYNAMIC_SHAPE = 'not-traced-dynamic-shape'
_REASON_SCALAR_GET_TRACED = 'traced-scalar'
_REASON_TENSOR_GET_TRACED = 'traced-tensor'
_REASON_USER_INCLUDED = 'traced-user-included'
_REASON_USER_EXCLUDED = 'not-traced-user-excluded'
_REASON_NOT_EXECUTED = 'not-traced-not-in-exec-path'
_REASON_NON_NUMERIC_TENSOR = 'not-traced-non-numeric-tensor'
_REASON_FEEDS_WHILELOOP_OP = 'not-traced-feeds-special-whileloop-op'
_OUTPUT_STREAM_ESCAPE = 'file://'
_TENSOR_TRACER_COLLECTION = 'tensor_tracer_variables'
TENSOR_TRACER_SUMMARY_COLLECTION = 'tensor_tracer_summary_writers'
_TRACE_FILE_NAME = 'trace.all'
_COMPACT_TRACE_FILE_PREFIX = 'compact_trace.'
_COMPACT_TRACE_ENTRY_INIT_VALUE = -1.0
_TENSOR_TRACER_STORAGE = 'tensor_tracer_storage'
_TT_SNAPSHOT = 'tensor_tracer_snapshot'
_REPLICA_ID_TAG = '#replica-id: '
_SKIP_REPORT_FILE = 'None' # Do not write report proto if --report_file=None
_TT_SUMMARY_NORM = tensor_tracer_flags.TT_SUMMARY_NORM
_TT_SUMMARY_MAX = tensor_tracer_flags.TT_SUMMARY_MAX
_TT_SUMMARY_MAX_ABS = tensor_tracer_flags.TT_SUMMARY_MAX_ABS
_TT_SUMMARY_MIN = tensor_tracer_flags.TT_SUMMARY_MIN
_TT_SUMMARY_MEAN = tensor_tracer_flags.TT_SUMMARY_MEAN
_TT_SUMMARY_VAR = tensor_tracer_flags.TT_SUMMARY_VAR
_TT_SUMMARY_SIZE = tensor_tracer_flags.TT_SUMMARY_SIZE
_TT_SUMMARY_SPARSITY = tensor_tracer_flags.TT_SUMMARY_SPARSITY
_TT_SUMMARY_TAG = 'tensor_tracer_summary'
_TT_TENSORBOARD_PLUGIN_NAME = 'tensor_tracer'
_TT_HOSTCALL_KEY = 'tensor_tracer_host_call'
_TT_EVENT_FILE_SUFFIX = '.tensor_tracer'
_TT_SUMMARY_MAX_QUEUE = 10
tt_gauge = monitoring.BoolGauge('/tensorflow/api/tensor_tracer/v1',
'tensor tracer usage', 'method')
def _graph_summary_tag(graph):
"""Generates and returns a summary tag name for the given graph."""
if graph is None:
raise RuntimeError('graph is None')
# The chance of collision with md5 is effectively 0.
hash_id = hashlib.md5()
hash_id.update(repr(graph).encode('utf-8'))
# hexdigest() returns a string.
return hash_id.hexdigest()
def set_parameters(tensor_tracer_params=None):
"""Enables tensor tracer and sets its parameters.
Example usage:
tensor_tracer_parameters = {'trace_dir': '/usr/tmp/trace_dir',
'trace_mode': 'norm',
'report_file': '/usr/tmp/trace_dir/report.all'}
tensor_tracer.set_parameters(tensor_tracer_parameters)
This sets up the parameters for tensor tracer. A call to tensor tracer as
below is necessary to enable debugging on CPUs and GPUs. On TPUs below can be
skipped as this call is hooked into tpu.rewrite.
tt = tensor_tracer.TensorTracer()
loss = tt.trace_cpu(tf.get_default_graph(), tensor_fetches=loss)
Args:
tensor_tracer_params: Tensor tracer parameter dictionary. Below gives
examples of these parameters: See tensor_tracer_report.py for all
parameters.
- enable: If set, tensor tracer will be enabled. Calling
enable_tensor_tracer automatically adds this parameters.
- trace_mode: The trace_mode to be used by tensor tracer. These include:
- summary: Collects multiple statistics for traced tensors, and writes
them a summary file that can be visualized using tensorboard. This
mode currently only works for TPUEstimator. It can be also be used
for other models, but outfeed must be handled by the user.
- norm: Collects norm of each traced tensor and writes them into a
text file pointed by 'trace_dir' flag. (Default mode).
- nan-inf: Checks the existince of NaNs and Infs in the tensor, and
writes a boolean value to a text file pointed by 'trace_dir' flag.
Note that 'norm' mode can also capture this information with more
numerical info.
- max-abs: Collects the absolute max for each traced tensors and
writes it into a text file pointed by 'trace_dir' flag.
- full-tensor: Writes the full tensor content of the traced tensors
into a text file pointed by 'trace_dir' flag.
- part-tensor: Writes a part of the tensor content of the traced
tensors into a text file pointed by 'trace_dir' flag.
- full_tensor_summary: Writes the full tensors as binary event files.
The outputs can be read using: trace =
tensor_tracer.read_tensor_tracer_event_file(event_file_path)
- report_file: Path to the metadata file that is written during graph
construction. If not set, metadata will be printed to stdout during
graph construction.
- trace_dir: Path where the execution traces will be written during the
graph execution. If not set, trace will be printed to stderr.
- trace_level: Tensor tracer aims to trace everything it can. This
introduces some overhead on graph execution and graph compilation
times. Using trace_level parameter, it is possible to trace operation
based on their priorities. For example, - trace_level=7 is the highest
trace_level, in which every op is traced. - trace_level=6 will skip
constant operations such as tf.constant. - trace_level=5 will skip
less important ops such as tf.identities. - The default trace_level=3,
that will skip concat ops, or random number generators. - To reduce
the graph compile time overhead, trace_level can be set to 0, that
will skip additions, and substractions, and multiplications as well.
- excluded_opnames: If set, any matching op name will not be traced.
excluded_opnames can be set as a regular expression. E.g,
excluded_opnames=.* will exclude everything.
- excluded_optypes: If set, any matching op type will not be traced.
excluded_optypes can be set as a regular expression. E.g,
excluded_optypes=.* will exclude everything. excluded_optypes=MatMul
will exclude all MatMul ops from tracing.
- included_opnames: If set, any matching op name will be forced to be
traced. included_opnames can be set as a regular expression. E.g,
'--included_opnames=some_op --excluded_opname=*.' will only trace
some_op.
- included_optypes: If set, any matching op type will be forced to be
traced. included_optypes can be set as a regular expression. E.g,
'--included_optypes=some_op_type --excluded_optypes=*.' will trace
only the ops with type 'some_op_type'
- flush_summaries: If summary mode is used, flush_summaries=1 will
flush summaries using outside compilation. Note that, if used with
low level APIs, flush_summaries=1 is necessary to obtain results.
Advanced Flags:
- trace_scalar: Scalar values are not traced by default. If this flag is
set, scalar values will also be traced.
- op_range: In the form of '%d:%d' that limits the tracing to the ops
within this limit. --op_range='5:10' will trace only the ops that have
topological order between 5-10.
- submode: 'brief' or 'detailed'. If the trace mode is not compact,
brief mode will print only the id of each traced tensor to save some
space. 'detailed' mode prints the full tensor name.
- use_fingerprint_subdirectory: The trace directory will be chosen as
using the fingerprint of the trace metadata under the provided
trace_dir.
"""
enable_flags = '--%s=1' % tensor_tracer_flags.FLAG_NAME_ENABLE
if tensor_tracer_params:
for key, value in tensor_tracer_params.items():
enable_flags += ' --%s=%s' % (key, value)
os.environ[tensor_tracer_flags.FLAGS_ENV_VAR] = enable_flags
def op_priority(op_type):
"""Returns the priority of the op.
If the priority of the op is k, it will be traced if trace_level>=k.
Args:
op_type: String name of the operation type.
Returns:
Integer value corresponding the priority of the op.
"""
if op_type in ('Const', 'Shape', 'BroadcastGradientArgs', 'Range',
'VariableShape', 'Fill', 'OneHot', 'ShapeN'):
# Lowest priority ops, e.g., constant ops across different steps,
# They will be traced only if trace_level>=7
return 7
if op_type in ('Identity', 'Cast', 'Reshape', 'ExpandDims', 'StopGradient',
'PreventGradient', 'Squeeze', 'Gather', 'GatherNd'):
# Operations without numerical effects.
# They will be only if trace_level>=6
return 6
if op_type in ('ConcatV2', 'Concat', 'StridedSlice', 'Slice', 'Pack', 'Tile',
'CollectivePermute', 'SplitV', 'DynamicPartition'):
# Operations that merge or slice an input, will be traced if trace_level>=5
return 5
if op_type in ('Pad', 'RandomUniformInt', 'GreaterEqual'):
# Operations less likely to provide useful information,
# will be traced if trace_level>=4
return 4
if op_type in ('Sum', 'AddV2', 'Add', 'AddN', 'BiasAdd', 'CrossReplicaSum'):
# Add operations that are less likely create any issues, will be traced
# if trace_level>=3 (default=3)
return 3
if op_type in ('Neg', 'Sub'):
# Sub operations that are less likely create any issues, will be traced
# trace_level>=2
return 2
if op_type in ('Mul', 'Square', 'MatMul', 'RandomUniform', 'Select',
'Maximum', 'Mean', 'Variance', 'Exp', 'Rsqrt'):
# Multiplication and some other operations, will be traced if trace_level>=1
return 1
# Unclassified op_types default to being traced at level 2 and above.
return 2
def read_tensor_tracer_event_file(event_file):
"""Reads the event file written by tensor tracer.
This can be used to read the full tensors written into binary event files by
by TensorTracer with trace_mode=full_tensor_summary.
Example usage:
result_dict_list = tensor_tracer.read_tensor_tracer_event_file(
event_file_path)
for result_dict in result_dict_list:
for step, tensor_dict in result_dict.items():
for tensor_name, full_tensor_content in tensor_dict.items():
logging.info(tensor_name, full_tensor_content)
Args:
event_file: Path to the event file that contains only tensor tracer events.
Returns:
A list of event dictionaries, each of which with the form:
{step_number: {tensor_name: tensor_content}}. This is a list instead of
a single event dictionary because it is possible that an event file may
have multiple event traces, each of them covering the same step ranges.
Raises:
ValueError: If an unexpected trace is found.
"""
# Keeps track of how many times that a step number shows up in these events.
step_occurrence_count = collections.defaultdict(int)
# List of step occurrences.
step_occurrence_list = []
for trace_event in summary_iterator.summary_iterator(event_file):
# First event is an event with file_version: "brain.Event:2"
if not trace_event.HasField('summary'):
continue
if len(trace_event.summary.value) != 1:
raise ValueError('Single step contains %d summary values,'
' expected 1.' % len(trace_event.summary.value))
step = trace_event.step
step_occurrence_count[step] += 1 # a new occurrence for this step.
occurrence_idx = step_occurrence_count[step] - 1
occurrence_size = len(step_occurrence_list)
if occurrence_idx == occurrence_size:
# This particular occurrence isn't yet recorded on step_occurrence_list.
# So append this new occurrence to the end of step_occurrence_list.
new_occurrence = collections.defaultdict(dict)
step_occurrence_list.append(new_occurrence)
else:
# This particular occurrence must be already recorded on
# step_occurrence_list (i.e. occurrence_idx < occurrence_size).
if occurrence_idx > occurrence_size:
raise ValueError('Unexpected: occurrence_idx (%d) > '
'occurrence_size (%d)' % (occurrence_idx,
occurrence_size))
tensor_value = trace_event.summary.value[0]
tensor_name = tensor_value.tag
real_shape = [d.size for d in tensor_value.tensor.tensor_shape.dim]
tensor_content = np.frombuffer(
tensor_value.tensor.tensor_content,
dtypes.DType(tensor_value.tensor.dtype).as_numpy_dtype()
).reshape(real_shape)
step_occurrence_list[occurrence_idx][step][tensor_name] = tensor_content
return step_occurrence_list
def trace_tensor(tensor, tracepoint_name=None):
"""Programmatic interface to trace a tensor with Tensor Tracer.
Tensor Tracer, by default, traces all tensors in the execution. This function
can be used to limit traced tensors. If this function is called for a subset
of the tensors, only those will be traced.
For example, Tensor Traacer will only trace c below.
c = tf.MatMul(a, b)
tensor_tracer.trace_tensor(c)
d = tf.add(c, 1)
Args:
tensor: the tensor object for which the tracing is requested.
tracepoint_name: an optional tensor tracepoint name string. A tracepoint
name is an Tensor Tracer internal name for the tensor. It is useful when
comparing equivalent traces from different models that have different
tensor namings. Equivalent tensors (with different names) can be mapped
to each other by assigning a common tracepoint_name.
Returns:
The provided tensor.
"""
if tracepoint_name is None:
tracepoint_name = tensor.name
tensor.graph.get_collection(_TENSOR_TRACER_COLLECTION)
tensor.graph.add_to_collection(_TENSOR_TRACER_COLLECTION,
(tensor, tracepoint_name))
return tensor
def keras_layer_tracepoint(layer, checkpoint_name):
"""An interface for adding the tensor outputs of a keras layer.
Encapsulates trace_tensor.
Args:
layer: A keras layer.
checkpoint_name: a string name for the checkpoint. This name has to be a
unique name if used within model comparison. The tensors that have the same
checkpoint identifier is compared in model comparison.
Returns:
The provided layer.
"""
try:
outputs = layer.output
if tensor_util.is_tf_type(outputs):
trace_tensor(outputs, '%s' % (checkpoint_name))
else:
idx = 0
for output_tensor in outputs:
if tensor_util.is_tf_type(outputs):
trace_tensor(output_tensor, '%s_%d' % (checkpoint_name, idx))
idx += 1
except AttributeError:
pass
except RuntimeError:
pass
return layer
class TensorTracer:
"""A software construct for tracing tensor values in a TF graph.
This utility is disabled by default. It is hooked into tpu.rewrite, so it can
easily be enabled on TPUs by setting the TENSOR_TRACER_FLAGS env variable as
below without a code change.
export TENSOR_TRACER_FLAGS="--enable=1"
Below is the use example to enable it on CPUs or GPUs, or for more advance use
cases on TPUs.
a = x + 1
b = a * 2
rs = tf.reduce_sum(b)
tensor_tracer.set_parameters({'trace_dir': 'path/to/trace_dir',
'report_file: 'path/to/report/file'})
tt = tensor_tracer.TensorTracer()
if on_tpu:
rs = tt.trace_tpu(tf.get_default_graph(),
tensor_fetches=rs)
else:
rs = tt.trace_cpu(tf.get_default_graph(),
tensor_fetches=rs)
session.run(rs)
If it is enabled, it will trace the output tensor values of
selected Ops in the graph. It has two outputs: (1) the traces and (2)
a report. The traces are dumped to a specified directory during the graph
execution, while the report is dumped during the graph construction.
By passing options via the env variable, users can change:
(1) the trace mode (e.g., detecting NaN/Inf, printing partial or
full tensor values)
(2) which Ops to be traced (via op.name or op.type)
(3) output trace file path.
"""
# The set of graphs that are rewritten by tensor tracer.
_traced_graphs = set()
@staticmethod
def is_enabled():
"""Returns True if TensorTracer is enabled."""
try:
enable = tensor_tracer_flags.TTParameters().is_enabled()
# Add metrics to determine API usage.
if enable: tt_gauge.get_cell('is_enabled').set(True)
return enable
except (ValueError, RuntimeError) as e:
logging.warning(
'Tensor Tracer V1 flags processing error encountered in is_enabled '
'check. %s', e)
# TODO(b/210212559): Find a more robust fix.
# Should only produce exception if Tensor Tracer is enabled.
return True
@staticmethod
def check_device_type(device_type):
"""Checks if the given device type is valid."""
if device_type not in (_DEVICE_TYPE_TPU, _DEVICE_TYPE_CPU):
raise ValueError('Invalid device_type "%s"'%device_type)
@staticmethod
def check_trace_mode(device_type, trace_mode):
"""Checks if the given trace mode work on the given device type.
Args:
device_type: Device type, TPU, GPU, CPU.
trace_mode: Tensor tracer trace mode.
Raises:
ValueError: If the given trace mode is not supported for the device.
"""
if trace_mode == tensor_tracer_flags.TRACE_MODE_FULL_TENSOR_SUMMARY:
if device_type != _DEVICE_TYPE_TPU:
raise ValueError('Device_type "%s" is not yet supported for '
'trace mode "%s"' % (device_type, trace_mode))
@staticmethod
def loop_cond_op(op):
return op.type in ('LoopCond', 'RefLoopCond')
@staticmethod
def while_loop_op(op):
"""Returns true if op is one of the special ops of in a while loop.
Args:
op: A tf.Operation.
Returns:
True if the given op is one of [Switch, Merge, Enter, Exit,
NextIteration, LoopCond], which are all building blocks for TF while
loops.
"""
return (control_flow_util.IsLoopSwitch(op) or
control_flow_util.IsLoopMerge(op) or
control_flow_util.IsLoopEnter(op) or
control_flow_util.IsLoopExit(op) or
TensorTracer.loop_cond_op(op) or
op.type in ('RefNextIteration', 'NextIteration'))
@staticmethod
def control_flow_op(op):
"""Returns true if op is one of the special ops of in a while loop.
Args:
op: A tf.Operation.
Returns:
True if the given op is one of [Switch, Merge, Enter, Exit,
NextIteration, LoopCond], which are all building blocks for TF while
loops.
"""
return (control_flow_util.IsSwitch(op) or
control_flow_util.IsMerge(op))
@staticmethod
def unsafe_op(op):
"""Returns True if this op is not safe to be traced."""
# Reasons for not including following op types:
# Assign: cause incorrect result with CPU tracing.
if op.type == 'Assign':
return True
return False
@staticmethod
def device_mismatch(device_type, op):
if device_type == _DEVICE_TYPE_TPU:
# pylint: disable=protected-access
return tpu_replication._TPU_REPLICATE_ATTR not in op.node_def.attr
# pylint: enable=protected-access
return False
@staticmethod
def unsafe_scalar_trace(op):
"""Return true if scalar output tensor from Op is not safe to be traced."""
# Tracing the following causes cycle in the graph on TPU.
if op.type in ('LoopCond', 'Enter', 'Merge', 'Const',
'Switch', 'Less', 'ReadVariableOp'):
return True
# Tracing the following will cause casting-issue
# with the norm tracing mode or other compilation issues on CPU.
if op.type in ('VarHandleOp', 'IteratorToStringHandle',
'IteratorGetNext', 'OneShotIterator',
'IteratorV2', 'MakeIterator',
'BatchDatasetV2', 'MapDataset',
'FixedLengthRecordDataset', 'TakeDataset', 'ZipDataset',
'Placeholder', 'PlaceholderWithDefault', 'StridedSlice'):
return True
return False
def _is_interesting_op(self, op):
"""Returns True if the given op is not an interesting one to be traced."""
return op_priority(op.type) <= self._parameters.trace_level
@staticmethod
def reason(op_idx, details):
"""Returns reason why the Op at op_idx is traced or not."""
return '%d %s'%(op_idx, details)
def __init__(self):
"""Initializes a TensorTracer.
Sets the various member fields from the flags (if given) or the defaults.
"""
self._replica_id = None
self._tt_config = tensor_tracer_report.TensorTracerConfig()
self._parameters = None
self._host_call_fn = {}
# _cache_variables is a dict (key = graph, value = dicts
# (key = name, value = tensors))
self._cache_variables = {}
self._history_value_cache = {}
self._traced_op_names = set()
self._report_proto = None
# _temp_cache_var is a dict (key = graph, value = [])
self._temp_cache_var = {}
self._report_proto_path = ''
self._outmost_context = None
def report_proto(self):
"""Getter for tensor_tracer.proto object for summary and full_tensor_summary modes.
Returns:
A tensor_tracer.proto object.
Raises:
ValueError if called before tracing happens, or when trace mode is not
summary or full_tensor_summary.
"""
if self._report_proto:
return self._report_proto
else:
raise ValueError('Call to report_proto must be done after tracing.'
'Report proto only exists for '
'trace_mode=[summary|full_tensor_summary]')
def report_proto_path(self):
"""Getter for path where tensor_tracer.proto object should be written.
Returns:
A string path.
"""
return self._report_proto_path
def _escape_namescopes(self, variable_name):
return variable_name.replace('/', '_').replace(':', '_')
def _cache_variable_for_graph(self, graph):
if graph not in self._cache_variables:
self._cache_variables[graph] = {}
return self._cache_variables[graph]
def _create_or_get_tensor_history_values_cache(self,
cache_name,
graph,
shape=None,
dtype=dtypes.float32):
"""Creates a variable as the cache to store historic intermediate tensor values.
Args:
cache_name: Name to be given to the cache (an instance of tf.variable).
graph: Tensorflow graph.
shape: A list of dimensions.
dtype: Data type of created cache.
Returns:
A ref to newly created or existing cache with the given dimensions.
Raises:
ValueError:
(1) If graph is None, or
(2) shape is None when a new cache needs to be created.
"""
if graph is None:
raise ValueError('Invalid graph.')
if graph not in self._history_value_cache:
self._history_value_cache[graph] = {}
if cache_name not in self._history_value_cache[graph]:
if shape is None:
raise ValueError('shape must be provided at cache creation.')
if dtype.is_integer:
init_val = int(_COMPACT_TRACE_ENTRY_INIT_VALUE)
else:
init_val = _COMPACT_TRACE_ENTRY_INIT_VALUE
# Create in proper graph and base name_scope.
with graph.as_default() as g, g.name_scope(None):
self._history_value_cache[graph][
cache_name] = variable_scope.get_variable(
'tt_history' + '_' + self._escape_namescopes(cache_name),
shape=shape,
dtype=dtype,
initializer=init_ops.constant_initializer(init_val),
trainable=False,
use_resource=True,
collections=[
_TENSOR_TRACER_STORAGE, ops.GraphKeys.LOCAL_VARIABLES
])
return self._history_value_cache[graph][cache_name]
def _create_or_get_tensor_values_cache(self, cache_name, graph,
shape=None, dtype=dtypes.float32):
"""Creates a variable as the cache to store intermediate tensor values.
Args:
cache_name: Name to be given to the cache (an instance of tf.variable).
graph: Tensorflow graph.
shape: A list of dimensions.
dtype: Data type of created cache.
Returns:
A ref to newly created or existing cache with the given dimensions.
Raises:
ValueError:
(1) If graph is None, or
(2) shape is None when a new cache needs to be created.
"""
if graph is None:
raise ValueError('Invalid graph.')
graph_cache_var = self._cache_variable_for_graph(graph)
if cache_name not in graph_cache_var:
if shape is None:
raise ValueError('shape must be provided at cache creation.')
if dtype.is_integer:
init_val = int(_COMPACT_TRACE_ENTRY_INIT_VALUE)
else:
init_val = _COMPACT_TRACE_ENTRY_INIT_VALUE
# Create in proper graph and base name_scope.
with graph.as_default() as g, g.name_scope(None):
graph_cache_var[cache_name] = variable_scope.get_variable(
_TT_SNAPSHOT + '_' + self._escape_namescopes(cache_name),
shape=shape, dtype=dtype,
initializer=init_ops.constant_initializer(init_val),
trainable=False,
use_resource=True,
collections=[_TENSOR_TRACER_STORAGE, ops.GraphKeys.LOCAL_VARIABLES])
return graph_cache_var[cache_name]
def _add_replica_id_to_graph(self):
"""Adds nodes for computing the replica ID to the graph."""
if self._tt_config.num_replicas:
with ops.control_dependencies(None):
# Uses None as dependency to run outside of TPU graph rewrites.
self._replica_id = tpu_ops.tpu_replicated_input(
list(range(self._tt_config.num_replicas)),
name='tt_replica_id')
else:
self._replica_id = 'unknown'
def _inside_op_range(self, idx):
"""Return True if the given index is inside the selected range."""
if idx < self._parameters.op_range[0]:
return False
return (self._parameters.op_range[1] < 0 or
idx <= self._parameters.op_range[1])
def _is_user_included_op(self, op):
"""Checks whether the op is included in the tensor tracer flags.
Args:
op: tf Operation
Returns:
True, if the op is included.
An op is included if:
- Its op name is given in included_opnames
- Its op type is given in included_optypes
- The op is at most _trace_ops_before_included hops before an included op
- The op is at most _trace_ops_after_included hops after an included op
"""
for opname_re in self._parameters.included_opname_re_list:
if opname_re.match(op.name):
return True
for optype_re in self._parameters.included_optype_re_list:
if optype_re.match(op.type):
return True
return False
def _is_user_excluded_op(self, op):
for opname_re in self._parameters.excluded_opname_re_list:
if opname_re.match(op.name):
return True
for optype_re in self._parameters.excluded_optype_re_list:
if optype_re.match(op.type):
return True
return False
def _signature_types(self):
"""Returns a dictionary holding the order of signatures in the cache for the selected trace mode."""
if self._parameters.trace_mode in set([
tensor_tracer_flags.TRACE_MODE_NAN_INF,
tensor_tracer_flags.TRACE_MODE_NORM,
tensor_tracer_flags.TRACE_MODE_HISTORY,
tensor_tracer_flags.TRACE_MODE_MAX_ABS]):
return {self._parameters.trace_mode: 0}
if self._parameters.trace_mode == tensor_tracer_flags.TRACE_MODE_SUMMARY:
return self._parameters.summary_signatures
return {}
def _num_signature_dimensions(self):
return len(self._signature_types())
def _use_temp_cache(self):
"""Returns true if the intermediate values should be stacked instead of being stored in a tf.Variable.
Returns:
A boolean, denoting whether to use a temporary cache or not.
"""
# If full tensors need to be stored tf.variables, then do not use temp
# variables to store them.
if self._use_tensor_buffer():
return False
if self._use_tensor_values_cache():
return self._parameters.use_temp_cache_var
else:
# Temporary caches only replaces tf.Variables caches. If no cache is used
# return False.
return False
def _use_tensor_values_cache(self):
"""Returns True if immediate tensors should be first saved to a cache."""
return self._parameters.use_compact_trace
def _use_tensor_buffer(self):
"""Returns true if the whole tensor needs to be cached/buffered in memory."""
return (self._parameters.trace_mode ==
tensor_tracer_flags.TRACE_MODE_FULL_TENSOR_SUMMARY)
def _merge_tensor_signatures(self, signatures):
"""Returns a tensor that merges the given signatures.
Args:
signatures: A dictionary of the signature updates from signature name to
a tensor of dimension [1].
Returns:
A tensor that concats the signature values in a predefined order.
Raises:
ValueError: Unable to merge signatures.
"""
sorted_update = []
if self._num_signature_dimensions() > 1:
signature_indices = self._signature_types()
for _, val in sorted(signatures.items(),
key=lambda item: signature_indices[item[0]]):
sorted_update.append(val)
updates = array_ops_stack.stack(
sorted_update, axis=0, name='merge_single_op_signatures')
elif self._num_signature_dimensions() == 1:
# Avoid stack operation if there is only a single signature.
(_, val), = signatures.items()
updates = val
else:
raise ValueError('Cannot merge 0 signatures. Check the value passed for '
'flag --signatures.')
return updates
def _save_tensor_value_to_tmp_cache(self, cache_idx, updates, graph):
"""Returns an op that will save the given updates to an entry in the cache.
Args:
cache_idx: The cache index of the tensor within the cache.
updates: A dictionary of the signature updates from signature name to
a tensor of dimension [1].
graph: A TensorFlow graph.
Raises:
RuntimeError:
(1) graph is not already in self._temp_cache_var, or
(2) cache_idx is out of range.
"""
updates = self._merge_tensor_signatures(updates)
updates = array_ops.reshape(updates,
[self._num_signature_dimensions()])
if graph not in self._temp_cache_var:
raise RuntimeError('graph is not in self._temp_cache_var')
if cache_idx >= len(self._temp_cache_var[graph]):
raise RuntimeError('cache_idx (%d) is out of range (%d)' % (
cache_idx, len(self._temp_cache_var[graph])))
self._temp_cache_var[graph][cache_idx] = updates
def _save_tensor_value_to_cache_op(self, cache_idx, updates, graph):
"""Returns an op that will save the given updates to an entry in the cache.
Args:
cache_idx: The cache index of the tensor within the cache.
updates: A dictionary of the signature updates.
graph: A TensorFlow graph.
Returns:
Cache update operation.
"""
# state_ops.scatter_update allows updates only along the first dimension.
# Make a compact array by concatenating different signatures, and update
# them all together.
updates = self._merge_tensor_signatures(updates)
updates = array_ops.reshape(updates,
[1, self._num_signature_dimensions()])
indices = constant_op.constant([cache_idx])
cache = self._create_or_get_tensor_values_cache(_TT_SUMMARY_TAG, graph)
return state_ops.scatter_update(cache, indices, updates).op
def _snapshot_tensor(self, tensor):
"""Creates a new tf.Variable and a new tf.Operation that assigns the value of the tensor to this variable.
Args:
tensor: tensor whose values will be stored in a new tf.Variable.
Returns:
An assignment operation.
"""
snapshot_variable = self._create_or_get_tensor_values_cache(
tensor.name, tensor.op.graph,
tensor.shape.as_list(), tensor.dtype)
return state_ops.assign(snapshot_variable, tensor).op
def _preprocess_traced_tensor(self, tensor):
"""Computes NAN/Norm/Max on TPUs before sending to CPU.
Args:
tensor: The tensor to be traced.
Returns:
A tensor that should be input to the trace_function.
Raises:
RuntimeError: If the signature is invalid.
"""
def _detect_nan_inf(tensor):
"""Trace function for detecting any NaN/Inf in the tensor."""
if tensor.dtype.is_floating:
mask = math_ops.reduce_any(
gen_math_ops.logical_or(
gen_math_ops.is_nan(tensor), gen_math_ops.is_inf(tensor)))
output_tensor = cond.cond(
mask,
lambda: constant_op.constant([1.0]),
lambda: constant_op.constant([0.0]))
else:
output_tensor = constant_op.constant([0.0])
return output_tensor
def _compute_signature(tensor, tf_op, cast_to_f32=True):
if cast_to_f32:
tensor = math_ops.cast(tensor, dtypes.float32)
output_tensor = tf_op(tensor)
# Return type should be scalar. Set it if it does not have the
# information.
if not output_tensor.get_shape().is_fully_defined():
output_tensor = array_ops.reshape(output_tensor, [])
return output_tensor
def _show_size(tensor):
# In order to check the size of a tensor.
# Not all sizes are known at the compile time, also, different replicas
# sometimes get different sizes of tensors.
# Collect it here to be used in merging replica data.
tsize = _compute_signature(tensor, array_ops.size, cast_to_f32=False)
# Cast to float32, so that it can be placed into same cache with other
# signatures.
return math_ops.cast(tsize, dtypes.float32)
def _show_max(tensor, cast_to_f32=True):
# returns -inf for empty tensor
return _compute_signature(tensor, math_ops.reduce_max, cast_to_f32)
def _show_min(tensor, cast_to_f32=True):
# returns inf for empty tensor
return _compute_signature(tensor, math_ops.reduce_min, cast_to_f32)
def _show_norm(tensor, cast_to_f32=True):
# returns 0 for empty tensor
return _compute_signature(tensor, linalg_ops.norm, cast_to_f32)
def _show_sparsity(tensor, cast_to_f32=True, tolerance=1e-06):
# returns nan for empty tensor and treats nans as non-zero numbers
def sparsity_fn(tensor):
non_zeros = math_ops.greater_equal(math_ops.abs(tensor), tolerance)
nans = math_ops.is_nan(tensor)
return nn_impl.zero_fraction(math_ops.logical_or(non_zeros, nans))
return _compute_signature(tensor, sparsity_fn, cast_to_f32)
def _show_mean_and_variance(tensor, cast_to_f32=True):
"""Returns the mean and variance of the given tensor."""
if cast_to_f32:
tensor = math_ops.cast(tensor, dtypes.float32)
# returns nan for empty tensor
mean, var = nn_impl.moments(array_ops.reshape(tensor, [-1]), axes=[0])
# The shape has to be 1. Set it if it does not have the information.
if not mean.get_shape().is_fully_defined():
mean = array_ops.reshape(mean, [])
if not var.get_shape().is_fully_defined():
var = array_ops.reshape(var, [])
return mean, var
def _show_max_abs(tensor, cast_to_f32=True):
return _compute_signature(
tensor, lambda t: math_ops.reduce_max(math_ops.abs(t)), cast_to_f32)
if self._parameters.trace_mode == tensor_tracer_flags.TRACE_MODE_NAN_INF:
return {self._parameters.trace_mode: _detect_nan_inf(tensor)}
if (self._parameters.trace_mode ==
tensor_tracer_flags.TRACE_MODE_PART_TENSOR):
return {self._parameters.trace_mode: tensor}
if (self._parameters.trace_mode in (
tensor_tracer_flags.TRACE_MODE_FULL_TENSOR,
tensor_tracer_flags.TRACE_MODE_FULL_TENSOR_SUMMARY)):
return {self._parameters.trace_mode: tensor}
if self._parameters.trace_mode == tensor_tracer_flags.TRACE_MODE_NORM:
return {self._parameters.trace_mode: array_ops.reshape(
_show_norm(tensor), [1])}
if self._parameters.trace_mode == tensor_tracer_flags.TRACE_MODE_HISTORY:
return {self._parameters.trace_mode: array_ops.reshape(
_show_norm(tensor), [1])}
if self._parameters.trace_mode == tensor_tracer_flags.TRACE_MODE_MAX_ABS:
return {self._parameters.trace_mode: _show_max_abs(tensor)}
if self._parameters.trace_mode == tensor_tracer_flags.TRACE_MODE_SUMMARY:
tensor = math_ops.cast(tensor, dtypes.float32)
result_dict = {}
# Call mean and variance computation here to avoid adding the same nodes
# twice.
if (_TT_SUMMARY_MEAN in self._signature_types() or
_TT_SUMMARY_VAR in self._signature_types()):
mean, variance = _show_mean_and_variance(tensor, cast_to_f32=False)
for signature_name, _ in sorted(self._signature_types().items(),
key=lambda x: x[1]):
if signature_name == _TT_SUMMARY_NORM:
signature_result_tensor = _show_norm(tensor, cast_to_f32=False)
elif signature_name == _TT_SUMMARY_MAX:
signature_result_tensor = _show_max(tensor, cast_to_f32=False)
elif signature_name == _TT_SUMMARY_MAX_ABS:
signature_result_tensor = _show_max_abs(tensor, cast_to_f32=False)
elif signature_name == _TT_SUMMARY_MIN:
signature_result_tensor = _show_min(tensor, cast_to_f32=False)
elif signature_name == _TT_SUMMARY_SPARSITY:
signature_result_tensor = _show_sparsity(tensor)