Foundations to Frontier
Tests
C. Programming, Tools and HPC › C3 Deep Learning Frameworks

JAX: jit, grad, vmap, pmap and Functional Style

JAX is NumPy plus composable function transformations: grad (derivatives of any order), jit (compile with XLA), vmap (automatic vectorization) and pmap or sharding (parallelism across devices). All of them work by tracing: running a pure Python function on abstract values to record a jaxpr, an intermediate program that each transformation rewrites or compiles. This topic explains tracing, why JAX requires a functional style (pure functions, immutable arrays, explicit random keys, lax control flow, pytrees), and how the transformations compose. In the exercises you build a mini-JAX in pure Python with tracers, jaxprs, a reverse-mode grad that can be applied to itself, vmap batching rules and a shape-keyed jit cache, then use vmap∘grad to compute the gravity-gradient tensor and measure what vmap and jit save.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

Functions that rewrite functions

Imagine giving a recipe to an assistant who, instead of cooking it, writes it down as a precise list of steps. With that list they can do clever things: produce a second recipe that tells you how the dish changes if you change one ingredient (that’s grad), cook a hundred portions at once instead of one at a time (vmap), or reorganize the kitchen so the recipe runs as fast as possible (jit). JAX is that assistant for numerical Python: it reads your function once, writes down its steps, and transforms them.

Tracing: how jax.grad and jax.jit see your function
f(x) =
transform:
grad(f)(0.70) = 1.179607 · jaxpr with 8 equations
{ lambda v1 .
    v2 = sin v1
    v3 = mul v2 v1
    v4 = add v3 2.0
    v5 = mul 1.0 v1
    v6 = mul 1.0 v2
    v7 = cos v1
    v8 = mul v5 v7
    v9 = add v6 v8
  in v9 }
jax.jit cache (one trace per input shape and dtype)
traces so far: 0
The jaxpr is what JAX sees: Python control flow, prints and other side effects happen only while tracing and leave no trace in it. grad emits the backward pass as more equations of the same kinds, which is why grad(grad(f)) works, and why its jaxpr grows with each application. jit hands the jaxpr to XLA, which fuses and compiles it; a new shape or dtype means a new trace and a new compilation.
Why engineers care

JAX is used for large-scale ML (Google DeepMind’s models), for differentiable physics (Brax, JAX-MD, JAX-Fluids), and for scientific computing that needs exact derivatives of complicated simulations: trajectory optimization, orbit determination, uncertainty propagation through Jacobians, all running on GPUs or TPUs from the same code.

📝 Quick check (Level 0)
0/3 answered
  1. 1. jax.grad takes a function and returns…
  2. 2. vmap lets you…
  3. 3. To transform a function, JAX first…

Level 1: Beginner

★★☆☆☆ Basic⏱ 25 minSecondary-school mathematics: arithmetic and elementary algebra.

NumPy, transformed

import jax
import jax.numpy as jnp

def loss(w, x, y):
    return (jnp.tanh(jnp.dot(w, x)) - y) ** 2           # one example

g = jax.grad(loss)                                       # d loss / d w
per_example = jax.vmap(g, in_axes=(None, 0, 0))          # map over rows of X and y
fast = jax.jit(per_example)                              # compile the whole thing with XLA
grads = fast(w, X, y)                                    # shape (batch, n_features)

hess = jax.jacfwd(jax.jacrev(loss))                      # Hessian: forward-over-reverse

The four transformations:

  • grad: reverse-mode derivative of a scalar function, with respect to argnums; value_and_grad, jacrev, jacfwd, hessian, jvp and vjp are relatives.
  • jit: trace once per input shape and dtype, compile with XLA (operation fusion, memory planning), and cache.
  • vmap: write the function for one example and get the batched version without loops, using in_axes and out_axes.
  • pmap (and its modern replacement, jax.sharding with jit or shard_map): run the same program on several devices with collectives such as lax.psum and lax.pmean.
📝 Quick check (Level 1)
0/3 answered
  1. 1. jax.grad requires the function's output to be…
  2. 2. in_axes=(None, 0, 0) in vmap means…
  3. 3. What triggers a new jit compilation?

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 40 minUndergraduate students and practising engineers.

Tracing and jaxprs

When you call a transformed function, JAX replaces each argument with a tracer that knows only its shape and dtype (an abstract value), runs your Python code, and records every primitive operation (sin, mul, dot_general, reduce_sum, …) into a jaxpr. jax.make_jaxpr(f)(x) prints it. Each transformation is an interpreter of jaxprs:

  • grad emits the backward pass as new equations built from the same primitives (one VJP rule per primitive). That is why grad(grad(f)) works: the output of grad is an ordinary traceable function.
  • vmap re-runs the jaxpr with batching rules per primitive (elementwise ops broadcast along the batch axis, a reduction shifts its axes by one, a matrix-vector product becomes a matrix-matrix product).
  • jit passes the jaxpr to XLA, keyed by the abstract signature.

Consequences: Python print, list appends and other side effects run only during tracing; if x > 0 on a tracer raises a ConcretizationTypeError because the tracer has no value; use jnp.where, lax.cond, lax.while_loop, lax.fori_loop or lax.scan instead.

🐍 Exercise 1: a mini-JAX
Build tracers and jaxprs (Var, Lit, Trace, Tracer, bind, make_jaxpr, eval_jaxpr) over primitives add, sub, mul, div, neg, sin, cos, exp, log, pow, reduce_sum, reshape, broadcast_to; a jnp namespace; reverse-mode grad written with bind so it can be traced (and differentiated) again; vmap with batching rules; and a jit that caches one jaxpr per input shape. Check grad, grad∘grad∘grad, per-example gradients with vmap(grad), retracing and ConcretizationTypeError.
📝 Quick check (Level 2)
0/3 answered
  1. 1. A print() inside a jitted function runs…
  2. 2. Why does grad(grad(f)) work?
  3. 3. Under vmap, a reduce_sum over per-example axis 0 becomes a sum over…

Level 3: Advanced

★★★★☆ Advanced⏱ 30 minGraduate level, with full derivations and proofs.

The functional style JAX needs

  • Pure functions: outputs depend only on inputs; no hidden state, no mutation of globals. Model parameters are passed in and returned.
  • Immutable arrays: x.at[i].set(v) returns a new array (XLA updates in place when it can prove safety).
  • Explicit randomness: key = jax.random.key(0); key, sub = jax.random.split(key). The same key gives the same numbers, so a jitted, vmapped or parallel computation is reproducible, and independent streams come from splitting (compare C2.4).
  • Pytrees: nested tuples, lists and dicts of arrays are first-class: grad returns gradients with the same structure as the parameters; jax.tree_util.tree_map applies a function leaf by leaf.
  • Static versus traced: shapes must be known at trace time; mark Python values that change control flow as static (static_argnums) and expect one compilation per value.

Choosing the derivative

For f: ℝⁿ → ℝᵐ, reverse mode builds a Jacobian row by row (m passes, jacrev), forward mode column by column (n passes, jacfwd). Scalar losses of many parameters favour reverse mode; few inputs and many outputs favour forward mode; Hessians are usually forward-over-reverse. jacrev is literally vmap over the rows of the identity applied to vjp: transformations compose.

📝 Quick check (Level 3)
0/3 answered
  1. 1. How do you update element i of a JAX array?
  2. 2. Jacobian of f: ℝ³ → ℝ¹⁰⁰⁰: which mode needs fewer passes?
  3. 3. Calling jax.random.normal twice with the same key gives…

Level 4: Expert

★★★★★ Expert⏱ 40 minResearchers: original papers and open problems.

Transformations at work

Exercise 1. The mini-JAX traces sin(x)·x + 2 to three equations (sin, mul, add); grad(sin)(1) = cos 1 exactly; the third derivative of sin at 0.5 is −cos 0.5 to 1e−14; vmap(grad(loss), in_axes=(None, 0, 0)) reproduces hand-derived per-example gradients; a jitted function with a side effect traces once for shape (3,) and again only for shape (4,); jit(lambda t: t if t > 0 else -t) raises ConcretizationTypeError while the eager version works.

Exercise 2: the gravity-gradient tensor and the cost of loops. Composing jacrev = vmap(grad(⟨u, f⟩)) over the identity gives the Jacobian of the two-body acceleration a(r) = −μr/|r|³ at r = (7000, 1200, −300) km. It matches the analytic tensor μ/r³ (3r̂r̂ᵀ − I) to 2e−16 relative, is symmetric, and has trace 6e−22, i.e. zero to round-off, as Laplace’s equation requires outside the mass. jacrev(grad(U)) of the potential U = −μ/|r| gives its negative to 1e−16.

For per-example gradients of a tanh regression loss with 8 features, counting primitive kernel launches per call (after warm-up):

Batch size B Python loop of grad vmap(grad) jit(vmap(grad))
16 432 54 53
64 1728 54 53
256 6912 54 53

The loop launches 27 kernels per example and re-traces every call; vmap launches a fixed number whatever B; jit additionally skips tracing (zero new variables per call). Measured wall-clock time at B = 256 is two orders of magnitude lower for jit(vmap) than for the loop in CPython (the exact factor depends on the machine and on Pyodide). Real JAX adds XLA fusion on top, merging those 53 kernels into a few.

🐍 Exercise 2 (research): Jacobians and the price of Python loops
Using the mini-JAX, define jacrev by vmapping grad over cotangent basis vectors, compute the gravity-gradient tensor of the two-body acceleration and the Hessian of the potential, check them against μ/r³(3r̂r̂ᵀ − I), symmetry and zero trace; then count kernel launches, traced variables and time for per-example gradients with a Python loop, vmap and jit(vmap) at three batch sizes.

JAX in AI, robotics and aerospace

  • Differentiable simulators: Brax (rigid-body robotics), JAX-MD, JAX-Fluids; trajectory optimization by differentiating through rollouts.
  • Orbit determination and uncertainty: exact Jacobians of propagators for least-squares fitting and covariance propagation (state transition matrices via jacfwd of an integrator).
  • Large models: sharded training on TPU pods (Gemini, AlphaFold 2 were developed with JAX).
  • Probabilistic programming: NumPyro and BlackJAX use vmap and grad for vectorized MCMC.

References

  1. J. Bradbury et al. (2018). JAX: composable transformations of Python+NumPy programs. github.com/jax-ml/jax.
  2. R. Frostig, M. J. Johnson, C. Leary (2018). “Compiling machine learning programs via high-level tracing.” SysML Conference.
  3. JAX documentation (docs.jax.dev): Autodidax: JAX core from scratch, JAX sharp bits, Pseudorandom numbers.
  4. A. G. Baydin et al. (2018). “Automatic differentiation in machine learning: a survey.” JMLR, 18(153).
  5. O. Montenbruck, E. Gill (2000). Satellite Orbits: Models, Methods and Applications. Springer (gravity-gradient and variational equations).