Introduction to Gradients and Automatic Differentiation

View on Run in Google Colab View source on GitHub Download notebook

Automatic Differentiation and Gradients

Automatic differentiation is useful for implementing machine learning algorithms such as backpropagation for training neural networks.

In this guide, we will discuss ways you can compute gradients with TensorFlow, especially in eager execution.


import tensorflow as tf

Computing gradients

To differentiate automatically, TensorFlow needs to remember what operations happen in what order during the forward pass. Then, during the backward pass, TensorFlow traverses this list of operations in reverse order to compute gradients.

Gradient tapes

TensorFlow provides the tf.GradientTape API for automatic differentiation; that is, computing the gradient of a computation with respect to its input variables. TensorFlow "records" all operations executed inside the context of a tf.GradientTape onto a "tape". TensorFlow then uses that tape and the gradients associated with each recorded operation to compute the gradients of a "recorded" computation using reverse mode differentiation.

With scalars:

x = tf.constant(3.0)
# y = x ^ 2
with tf.GradientTape() as t:
  y = x * x
# dy = 2x
dy_dx = t.gradient(y, x)

Using matrices:

x = tf.constant([3.0, 3.0])

with tf.GradientTape() as t:
  z = tf.multiply(x, x)


# Find derivative of z with respect to the original input tensor x
print(t.gradient(z, x))
tf.Tensor([9. 9.], shape=(2,), dtype=float32)
tf.Tensor([6. 6.], shape=(2,), dtype=float32)

All operations on tf.Variable are added to the tape. To record gradients with respect to constant tensor inputs (as above), you need to add to tell the gradient tape to track the input tensor.

Intermediate results

You can also request gradients of the output with respect to intermediate values computed during a "recorded" tf.GradientTape context.

x = tf.constant([3.0, 3.0])

with tf.GradientTape() as t:
  y = tf.multiply(x, x)
  z = tf.multiply(y, y)

# Use the tape to compute the derivative of z with respect to the
# intermediate value y.
# dz_dx = 2 * y, where y = x ^ 2
print(t.gradient(z, y))
tf.Tensor([18. 18.], shape=(2,), dtype=float32)

Gradient tapes automatically watch any variable accessed within their scope. You can list them in order they are created.

x = tf.Variable(2.0)
y = tf.Variable(3.0)

with tf.GradientTape() as t:
  # Don't need any calls to watch(), as when variables x and y
  # get used, they will be automatically watched
  y_sq = y * y
  z = x + y_sq

(<tf.Variable 'Variable:0' shape=() dtype=float32, numpy=2.0>,
 <tf.Variable 'Variable:0' shape=() dtype=float32, numpy=3.0>)

By default, the resources held by a GradientTape are released as soon as GradientTape.gradient() method is called. To compute multiple gradients over the same computation, create a persistent gradient tape. This allows multiple calls to the gradient() method as resources are released when the tape object is garbage collected. For example:

x = tf.constant(3.0)
with tf.GradientTape(persistent=True) as t:
  y = x * x
  z = y * y
print(t.gradient(z, x))  # 108.0 (4*x^3 at x = 3)
print(t.gradient(y, x))  # 6.0 (2 * x)
del t  # Drop the reference to the tape
tf.Tensor(108.0, shape=(), dtype=float32)
tf.Tensor(6.0, shape=(), dtype=float32)

Notes on performance

  • There is a tiny overhead associated with doing operations inside a gradient tape context. For most eager execution this will not be a noticeable cost, but you should still use tape context around the areas only where it is required.

  • Gradient tapes use memory to store intermediate results, including inputs and outputs, for use during the backwards pass.

    For efficiency, some ops (like ReLU) don't need to keep their intermediate results and they are pruned during the forward pass. However, if you use persistent=True on your tape, nothing is discarded and your peak memory usage will be higher.

Recording control flow

Because tapes record operations as they are executed, Python control flow (using ifs and whiles for example) is naturally handled:

def f(x, y):
  output = 1.0
  for i in range(y):
    if i > 1 and i < 5:
      output *= x  # tf.multiply(output, x)
  return output

def grad(x, y):
  with tf.GradientTape() as t:
    out = f(x, y)
  return t.gradient(out, x)

x = tf.constant(2.0)

print(grad(x, 6).numpy())  # 12.0
print(grad(x, 5).numpy())  # 12.0
print(grad(x, 4).numpy())  # 4.0


Getting a gradient of None

When a gradient is not available for any reason, you will usually get a gradient of None.

A common situation is trying to get the gradient of a non-float and non-complex value.

with tf.GradientTape() as tape:
  x = tf.Variable([[2, 2], [2, 2]], dtype=tf.int8)
  y = x * x
print(tape.gradient(y, x))
WARNING:tensorflow:The dtype of the target tensor must be floating (e.g. tf.float32) when calling GradientTape.gradient, got tf.int8
WARNING:tensorflow:The dtype of the source tensor must be floating (e.g. tf.float32) when calling GradientTape.gradient, got tf.int8

In other situations, you may be doing operations that are not differentiable. DecodeJpeg, for example, does not produce a gradient. To see which operations have gradients registered for them, see the list of raw ops.

Finally, you may just be deriving gradients where there is no connection between the input and out.

x = tf.Variable(2.)
y = tf.Variable(3.)

with tf.GradientTape() as tape:
  z = y * y
print(tape.gradient(x, y))

It may be convenient to return 0 instead of None. You can decided what to return when you have unconnected gradients using the unconnected_gradient argument.

x = tf.Variable(2.)
y = tf.Variable(3.)

with tf.GradientTape() as tape:
  z = y * y
print(tape.gradient(x, y, unconnected_gradients=tf.UnconnectedGradients.ZERO))
tf.Tensor(0.0, shape=(), dtype=float32)

Custom gradients

In some cases, you may want to control exactly how gradients are calculated rather than using the default. These situations include:

  • There is no defined gradient for a new op you are writing.
  • The default calculations are numerically unstable.
  • You wish to cache an expensive computation from the forward pass.
  • You want to modify a value (for example using: tf.clip_by_value, tf.math.round) without modifying the gradient.

For writing a new op, you can use tf.RegisterGradient to set up your own. See that page for details. (Note that the gradient registry is global, so change it with caution.)

For the latter two cases, you can use tf.custom_gradient. Here is an example that applies tf.clip_by_norm to the gradient.

# Establish an identity operation, but clip during the gradient pass
def clip_gradients(y):
  def backward(dy):
    return tf.clip_by_norm(dy, 0.5)
  return y, backward

v = tf.Variable(2.0)
with tf.GradientTape() as t:
  output = clip_gradients(v * v)
print(t.gradient(output, v))  # calls "backward", which clips 4 to 2

tf.Tensor(2.0, shape=(), dtype=float32)

See the tf.custom_gradient decorator for more details.

Higher-order gradients

Operations inside of the GradientTape context manager are recorded for automatic differentiation. If gradients are computed in that context, then the gradient computation is recorded as well. As a result, the exact same API works for higher-order gradients as well. For example:

x = tf.Variable(1.0)  # Create a Tensorflow variable initialized to 1.0

with tf.GradientTape() as t:
  with tf.GradientTape() as t2:
    y = x * x * x

  # Compute the gradient inside the 't' context manager
  # which means the gradient computation is differentiable as well.
  dy_dx = t2.gradient(y, x)
d2y_dx2 = t.gradient(dy_dx, x)

print("dy_dx:", dy_dx.numpy())  # 3.0
print("d2y_dx2:", d2y_dx2.numpy())  # 6.0
dy_dx: 3.0
d2y_dx2: 6.0

Advanced features for GradientTape

In this section, we examine some less-common uses of GradientTape.

Controlling gradient recording

You can choose to only watch individual variables. To do so, you can turn off the default watching of all variables. In that case, you will be required to watch all variables manually.

x = tf.Variable(2.0)
y = tf.Variable(3.0)

with tf.GradientTape(watch_accessed_variables=False, persistent=True) as t:
  # Only watch y
  y_sq = y * y
  z = x + y_sq

# Gradient will be None, as x is not watched, so the tape cannot
# differentiate it
print("Gradient with respect to x:", t.gradient(z, x))
# Gradient will be 6, as y is watched
print("Gradient with respect to y:", t.gradient(z, y))
del t
Gradient with respect to x: None
Gradient with respect to y: tf.Tensor(6.0, shape=(), dtype=float32)

If you wish to stop recording gradients, you can use stop_recording() to temporarily suspend recording.

If you wish to start over entirely, use reset(). Simply exiting the gradient tape block and restarting is usually easier to read, but you can use reset when exiting the tape block is difficult or imnpossible.

x = tf.Variable(2.0)
y = tf.Variable(3.0)

with tf.GradientTape(persistent=True) as t:
  y_sq = y * y
  # Stop recording so we can calculate an intermediate gradient
  with t.stop_recording():
    print("y with respect to y_sq:", t.gradient(y_sq, y))  # Will be 1
  z = x + y_sq

print("z with respect to y after reset:", t.gradient(z, y))  # None
y with respect to y_sq: tf.Tensor(6.0, shape=(), dtype=float32)
z with respect to y after reset: None