Search code examples
tensorflowkeraslstmtensorflow2.0keras-layer

I'm getting "Tensor.op is meaningless when eager execution is enabled." in my simple encoder model. (TF 2.0)


The code of my encoder model is given below, I have made it using functional API(TF 2.0)

embed_obj = EndTokenLayer()
def encoder_model(inp):
  input_1 = embed_obj(inp)
  h = Masking([(lambda x: x*0)(x) for x in range(128)])(input_1)
  lstm1 , state_h, state_c = LSTM(512, return_sequences=True, return_state=True)(h)
  model = Model(inputs=input_1, outputs=[lstm1, state_h, state_c])

  return model

And when I'm calling my model:


for x,y in train.take(1):
  k = x
model = encoder_model(k)

I'm getting the following error:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-98-46e9c9596137> in <module>()
      2 for x,y in train.take(1):
      3   k = x
----> 4 model = encoder_model(k)

7 frames
/usr/local/lib/python3.6/dist-packages/tensorflow/python/framework/ops.py in op(self)
   1111   def op(self):
   1112     raise AttributeError(
-> 1113         "Tensor.op is meaningless when eager execution is enabled.")
   1114 
   1115   @property

AttributeError: Tensor.op is meaningless when eager execution is enabled.

Solution

  • In TF2, static graph (preventing eager execution with dynamic graph) can be constructed by using a decorator. Try @tf.function decorator

    @tf.function
    def encoder_model(inp):
      input_1 = embed_obj(inp)
      h = Masking([(lambda x: x*0)(x) for x in range(128)])(input_1)
      lstm1 , state_h, state_c = LSTM(512, return_sequences=True, return_state=True)(h)
      model = Model(inputs=input_1, outputs=[lstm1, state_h, state_c])
    
      return model
    

    Then call the function

    for x,y in train.take(1):
      k = x
    model = encoder_model(k)