1# Copyright 2016 The TensorFlow Authors. All Rights Reserved.
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7#     http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14# ==============================================================================
15"""TensorFlow Debugger (tfdbg) Utilities."""
16
17from __future__ import absolute_import
18from __future__ import division
19from __future__ import print_function
20
21import re
22
23from six.moves import xrange  # pylint: disable=redefined-builtin
24
25
26def add_debug_tensor_watch(run_options,
27                           node_name,
28                           output_slot=0,
29                           debug_ops="DebugIdentity",
30                           debug_urls=None,
31                           tolerate_debug_op_creation_failures=False,
32                           global_step=-1):
33  """Add watch on a `Tensor` to `RunOptions`.
34
35  N.B.:
36    1. Under certain circumstances, the `Tensor` may not get actually watched
37      (e.g., if the node of the `Tensor` is constant-folded during runtime).
38    2. For debugging purposes, the `parallel_iteration` attribute of all
39      `tf.while_loop`s in the graph are set to 1 to prevent any node from
40      being executed multiple times concurrently. This change does not affect
41      subsequent non-debugged runs of the same `tf.while_loop`s.
42
43  Args:
44    run_options: An instance of `config_pb2.RunOptions` to be modified.
45    node_name: (`str`) name of the node to watch.
46    output_slot: (`int`) output slot index of the tensor from the watched node.
47    debug_ops: (`str` or `list` of `str`) name(s) of the debug op(s). Can be a
48      `list` of `str` or a single `str`. The latter case is equivalent to a
49      `list` of `str` with only one element.
50      For debug op types with customizable attributes, each debug op string can
51      optionally contain a list of attribute names, in the syntax of:
52        debug_op_name(attr_name_1=attr_value_1;attr_name_2=attr_value_2;...)
53    debug_urls: (`str` or `list` of `str`) URL(s) to send debug values to,
54      e.g., `file:///tmp/tfdbg_dump_1`, `grpc://localhost:12345`.
55    tolerate_debug_op_creation_failures: (`bool`) Whether to tolerate debug op
56      creation failures by not throwing exceptions.
57    global_step: (`int`) Optional global_step count for this debug tensor
58      watch.
59  """
60
61  watch_opts = run_options.debug_options.debug_tensor_watch_opts
62  run_options.debug_options.global_step = global_step
63
64  watch = watch_opts.add()
65  watch.tolerate_debug_op_creation_failures = (
66      tolerate_debug_op_creation_failures)
67  watch.node_name = node_name
68  watch.output_slot = output_slot
69
70  if isinstance(debug_ops, str):
71    debug_ops = [debug_ops]
72
73  watch.debug_ops.extend(debug_ops)
74
75  if debug_urls:
76    if isinstance(debug_urls, str):
77      debug_urls = [debug_urls]
78
79    watch.debug_urls.extend(debug_urls)
80
81
82def watch_graph(run_options,
83                graph,
84                debug_ops="DebugIdentity",
85                debug_urls=None,
86                node_name_regex_whitelist=None,
87                op_type_regex_whitelist=None,
88                tensor_dtype_regex_whitelist=None,
89                tolerate_debug_op_creation_failures=False,
90                global_step=-1,
91                reset_disk_byte_usage=False):
92  """Add debug watches to `RunOptions` for a TensorFlow graph.
93
94  To watch all `Tensor`s on the graph, let both `node_name_regex_whitelist`
95  and `op_type_regex_whitelist` be the default (`None`).
96
97  N.B.:
98    1. Under certain circumstances, the `Tensor` may not get actually watched
99      (e.g., if the node of the `Tensor` is constant-folded during runtime).
100    2. For debugging purposes, the `parallel_iteration` attribute of all
101      `tf.while_loop`s in the graph are set to 1 to prevent any node from
102      being executed multiple times concurrently. This change does not affect
103      subsequent non-debugged runs of the same `tf.while_loop`s.
104
105
106  Args:
107    run_options: An instance of `config_pb2.RunOptions` to be modified.
108    graph: An instance of `ops.Graph`.
109    debug_ops: (`str` or `list` of `str`) name(s) of the debug op(s) to use.
110    debug_urls: URLs to send debug values to. Can be a list of strings,
111      a single string, or None. The case of a single string is equivalent to
112      a list consisting of a single string, e.g., `file:///tmp/tfdbg_dump_1`,
113      `grpc://localhost:12345`.
114      For debug op types with customizable attributes, each debug op name string
115      can optionally contain a list of attribute names, in the syntax of:
116        debug_op_name(attr_name_1=attr_value_1;attr_name_2=attr_value_2;...)
117    node_name_regex_whitelist: Regular-expression whitelist for node_name,
118      e.g., `"(weight_[0-9]+|bias_.*)"`
119    op_type_regex_whitelist: Regular-expression whitelist for the op type of
120      nodes, e.g., `"(Variable|Add)"`.
121      If both `node_name_regex_whitelist` and `op_type_regex_whitelist`
122      are set, the two filtering operations will occur in a logical `AND`
123      relation. In other words, a node will be included if and only if it
124      hits both whitelists.
125    tensor_dtype_regex_whitelist: Regular-expression whitelist for Tensor
126      data type, e.g., `"^int.*"`.
127      This whitelist operates in logical `AND` relations to the two whitelists
128      above.
129    tolerate_debug_op_creation_failures: (`bool`) whether debug op creation
130      failures (e.g., due to dtype incompatibility) are to be tolerated by not
131      throwing exceptions.
132    global_step: (`int`) Optional global_step count for this debug tensor
133      watch.
134    reset_disk_byte_usage: (`bool`) whether to reset the tracked disk byte
135      usage to zero (default: `False`).
136  """
137
138  if isinstance(debug_ops, str):
139    debug_ops = [debug_ops]
140
141  node_name_pattern = (re.compile(node_name_regex_whitelist)
142                       if node_name_regex_whitelist else None)
143  op_type_pattern = (re.compile(op_type_regex_whitelist)
144                     if op_type_regex_whitelist else None)
145  tensor_dtype_pattern = (re.compile(tensor_dtype_regex_whitelist)
146                          if tensor_dtype_regex_whitelist else None)
147
148  ops = graph.get_operations()
149  for op in ops:
150    # Skip nodes without any output tensors.
151    if not op.outputs:
152      continue
153
154    node_name = op.name
155    op_type = op.type
156
157    if node_name_pattern and not node_name_pattern.match(node_name):
158      continue
159    if op_type_pattern and not op_type_pattern.match(op_type):
160      continue
161
162    for slot in xrange(len(op.outputs)):
163      if (tensor_dtype_pattern and
164          not tensor_dtype_pattern.match(op.outputs[slot].dtype.name)):
165        continue
166
167      add_debug_tensor_watch(
168          run_options,
169          node_name,
170          output_slot=slot,
171          debug_ops=debug_ops,
172          debug_urls=debug_urls,
173          tolerate_debug_op_creation_failures=(
174              tolerate_debug_op_creation_failures),
175          global_step=global_step)
176  run_options.debug_options.reset_disk_byte_usage = reset_disk_byte_usage
177
178
179def watch_graph_with_blacklists(run_options,
180                                graph,
181                                debug_ops="DebugIdentity",
182                                debug_urls=None,
183                                node_name_regex_blacklist=None,
184                                op_type_regex_blacklist=None,
185                                tensor_dtype_regex_blacklist=None,
186                                tolerate_debug_op_creation_failures=False,
187                                global_step=-1,
188                                reset_disk_byte_usage=False):
189  """Add debug tensor watches, blacklisting nodes and op types.
190
191  This is similar to `watch_graph()`, but the node names and op types are
192  blacklisted, instead of whitelisted.
193
194  N.B.:
195    1. Under certain circumstances, the `Tensor` may not get actually watched
196      (e.g., if the node of the `Tensor` is constant-folded during runtime).
197    2. For debugging purposes, the `parallel_iteration` attribute of all
198      `tf.while_loop`s in the graph are set to 1 to prevent any node from
199      being executed multiple times concurrently. This change does not affect
200      subsequent non-debugged runs of the same `tf.while_loop`s.
201
202  Args:
203    run_options: An instance of `config_pb2.RunOptions` to be modified.
204    graph: An instance of `ops.Graph`.
205    debug_ops: (`str` or `list` of `str`) name(s) of the debug op(s) to use.
206      See the documentation of `watch_graph` for more details.
207    debug_urls: URL(s) to send debug values to, e.g.,
208      `file:///tmp/tfdbg_dump_1`, `grpc://localhost:12345`.
209    node_name_regex_blacklist: Regular-expression blacklist for node_name.
210      This should be a string, e.g., `"(weight_[0-9]+|bias_.*)"`.
211    op_type_regex_blacklist: Regular-expression blacklist for the op type of
212      nodes, e.g., `"(Variable|Add)"`.
213      If both node_name_regex_blacklist and op_type_regex_blacklist
214      are set, the two filtering operations will occur in a logical `OR`
215      relation. In other words, a node will be excluded if it hits either of
216      the two blacklists; a node will be included if and only if it hits
217      neither of the blacklists.
218    tensor_dtype_regex_blacklist: Regular-expression blacklist for Tensor
219      data type, e.g., `"^int.*"`.
220      This blacklist operates in logical `OR` relations to the two whitelists
221      above.
222    tolerate_debug_op_creation_failures: (`bool`) whether debug op creation
223      failures (e.g., due to dtype incompatibility) are to be tolerated by not
224      throwing exceptions.
225    global_step: (`int`) Optional global_step count for this debug tensor
226      watch.
227    reset_disk_byte_usage: (`bool`) whether to reset the tracked disk byte
228      usage to zero (default: `False`).
229  """
230
231  if isinstance(debug_ops, str):
232    debug_ops = [debug_ops]
233
234  node_name_pattern = (re.compile(node_name_regex_blacklist) if
235                       node_name_regex_blacklist else None)
236  op_type_pattern = (re.compile(op_type_regex_blacklist) if
237                     op_type_regex_blacklist else None)
238  tensor_dtype_pattern = (re.compile(tensor_dtype_regex_blacklist) if
239                          tensor_dtype_regex_blacklist else None)
240
241  ops = graph.get_operations()
242  for op in ops:
243    # Skip nodes without any output tensors.
244    if not op.outputs:
245      continue
246
247    node_name = op.name
248    op_type = op.type
249
250    if node_name_pattern and node_name_pattern.match(node_name):
251      continue
252    if op_type_pattern and op_type_pattern.match(op_type):
253      continue
254
255    for slot in xrange(len(op.outputs)):
256      if (tensor_dtype_pattern and
257          tensor_dtype_pattern.match(op.outputs[slot].dtype.name)):
258        continue
259
260      add_debug_tensor_watch(
261          run_options,
262          node_name,
263          output_slot=slot,
264          debug_ops=debug_ops,
265          debug_urls=debug_urls,
266          tolerate_debug_op_creation_failures=(
267              tolerate_debug_op_creation_failures),
268          global_step=global_step)
269    run_options.debug_options.reset_disk_byte_usage = reset_disk_byte_usage
270