Skip to content

CudnnLSTM doesn't work with AdamOptimizer #6620

Closed

Description

@boche

I am testing how to use CudnnLSTM, there is not a lot of documentation on this. In my own experiment, I found when use AdamOptimizer with CudnnLSTM, it always raises the following Exception.

I also found another repository using CudnnLSTM, and uploaded it here: https://github.com/boche/LM-PTB-CUDNNLSTM. It also raises the same exception.

File "ptb_word_lm.py", line 465, in main
m = PTBModel(is_training=True, config=config, debug=FLAGS.debug)
File "ptb_word_lm.py", line 254, in init
self._train_op = optimizer.apply_gradients(zip(allgrads, allvars))
File "/data/ASR1/ramons/anaconda2/envs/tensorflow/lib/python2.7/site-packages/tensorflow/python/training/optimizer.py", line 409, in apply_gradients
self._create_slots(var_list)
File "/data/ASR1/ramons/anaconda2/envs/tensorflow/lib/python2.7/site-packages/tensorflow/python/training/adam.py", line 119, in _create_slots
self._zeros_slot(v, "m", self._name)
File "/data/ASR1/ramons/anaconda2/envs/tensorflow/lib/python2.7/site-packages/tensorflow/python/training/optimizer.py", line 609, in _zeros_slot
named_slots[var] = slot_creator.create_zeros_slot(var, op_name)
File "/data/ASR1/ramons/anaconda2/envs/tensorflow/lib/python2.7/site-packages/tensorflow/python/training/slot_creator.py", line 121, in create_zeros_slot
val = array_ops.zeros(primary.get_shape().as_list(), dtype=dtype)
File "/data/ASR1/ramons/anaconda2/envs/tensorflow/lib/python2.7/site-packages/tensorflow/python/framework/tensor_shape.py", line 782, in as_list
raise ValueError("as_list() is not defined on an unknown TensorShape.")
ValueError: as_list() is not defined on an unknown TensorShape.

For now, using GradientDescentOptimizer is okay, but it seems all other fancy optimizers all have similar problems. I have looked up this problem on stackoverflow, and found a related thread: http://stackoverflow.com/questions/40698821/tensorflow-adamoptimizer-throws-error-when-variable-has-validate-shape-false .

It seems the problem is that parameter buffer used in CudnnLSTM doesn't have fixed shape (validate_shape=False, defined in line 145 of https://github.com/boche/LM-PTB-CUDNNLSTM/blob/master/ptb_word_lm.py ) , which is required by AdamOptimizer.

Cudnn seems to be faster (less time per epoch), but if we can't use better learning algorithms with it (meaning more epochs), then the total running time may not be improved so much.

Activity

  1. robotnc commented on Jan 5, 2017

    @robotnc

    I also met the problem. Now I am using a method like this: Compute the params size first , and build the cudnn_lstm model with fixed shape. It can work, but looks ugly. Hope to get a better solution.

  2. zhangyaobit commented on Jan 12, 2017

    @zhangyaobit

    @boche, yeah, you are right that CudnnLSTM doesn't have a shape known at static time, which is required by AdamOptimizer. As CuDNN manages the internal storage structure for weight and bias parameters, this shape is hardware-and-CuDNN dependent and only available at runtime. I think the solution by @robotnc is a right, natural thing to do, given the this requirement of a known shape by AdamOptimizer, and the fact that it could only be provided at runtime by CuDNN.

  3. ebrevdo commented on Apr 25, 2017

    @ebrevdo
    Contributor

    Looks like a serious issue; @zheng-xq @zhangyaobit - can we add static shape info to the parameters created by cudnn-rnn? Perhaps by exposing the cudnn library helper functions via swig? Is there a document describing how the shape varies as a fn of hardware and version?

    Alternatively can we modify the Adam optimizer to not require static shapes?

  4. ebrevdo commented on Apr 25, 2017

    @ebrevdo
    Contributor

    Following up: looking at the slot_creator code, looks like we no longer require static shapes. Can you check to see if the error still exists in the TF nightlies?

  5. alquraishi commented on Apr 25, 2017

    @alquraishi

    I just tried it with the latest nightly build and the problem is still there.

    Note that what's needed is not really the shape, but the size of the parameter buffer, since what's being passed to CudnnLSTM is just a flat 1D vector anyway. And the size should not vary from HW iteration to another (otherwise there cannot be a 'canonical' version and the whole premise of RNNParamsSaveable would be moot). Given that, it seems like a very simple solution would be to just calculate the size and return that for model.params_size(). For an LSTM it's literally just:

    params_size = ((input_size * layer_size * 4) + (layer_size * layer_size * 4) + (layer_size * 2 * 4)) * dir_count
    

    for one layer. Multiple layers would need to modify the input_size for layers > 1 to be the size of the previous layer.

  6. alquraishi commented on May 11, 2017

    @alquraishi

    Any updates on this?

  7. removed their assignment
    on Jun 21, 2017
  8. albertz commented on Jul 5, 2017

    @albertz
    Contributor

    A related issue is #5972, to be able to optimize variables with dynamic/unknown shape.

  9. dchaws commented on Aug 24, 2017

    @dchaws

    @robotnc Could you elaborate more on your workaround? Thanks!

  10. albertz commented on Aug 25, 2017

    @albertz
    Contributor

    @dchaws: When you create the variable, use the static size params_size like @alquraishi describes. That's all.

  11. 2 remaining items

  12. self-assigned this
    on Nov 2, 2017
  13. protoget commented on Nov 3, 2017

    @protoget
    Contributor

    AdamOptimizer should work with the new Cudnn layer API in cudnn_rnn.py

    We have a CL to switch tf.contrib.cudnn_rnn.CudnnLSTM to point to classes in cudnn_rnn.py instead of cudnn_rnn_ops.py, it's running a series of tests, should be submitted soon.

    The following should work with the new layer API.

      num_layers = 4
      num_units = 2
      batch_size = 8
      dir_count = 1
    
      inputs = tf.random_uniform([
          num_layers * dir_count, batch_size, num_units], dtype=tf.float32)
    
      lstm = cudnn_rnn.CudnnLSTM(num_layers, num_units,
                                 name="awesome_lstm")
    
      outputs, _ = lstm(inputs)
      loss = tf.reduce_sum(outputs)
      var = lstm.trainable_variables[0]
    
      grad = tf.gradients(loss, var)[0]
      print('grad.shape: %s' % grad.shape)
      print('var.shape: %s' % var.shape)
    
      opt = tf.train.AdamOptimizer()
      train_op = opt.apply_gradients([(grad, lstm.trainable_variables[0])])
    
      with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())
        print(sess.run(outputs))
        sess.run(train_op)
        print(sess.run(outputs))
  14. stefbraun commented on Nov 3, 2017

    @stefbraun

    @protoget what does "CL" stand for?

  15. ebrevdo commented on Nov 3, 2017

    @ebrevdo
    Contributor
  16. amitoengg commented on Nov 3, 2017

    @amitoengg

    TypeError: call() takes at least 5 arguments (2 given)
    Also , I am having difficulty figuring out the param sizes for bidirectional Cudnns. So If my expected output for a single layer bi-directional cudnnLSTM is 2*dim and input is of size [batch_size,seq_len,dim] how should i set up the h,c matrices . Is the following method correct in terms of usage. (Basically i cannot figure out the link between num_units,input_size in CudnnLSTM and in h and c matrix.

    def createCudnnLayer(batch_size, input, input_length, dim, dropout_rate,scope_name, reuse, is_training) :

    with tf.variable_scope(scope_name, reuse=reuse):
        inputs = tf.transpose(input, [1, 0, 2])
        cell = tf.contrib.cudnn_rnn.CudnnLSTM(direction='bidirectional',
                                              num_layers=1,
                                              num_units=dim*2,
                                              input_size=dim*2,
                                              dropout=dropout_rate if is_training else 0)
        params_size_t = cell.params_size()
        rnn_params = tf.get_variable(
            "cudnn_params",
            initializer=tf.random_uniform(
                [params_size_t], -0.1, 0.1),
            validate_shape=False)
        c = tf.zeros([2, batch_size, dim], tf.float32)
        h = tf.zeros([2, batch_size, dim],tf.float32)
        outputs, h, c = cell(input_data=inputs, input_h=h, input_c=c, params=rnn_params, is_training=is_training)
        outputs = tf.transpose(outputs, [1, 0, 2])
        f_rep = outputs[:, :, 0:dim]
        b_rep = outputs[:, :, dim:2*dim]
        return (f_rep,b_rep) 
    
  17. protoget commented on Nov 4, 2017

    @protoget
    Contributor

    You might be using the old cudnn_rnn "ops" API instead of the "layers" API.
    The new nightly build (tmr) should now point tf.contrib.cudnn_rnn.CuDNNLSTM to the layers API.

    With the layer API, you don't need to figure out the size yourself, the layer creates and owns the variables.

  18. amitoengg commented on Nov 5, 2017

    @amitoengg

    excellent !! Thanks it works now.

  19. yao-zhao commented on Nov 30, 2017

    @yao-zhao

    will this change be included in tf-1.5? any examples for multi gpu usage of the new CudnnLSTM?

  20. protoget commented on Nov 30, 2017

    @protoget
    Contributor

    yes it'd be included in 1.5.
    You can check cudnn_rnn_test.py.
    ptb_word_lm.py is updated but not released to the public yet.

  21. amitoengg commented on Nov 30, 2017

    @amitoengg

    Thanks again. Could you please advise on how to use CudnnLSTM trained models on cpu's at test time ? i,e how to convert Bidirectional CudnnLSTM to say Bidirectional BasicLSTM that can be used on cpus.

  22. alquraishi commented on Jan 15, 2018

    @alquraishi

    I'm no longer seeing problems with Adam, but both RMSprop and Adagrad don't appear to work with cudnnLSTM. This is the error I'm getting with RMSprop:

    Shape of a new variable (geomnet/geomnet/layer0/fw/cudnn_lstm/opaque_kernel/RMSProp/) must be fully defined, but instead was <unknown>.

    And Adagrad:

    ValueError: If initializer is a constant, do not specify shape.

    I tried steepest, momentum, adam, and adadelta and they all work.

  23. protoget commented on Jan 23, 2018

    @protoget
    Contributor

    Re @alquraishi I have a fix pending review and hopefully submit in 2 dasy.

  24. xingjinglu commented on Jan 24, 2018

    @xingjinglu

    @protoget It does need to give state_h and state_c variable for CudnnLSTM in TF 1.5?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions