Computing gradients in AutoGraph

Hey, all. I’m in the process of getting familiar with TF’s autograph — the series of posts by @pgaleone were super helpful.

If I want to compute and return gradients inside the graph definition using the tf.function decorator, is using tf.GradientTape a sensible approach for TF 2? This is what I have so far for the simple graph illustrated below:

def create_graph(x, y, get_grads):
  with tf.GradientTape(persistent=True) as tape:
    c = x + y
    d = y + 1
    e = c * d 
  if get_grads == False:
    return [e, {}]
    de_da = tape.gradient(e, x)
    de_db = tape.gradient(e, y)
    de_dc = tape.gradient(e, c)
    de_dd = tape.gradient(e, d)
    de_de = tape.gradient(e, e)    
    return [e,{'d_da':de_da, 
graph = tf.function(create_graph)

1 Like