Skip to content

← JAX Autodiff step 3 of 25

Medium Primitives

jvp for Sensitivity Analysis

Jump to the task

Estimate how a loss changes

A directional derivative describes how a loss responds to a small input change. For a scalar weight w and a direction dw, consider the path w + epsilon*dw. Its loss has rate of change loss_prime(w) * dw at epsilon=0. JAX calls this rate an output tangent.

import jax
import jax.numpy as jnp

x = jnp.array([1.0, 2.0])

def loss(w):
    return jnp.sum((w * x) ** 2)

value, tangent = jax.jvp(loss, (1.0,), (0.1,))
# value = 5.0
# tangent = 10.0 * 0.1 = 1.0

The linear estimate for loss(1 + epsilon*0.1) is 5 + epsilon*1. For epsilon=1, it predicts a change of 1, while the actual change is loss(1.1) - loss(1.0) = 1.05. A directional derivative is not an exact finite change. The approximation improves as the step gets smaller.

Keep the direction separate from the input

jax.jvp(loss, (w,), (dw,)) evaluates the derivative at w. It does not evaluate the loss at w + dw. Negative dw reverses the direction, and scaling dw scales the tangent. Do not normalize it.

The result is (value, tangent). The exercise needs only the second entry. Both w and dw are scalar here; zero-dimensional JAX arrays are valid too. Their floating-point dtypes must match. A length-one array is a different shape from a scalar.

JVP computes a derivative along one direction. Reverse-mode grad computes the full gradient of a scalar loss. Which is faster depends on the function and the derivatives you need; there is no guaranteed speed advantage for this scalar example.

Problem

Implement sensitivity(w, b, x, dw) using jax.jvp for loss(w) = sum((w*x + b)**2). Hold b and x fixed.

w, b and dw are real floating-point scalars, and x is a one-dimensional real floating-point JAX array. Return the scalar directional derivative with respect to w in direction dw: sum(2*(w*x + b)*x) * dw.

For w=1.0, b=2.0, x=[3.0], and dw=-0.5, the derivative with respect to w is 30. Multiplying by dw gives the result -15.0. The formula is a check on the answer; practice obtaining it with JVP.