Running the Tensorflow 2.0 code gives 'ValueError: tf.function-decorated function tried to create variables on non-first call'. What am I doing wrong?

Gaurav Singh picture Gaurav Singh · Oct 12, 2019 · Viewed 14.1k times · Source

error_giving_notebook

non_problematic_notebook

As it can be seen that I have used tf.function decorator in the 'error_giving_notebook' and it throws a ValueError while the same notebook without any changes except for removing the tf.function decorator runs smoothly in 'non_problematic_notebook'. What can be the reason?

Answer

Apoorv Mishra picture Apoorv Mishra · Dec 6, 2019

As you are trying to use function decorator in TF 2.0, please enable run function eagerly by using below line after importing TensorFlow:

tf.config.experimental_run_functions_eagerly(True)

Since the above is deprecated(no longer experimental?), please use the following instead:

tf.config.run_functions_eagerly(True)

If you want to know more do refer to this link.