I'm trying to compute gradients with respect to some variables defined inside a loop in a tf.function, however I always get a None result. Here is a basic example replicating the problem:
@tf.function
def problem():
test = tf.constant(1.0)
with tf.GradientTape() as tape:
for i in tf.range(5):
test1 = test
tape.watch(test1)
test2 = test1
grad = tape.gradient(test2, test1)
return grad
print(problem()) #None
Of course in this particular case I don't even need the loop. However in a more general situation I would like to store the test1 variable (and possibly others) inside a TensorArray (or similar structure) during the loop, and then compute gradients with respect to those. Is this possible?