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.
{ 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 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.
- 1. jax.grad takes a function and returns…
- 2. vmap lets you…
- 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-reverseThe four transformations:
grad: reverse-mode derivative of a scalar function, with respect toargnums;value_and_grad,jacrev,jacfwd,hessian,jvpandvjpare 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, usingin_axesandout_axes.pmap(and its modern replacement,jax.shardingwithjitorshard_map): run the same program on several devices with collectives such aslax.psumandlax.pmean.
- 1. jax.grad requires the function's output to be…
- 2. in_axes=(None, 0, 0) in vmap means…
- 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.
- 1. A print() inside a jitted function runs…
- 2. Why does grad(grad(f)) work?
- 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:
gradreturns gradients with the same structure as the parameters;jax.tree_util.tree_mapapplies 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.
- 1. How do you update element i of a JAX array?
- 2. Jacobian of f: ℝ³ → ℝ¹⁰⁰⁰: which mode needs fewer passes?
- 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.
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
jacfwdof 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
- J. Bradbury et al. (2018). JAX: composable transformations of Python+NumPy programs. github.com/jax-ml/jax.
- R. Frostig, M. J. Johnson, C. Leary (2018). “Compiling machine learning programs via high-level tracing.” SysML Conference.
- JAX documentation (docs.jax.dev): Autodidax: JAX core from scratch, JAX sharp bits, Pseudorandom numbers.
- A. G. Baydin et al. (2018). “Automatic differentiation in machine learning: a survey.” JMLR, 18(153).
- O. Montenbruck, E. Gill (2000). Satellite Orbits: Models, Methods and Applications. Springer (gravity-gradient and variational equations).