Skip to content

Gradients do not exist for variables after tf.concat(). #37726

Closed

Description

@konopik

Tensorflow is unable to compute gradients after merging two variables with tf.concat(). The issue is demonstrated in the following colab: https://colab.research.google.com/drive/1dkCcL5jfBmo47EsvmhNumjIkCGIdeFd5

System information

  • Have I written custom code (as opposed to using a stock example script provided in TensorFlow): I have based my issue on codes composed from oficial tutorials.
  • OS Platform and Distribution (e.g.,Linux Ubuntu 16.04): Google Colab
  • TensorFlow installed from (source or binary): Binary
  • TensorFlow version (use command below): v2.1.0-0-ge5bf8de410 2.1.0
    I have tested the code also on TF 2.2 rc1.
  • Python version: 3.6.9

Describe the current behavior

Tensorflow is unable to compute gradients after merging two variables with tf.concat(). The variables are not modified during training despite setting them as trainable.

Describe the expected behavior

Tensorflow should be able to compute gradients also for concatenated variables.

Standalone code to reproduce the issue

The full test is available in Colab: colab

The most important part is the following:

class CustomEmbedding(tf.keras.layers.Layer):
  
  def __init__(self, input_dim, output_dim, mask_zero=False, **kwargs):
    super(CustomEmbedding, self).__init__(**kwargs)
    self.input_dim = input_dim
    self.output_dim = output_dim
    self.mask_zero = mask_zero
    self.embeddings = None
   
  def build(self, input_shape):
    e1 = self.add_weight(
      shape=(int(self.input_dim/2), self.output_dim),
      dtype="float32", trainable=True,
      name="e1")

    e2 = self.add_weight(
      shape=(self.input_dim-int(self.input_dim/2), self.output_dim),
      dtype="float32", trainable=True,
      name="e2")
    
    self.embeddings = tf.concat((e1, e2), 0)

    tf.print(self.embeddings)
    
  def call(self, inputs):
    return tf.nn.embedding_lookup(self.embeddings, inputs)
  
  def compute_mask(self, inputs, mask=None):
    if not self.mask_zero:
      return None
    return tf.not_equal(inputs, 0)

model = tf.keras.Sequential()
model.add(layers.Embedding(3,32,trainable=False))
model.add(layers.LSTM(32))
model.add(layers.Dense(16, "relu"))
model.add(layers.Dense(2, "softmax"))

model.compile(optimizer='adam',
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
              metrics=['accuracy'])

model.fit(data)

Other info / logs

[[-0.042568922 0.302248985 0.401204079 ... -0.204555377 0.235091716 0.257138401]
 [-0.372319102 -0.415126026 0.340110391 ... -0.386968911 -0.410127133 -0.135176718]
 [0.341201216 0.208624214 0.357687324 ... 0.0621320605 0.0829377472 0.119318634]
 [0.380090982 0.0431897044 -0.2187078 ... -0.246274695 0.0664974749 0.223051161]]
Train for 400 steps
WARNING:tensorflow:Gradients do not exist for variables ['sequential_4/custom_embedding_4/e1:0', 'sequential_4/custom_embedding_4/e2:0'] when minimizing the loss.
WARNING:tensorflow:Gradients do not exist for variables ['sequential_4/custom_embedding_4/e1:0', 'sequential_4/custom_embedding_4/e2:0'] when minimizing the loss.
400/400 [==============================] - 4s 11ms/step - loss: 0.3301 - accuracy: 1.0000
[[-0.042568922 0.302248985 0.401204079 ... -0.204555377 0.235091716 0.257138401]
 [-0.372319102 -0.415126026 0.340110391 ... -0.386968911 -0.410127133 -0.135176718]
 [0.341201216 0.208624214 0.357687324 ... 0.0621320605 0.0829377472 0.119318634]
 [0.380090982 0.0431897044 -0.2187078 ... -0.246274695 0.0664974749 0.223051161]]

Activity

  1. added
    TF 2.1
    comp:ops
    on Mar 20, 2020
  2. gadagashwini-zz commented on Mar 20, 2020

    @gadagashwini-zz
    Contributor

    @konopik, I tried to reproduce the issue on colab but getting error InvalidArgumentError: indices[0,2] = 7 is not in [0, 3) [Op:GatherV2] name: custom_embedding_1/embedding_lookup/.
    Please take a look at gist and confirm. Thanks

  3. added
    stat:awaiting response
    on Mar 20, 2020
  4. konopik commented on Mar 20, 2020

    @konopik
    Author

    Sorry for mixing two issues together. This problem is not the core of my issue. Moreover, I see that it occurs in the CPU mode only. I have removed this cell. It is not related to the problem.

    When GPU acceleration is turned only. This error is silently ignored. May be another issue?

  5. removed
    stat:awaiting response
    on Mar 22, 2020
  6. gadagashwini-zz commented on Mar 23, 2020

    @gadagashwini-zz
    Contributor

    Was able to replicate the reported issue with Tf 2.1.
    Please find the gist here. Thanks!

  7. added
    TF 2.2
    TF 2.1
    stat:awaiting tensorflower
    and removed
    TF 2.1
    on Mar 27, 2020
  8. 13 remaining items

  9. Hoimar2 commented on Apr 19, 2021

    @Hoimar2

    I have another minimal example that is similar to this:

    a = tf.Variable(3.)
    b = tf.Variable(2.)
    #remove the comment sign # to make it work
    #a = tf.Variable([3.])
    #b = tf.Variable([2.])
    with tf.GradientTape() as g:
        g.watch(a)
        g.watch(b)
        c = tf.reduce_sum(tf.concat([a , b] , axis = 0))
    print(g.gradient(c , a))
    
  10. oonisim commented on May 3, 2021

    @oonisim

    Please advise if this issue has been resolved. I am using 2.4.0 and having the issue of the tape.gradient() returns None with tf.concat().

    Tried to workaround by using tf.Variable which has the same result of tf.concat but still tape.gradient() returns None.

            _Y = tf.Variable(
                initial_value=tf.zeros(shape=tf.shape(self.Y), dtype=TYPE_NN_FLOAT),
                trainable=True
            )
            # tf.concat([_ye, _ys], axis=1)
            _Y[::, 0:1].assign(_ye)
            _Y[::, 1:].assign(_ys)
    
  11. jm-willy commented on May 5, 2021

    @jm-willy

    I absolutely needed tf.concat to experiment around, so I found this easy workaround:

    import tensorflow as tf
    
    x = tf.random.normal((1, 2))
    w1 = tf.Variable([[1.0]])
    w2 = tf.Variable([[3.0]])
    
    # jm-willy's workaround
    w = tf.Variable(tf.concat([w1, w2], 0))  # This. Replacing tf.Variable with tf.constant returns None
    y = tf.reduce_sum(x, 1)
    with tf.GradientTape() as tape:
        r = tf.matmul(w, x)
        loss = tf.metrics.mse(y, r)
    print(w)
    print(tape.gradient(loss, w))
    print('*' * 100)
    
    # acxz's workaround
    with tf.GradientTape() as tape:
        w = tf.concat([w1, w2], 0)
        y = tf.reduce_sum(x, 1)
        r = tf.matmul(w, x)
        loss = tf.metrics.mse(y, r)
    print(w)
    print(tape.gradient(loss, w))
    print('*' * 100)
    
    # Lescurel's Reproducible Example which returns None
    w = tf.concat([w1, w2], 0)
    y = tf.reduce_sum(x, 1)
    with tf.GradientTape() as tape:
        r = tf.matmul(w, x)
        loss = tf.metrics.mse(y, r)
    print(w)
    print(tape.gradient(loss, w))
    print('*' * 100)
    

    output:

    <tf.Variable 'Variable:0' shape=(2, 1) dtype=float32, numpy=
    array([[1.],
           [3.]], dtype=float32)>
    tf.Tensor(
    [[-2.203636 ]
     [ 2.7455258]], shape=(2, 1), dtype=float32)
    ****************************************************************************************************
    tf.Tensor(
    [[1.]
     [3.]], shape=(2, 1), dtype=float32)
    tf.Tensor(
    [[-2.203636 ]
     [ 2.7455258]], shape=(2, 1), dtype=float32)
    ****************************************************************************************************
    tf.Tensor(
    [[1.]
     [3.]], shape=(2, 1), dtype=float32)
    None
    ****************************************************************************************************
    

    Replacing tf.Variable with tf.constant returns None. Seems like tf.concat returns a non-trainable object and thus gradient can't flow.

    Since tf.concat is a commonly used function, I think the docs should be modified to include a temporal solution until the underlying bug is fixed.

    How is the Keras LSTM implementation able to work?. Because it uses tf.keras.concatenateor tf.concat each iteration.

    @acxz @Lescurel

  12. added
    comp:core
    and removed
    comp:ops
    on May 5, 2021
  13. saxenasaurabh commented on May 6, 2021

    @saxenasaurabh
    Member

    tf.concat on scalars is not supported, please use tf.stack for scalars instead. The fact that calling tf.concat on scalars in eager mode does not raise an error is a bug. For example:

    def f(a, b):
      return tf.concat([a , b], axis = 0)
    
    f(1., 2.)  # Works but it should not
    
    tf.function(f)(1., 2.)  # Does not work
    

    Raises:

    ValueError: Can't concatenate scalars (use tf.stack instead)

    I agree we should raise a better error message here instead of silently dropping gradients.

  14. google-ml-butler commented on May 6, 2021

    @google-ml-butler

    Are you satisfied with the resolution of your issue?
    Yes
    No

  15. jm-willy commented on May 6, 2021

    @jm-willy

    @saxenasaurabh The code above returns None for tensors w1 = tf.Variable([[1.0], [1.0]]) w2 = tf.Variable([[3.0], [3.0]]). Same with scalarsw1 = tf.Variable([[1.0]]) w2 = tf.Variable([[3.0]])

  16. bxshi commented on Jun 14, 2021

    @bxshi

    Hi @jm-willy thanks for putting together the workarounds! To make sure I understand this issue correctly, the problem is after tf.concat w1 and w2 got no gradients, right?

    In

    # jm-willy's workaround
    w = tf.Variable(tf.concat([w1, w2], 0))  # This. Replacing tf.Variable with tf.constant returns None
    y = tf.reduce_sum(x, 1)
    with tf.GradientTape() as tape:
        r = tf.matmul(w, x)
        loss = tf.metrics.mse(y, r)
    print(w)
    print(tape.gradient(loss, [w1,w2,w]))
    print('*' * 100)
    

    If I print out the gradients for w1, w2, and w using TF2.5, it shows w1 and w2 still get None as their gradients.

    [None, None, <tf.Tensor: shape=(2, 1), dtype=float32, numpy=
    array([[0.6949118],
           [3.9068654]], dtype=float32)>]
    

    whereas in acxz's workaround w1 and w2 do have gradients:

    [<tf.Tensor: shape=(1, 1), dtype=float32, numpy=array([[0.6949118]], dtype=float32)>, <tf.Tensor: shape=(1, 1), dtype=float32, numpy=array([[3.9068654]], dtype=float32)>, <tf.Tensor: shape=(2, 1), dtype=float32, numpy=
    array([[0.6949118],
           [3.9068654]], dtype=float32)>]
    

    My question is, is there any other workarounds that works without explicitly calling gradient tape? I'm using Keras model API and use fit/evaluate/etc to run the model, hence do not have direct access to gradient tapes...

  17. sylviemonet commented on Aug 17, 2021

    @sylviemonet

    Hi, if someone worked out this problem? How to get the gradients if we have lots of tf.concat in our function?

    I'm using an amount of tf.concat in my functions, and to get the gradients I've got InvalideArgumenError every time. It doesn't point out which line/concat is wrong...

    InvalidArgumentError: Determined shape must either match input shape along split_dim exactly if fully specified, or be less than the size of the input along split_dim if not fully specified. Got: 2 [Op:SplitV] name: split

    I've tried to replace all tf.concat -> tf.stack/tf.reshape, then it tunrs out another problem:

    InvalidArgumentError: Input to reshape is a tensor with 16 values, but the requested shape has 2 [Op:Reshape]

  18. joonjeon commented on Apr 18, 2022

    @joonjeon

    Hi!

    Same issue here... I am trying to re-write MAVNet (https://github.com/sudakshin/imitation_learning/blob/master/2.train_model/MavNet.py) into genuine Tensorflow (instead of TFLearn) and train it. Note that MAVNet consists of numerous tf.concat().
    For some reason, gradient flow seems to break whenever it passes tf.concat(), and the network is not trained at all.

    On the other hand, when trying to train another neural network that is similar to MAVNet but does not have such tf.concat() functions, the whole network is trained properly.

    This issue is reproduced in not only TF 2.3, but also in TF 2.8.

    I believe this is a very serious issue since, as far as this issue persists, all neural network models that rely on tf.concat, tf.keras.layers.concatenate, or tf.keras.layers.Concatenate will not be trained properly at all...

  19. sylviemonet commented on Apr 18, 2022

    @sylviemonet

    Hi, if someone worked out this problem? How to get the gradients if we have lots of tf.concat in our function?

    I'm using an amount of tf.concat in my functions, and to get the gradients I've got InvalideArgumenError every time. It doesn't point out which line/concat is wrong...

    InvalidArgumentError: Determined shape must either match input shape along split_dim exactly if fully specified, or be less than the size of the input along split_dim if not fully specified. Got: 2 [Op:SplitV] name: split

    I've tried to replace all tf.concat -> tf.stack/tf.reshape, then it tunrs out another problem:

    InvalidArgumentError: Input to reshape is a tensor with 16 values, but the requested shape has 2 [Op:Reshape]

    I've realized that my problem is not depending on the tf.concat(). I was wrongly given the shape of the gradient when I define the customer gradient.

    PS: In my opinion, because of the invisible of process inside TF, we can not really trace what happened inside TensorFlow and when something was wrong, the Error can not exactly represent the real issue. Please check again your code and the gradients you are manipulating. Make sure what the issue in your case.

  20. worthy7 commented on Oct 22, 2024

    @worthy7

    Hi I want to chime in on this issue. I wrote a custom loss function, and instead of using compile I have narrowed it down to the with tf.GradientTape process.

    Here I can see the loss, so there is no issue in calculation.
    But when tape.gradient is called, it returns None.

    
        # Iterate over the batches of the dataset.
    for step, (x_batch_train, y_batch_train) in enumerate(train_dataset):
       with tf.GradientTape() as tape:
          # Run the forward pass of the layer.
          # The operations that the layer applies
          # to its inputs are going to be recorded
          # on the GradientTape.
          y_pred = model(x_batch_train, training=True)
    
          # Compute the loss value for this minibatch.
          print("losses, mse, kloss")
          mseloss_value = keras.losses.mean_squared_error(y_batch_train, y_pred)
          print(mseloss_value.numpy())
          print(mseloss_value)
          loss_value = kloss(y_batch_train, y_pred) # 0, 3 # tf.Tensor(0.6553927, shape=(), dtype=float32)
          print(loss_value.numpy())
          print(loss_value)
    
    

    k loss

    
        def _score_loss_fixed_for_each(self, y_true, y_pred, sample_weight=None):
            y_pred = ops.convert_to_tensor(y_pred)
            y_true = ops.convert_to_tensor(y_true, dtype=y_pred.dtype)
            y_true, y_pred = squeeze_or_expand_to_same_rank(y_true, y_pred)
    
            pos_preds = tf.raw_ops.GreaterEqual(x=y_pred, y=0)
            pos_real = tf.raw_ops.GreaterEqual(x=y_true, y=0)
    
            pred_real_same = tf.raw_ops.Equal(x=pos_preds, y=pos_real)
    
            casted_pred_real_same = tf.raw_ops.Cast(
                x=pred_real_same, DstT=tf.float32)
    
            trade_value = tf.abs(
                (tf.abs(y_true) * (casted_pred_real_same-1)))
    
            meaned = ops.mean(trade_value, axis=-1)
            return meaned
    

    I changed my kloss function many times to try and narrow down the issue. If I just copy and paste mse code, it works fine. There is something really buggy happening.

    
    optimizer = keras.optimizers.Adam(learning_rate=0.0001)
    
        # Iterate over the batches of the dataset.
    for step, (x_batch_train, y_batch_train) in enumerate(train_dataset):
       with tf.GradientTape() as tape:
          # Run the forward pass of the layer.
          # The operations that the layer applies
          # to its inputs are going to be recorded
          # on the GradientTape.
          y_pred = model(x_batch_train, training=True)
    
          # Compute the loss value for this minibatch.
          print("losses, mse, kloss")
          mseloss_value = keras.losses.mean_squared_error(y_batch_train, y_pred)
          print(mseloss_value.numpy())
          print(mseloss_value)
          loss_value = kloss(y_batch_train, y_pred) # 0, 3 # tf.Tensor(0.6553927, shape=(), dtype=float32)
          print(loss_value.numpy())
          print(loss_value)
    
       # Use the gradient tape to automatically retrieve
       # the gradients of the trainable variables with respect to the loss.
       print(f"loss: {loss_value}")
       grads = tape.gradient(loss_value, model.trainable_weights)
       optimizer.apply_gradients(zip(grads, model.trainable_weights))
    
    

    recall that my print for the loss value worked. I do not know how this is printing. I am not using GPU for anything.

  21. worthy7 commented on Oct 23, 2024

    @worthy7

    Ok I fixed this eventually: all math must contain y_pred (which is tracked) or else it will start untracking.
    #61285 (comment)

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

Metadata

Metadata

Labels

TF 2.1TF 2.2comp:corestat:awaiting tensorflowertype:bug

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions