tfdbg
tfdbg的目的
由于 TensorFlow 的计算图模式,使用通用调试程序(如 Python 的 pdb)很难完成调试。
虽然这种静态图很难调试,但是因为静态计算的机制相比动态计算允许编译器进行更大程度的优化,更符合工业要求(空间、时间上考虑)。
本篇博客记录如何使用Tensorflow内置工具tfdbg进行debug。
tfdbg的介绍
tfdbg有两种debug方式进行调试程序。
- 基于命令行调试。类为
tf_debug.LocalCLIDebugWrapperSession - 图形界面调试,需要借助于
Tensorboard。类为tf_debug.TensorBoardDebugWrapperSession
详细的debug指南详见tensorflow debug官方文档。
使用Tensorboard进行图形界面调试详见The Debugger Dashboard
张量过滤器编写
使用tfdbg进行调试的时候,需要对错误进行调试。比如在训练过程中经常出现nan和inf的问题。对于这种错误我们需要进行调试。这个时候我们就需要过滤出出现inf和nan的tensor。因此调试tfdbg的代码工作就是编写这些张量过滤器
张量过滤器的签名是def function(datum, tensor) -> bool
如下是tensorflow内置的has_inf_or_nan张量过滤器,这个过滤器用来判断tensor是否包含inf和nan
其源码为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
30def has_inf_or_nan(datum, tensor):
"""A predicate for whether a tensor consists of any bad numerical values.
This predicate is common enough to merit definition in this module.
Bad numerical values include `nan`s and `inf`s.
The signature of this function follows the requirement of the method
`DebugDumpDir.find()`.
Args:
datum: (`DebugTensorDatum`) Datum metadata.
tensor: (`numpy.ndarray` or None) Value of the tensor. None represents
an uninitialized tensor.
Returns:
(`bool`) True if and only if tensor consists of any nan or inf values.
"""
_ = datum # Datum metadata is unused in this predicate.
if isinstance(tensor, InconvertibleTensorProto):
# Uninitialized tensor doesn't have bad numerical values.
# Also return False for data types that cannot be represented as numpy
# arrays.
return False
elif (np.issubdtype(tensor.dtype, np.floating) or
np.issubdtype(tensor.dtype, np.complex) or
np.issubdtype(tensor.dtype, np.integer)):
return np.any(np.isnan(tensor)) or np.any(np.isinf(tensor))
else:
return False
编写完之后需要使用sess.add_tensor_filter注册张量过滤器才可以使用
使用tfdbg调试keras
只需要修改非常少的代码,具体介绍及example可见
- https://www.tensorflow.org/guide/debugger#debugging_keras_models_with_tfdbg
- https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/debug/examples/debug_keras.py
tf.debugging
todo: 需要研究一下怎么使用
输出张量
这个类似于一般的python程序的print函数,tensorflow实现了tf.print这个函数用于打印张量。使用方式可见tensorflow输出张量。
个人觉得这个东西有点鸡肋,在使用上比较繁琐