Skip to content

Tensorflow crashed when using AdamOptimizer #323

Closed

Description

@chuanwen

I tried the cnn in the tutorial for MNIST data, but initialize the parameters with stddev=1 (instead of stddev=0.1).

Error message:
I tensorflow/core/common_runtime/local_device.cc:25] Local device intra op parallelism threads: 4
I tensorflow/core/common_runtime/local_session.cc:45] Local session inter op parallelism threads: 4
0 0.098
W tensorflow/core/common_runtime/executor.cc:1027] 0x4472710 Compute status: Invalid argument: ReluGrad input is not finite. : Tensor had NaN values
[[Node: gradients/Relu_grad/Relu/CheckNumerics = CheckNumericsT=DT_FLOAT, message="ReluGrad input is not finite.", _device="/job:localhost/replica:0/task:0/cpu:0"]]
W tensorflow/core/common_runtime/executor.cc:1027] 0x4472710 Compute status: Invalid argument: ReluGrad input is not finite. : Tensor had NaN values
[[Node: gradients/Relu_1_grad/Relu_1/CheckNumerics = CheckNumericsT=DT_FLOAT, message="ReluGrad input is not finite.", _device="/job:localhost/replica:0/task:0/cpu:0"]]
W tensorflow/core/common_runtime/executor.cc:1027] 0x4472710 Compute status: Invalid argument: ReluGrad input is not finite. : Tensor had NaN values
[[Node: gradients/Relu_2_grad/Relu_2/CheckNumerics = CheckNumericsT=DT_FLOAT, message="ReluGrad input is not finite.", _device="/job:localhost/replica:0/task:0/cpu:0"]]
Traceback (most recent call last):
File "2_cnn.py", line 67, in
session.run(train_step, feed_dict={X: x, Y: y, keep_prob: 0.5})
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 345, in run
results = self._do_run(target_list, unique_fetch_targets, feed_dict_string)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 419, in _do_run
e.code)
tensorflow.python.framework.errors.InvalidArgumentError: ReluGrad input is not finite. : Tensor had NaN values
[[Node: gradients/Relu_grad/Relu/CheckNumerics = CheckNumericsT=DT_FLOAT, message="ReluGrad input is not finite.", _device="/job:localhost/replica:0/task:0/cpu:0"]]
Caused by op u'gradients/Relu_grad/Relu/CheckNumerics', defined at:
File "2_cnn.py", line 55, in
train_step = tf.train.AdamOptimizer().minimize(loss)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/training/optimizer.py", line 165, in minimize
gate_gradients=gate_gradients)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/training/optimizer.py", line 205, in compute_gradients
loss, var_list, gate_gradients=(gate_gradients == Optimizer.GATE_OP))
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/gradients.py", line 414, in gradients
in_grads = _AsList(grad_fn(op_wrapper, *out_grads))
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/nn_grad.py", line 107, in _ReluGrad
t = _VerifyTensor(op.inputs[0], op.name, "ReluGrad input is not finite.")
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/nn_grad.py", line 100, in _VerifyTensor
verify_input = array_ops.check_numerics(t, message=msg)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/gen_array_ops.py", line 48, in check_numerics
name=name)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/op_def_library.py", line 633, in apply_op
op_def=op_def)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 1710, in create_op
original_op=self._default_original_op, op_def=op_def)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 988, in init
self._traceback = _extract_stack()

...which was originally created as op u'Relu', defined at:
File "2_cnn.py", line 32, in
h_conv1 = tf.nn.relu(conv2d(X1, w_conv1) + b_conv1)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/gen_nn_ops.py", line 506, in relu
return _op_def_lib.apply_op("Relu", features=features, name=name)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/op_def_library.py", line 633, in apply_op
op_def=op_def)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 1710, in create_op
original_op=self._default_original_op, op_def=op_def)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 988, in init
self._traceback = _extract_stack()

Activity

  1. rafaljozefowicz commented on Nov 22, 2015

    @rafaljozefowicz

    Your weights are likely diverging. Try reducing the learning rate and/or revert your initialization change.

  2. chuanwen commented on Nov 22, 2015

    @chuanwen
    Author

    it also crashed when I did following:

    • same weight initialization as the tutorial
    • change full_connect to 512 units
    • change batch_size to 200

    Training crashed say, at step 3500 (when accuracy is near 99.2%).

  3. vincentvanhoucke commented on Nov 24, 2015

    @vincentvanhoucke
    Contributor

    Consider increasing the epsilon value of the optimizer.

  4. jpiabrantes commented on Nov 24, 2015

    @jpiabrantes

    I am getting the same error on my Neural Network. I get this error when using AdagradOptimizer, AdamOptimizer, MomentumOptimizer and even GradientDescentOptimizer. The error happens after the first epoch so the algorithm was already trained with each minibatch at least once. The function I am minimizing is the Root Mean Square error of the output of the networks with the labels.

    I am logging the weights max and min and they are between -1 and 1 until the error is raised. If I use a sigmoid activation function the weights will be between -1 and 1 until they get nan values. I have no idea of why this is happening, how can I debug it?

  5. vincentvanhoucke commented on Nov 24, 2015

    @vincentvanhoucke
    Contributor

    One thing you can do is run with a tiny learning rate, or even zero learning rate. If you still have divergence then, you have a bug in your setup. If not, increase your rate slowly and see if there is a regime in which things train without diverging. It's completely possible to have weights that are in a good range, but activations or gradients going to infinity because of the shape of the loss, or too high a learning rate. It's obviously always a possibility that there is a bug in the optimizers, but in my experience, every single instance of this kind of problem could be traced back to a weirdly wired model, learning rate issues, bad randomization of the input examples, or - in the case of Adam or RMSProp - issues with the epsilon value.

  6. delip commented on Nov 24, 2015

    @delip

    OP: it might help if you can paste your entire code in a gist and report it
    here.

    On Tuesday, November 24, 2015, Vincent Vanhoucke [email protected]
    wrote:

    One thing you can do is run with a tiny learning rate, or even zero
    learning rate. If you still have divergence then, you have a bug in your
    setup. If not, increase your rate slowly and see if there is a regime in
    which things train without diverging. It's completely possible to have
    weights that are in a good range, but activations or gradients going to
    infinity because of the shape of the loss, or too high a learning rate.
    It's obviously always a possibility that there is a bug in the optimizers,
    but in my experience, every single instance of this kind of problem could
    be traced back to a weirdly wired model, learning rate issues, bad
    randomization of the input examples, or - in the case of Adam or RMSProp -
    issues with the epsilon value.

    —
    Reply to this email directly or view it on GitHub
    #323 (comment)
    .

  7. jpiabrantes commented on Nov 24, 2015

    @jpiabrantes

    @vincentvanhoucke Thank you for your help. I tried to debug it following your advices:

    I ran the algorithm with learning_rate = 0. Didn't raise any error.
    I then tried to run the algorithm with different learning rates (lr) and obtained the following results:

    lr_results

    All the learning rates, but the lr = 1E-8, made the program raise the error. The learning rate 1E-8 didn't learn anything.

    Basically I have a neural network with one hidden layer:

    def model(data, train=False):
        hidden = tf.nn.relu(tf.matmul(data, fc1_weights) + fc1_biases)
        return tf.matmul(hidden, fc2_weights) + fc2_biases

    And a RMS loss function to optimize:

    train_prediction = model(train_data_node, True)
    loss = tf.reduce_mean(tf.sqrt(tf.pow(((tf.sub(train_prediction,train_labels_node))),2)),name='RMS')
    batch_index = tf.Variable(0)
    learning_rate = tf.train.exponential_decay(
          1E-8,                # Base learning rate.
          batch_index * BATCH_SIZE,  # Current index into the dataset.
          train_size,          # Decay step.
          0.95,                # Decay rate.
          staircase=True)
    optimizer = tf.train.MomentumOptimizer(learning_rate,0.9).minimize(loss, global_step=batch_index) 

    My full code is here: gist .
    If you want to run it you will also need the data that is [here](/home/joao/Dropbox/data analysis/rossman/results/results1/nn_train.dat
    /home/joao/Dropbox/data analysis/rossman/results/results1/nn_val.dat) and here.

  8. vincentvanhoucke commented on Nov 24, 2015

    @vincentvanhoucke
    Contributor

    @jpiabrantes One thing that stands out here is that you use a square root in your loss. That's known to be very unstable numerically for very small values. Can you try 1) not taking the square root or 2) adding a small constant, e.g.: tf.sqrt(1e-4 + ...).
    If that's indeed the problem, then one possible approach we can provide tooling around is to optionally cap the gradient of the sqrt function, because it's a common use case. Another possibility is to use gradient clipping in general (see: clip_by_norm(), which we should provide better examples for).
    Let me know what happens.

    The other avenue is to tune your learning rate decay. Gradients tend to paradoxically grow in magnitude as training progresses, and sometimes that introduces numerical issues late in training. It is still possible that we have issues with numerical precision somewhere, but my hunch is that these errors are legitimate divergence issues (for some twisted definition of 'legitimate').

  9. jpiabrantes commented on Nov 25, 2015

    @jpiabrantes

    @vincentvanhoucke You were right. My problem was due to the loss function being RMS. If I use the loss functions you proposed everything works fine. Thank you for the help.

  10. navraj28 commented on Dec 3, 2015

    @navraj28

    @vincentvanhoucke: I copied the MNIST Conv Net. Since, I have just a handful of images, each Batch is applying some random changes to the images. Code snippet below. The first iteration is successful. 2nd one gives the above error.

    def preprocessImages(x):
        retValue = numpy.empty_like(x)
        for i in range(len(data)):
        image = x[i]
        image = tf.reshape(image, [388,190,1])
        image = tf.image.random_brightness(image, max_delta=63)
        # Subtract off the mean and divide by the variance of the pixels.
        float_image = tf.image.per_image_whitening(image)
        float_image_Mat = sess.run(float_image)
        retValue[i] = float_image_Mat.reshape((388*190))
    return retValue
    
    for i in range(500):
        feed_dict={x: preprocessImages(data), y_: labelsAsOneHotVector, keep_prob: 0.5}
        train_step.run(feed_dict)
        if i%100 == 0:
            train_accuracy = accuracy.eval(feed_dict)
            print("step %d, training accuracy %g"%(i, train_accuracy))
    

    First iteration works fine!

    step 0, training accuracy 0.680851
    W tensorflow/core/common_runtime/executor.cc:1027] 0x2a1a82e0 Compute status: Invalid     argument: ReluGrad input is not finite. : Tensor had NaN values
    
  11. vincentvanhoucke commented on Dec 3, 2015

    @vincentvanhoucke
    Contributor

    @navraj28 diverging when you use SGD can happen for many reasons:

    • your learning rate is too high. Note that the right learning rate can be data dependent.
    • your input data is not well randomized, or highly redundant, which could happen if you're just feeding the same data with few distortions.
      This bug is about the AdamOptimizer. I am going to close it. Feel free to reopen if you have new evidence of a bug.
  12. lightscalar commented on Dec 17, 2015

    @lightscalar
  13. nate331 commented on Dec 17, 2015

    @nate331

    @lightscalar that solved it for me. Thx.

  14. Muaazbinsaeed commented on Dec 18, 2015

    @Muaazbinsaeed

    Thanx lightscalar

  15. Muaazbinsaeed commented on Dec 18, 2015

    @Muaazbinsaeed

    cross_entropy = -tf.reduce_sum(y*tf.log(yconv+ 1e-9))

    This works fine

  16. zh4ngx commented on Dec 31, 2015

    @zh4ngx

    @lightscalar @Muaazbinsaeed Nice - I was stuck on this for awhile and convinced that my activations/weights were somehow exploding.

  17. washt commented on Jan 28, 2016

    @washt

    Thanks @lightscalar, that fixed the issue for me too!!

  18. julienroyd commented on Mar 1, 2016

    @julienroyd

    I had exactly the same problem and you fixed the issue for me too! Thanks @lightscalar !!

  19. darolt commented on Apr 19, 2016

    @darolt
  20. NickShahML commented on Jun 3, 2016

    @NickShahML

    @lightscalar big thanks

  21. edgarriba commented on Jan 16, 2017

    @edgarriba

    @vincentvanhoucke Is there any improvement regarding numerical precisions for tf.sqrt() with last versions? Running v0.12 and still getting the mentioned issue.

  22. yaroslavvb commented on Jan 16, 2017

    @yaroslavvb
    Contributor

    @edgarriba that's not an issue with precision of tf.sqrt -- square root operation in general is unstable for small values. The bigger underlying issue is that SGD-like algorithms are fundamentally unstable and can produce NaN/Infinity during normal functioning. A stable algorithm would need to do some sanity checks before taking a step, and none of the tf built-in optimizers are doing that.

  23. edgarriba commented on Jan 16, 2017

    @edgarriba

    @yanchen036 oh I see, thanks to clarify! I hope this feature comes some day since sometimes find such errors during the training is a bit painful.

  24. yaroslavvb commented on Jan 16, 2017

    @yaroslavvb
    Contributor

    We use an optimizer that does a line-search at each step, that makes things more predictable

  25. edgarriba commented on Jan 16, 2017

    @edgarriba

    Is it an internal code or is already part of TF?

  26. yaroslavvb commented on Jan 16, 2017

    @yaroslavvb
    Contributor

    Sorry, by "we" I meant OpenAI, not Google, and we'll be open-sourcing our optimization code soon. However, its tailored for RL problems rather than a generic optimizer. You can use l-BFGS optimizer through the scipy optimizer interface, that one is supposed to be stable, although you incur some extra overhead in transferring data between TF and scipy

  27. yzcjtr commented on Oct 18, 2017

    @yzcjtr

    I've come across a similar bug during calculating the L2 norm along a certain dimension of a feature map. The gradients no longer explode after I added small values(1e-10) elementwise to that feature map. Hope this could help someone.

  28. added a commit that references this issue on Jan 23, 2020
  29. added a commit that references this issue on May 15, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions