如何在张量流中追踪NaN

时间:2018-07-17 19:12:51

标签: python debugging tensorflow nan

我有一个在图像上运行的VAE。如果我使用交叉熵,L1或L2损失,那么一切都会正常进行。如果我使用MS-SSIM丢失,则在<= 128px的图像上可以正常工作,但是在> 128px的图像上得到NaN(经过几次迭代,通常在5K迭代之前)。使用L1,L2或CE丢失的任何大小的图像都不会出现问题,使用<= 128px的图像时,MS-SSIM也不会出现问题。

我的问题有两个:

  1. 在这种特殊情况下,该NaN来自何处。代码本身对我来说很安全。 (除非这是一个消失的梯度问题)。
  2. 一个人如何调试张量流中的NaN来追踪它。我看了一下调试器,但看不到怎么做

详细信息:

丢失函数的构造如下:

 if loss_fn == 0: self.gen_loss = tf.reduce_mean ( msa.tf.mmath.ce_loss(msa.tf.mmath.lmap(self.x, input_range, (0,1)), msa.tf.mmath.lmap(self.y, output_range, (0,1))) )# / data_size
 elif loss_fn == 1: self.gen_loss = self.l1_loss
 elif loss_fn == 2: self.gen_loss = self.l2_loss
 elif loss_fn == 3: self.gen_loss = 1.0 - tf.reduce_mean( msa.tf.ssim.ms_ssim(self.x, self.y) ) # see end of post for ms_ssim
 self.kl_loss = tf.reduce_mean ( msa.tf.mmath.kl_loss(self.z_mu, self.z_log_sigma_sq) )
 self.loss = kl_weight * self.kl_loss + self.gen_loss

就像我说的那样,问题仅在loss_fn == 3 时才会发生。 完整的错误在下面,但是我知道它是gen_loss,因为我可以看到它毫无预警地变成了nan_loss,有时甚至很早(在这里,是第9次迭代):

i:1 e:0.006 | gen_loss:0.9598 kl_loss:0.0000 l1_loss:0.5096 l2_loss:0.3638 loss:0.9598
i:2 e:0.011 | gen_loss:0.9582 kl_loss:0.0000 l1_loss:0.5017 l2_loss:0.3555 loss:0.9582
i:3 e:0.017 | gen_loss:0.9633 kl_loss:0.0000 l1_loss:0.5131 l2_loss:0.3693 loss:0.9633
i:4 e:0.022 | gen_loss:0.9583 kl_loss:0.0000 l1_loss:0.4945 l2_loss:0.3424 loss:0.9583
i:5 e:0.028 | gen_loss:0.9490 kl_loss:0.0000 l1_loss:0.4848 l2_loss:0.3359 loss:0.9490
i:6 e:0.033 | gen_loss:0.9493 kl_loss:0.0000 l1_loss:0.5229 l2_loss:0.3786 loss:0.9493
i:7 e:0.039 | gen_loss:0.9400 kl_loss:0.0000 l1_loss:0.4548 l2_loss:0.2993 loss:0.9400
i:8 e:0.044 | gen_loss:0.9497 kl_loss:0.0000 l1_loss:0.4968 l2_loss:0.3501 loss:0.9498
i:9 e:0.050 | gen_loss:nan kl_loss:0.0000 l1_loss:0.4854 l2_loss:0.3355 loss:nan

有趣的是-这是关键-仅在使用256x256或更大的图像时才会发生。当我使用128x128的图像时,MS-SSIM可以正常运行。我使用MS-SSIM(以及使用L1的256x256 +)以128x128训练了数以百计的模型达数月之久,而且它们都能正常工作。一旦我转到256x256(或512x512),就会发生这种情况。

我尝试过:

  • 256x256和128x128的架构完全相同
  • 不同的架构
  • 较低的学习率(使用adam时降至1e-5,对于128x128,我使用3e-4)
  • 0.5-0.9 Beta1(adam)
  • 使用1,2,3,4级的ms-ssim级别
  • 将EPS添加到任何日志,sqrt,分母等

完整错误:

InvalidArgumentError: Nan in summary histogram for: z    [[Node: z = HistogramSummary[T=DT_FLOAT,
_device="/job:localhost/replica:0/task:0/device:CPU:0"](z/tag, vae/add/_41)]]

Caused by op u'z', defined at:   File "/home/memo/anaconda2/lib/python2.7/site-packages/spyder/utils/ipython/start_kernel.py", line 227, in <module>
    main()   File "/home/memo/anaconda2/lib/python2.7/site-packages/spyder/utils/ipython/start_kernel.py", line 223, in main
    kernel.start()   File "/home/memo/anaconda2/lib/python2.7/site-packages/ipykernel/kernelapp.py", line 474, in start
    ioloop.IOLoop.instance().start()   File "/home/memo/anaconda2/lib/python2.7/site-packages/zmq/eventloop/ioloop.py", line 177, in start
    super(ZMQIOLoop, self).start()   File "/home/memo/anaconda2/lib/python2.7/site-packages/tornado/ioloop.py", line 888, in start
    handler_func(fd_obj, events)   File "/home/memo/anaconda2/lib/python2.7/site-packages/tornado/stack_context.py", line 277, in null_wrapper
    return fn(*args, **kwargs)   File "/home/memo/anaconda2/lib/python2.7/site-packages/zmq/eventloop/zmqstream.py", line 440, in _handle_events
    self._handle_recv()   File "/home/memo/anaconda2/lib/python2.7/site-packages/zmq/eventloop/zmqstream.py", line 472, in _handle_recv
    self._run_callback(callback, msg)   File "/home/memo/anaconda2/lib/python2.7/site-packages/zmq/eventloop/zmqstream.py", line 414, in _run_callback
    callback(*args, **kwargs)   File "/home/memo/anaconda2/lib/python2.7/site-packages/tornado/stack_context.py", line 277, in null_wrapper
    return fn(*args, **kwargs)   File "/home/memo/anaconda2/lib/python2.7/site-packages/ipykernel/kernelbase.py", line 276, in dispatcher
    return self.dispatch_shell(stream, msg)   File "/home/memo/anaconda2/lib/python2.7/site-packages/ipykernel/kernelbase.py", line 228, in dispatch_shell
    handler(stream, idents, msg)   File "/home/memo/anaconda2/lib/python2.7/site-packages/ipykernel/kernelbase.py", line 390, in execute_request
    user_expressions, allow_stdin)   File "/home/memo/anaconda2/lib/python2.7/site-packages/ipykernel/ipkernel.py", line 196, in do_execute
    res = shell.run_cell(code, store_history=store_history, silent=silent)   File "/home/memo/anaconda2/lib/python2.7/site-packages/ipykernel/zmqshell.py", line 501, in run_cell
    return super(ZMQInteractiveShell, self).run_cell(*args, **kwargs)   File "/home/memo/anaconda2/lib/python2.7/site-packages/IPython/core/interactiveshell.py", line 2717, in run_cell
    interactivity=interactivity, compiler=compiler, result=result)   File "/home/memo/anaconda2/lib/python2.7/site-packages/IPython/core/interactiveshell.py", line 2827, in run_ast_nodes
    if self.run_code(code, result):   File "/home/memo/anaconda2/lib/python2.7/site-packages/IPython/core/interactiveshell.py", line 2881, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)   File "<ipython-input-1-1c98e289993a>", line 1, in <module>
    runfile('/home/memo/Dropbox/research/pypackages/msa/__tests/train_autovae.py', wdir='/home/memo/Dropbox/research/pypackages/msa/__tests')   File "/home/memo/anaconda2/lib/python2.7/site-packages/spyder/utils/site/sitecustomize.py", line 866, in runfile
    execfile(filename, namespace)   File "/home/memo/anaconda2/lib/python2.7/site-packages/spyder/utils/site/sitecustomize.py", line 94, in execfile
    builtins.execfile(filename, *where)   File "/home/memo/Dropbox/research/pypackages/msa/__tests/train_autovae.py", line 88, in <module>
    adam_beta1 = a.adam_beta1,   File "/mnt/data/Dropbox/research/pypackages/msa/tf/models/autovae.py", line 385, in __init__
    if log_z: tf.summary.histogram('z', self.z)   File "/home/memo/anaconda2/lib/python2.7/site-packages/tensorflow/python/summary/summary.py", line 203, in histogram
    tag=tag, values=values, name=scope)   File "/home/memo/anaconda2/lib/python2.7/site-packages/tensorflow/python/ops/gen_logging_ops.py", line 283, in histogram_summary
    "HistogramSummary", tag=tag, values=values, name=name)   File "/home/memo/anaconda2/lib/python2.7/site-packages/tensorflow/python/framework/op_def_library.py", line 787, in _apply_op_helper
    op_def=op_def)   File "/home/memo/anaconda2/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 3392, in create_op
    op_def=op_def)   File "/home/memo/anaconda2/lib/python2.7/site-packages/tensorflow/python/framework/ops.py", line 1718, in __init__
    self._traceback = self._graph._extract_stack()  # pylint: disable=protected-access

InvalidArgumentError (see above for traceback): Nan in summary histogram for: z      [[Node: z = HistogramSummary[T=DT_FLOAT,
_device="/job:localhost/replica:0/task:0/device:CPU:0"](z/tag, vae/add/_41)]]

ms-ssim丢失的完整代码

"""
Structural Similarity index for images in tensorflow
adapted from
https://stackoverflow.com/questions/39051451/ssim-ms-ssim-for-tensorflow
"""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import tensorflow as tf
import numpy as np
import math

EPS = 1e-6

def _fspecial_gauss(size, sigma):
    """Function to mimic the 'fspecial' gaussian MATLAB function
    """
    if type(size)==int: size=(size,size)

    y_data, x_data = np.mgrid[-size[0]//2 + 1:size[0]//2 + 1, -size[1]//2 + 1:size[1]//2 + 1]

    x_data = np.expand_dims(x_data, axis=-1)
    x_data = np.expand_dims(x_data, axis=-1)

    y_data = np.expand_dims(y_data, axis=-1)
    y_data = np.expand_dims(y_data, axis=-1)

    x = tf.constant(x_data, dtype=tf.float32)
    y = tf.constant(y_data, dtype=tf.float32)

    g = tf.exp(-((x**2 + y**2)/(2.0*sigma**2)))
    return g / tf.reduce_sum(g)


def ssim(img1, img2, cs_map=False, mean_metric=True, size=11, sigma=1.5):
    # convert multichannel (e.g. RGB) images to batch
    img1 = tf.expand_dims(tf.concat(tf.unstack(img1, axis=-1), axis=0), axis=-1)
    img2 = tf.expand_dims(tf.concat(tf.unstack(img2, axis=-1), axis=0), axis=-1)

    window = _fspecial_gauss(size, sigma) # window shape [size, size, 1, 1]
    K1 = 0.01
    K2 = 0.03
    L = 1  # depth of image (255 in case the image has a differnt scale)
    C1 = (K1*L)**2
    C2 = (K2*L)**2
    mu1 = tf.nn.conv2d(img1, window, strides=[1,1,1,1], padding='VALID')
    mu2 = tf.nn.conv2d(img2, window, strides=[1,1,1,1], padding='VALID')
    mu1_sq = mu1*mu1
    mu2_sq = mu2*mu2
    mu1_mu2 = mu1*mu2
    sigma1_sq = tf.nn.conv2d(img1*img1, window, strides=[1,1,1,1], padding='VALID') - mu1_sq
    sigma2_sq = tf.nn.conv2d(img2*img2, window, strides=[1,1,1,1], padding='VALID') - mu2_sq
    sigma12 = tf.nn.conv2d(img1*img2, window, strides=[1,1,1,1], padding='VALID') - mu1_mu2

    if cs_map:
        value = (((2*mu1_mu2 + C1)*(2*sigma12 + C2))/(EPS + (mu1_sq + mu2_sq + C1) * (sigma1_sq + sigma2_sq + C2)),
                (2.0*sigma12 + C2)/(EPS + sigma1_sq + sigma2_sq + C2))
    else:
        value = ((2*mu1_mu2 + C1)*(2*sigma12 + C2))/(EPS + (mu1_sq + mu2_sq + C1) * (sigma1_sq + sigma2_sq + C2))

    if mean_metric:
        value = tf.reduce_mean(value)
    return value


def ms_ssim(img1, img2, mean_metric=True, level=None, max_level=4, size=11, sigma=1.5):
    if type(size)==int: size=(size,size)
    if level is None:
        img_shape = np.int32(img1.shape.as_list()[1:3])
        size = np.int32(size)
        size_log2 = np.log2(size)
        levels = np.int32(np.log2(img_shape) - size_log2)+1 # find levels for each
        level = min(levels[0], levels[1])
        if max_level: level = min(level, max_level)
        print('ms_ssim | levels:', levels, ', using:', level, ', smallest dims:', np.array(img_shape)//(2**(level-1)))
#    weight = tf.constant([0.0448, 0.2856, 0.3001, 0.2363, 0.1333], dtype=tf.float32)
    weight = tf.constant([1.0/level]*level, dtype=tf.float32)
    mssim = []
    mcs = []
    for l in range(level):
        ssim_map, cs_map = ssim(img1, img2, cs_map=True, mean_metric=False, size=size, sigma=sigma)
        mssim.append(tf.reduce_mean(ssim_map))
        mcs.append(tf.reduce_mean(cs_map))
        filtered_im1 = tf.nn.avg_pool(img1, [1,2,2,1], [1,2,2,1], padding='SAME')
        filtered_im2 = tf.nn.avg_pool(img2, [1,2,2,1], [1,2,2,1], padding='SAME')
        img1 = filtered_im1
        img2 = filtered_im2

    # list to tensor of dim D+1
    mssim = tf.stack(mssim, axis=0)
    mcs = tf.stack(mcs, axis=0)

    value = (tf.reduce_prod(mcs[0:level-1]**weight[0:level-1])*
                            (mssim[level-1]**weight[level-1]))

    if mean_metric:
        value = tf.reduce_mean(value)
    return value

0 个答案:

没有答案