We can't find the internet
Attempting to reconnect
Something went wrong!
Attempting to reconnect
← JAX Foundations step 11 of 25
jax.value_and_grad
Get the loss and its gradient together
A training step needs a gradient to update the parameters. It often
also needs the loss value to show progress. jax.value_and_grad
returns both from one transformed function call:
import jax
import jax.numpy as jnp
def loss(w, x):
return jnp.sum((w * x) ** 2)
value, grad_w = jax.value_and_grad(loss)(3.0, jnp.array([1.0, 2.0]))
# value = 9 + 36 = 45.0
# grad_w = 2 * 3 * (1 + 4) = 30.0
The value comes first, then the gradient. They have different meanings
and need not be equal. jax.grad alone returns only the gradient.
Using value_and_grad lets JAX return the value computed for the
derivative rather than asking you to evaluate the loss separately.
This is not a promise of a fixed speedup or a single device operation:
compilation and the operations in the loss determine the actual work.
Select what to differentiate
argnums=0, the default, differentiates with respect to the first
positional argument. Other arguments still affect the loss, but are
held fixed for that derivative. The loss must return a scalar with
shape (), not a one-element array with shape (1,).
If a loss also returns a metric, has_aux=True handles the pair
(loss, metric). The transformed result is ((value, metric), grad).
Only the loss determines that gradient. This exercise does not need
auxiliary output.
Problem
Implement loss_and_grad(w, b, x) using jax.value_and_grad.
w and b are real floating-point scalars, and x is a one-dimensional
floating-point array. The loss is sum((w*x + b)**2).
Differentiate with respect to w only, holding b and x fixed.
Return a JAX array with shape (2,), containing [loss, grad_w].
The inner loss is scalar; this two-element array is the outer
function's result. Use a sum, not a mean.
For w=0.0, b=1.0, and x=[1.0, 2.0], the loss is 1 + 1 = 2.
Its derivative is 2*1*1 + 2*1*2 = 6, so return [2.0, 6.0].
The exercise is practice using value_and_grad. Numerical output
checks verify the result, but cannot enforce how you computed it.
Understand the ideas behind this exercise. The Problem tab contains the exact implementation requirements.
Get the loss and its gradient together
A training step needs a gradient to update the parameters. It often
also needs the loss value to show progress. jax.value_and_grad
returns both from one transformed function call:
import jax
import jax.numpy as jnp
def loss(w, x):
return jnp.sum((w * x) ** 2)
value, grad_w = jax.value_and_grad(loss)(3.0, jnp.array([1.0, 2.0]))
# value = 9 + 36 = 45.0
# grad_w = 2 * 3 * (1 + 4) = 30.0
The value comes first, then the gradient. They have different meanings
and need not be equal. jax.grad alone returns only the gradient.
Using value_and_grad lets JAX return the value computed for the
derivative rather than asking you to evaluate the loss separately.
This is not a promise of a fixed speedup or a single device operation:
compilation and the operations in the loss determine the actual work.
Select what to differentiate
argnums=0, the default, differentiates with respect to the first
positional argument. Other arguments still affect the loss, but are
held fixed for that derivative. The loss must return a scalar with
shape (), not a one-element array with shape (1,).
If a loss also returns a metric, has_aux=True handles the pair
(loss, metric). The transformed result is ((value, metric), grad).
Only the loss determines that gradient. This exercise does not need
auxiliary output.
Compute derivatives by following the operations
Automatic differentiation computes derivatives by applying the chain rule to a program's operations. It does not estimate them by evaluating nearby inputs, as finite differences do, or rearrange the whole expression using symbolic algebra.
For f(g(x)), the chain rule combines the derivative of g with the derivative
of f at g(x). Repeating this process lets a framework differentiate a long
sequence of operations.
Forward mode follows an input change
For a function with n inputs and m outputs, the Jacobian J is an (m, n)
matrix of derivatives. Entry (i, j) describes how output i changes with input
j.
Forward-mode differentiation computes Jv: the output's rate of change when the
input moves in direction v. For example, if f(x) = sum(x_i^2), then at
x = [1, 2] the gradient is [2, 4]. In direction v = [3, 0], the rate of
change is 2 * 3 + 4 * 0 = 6.
This is a directional derivative. It gives one Jacobian column only when v
selects one input coordinate, such as [1, 0].
Reverse mode works backward from an output
Reverse mode computes J^T u, where u weights the outputs. For a scalar loss,
choosing u = 1 gives the gradient with respect to all inputs. This makes reverse
mode useful for training: a model can have many parameters but just one loss.
Forward mode can be useful when you need sensitivity to only a few input directions. Neither mode needs to construct the full Jacobian for these products. That can save substantial memory. Higher-order differentiation can similarly compute a Hessian-vector product without storing the full matrix of second derivatives.
Changing gradient flow changes what is differentiated
A stop-gradient operation keeps a value in the forward calculation but treats it as constant during differentiation. A custom derivative supplies a derivative rule explicitly. It should match the intended function unless the exercise asks for a surrogate, such as an approximation used during training.
Your code, saved here
Sign in to access your accepted solutions and saved draft history. You can keep reading the lesson without an account.
Sign in to your accountStuck?
JAX reference solution
Sign in to track your attempts toward unlocking the reference solution.