具有虚拟输入的简单模型中具有 softmax 交叉熵的 NaN

NaN with softmax cross entropy in simple model with dummy inputs

我正在简化我的模型以查看 NaN 错误发生的位置并将其缩小到我的损失函数:

import tensorflow as tf
from tensorflow.python import debug as tf_debug

def train_input_fn():
  pass


def model_fn(features, labels, mode, params):

  classes = 225
  enc = tf.ones((1,20,1024), dtype=tf.float16)
  labels = tf.ones((1,20), dtype=tf.int32)

  logits = tf.layers.dense(enc, classes)
  loss = tf.reduce_sum(tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=labels)) / 20
  train_op = tf.train.AdamOptimizer(learning_rate=0.00001, beta1=0.9, beta2=0.999).minimize(loss)

  return tf.estimator.EstimatorSpec(mode, loss=loss, train_op=train_op)


if __name__ == '__main__':

  model_directory = path/to/logdir
  hooks = [tf_debug.LocalCLIDebugHook(ui_type="readline")]

  classifier = tf.estimator.Estimator(
      model_fn=model_fn,
      model_dir=model_directory,
      params={},
  )

  classifier.train(input_fn=lambda: train_input_fn(), hooks = hooks)

在新模型目录上使用 tensorflow 调试器进行第三次或第四次 'run' 后,我得到 'NaN loss during training.'。我已经尝试将学习率设置得很低,但没有任何改变。我正在使用 tensorflow-gpu 1.8.

我试过你给的代码。我从第一步就得到了 NaN。

而且我检查了 official documentation

logits: Unscaled log probabilities of shape [d_0, d_1, ..., d_{r-1}, num_classes] and dtype float32 or float64.

enc = tf.ones((1,20,1024), dtype=tf.float16) 更改为 enc = tf.ones((1,20,1024), dtype=tf.float32) 并且成功了!

将 tf.float16 用于 Adam 优化变量使得有必要使用更高的 epsilon 值来实现数值稳定性。当我添加 epsilon=1e-04 (标准是 1e-08)到 Adam 优化器,它对我有用。