Improve error message when function local variables are GC'd.
New message: ``` ValueError: A tf.Variable created inside your tf.function has been garbage-collected. Your code needs to keep Python references to variables created inside `tf.function`s. A common way to raise this error is to create and return a variable only referenced inside your function: @tf.function def f(): v = tf.Variable(1.0) return v v = f() # Crashes with this error message! The reason this crashes is that @tf.function annotated function returns a **`tf.Tensor`** with the **value** of the variable when the function is called rather than the variable instance itself. As such there is no code holding a reference to the `v` created inside the function and Python garbage collects it. The simplest way to fix this issue is to create variables outside the function and capture them: v = tf.Variable(1.0) @tf.function def f(): return v f() # <tf.Tensor: ... numpy=1.> v.assign_add(1.) f() # <tf.Tensor: ... numpy=2.> ``` PiperOrigin-RevId: 225957777
Loading
Please sign in to comment