Run this notebook online:Binder or Colab: Colab

2.5. Automatic Differentiation

As we have explained in Section 2.4, differentiation is a crucial step in nearly all deep learning optimization algorithms. While the calculations for taking these derivatives are straightforward, requiring only some basic calculus, for complex models, working out the updates by hand can be a pain (and often error-prone).

Deep learning frameworks expedite this work by automatically calculating derivatives, i.e., automatic differentiation. In practice, based on our designed model the system builds a computational graph, tracking which data combined through which operations to produce the output. Automatic differentiation enables the system to subsequently backpropagate gradients. Here, backpropagate simply means to trace through the computational graph, filling in the partial derivatives with respect to each parameter.

%mavenRepo snapshots

%maven ai.djl:api:0.10.0-SNAPSHOT
%maven org.slf4j:slf4j-api:1.7.26
%maven org.slf4j:slf4j-simple:1.7.26

%maven ai.djl.mxnet:mxnet-engine:0.10.0-SNAPSHOT
%maven ai.djl.mxnet:mxnet-native-auto:1.7.0-backport
import ai.djl.ndarray.*;
import ai.djl.engine.Engine;
import ai.djl.ndarray.types.*;
%load ../utils/
NDManager manager = NDManager.newBaseManager();

2.5.1. A Simple Example

As a toy example, say that we are interested in differentiating the function \(y = 2\mathbf{x}^{\top}\mathbf{x}\) with respect to the column vector \(\mathbf{x}\). To start, let us create the variable x and assign it an initial value.

NDArray x = manager.arange(4f);
ND: (4) gpu(0) float32
[0., 1., 2., 3.]

Before we even calculate the gradient of \(y\) with respect to \(\mathbf{x}\), we will need a place to store it. It is important that we do not allocate new memory every time we take a derivative with respect to a parameter because we will often update the same parameters thousands or millions of times and could quickly run out of memory. Note that a gradient of a scalar-valued function with respect to a vector \(\mathbf{x}\) is itself vector-valued and has the same shape as \(\mathbf{x}\).

// We allocate memory for a NDArrays's gradient by invoking `attachGradient`
// After we calculate a gradient taken with respect to `x`, we will be able to
// access it via the `getGradient` attribute, whose values are initialized with 0s
ND: (4) gpu(0) float32
[0., 0., 0., 0.]

We place our code inside a try-with-resources and declare the GradientCollector object that will build the computational graph. Now let us calculate \(y\).

Since x is a vector of length 4, an inner product of x and x is performed, yielding the scalar output that we assign to y. Next, we can automatically calculate the gradient of y with respect to each component of x by calling the function for backpropagation and printing the gradient.

try (GradientCollector gc = Engine.getInstance().newGradientCollector()) {
    NDArray y =;
ND: () gpu(0) float32
ND: (4) gpu(0) float32
[ 0.,  4.,  8., 12.]

The gradient of the function \(y = 2\mathbf{x}^{\top}\mathbf{x}\) with respect to \(\mathbf{x}\) should be \(4\mathbf{x}\). Let us quickly verify that our desired gradient was calculated correctly.

ND: (4) gpu(0) boolean
[ true,  true,  true,  true]

Now let us calculate another function of x.

try (GradientCollector gc = Engine.getInstance().newGradientCollector()) {
    NDArray y = x.sum();
x.getGradient() // Overwritten by the newly calculated gradient
ND: (4) gpu(0) float32
[1., 1., 1., 1.]

2.5.2. Backward for Non-Scalar Variables

Technically, when y is not a scalar, the most natural interpretation of the differentiation of a vector y with respect to a vector x is a matrix. For higher-order and higher-dimensional y and x, the differentiation result could be a high-order tensor.

However, while these more exotic objects do show up in advanced machine learning (including in deep learning), more often when we are calling backward on a vector, we are trying to calculate the derivatives of the loss functions for each constituent of a batch of training examples. Here, our intent is not to calculate the differentiation matrix but rather the sum of the partial derivatives computed individually for each example in the batch.

// When we invoke `backward` on a vector-valued variable `y` (function of `x`),
// a new scalar variable is created by summing the elements in `y`. Then the
// gradient of that scalar variable with respect to `x` is computed
try (GradientCollector gc = Engine.getInstance().newGradientCollector()) {
    NDArray y = x.mul(x); // y is a vector
x.getGradient() // Overwritten by the newly calculated gradient
ND: (4) gpu(0) float32
[0., 2., 4., 6.]

2.5.3. Detaching Computation

Sometimes, we wish to move some calculations outside of the recorded computational graph. For example, say that y was calculated as a function of x, and that subsequently z was calculated as a function of both y and x. Now, imagine that we wanted to calculate the gradient of z with respect to x, but wanted for some reason to treat y as a constant, and only take into account the role that x played after y was calculated.

Here, we can detach y using stopGradient to return a new variable u that has the same value as y but discards any information about how y was computed in the computational graph. In other words, the gradient will not flow backwards through u to x. Thus, the following backpropagation function computes the partial derivative of z = u * x with respect to x while treating u as a constant, instead of the partial derivative of z = x * x * x with respect to x.

try (GradientCollector gc = Engine.getInstance().newGradientCollector()) {
    NDArray y = x.mul(x);
    NDArray u = y.stopGradient();
    NDArray z = u.mul(x);
ND: (4) gpu(0) boolean
[ true,  true,  true,  true]

We can subsequently invoke backpropagation on y to get the derivative of y = x * x with respect to x, which is 2 * x.

try (GradientCollector gc = Engine.getInstance().newGradientCollector()) {
    NDArray y = x.mul(x);
    y = x.mul(x);
ND: (4) gpu(0) boolean
[ true,  true,  true,  true]

2.5.4. Computing the Gradient of Java Control Flow

One benefit of using automatic differentiation is that even if building the computational graph of a function required passing through a maze of Java control flow (e.g., conditionals, loops, and arbitrary function calls), we can still calculate the gradient of the resulting variable. In the following snippet, note that the number of iterations of the while loop and the evaluation of the if statement both depend on the value of the input a.

public NDArray f(NDArray a) {
    NDArray b = a.mul(2);
    while (b.norm().getFloat() < 1000) {
        b = b.mul(2);
    NDArray c;
    if (b.sum().getFloat() > 0) {
        c = b;
    }else {
        c = b.mul(100);
    return c;

Let us compute the gradient.

We can then analyze the f function defined above. Note that it is piecewise linear in its input a. In other words, for any a there exists some constant scalar k such that f(a) = k * a, where the value of k depends on the input a. Consequently d / a allows us to verify that the gradient is correct.

NDArray a = manager.randomNormal(new Shape(1));
try (GradientCollector gc = Engine.getInstance().newGradientCollector()) {
    NDArray d = f(a);

ND: (1) gpu(0) boolean
[ true]

2.5.5. Summary

  • Deep learning frameworks can automate the calculation of derivatives. To use it, we first attach gradients to those variables with respect to which we desire partial derivatives. We then record the computation of our target value, execute its function for backpropagation, and access the resulting gradient.

2.5.6. Exercises

  1. Why is the second derivative much more expensive to compute than the first derivative?

  2. After running the function for backpropagation, immediately run it again and see what happens.

  3. In the control flow example where we calculate the derivative of d with respect to a, what would happen if we changed the variable a to a random vector or matrix. At this point, the result of the calculation f(a) is no longer a scalar. What happens to the result? How do we analyze this?

  4. Redesign an example of finding the gradient of the control flow. Run and analyze the result.

  5. Let \(f(x) = \sin(x)\). Plot \(f(x)\) and \(\frac{df(x)}{dx}\), where the latter is computed without exploiting that \(f'(x) = \cos(x)\).