Skip to content

← JAX Autodiff step 1 of 25

Easy Primitives

jvp Basics

Jump to the task

Follow a direction through a function

Suppose an input changes from x to x + epsilon*v, where epsilon is a small number. The vector v describes which input entries change and by how much relative to one another. A directional derivative tells you the output's rate of change along that direction.

jax.jvp returns the ordinary function value, called the primal, and this directional derivative, called the output tangent:

import jax
import jax.numpy as jnp

def square(x):
    return x ** 2

value, tangent = jax.jvp(square, (3.0,), (2.0,))
# value = 9.0
# tangent = 2 * 3 * 2 = 12.0

For small epsilon, square(3 + epsilon*2) is approximately 9 + epsilon*12. The tangent is a rate, not the value of the function at a displaced input. You do not need to choose an epsilon for JAX: it applies derivative rules to the operations in your function.

From tangents to a Jacobian-vector product

The Jacobian collects the derivatives of every output with respect to every input. Multiplying that matrix by v gives the output tangent, written J(x) @ v. JAX computes this product without needing to build the whole matrix. For a scalar loss, it is the dot product of the gradient and v; for an array output, it has that output's shape.

x = jnp.array([1.0, 2.0, 3.0])
v = jnp.array([1.0, 0.0, 0.0])
value, tangent = jax.jvp(lambda x: jnp.sum(x**2), (x,), (v,))
# value = 14.0; tangent = 2.0

Only the first input entry changes along this direction, so only its derivative contributes. A direction need not have length one: scaling v scales the tangent.

Pass the positional inputs and their tangents as matching tuples or lists. For one argument, (x,) and (v,) are convenient. Here the real floating-point arrays x and v must have the same shape and dtype.

Problem

Implement jvp_quadratic(x, v) using jax.jvp for f(x) = sum(x**2). Both inputs are one-dimensional real floating-point JAX arrays with matching shape and dtype.

Return a JAX array with shape (2,): [value, tangent]. The first entry is sum(x**2), and the second is sum(2*x*v). Use a sum, not a mean.

For x=[2.0, -1.0] and v=[-0.5, 3.0], the value is 5 and the tangent is 2*2*(-0.5) + 2*(-1)*3 = -8, so return [5.0, -8.0]. Use the formula to check your answer while practicing the JVP API.