liveBook · Manning

Jax.grad

As explained in Deep Learning with Python, Third Edition

A JAX function that creates a gradient-computing function for differentiable inputs and outputs.

jax.grad transforms a loss function into another function that computes gradients. Define the loss, create the gradient function, then call it with the original arguments. section 3.5.3

Differentiate a scalar loss

Define a loss that returns a scalar, transform it with jax.grad, and evaluate the result: compute_loss(input_var) returns jnp.square(input_var); grad_fn = jax.grad(compute_loss); grad_fn(jnp.array(3.0)) returns the loss gradient with respect to input_var. section 3.5.3

Use these rules when applying jax.grad:

  • Return a scalar loss from the differentiated function. section 3.5.3
  • Place the state arrays requiring gradients in the first argument; that argument may be one array, a list, or a dictionary of arrays. section 3.5.3
  • Use jax.value_and_grad when the computation must return both the loss and its gradients, including optional auxiliary outputs. section 3.5.1 section 3.5.3
Listing 10.13 Loss maximization via stochastic gradient ascent: JAX
import jax

grad_fn = jax.grad(compute_loss)

@jax.jit
def gradient_ascent_step(image, filter_index, learning_rate):
    grads = grad_fn(image, filter_index)
    grads = ops.normalize(grads)
    image += learning_rate * grads
    return image

A JAX gradient function can drive a JIT-compiled gradient-ascent step that normalizes gradients and updates an input image. section 10.2.3

How Deep Learning with Python, Third Edition covers it

How deep it goes
Explains function transformation, scalar-loss constraints, argument conventions, auxiliary outputs, and a worked example without deriving automatic differentiation internals.
Examples
Uses a squared scalar loss, structured model state, auxiliary outputs, and stochastic gradient ascent on an input image.
What it assumes
Assumes familiarity with JAX arrays, numerical operations, and defining Python functions; teaches gradient transformation from the example onward.
What you can do after
Apply it via JAX to create reusable gradient functions for scalar losses and use them in optimization steps.
How it connects
Connects gradient computation with loss functions, array operations, value_and_grad, JIT compilation, and gradient ascent.

Also explained in

Compare how 2 books explain jax.grad →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Deep Learning with Python, Third Edition. The section links point to the parts of the book it draws on.