Tensorflow:Don';如果梯度为Nan,则不更新
我有一个深度模型要在CIFAR-10上训练。训练可以很好地使用CPU。然而,当我使用GPU支持时,它会导致某些批次的梯度为NAN(我使用Tensorflow:Don';如果梯度为Nan,则不更新,tensorflow,backpropagation,Tensorflow,Backpropagation,我有一个深度模型要在CIFAR-10上训练。训练可以很好地使用CPU。然而,当我使用GPU支持时,它会导致某些批次的梯度为NAN(我使用tf.check_numerics检查它),并且它会随机发生,但时间足够早。我相信这个问题与我的GPU有关 我的问题是:如果至少有一个渐变具有NAN并强制模型继续下一批,是否有不更新的方法 编辑:也许我应该详细说明我的问题 以下是我应用渐变的方式: with tf.control_dependencies([tf.check_numerics(grad, mes
tf.check_numerics
检查它),并且它会随机发生,但时间足够早。我相信这个问题与我的GPU有关
我的问题是:如果至少有一个渐变具有NAN并强制模型继续下一批,是否有不更新的方法
编辑:也许我应该详细说明我的问题
以下是我应用渐变的方式:
with tf.control_dependencies([tf.check_numerics(grad, message='Gradient %s check failed, possible NaNs' % var.name) for grad, var in grads]):
# Apply the gradients to adjust the shared variables.
apply_gradient_op = opt.apply_gradients(grads, global_step=global_step)
我曾想过使用
tf。首先检查数值
以验证渐变中是否存在NaN,然后,如果存在NaN(检查失败),我可以在不使用opt的情况下“通过”。应用渐变
。但是,有没有一种方法可以捕获tf.control\u dependencies的错误呢?我可以找到它,尽管不是以最优雅的方式。
我的解决办法如下:
1) 首先检查所有渐变
2) 如果渐变是无NaN的,则应用它们
3) 否则,应用伪更新(使用零值),这需要渐变覆盖
这是我的代码:
首先定义自定义渐变:
@tf.RegisterGradient("ZeroGrad")
def _zero_grad(unused_op, grad):
return tf.zeros_like(grad)
然后定义一个异常处理函数:
#this is added for gradient check of NaNs
def check_numerics_with_exception(grad, var):
try:
tf.check_numerics(grad, message='Gradient %s check failed, possible NaNs' % var.name)
except:
return tf.constant(False, shape=())
else:
return tf.constant(True, shape=())
然后创建条件节点:
num_nans_grads = tf.Variable(1.0, name='num_nans_grads')
check_all_numeric_op = tf.reduce_sum(tf.cast(tf.stack([tf.logical_not(check_numerics_with_exception(grad, var)) for grad, var in grads]), dtype=tf.float32))
with tf.control_dependencies([tf.assign(num_nans_grads, check_all_numeric_op)]):
# Apply the gradients to adjust the shared variables.
def fn_true_apply_grad(grads, global_step):
apply_gradients_true = opt.apply_gradients(grads, global_step=global_step)
return apply_gradients_true
def fn_false_ignore_grad(grads, global_step):
#print('batch update ignored due to nans, fake update is applied')
g = tf.get_default_graph()
with g.gradient_override_map({"Identity": "ZeroGrad"}):
for (grad, var) in grads:
tf.assign(var, tf.identity(var, name="Identity"))
apply_gradients_false = opt.apply_gradients(grads, global_step=global_step)
return apply_gradients_false
apply_gradient_op = tf.cond(tf.equal(num_nans_grads, 0.), lambda : fn_true_apply_grad(grads, global_step), lambda : fn_false_ignore_grad(grads, global_step))