Module contents
Lesson 24 of 24Advanced 90 min

JAX: function transformations (optional)

Optional introduction to pure programs transformed by grad, jit and vmap and compiled with XLA: tracing rules, static and traced values, pytrees, explicit PRNG keys and comparison with PyTorch. On native Windows JAX uses CPU; NVIDIA GPU requires experimental WSL2 support.

After this lesson you can

  • Write pure functions and compose grad, jit and vmap transformations.
  • Explain jit tracing, distinguish static from traced values and avoid recompilation and concretization errors.
  • Manipulate parameters as pytrees using jax.tree_util.
  • Manage randomness with explicit keys, split and fold_in, relating them to counter-based generators.
  • Compare the same training in JAX and PyTorch and explain when each is useful.

Before you start

Motivation: write one example, transform the function

You want the gradient norm of each batch example: to clip per example (differential privacy), estimate gradient variance or find examples pushing the model most. In PyTorch, loss.backward() gives the sum or mean of those gradients, never each separately. Options are a loop of BB backwards or rewriting the network to preserve the batch axis in backward. In JAX it is one line:

gradientes_por_ejemplo = jax.vmap(jax.grad(perdida_de_un_ejemplo), in_axes=(None, 0, 0))

Read inside out. perdida_de_un_ejemplo(params, x, y) is a normal Python function knowing only one example. jax.grad turns it into another returning its gradient with respect to parameters. jax.vmap turns that into another accepting a whole batch and applying the prior function to each example without a Python loop. And jax.jit on top would compile the result with XLA into one program. None of the three knows anything about neural networks: they take a function and return a function. Thus they compose like Lego pieces, and much research is written in JAX:

  • Higher-order optimization. Hessians, Hessian-vector products and derivatives through an entire training loop (meta-learning) are compositions of grad, jvp and vjp.
  • Vectorize what is not a batch. With vmap, train ten seeds or a hundred hyperparameters in parallel by writing code for one run; in RL, vectorize thousands of simulated environments. DeepMind’s reference tree-search implementations (mctx, with AlphaZero and MuZero) and differentiable physical simulators like Brax use JAX for this reason.
  • One program, one compiler. Output of jit is a complete XLA program: fusion, no Python interpreter in the hot loop, and the same code on CPU, GPU or TPU.

The price is a stricter programming model: pure functions, immutable arrays, explicit randomness and tracing rules to know. This lesson is optional. The rest of the course uses PyTorch, and you have seen its version of these ideas with torch.func. But understanding JAX changes how you think about PyTorch and lets you read (and write) half the research code you encounter. A practical notice up front: on native Windows JAX works only on CPU; NVIDIA GPU requires WSL2, with support marked experimental. All JAX code in this lesson was run with JAX 0.12 on the lab laptop’s CPU, and output appears in comments.

Pure functions and jax.numpy

jax.numpy reproduces almost all NumPy API: jnp.dot, jnp.where, jnp.linalg.solve, broadcasting and indexing work as expected. The difference is what you cannot do.

JAX transformations need pure functions because they do not execute your function as you would: they reinterpret it. To differentiate, traverse it with values carrying derivatives; to vectorize, with values carrying a batch axis; to compile, with values having no value, only shape. What a function does outside its arguments and result (printing, appending to a list, reading a counter) cannot be reinterpreted, and occurs once at a time you do not control, or never.

The first visible consequence is that JAX arrays are immutable. Instead of assigning, request a modified copy:

import jax
import jax.numpy as jnp

x = jnp.arange(5.0)
x[0] = 10.0                 # TypeError: JAX arrays are immutable and do not support in-place item assignment
y = x.at[0].set(10.0)       # [10.  1.  2.  3.  4.], y x sigue siendo [0. 1. 2. 3. 4.]
z = x.at[1:3].add(1.0)      # [0. 2. 3. 3. 4.]
jnp.zeros(4).at[jnp.array([0, 2, 2])].add(1.0)   # [1. 0. 2. 0.]: los índices repetidos se acumulan

x.at[idx] supports set, add, multiply, min, max and get, with NumPy indexing. The last line is scatter-add like scatter operations: unlike a[idx] += 1 in NumPy, which adds only once with repeated indices, here contributions accumulate. Copy cost? Inside jit, XLA sees the original array is no longer used and updates in place: immutability is a programming-model property, not an execution property.

All are implemented alike: JAX calls ff with special objects, tracers, that record or reinterpret each primitive operation ff performs on them. Composing transformations stacks interpreters: in vmap(grad(f)), each primitive of ff is first seen by the grad interpreter and its output by vmap. Autodidax builds that core from scratch in a few hundred lines; here you will build toy versions of jit and vmap.

Composing transformations: shapes and equivalences

Before studying each transformation separately, get the overall picture, and the picture lies in shapes. Take the single-example function

f(w,x)=tanh⁡(x⊤w),w,x∈Rd,f(\vb{w}, \vb{x}) = \tanh(\vb{x}\T\vb{w}), \qquad \vb{w}, \vb{x} \in \R^d,

a neuron. Derivatives are with respect to w\vb{w} and vmap traverses x\vb{x}. Each transformation changes signature predictably: grad requires scalar output and returns something shaped like w\vb{w}; jacfwd and jacrev append the shape of w\vb{w} to output; vmap adds a leading batch axis to traversed input and output; jit changes nothing.

InteractiveComposing transformations
vmap(grad(f))(w, X)
f(w,x)=tanh⁡(x⊤w)f(\vb{w}, \vb{x}) = \tanh(\vb{x}\T\vb{w}) with w,x∈Rd\vb{w}, \vb{x} \in \R^d, d=3d = 3. Derivatives are with respect to w\vb{w} (argnums=0) and vmap maps over x\vb{x} (in_axes=(None, 0)). Batches: B=4B = 4, C=2C = 2, D=5D = 5.
f(w: [d], x: [d]) → []the single-example function, written once
layer 1: grad(w: [d], x: [d]) → [d]requires scalar output and returns an object with the shape of w\vb{w}
layer 2: vmap(w: [d], X: [B, d]) → [B, d]adds a new axis at the start of x\vb{x} and the output
jaxpr traced by JAX for vmap(grad(f))
{ lambda ; a:f32[3] b:f32[4,3]. let
c:f32[4] = dot_general[(([1], [0]), ([], []))] b a
d:f32[4] = tanh c
e:f32[4] = one_minus_square d
f:f32[4] = mul 1.0:f32[] e
g:f32[4,3] = dot_general[(([], []), ([0], [0]))] f b
in (g,) }
Same function (same values at (w, X)): 19 more compositions
and 11 more with jit in the middle
Add outside
Per-example gradients: the inexpensive form.
Output shape[B, d]
jaxpr equations5
Intermediates, B=4B = 428
Intermediates, B=256B = 2561792
This is the least expensive composition in its class (or tied for it). Those listed compute the same numbers, up to rounding.
Stack up to three transformations over f(w,x)=tanh⁡(x⊤w)f(\vb{w}, \vb{x}) = \tanh(\vb{x}\T\vb{w}); the last added is outermost. Each layer shows signature changes, and below is the jaxpr JAX 0.12 traces for that composition. Start with vmap(grad(f)), per-example gradients. Then try grad(vmap(f)): why does it fail? Load jacrev(vmap(f)), which computes the same numbers, and compare intermediates with B=256B = 256. Finish with per-example Hessians written both ways.

What you should have seen:

  • vmap(grad(f)) gives per-example gradients, a B×dB \times d matrix, with a five-equation jaxpr: the same as grad(f) with an extra axis per variable.
  • grad(vmap(f)) does not exist. vmap(f) returns a vector of BB outputs and grad differentiates scalar functions only. Transformation order matters, as with matrices.
  • jacrev(vmap(f)) and vmap(grad(f)) are the same function, but the former differentiates the whole batch as a function from Rd\R^d to RB\R^B. Its jaxpr constructs a B×BB \times B identity with iota and eq, and with B=256B = 256 handles over two hundred times more intermediate elements.
  • Per-example Hessians come from vmap(jacfwd(grad(f))) with shape B×d×dB \times d \times d. Written as jacrev(jacrev(vmap(f))) they are the same numbers, with quadratic memory explosion in BB.
  • jit inside a composition only nests a jit[...] call in the jaxpr: neither shapes nor values change.

The third observation is a simple theorem, with a cost consequence worth understanding before writing research code.

ProofPer-example gradients and batch Jacobian
Prove: Let ℓ(w;x)\ell(\vb{w}; \vb{x}) be a differentiable scalar loss and L(w)=(ℓ(w;x1),…,ℓ(w;xB))\vb{L}(\vb{w}) = (\ell(\vb{w}; \vb{x}_1), \dots, \ell(\vb{w}; \vb{x}_B)) the unaveraged batch loss. Row ii of Jacobian JL(w)∈RB×d\mat{J}_{\vb{L}}(\vb{w}) \in \R^{B \times d} is ∇wℓ(w;xi)⊤\grad_{\vb{w}} \ell(\vb{w}; \vb{x}_i)\T, so jacrev(vmap(l)) and vmap(grad(l)) agree; the first costs O(B2d)\bigO(B^2 d) and the second O(Bd)\bigO(B d).
0
Assume evaluating ℓ\ell on one example costs O(d)\bigO(d) and a VJP costs the same up to a constant.

Step 1 of 4. What is row ii of JL(w)\mat{J}_{\vb{L}}(\vb{w})?

You can measure it without installing JAX, because torch.func offers exactly the same transformations under the same names:

[ ]The same function, two costs (torch.func)Local GPU
import time, torch
from torch.func import grad, jacrev, jacfwd, vmap

def f(w, x):                      # un ejemplo: w y x en R^d
    return torch.tanh(x @ w)

def medir(fn, *args, rep=5):
    fn(*args)
    t0 = time.perf_counter()
    for _ in range(rep):
        fn(*args)
    return (time.perf_counter() - t0) / rep

torch.manual_seed(0)
for B in [512, 2048, 8192]:
    w, X = torch.randn(64), torch.randn(B, 64)
    por_ejemplo = vmap(grad(f), in_dims=(None, 0))           # vmap(grad(f))
    jac_lote = jacrev(vmap(f, in_dims=(None, 0)))             # jacrev(vmap(f))
    iguales = torch.allclose(por_ejemplo(w, X), jac_lote(w, X), atol=1e-6)
    t1, t2 = medir(por_ejemplo, w, X), medir(jac_lote, w, X)
    print(f"B = {B:5d}: iguales {iguales}, vmap(grad) {t1 * 1e3:6.2f} ms, jacrev(vmap) {t2 * 1e3:6.2f} ms ({t2 / t1:4.0f} veces)")

G = vmap(grad(f), in_dims=(None, 0))(w, X)
print("contra la fórmula (1 - tanh²) x:", torch.allclose(G, (1 - torch.tanh(X @ w) ** 2)[:, None] * X, atol=1e-6))
H = vmap(jacfwd(grad(f)), in_dims=(None, 0))(w, X[:8])
print("hessianas por ejemplo:", tuple(H.shape))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

On the lab laptop, vmap(grad) takes about a millisecond for all three sizes, while jacrev(vmap) goes from about twice as slow at B=512B = 512 to a factor of dozens or more than a hundred (depending on run) at B=8192B = 8192, where the B×BB \times B identity occupies 256 MiB. With small batches fixed overhead hides everything; quadratic cost appears when batch grows, precisely when it matters.

grad, value_and_grad, jacfwd and jacrev

jax.grad(f) requires ff to return a scalar (an array of shape ()) and differentiates with respect to the first argument; argnums=(0, 2) selects others, and gradient has the same structure as the argument, whether an array or dictionary of arrays. jax.value_and_grad(f) returns the (value, gradient) pair in one pass, desirable in a training loop, and has_aux=True lets ff additionally return metrics that are not differentiated.

f = lambda w: jnp.sum(jnp.tanh(w) ** 2)
w = jnp.array([0.5, -1.0, 2.0])
jax.grad(f)(w)                       # [ 0.72686195 -0.63969994  0.13621868]
jax.value_and_grad(f)(w)             # (1.7229271, el mismo gradiente)

F = lambda w: jnp.tanh(w) * jnp.sum(w)          # de R^3 en R^3
jax.jacfwd(F)(w).shape                          # (3, 3), y jnp.allclose(jacfwd(F)(w), jacrev(F)(w)) es True
jax.hessian(f)(w)                               # igual a jax.jacfwd(jax.grad(f))(w)
jax.grad(jax.grad(jax.grad(jnp.tanh)))(0.5)     # -0.56520915

The first line’s gradient is 2tanh⁡(wi)(1−tanh⁡2wi)2\tanh(w_i)(1 - \tanh^2 w_i), and the last is the third derivative of tanh⁡\tanh at 0.50.5, which by hand is −2(1−t2)2+4t2(1−t2)-2(1 - t^2)^2 + 4t^2(1 - t^2) with t=tanh⁡0.5t = \tanh 0.5: also −0.5652-0.5652. No special function is needed to differentiate three times: grad returns a pure Python function that can be transformed again. This differs from PyTorch autograd, where a second derivative requires create_graph=True and manual graph management.

The gradient is the scalar case of the Jacobian matrix, and JAX computes it in two ways differing in chain-rule traversal: forward mode, propagating an input direction forward (JVP, Jacobian-vector product), and reverse mode, propagating an output cotangent backward (VJP, vector-Jacobian product). jax.jvp and jax.vjp expose these primitives, and everything else is built by composing them.

Proof

Jej\mat{J}\vb{e}_j is column jj of J\mat{J} and J⊤ei\mat{J}\T\vb{e}_i is row ii written as a column; both equalities read a matrix by columns and rows. vmap computing the nn (or mm) products at once does not change the result: by the vmap definition you will see next, output is the stack of individual results.

∎

In code, the proposition is literally the implementation:

x0 = jnp.array([1.0, 2.0, 3.0])
J_cols = jax.vmap(lambda v: jax.jvp(F, (x0,), (v,))[1], out_axes=1)(jnp.eye(3))   # columnas
_, vjp = jax.vjp(F, x0)
J_filas = jax.vmap(lambda u: vjp(u)[0])(jnp.eye(3))                                # filas
jnp.allclose(jax.jacfwd(F)(x0), J_cols), jnp.allclose(jax.jacfwd(F)(x0), J_filas)  # (True, True)

The practical rule follows costs: jacrev when few outputs (one loss, m=1m = 1, is the extreme and why grad uses reverse mode) and jacfwd when few inputs. For a loss Hessian, jacfwd(grad(f)): gradient has as many outputs as inputs and forward over reverse avoids saving the gradient graph. Fine analysis of these strategies is in Jacobian computation strategies.

jit: tracing with abstract values

jax.jit(f) returns a function that, on its first call with arguments of given shape and dtype, executes ff with tracers, obtains an intermediate program called jaxpr, compiles it with XLA and caches the executable. Later calls with the same shape and dtype do not execute Python: they call the executable.

def f(x):
    return jnp.sin(x) * 2 + 1

print(jax.make_jaxpr(f)(jnp.ones(3)))
# { lambda ; a:f32[3]. let
#     b:f32[3] = sin a
#     c:f32[3] = mul b 2.0:f32[]
#     d:f32[3] = add c 1.0:f32[]
#   in (d,) }

jaxpr is an SSA-form program (each variable assigned once) with explicit types: a:f32[3] is a float32 array of shape (3,), and each equation applies a primitive (sin, mul, add, dot_general, cond…). Transformations see it and XLA receives it.

The definition yields three rules governing everything inside jit:

  1. Python control flow on traced values is impossible. if x.sum() > 0: needs True or False during tracing, which the tracer lacks: TracerBoolConversionError. Likewise float(x), int(x) or Boolean indexing x[x > 0], whose output shape depends on values. This is a concretization error.
  2. Control flow on shapes, dtypes and statics is permitted and resolved while tracing. if x.shape[0] > 2: or for _ in range(k): with static k are evaluated in Python, and jaxpr contains only the taken path or unrolled loop. Each distinct value means another trace and compilation.
  3. Python effects happen once per trace. print prints tracers on the first call and nothing on later ones; append to a global list stores a tracer that, used outside, raises UnexpectedTracerError; np.random.rand() is evaluated once and becomes a constant in the compiled program.
InteractiveWhat jit sees while tracing
Successive calls to f (select one)
With x = 0.5 * jnp.arange(k) in float32 and x = jnp.arange(3) in int32.
@jax.jit
def f(x, n):
print("trazando con", x, n)
y = 2 * x
if n > 0:
y = y + 1
return jnp.sin(y).sum()
Environment during tracing
xJitTracer(float32[3])
nJitTracer(~int32[])
yJitTracer(float32[3])
print output
trazando con JitTracer(float32[3]) JitTracer(~int32[])
Step 4 of 4
n > 0 is another tracer of type bool[]. Python if needs True or False now, during tracing, but the tracer does not have that value: a concretization error.
jaxpr: trace interrupted
{ lambda ; a:f32[3] b:i32[]. let
c:f32[3] = mul 2.0:f32[] a
d:bool[] = gt b 0:i32[]
TracerBoolConversionError: Attempted boolean conversion of traced array with shape bool[].
Executable cache for f
empty
  • tracer (shape and dtype)
  • static value
  • traces and compiles
  • reuses
  • error
How the condition is written
Compilations through call 10
Compilations across 7 calls0
Result of this callerror
No call compiles: they all fail while tracing the if. The other three variants are the alternatives.
The same function with four ways to write the condition on n. Replay the first call's trace: watch x and n become tracers, what print prints and what equations each line adds. With ‘Python if’, tracing dies at the if. Switch to static_argnums and traverse seven calls: each n value is a compilation, even 1.0 versus 1. With lax.cond or jnp.where, only shape or dtype changes recompile. Click a ‘cache’ call: no tracing occurs and print prints nothing. JAX 0.12 data.

The four variants tell the same story from different sides. With static_argnums=1, the if works because n is a Python number, but every n value is a different program: 6 compilations in 7 calls. With lax.cond, jaxpr contains both branches as subprograms and primitive cond chooses at runtime; n becomes data and only shape or dtype changes recompile: 4 compilations. jnp.where also avoids recompilation, but calculates both branches and selects elementwise (select_n), sometimes faster (no branches, and what cond does inside vmap) and sometimes wasteful (if one branch is expensive).

Comparison with TorchDynamo capture is instructive. Dynamo reads Python bytecode and, when encountering something it cannot capture, breaks the graph and returns to Python: never fails, sometimes slow. jit executes the function with tracers and has nowhere to return: what cannot be traced is an error. In exchange, what is traced is always a complete program, and recompilation rules are simple: Dynamo guards become a cache key of shapes, dtypes and static values. A bound follows directly from that key.

Proof

By definition, the cache key is the pair (static values, abstract values). A call compiles if and only if its key has not appeared before, so compilation count equals distinct sequence keys, a subset of the product of both value sets.

∎

A toy jit

The best way to internalize rules is to implement them. A tracer is an object with shape and dtype overloading operators to record equations; __bool__ raises concretization error. This is the same technique as the toy torch.compile tracer, with one crucial difference: here abstract values have no concrete value behind them.

[ ]Tracers and jaxprs from scratchBrowser
import numpy as np

class ErrorDeConcretizacion(Exception):
    pass

def aval(a):
    """Valor abstracto (forma, dtype). Los escalares de Python son de tipo débil (~), como en JAX."""
    if isinstance(a, bool):
        return (), "bool"
    if isinstance(a, int):
        return (), "~int32"
    if isinstance(a, float):
        return (), "~float32"
    a = np.asarray(a)
    return a.shape, a.dtype.name

def promover(d1, d2):
    if d1 == d2:
        return d1
    if d1.startswith("~") != d2.startswith("~"):           # el débil se adapta al fuerte...
        fuerte, debil = (d2, d1) if d1.startswith("~") else (d1, d2)
        return "float32" if "int" in fuerte and "float" in debil else fuerte   # ...salvo int con float
    return np.result_type(d1.strip("~"), d2.strip("~")).name

class Tracer:
    """Solo conoce forma y dtype, y apunta a la traza que registra lo que se hace con él."""
    def __init__(self, traza, forma, dtype, nombre):
        self.traza, self.shape, self.dtype, self.nombre = traza, tuple(forma), dtype, nombre

    def __repr__(self):
        return f"Tracer({self.dtype}{list(self.shape)})"

    def _binaria(self, prim, otro, fn):
        forma2, dtype2 = (otro.shape, otro.dtype) if isinstance(otro, Tracer) else aval(otro)
        dtype = "bool" if prim == "gt" else promover(self.dtype, dtype2)
        return self.traza.emitir(prim, fn, [self, otro], np.broadcast_shapes(self.shape, forma2), dtype)

    __add__ = __radd__ = lambda s, o: s._binaria("add", o, np.add)
    __mul__ = __rmul__ = lambda s, o: s._binaria("mul", o, np.multiply)
    __gt__ = lambda s, o: s._binaria("gt", o, np.greater)

    def __bool__(self):
        raise ErrorDeConcretizacion(f"conversión a bool de un tracer {self}: durante la traza no tiene valor")

class Traza:
    def __init__(self):
        self.ecuaciones, self.n = [], 0

    def nuevo(self, forma, dtype):
        self.n += 1
        return Tracer(self, forma, dtype, "abcdefghijklmnopqrstuvwxyz"[self.n - 1])

    def emitir(self, prim, fn, args, forma, dtype):
        sal = self.nuevo(forma, dtype)
        self.ecuaciones.append((sal, prim, fn, args))
        return sal

def sin(x):
    if not isinstance(x, Tracer):
        return np.sin(x)
    return x.traza.emitir("sin", np.sin, [x], x.shape, "float32" if "int" in x.dtype else x.dtype)

def suma(x):
    return x.traza.emitir("reduce_sum", np.sum, [x], (), x.dtype) if isinstance(x, Tracer) else np.sum(x)

def mostrar(entradas, salida, ecuaciones):
    nom = lambda a: a.nombre if isinstance(a, Tracer) else repr(a)
    tipo = lambda t: f"{t.nombre}:{t.dtype}{list(t.shape)}"
    lineas = [f"{{ lambda {' '.join(tipo(e) for e in entradas)}. let"]
    lineas += [f"    {tipo(s)} = {p} {' '.join(nom(a) for a in args)}" for s, p, _, args in ecuaciones]
    return "\n".join(lineas + [f"  in ({salida.nombre},) }}"])

With that, jit is a cache indexed by the definition’s key: on a miss, trace and save the equation list; on any call evaluate those equations with NumPy without calling the function again. A “compiler” optimizing nothing, but with exactly JAX’s cache semantics.

[ ]Toy jit: cache, statics and concretization errorBrowser
def jit(f, static_argnums=()):
    cache = {}

    def envuelta(*args):
        clave = tuple(("estático", type(a).__name__, a) if i in static_argnums else aval(a) for i, a in enumerate(args))
        if clave not in cache:                             # fallo de caché: trazar y "compilar"
            traza = Traza()
            entradas, args_traza = [], []
            for i, a in enumerate(args):
                if i in static_argnums:
                    args_traza.append(a)
                else:
                    t = traza.nuevo(*aval(a))
                    entradas.append(t)
                    args_traza.append(t)
            salida = f(*args_traza)                        # Python se ejecuta aquí, y solo aquí
            cache[clave] = (entradas, salida, list(traza.ecuaciones))
        entradas, salida, ecuaciones = cache[clave]
        # el "ejecutable": evaluar las ecuaciones registradas con NumPy, sin volver a llamar a f
        valores = {id(t): a for t, a in zip(entradas, [a for i, a in enumerate(args) if i not in static_argnums])}
        for s, _, fn, ops in ecuaciones:
            valores[id(s)] = fn(*[valores[id(o)] if isinstance(o, Tracer) else o for o in ops])
        return valores[id(salida)]

    envuelta.cache = cache
    envuelta.jaxpr = lambda k: mostrar(*list(cache.values())[k])
    return envuelta

def f(x, n):
    print("  trazando con", x, n)
    y = 2 * x
    if n > 0:
        y = y + 1
    return suma(sin(y))

x3, x5, x3i = np.arange(3, dtype=np.float32), np.arange(5, dtype=np.float32), np.arange(3, dtype=np.int32)
llamadas = [(x3, 1), (x3, 1), (x3, 2), (x5, 2), (x3, -1), (x3, 1.0), (x3i, 1)]

print("1) n trazado: el if pide un valor que no existe")
try:
    jit(f)(x3, 1)
except ErrorDeConcretizacion as e:
    print("  ErrorDeConcretizacion:", e)

print("2) static_argnums=1: n llega como valor de Python")
f_est = jit(f, static_argnums=(1,))
for x, n in llamadas:
    f_est(x, n)
print("  compilaciones:", len(f_est.cache))
print("jaxpr de la llamada f(x3, 1):")
print(f_est.jaxpr(0))
print("jaxpr de la llamada f(x3, -1): la suma no existe")
print(f_est.jaxpr(3))

These are the same 6 compilations JAX counts in the interactive, with the same print output: only tracing calls print. The key includes the static’s Python type, so 1.0 compiles separately from 1, as in JAX. Missing is rule 1’s way out, a cond recording both branches and choosing at execution:

[ ]A toy lax.condBrowser
def cond(pred, si, no, x):
    """lax.cond de juguete: si pred es un tracer, la elección queda para la ejecución."""
    if not isinstance(pred, Tracer):
        return si(x) if pred else no(x)
    return pred.traza.emitir("cond", lambda p, v: si(v) if p else no(v), [pred, x], x.shape, x.dtype)

def f_cond(x, n):
    y = 2 * x
    y = cond(n > 0, lambda y: y + 1, lambda y: y, y)
    return suma(sin(y))

f_c = jit(f_cond)
for x, n in llamadas:
    f_c(x, n)
print("compilaciones:", len(f_c.cache))
for clave in f_c.cache:
    print("  ", clave)
print("f_cond(x3, 1) =", round(float(f_c(x3, 1)), 4), "  f_cond(x3, -1) =", round(float(f_c(x3, -1)), 4))
print(f_c.jaxpr(0))

Four keys: two x shapes, float-typed n and integer x. Both results, 0.02370.0237 and 0.15250.1525, match jax.jit with lax.cond. Real cond truly traces both branches into subjaxprs (ours stores them as Python functions), hence requires the same return shape and dtype.

Loops: fori_loop, while_loop and scan

A Python for inside jit is unrolled: a thousand iterations mean a thousand copies of the body in jaxpr and slow compilation. For long loops or traced iteration counts, jax.lax offers three primitives:

PrimitivePython semanticsReverse-mode differentiable
lax.fori_loop(a, b, cuerpo, x)for i in range(a, b): x = cuerpo(i, x)yes, if a and b are static
lax.while_loop(cond, cuerpo, x)while cond(x): x = cuerpo(x)no (forward mode only)
lax.scan(f, c, xs)for x in xs: c, y = f(c, x); returns c and stacked yyes
from jax import lax
lax.fori_loop(0, 10, lambda i, s: s + i, 0)                  # 45
def paso(c, x):
    c = c + x
    return c, c ** 2
lax.scan(paso, 0.0, jnp.arange(1.0, 5.0))                    # (10., [  1.,   9.,  36., 100.])

lax.scan is JAX’s natural training loop: state (c) is parameters and optimizer state, each step’s input (xs) is step index or minibatch, and stacked output metrics. The body is traced once and XLA compiles the whole loop. while_loop cannot be reverse-mode differentiated because iteration count is unknown until execution and reverse mode needs to save them all; JAX says so with an explicit error and suggests scan.

An easily forgotten jit timing detail: as in CUDA, execution is asynchronous. The call returns once work is queued, with an array whose value does not yet exist. Measured without waiting, the final section’s 3000-step training “takes” 0.09 ms; with .block_until_ready(), nearly half a second. Any JAX measurement follows benchmarking methodology with that addition: warm up (first call compiles) and wait for the result.

vmap: write one example, execute the batch

jax.vmap(f, in_axes=0, out_axes=0) is the vectorization transformation. in_axes says for each argument which axis to traverse (None for an argument shared by all batch elements), and out_axes where to put the output batch axis. Its semantics is one equation:

vmap⁡(f)(X)[i]=f(X[i]),i=0,…,B−1,\operatorname{vmap}(f)(X)[i] = f(X[i]), \qquad i = 0, \dots, B - 1,

with indices applied on indicated axes. It is exactly np.stack([f(x) for x in X]) without the loop: the vectorization done manually in NumPy by rewriting f to accept another axis is done here by the transformation.

A = jnp.arange(6.0).reshape(2, 3)
v = jnp.array([1.0, 0.0, -1.0])
jax.vmap(jnp.dot, in_axes=(0, None))(A, v)                    # [-2. -2.]: un producto escalar por fila
jax.vmap(lambda x: x.sum(), in_axes=1)(A)                     # [3. 5. 7.]: recorre las columnas
jax.vmap(lambda x: jnp.outer(x, x), out_axes=2)(jnp.ones((5, 3))).shape   # (3, 3, 5)
producto = jax.vmap(jax.vmap(lambda a, b: a * b, in_axes=(None, 0)), in_axes=(0, None))
producto(jnp.arange(3.0), jnp.arange(4.0)).shape              # (3, 4): un vmap por eje
print(jax.make_jaxpr(jax.vmap(lambda x, w: jnp.tanh(x @ w), in_axes=(0, None)))(jnp.ones((8, 3)), jnp.ones(3)))
# { lambda ; a:f32[8,3] b:f32[3]. let
#     c:f32[8] = dot_general[
#       dimension_numbers=(([1], [0]), ([], []))
#       preferred_element_type=float32
#     ] a b
#     d:f32[8] = tanh c
#   in (d,) }

The last jaxpr is key: there is no loop. vmap does not execute ff BB times; it executes it once with tracers carrying a batch axis, and each primitive has a batching rule saying how to apply it to operands with that axis. One example’s dot product, dot_general over (3,)⋅(3,)(3,) \cdot (3,), becomes matrix-vector multiplication over (8,3)⋅(3,)(8, 3) \cdot (3,).

fi=xi⊤w,i=1,…,Bf_i = \vb{x}_i\T\vb{w}, \quad i = 1, \dots, B
What the user writes: one example's dot product, with batch on examples and shared weights (in_axes=(0, None)).
1/4

A toy vmap

The definition’s version, a loop and stack, is the reference against which any implementation is checked:

[ ]vmap by definition: loop and stackBrowser
import time

def vmap_bucle(f, in_axes=0):
    """vmap por definición: recorrer el eje de lote, llamar a f con cada rebanada y apilar."""
    def g(*args):
        ejes = in_axes if isinstance(in_axes, tuple) else (in_axes,) * len(args)
        B = {a.shape[e] for a, e in zip(args, ejes) if e is not None}
        assert len(B) == 1, f"tamaños de lote distintos: {B}"
        B = B.pop()
        salidas = [f(*[a if e is None else np.take(a, i, axis=e) for a, e in zip(args, ejes)]) for i in range(B)]
        return np.stack(salidas)
    return g

def neurona(w, x):                     # un solo ejemplo: w (d,), x (d,)
    return np.tanh(x @ w)

rng = np.random.default_rng(0)
w, X = rng.normal(size=8), rng.normal(size=(4000, 8))
y_bucle = vmap_bucle(neurona, in_axes=(None, 0))(w, X)
print(y_bucle.shape, np.allclose(y_bucle, np.tanh(X @ w)))

The real version propagates batch axis. A Lote object wraps an array with batch axis at position 0, and primitives receiving a Lote apply their rule: elementwise operations align operands by inserting size-1 axes after batch, matrix multiplication distinguishes which operands carry batch, and reductions shift their axis.

[ ]vmap with batching rulesBrowser
class Lote:
    """Un array con un eje de lote, siempre en la posición 0. `v.shape[1:]` es la forma de un ejemplo."""
    def __init__(self, v):
        self.v = v

    @property
    def ndim_ej(self):
        return self.v.ndim - 1

def _alinear(a, b):
    """Lleva los dos operandos a arrays de NumPy con el lote en el eje 0 y el mismo número de ejes."""
    if isinstance(a, Lote) and isinstance(b, Lote):
        va, vb, n = a.v, b.v, max(a.ndim_ej, b.ndim_ej)
        # broadcasting por ejemplo: rellenar con ejes de tamaño 1 justo después del eje de lote
        va = va.reshape(va.shape[:1] + (1,) * (n - a.ndim_ej) + va.shape[1:])
        vb = vb.reshape(vb.shape[:1] + (1,) * (n - b.ndim_ej) + vb.shape[1:])
        return va, vb
    if isinstance(a, Lote):                  # b no tiene lote: el broadcasting normal ya es correcto
        b = np.asarray(b)
        return a.v.reshape(a.v.shape[:1] + (1,) * max(0, b.ndim - a.ndim_ej) + a.v.shape[1:]), b
    va, vb = _alinear(b, a)
    return vb, va

def regla_elemento(fn):
    def r(a, b):
        return Lote(fn(*_alinear(a, b)))
    return r

def regla_matmul(a, b):
    if not isinstance(b, Lote):                  # (B, ..., k) @ b: matmul ya trata el eje 0 como lote
        return Lote(a.v @ b)
    if not isinstance(a, Lote):
        a = np.asarray(a)
        return Lote(b.v @ a.T if b.ndim_ej == 1 else a @ b.v)   # a @ b_i para cada i
    # los dos con lote: un producto distinto por ejemplo
    if b.ndim_ej == 1:
        return Lote(np.einsum("b...k,bk->b...", a.v, b.v))
    return Lote(np.einsum("bk,bkn->bn", a.v, b.v) if a.ndim_ej == 1 else a.v @ b.v)

def regla_suma(a, eje=None):
    if eje is None:
        return Lote(a.v.reshape(a.v.shape[0], -1).sum(1))
    return Lote(a.v.sum(axis=eje + 1 if eje >= 0 else eje))   # el eje de un ejemplo se desplaza uno

Lote.__add__ = lambda a, b: regla_elemento(np.add)(a, b)
Lote.__radd__ = lambda a, b: regla_elemento(np.add)(b, a)
Lote.__mul__ = lambda a, b: regla_elemento(np.multiply)(a, b)
Lote.__rmul__ = lambda a, b: regla_elemento(np.multiply)(b, a)
Lote.__matmul__ = regla_matmul
Lote.__rmatmul__ = lambda a, b: regla_matmul(b, a)

# primitivas "de la librería": despachan a la regla de lote si reciben un Lote
tanh = lambda x: Lote(np.tanh(x.v)) if isinstance(x, Lote) else np.tanh(x)
suma_ = lambda x, eje=None: regla_suma(x, eje) if isinstance(x, Lote) else np.sum(x, axis=eje)

def vmap(f, in_axes=0, out_axes=0):
    def g(*args):
        ejes = in_axes if isinstance(in_axes, tuple) else (in_axes,) * len(args)
        entr = [a if e is None else Lote(np.moveaxis(a, e, 0)) for a, e in zip(args, ejes)]
        sal = f(*entr)
        return np.moveaxis(sal.v, 0, out_axes) if isinstance(sal, Lote) else sal
    return g

def neurona2(w, x):
    return tanh(x @ w)

def mlp(params, x):                    # un ejemplo: x (d,)
    W1, b1, W2 = params
    h = tanh(x @ W1 + b1)
    return h @ W2

params = (rng.normal(size=(8, 16)), rng.normal(size=16), rng.normal(size=16))
for nombre, fn, a in [("neurona", neurona2, w), ("mlp", mlp, params)]:
    t0 = time.perf_counter(); yb = vmap_bucle(fn, in_axes=(None, 0))(a, X); t1 = time.perf_counter()
    yr = vmap(fn, in_axes=(None, 0))(a, X); t2 = time.perf_counter()
    print(f"{nombre}: iguales {np.allclose(yb, yr)}, bucle {1e3*(t1-t0):.1f} ms, reglas {1e3*(t2-t1):.2f} ms")

# dos argumentos con lote: un conjunto (ensemble) de 4000 neuronas, cada una con su ejemplo
Ws = rng.normal(size=(4000, 8))
print("ensemble:", np.allclose(vmap(neurona2, in_axes=(0, 0))(Ws, X), np.tanh((Ws * X).sum(1))))
# el lote puede entrar por cualquier eje: in_axes=1 recorre las columnas
print("in_axes=1:", np.allclose(vmap(lambda x: suma_(x * x), in_axes=1)(X.T), (X ** 2).sum(1)))

Functions neurona2 and mlp are written for one example and know nothing of batch; the same neurona2 works for an example batch and a neuron set depending on in_axes. The rule-based version is much faster than a loop because it makes one NumPy call per primitive rather than per example. What this toy lacks to be JAX is composition: a Lote inside another Lote (two nested vmaps) or a Lote whose content is a grad tracer. JAX solves it by assigning each transformation a level and making each primitive consult the highest-level interpreter first; Autodidax explains in detail.

Pytrees: parameters as nested structures

Network parameters are not one array: they are a list of layers, each with matrix and bias, perhaps with a dictionary of normalization statistics. JAX has no nn.Module in core; instead all transformations accept nested structures.

params = {"capa1": {"W": jnp.ones((2, 3)), "b": jnp.zeros(3)}, "capa2": [jnp.ones(3), None, (1.0, 2)]}
hojas, estructura = jax.tree.flatten(params)
[getattr(h, "shape", h) for h in hojas]    # [(2, 3), (3,), (3,), 1.0, 2]
estructura                                 # PyTreeDef({'capa1': {'W': *, 'b': *}, 'capa2': [*, None, (*, *)]})
jax.tree.map(lambda h: h * 2, params)["capa2"]   # [Array([2., 2., 2.]), None, (2.0, 4)]

p = {"W": jnp.ones((2, 3)), "b": jnp.zeros(3)}
g = jax.tree.map(jnp.ones_like, p)
jax.tree.map(lambda p, g: p - 0.1 * g, p, g)["b"]            # [-0.1 -0.1 -0.1]: SGD en una línea
jax.tree.map(lambda a, b: a + b, {"W": 1.0, "b": 2.0}, {"W": 1.0})
# ValueError: pytree structure error: different numbers of pytree children at key path

Three things make pytrees the piece connecting everything:

  • Gradient has parameter structure. grad(perdida)(params, X, Y) returns a pytree identical to params with gradients in leaves, and SGD update is tree.map over both trees. That is why tree.map with several trees requires matching structure: it makes accidentally adding one layer’s gradient to another impossible.
  • in_axes is also a pytree, a prefix of the argument tree: in_axes=(None, 0, 0) shares the entire parameter tree and traverses data, and in_axes=({"W": 0, "b": None},) would vectorize matrices only.
  • Optimizer state is a pytree. In optax, opt = optax.adam(1e-3), estado = opt.init(params) and actualizacion, estado = opt.update(grads, estado, params) are pure functions; Adam state is tuple (ScaleByAdamState(count, mu, nu), EmptyState()) where mu and nu are pytrees shaped like parameters. Compared with the PyTorch optimizer API, nothing mutates: state enters and exits and can be saved, vectorized or differentiated like any other value.

For your own classes, @jax.tree_util.register_dataclass on a @dataclass registers fields as children. What lies behind jax.tree fits in a cell:

[ ]Pytrees from scratchBrowser
def aplanar(arbol):
    """Devuelve (hojas, estructura). Nodos internos: dict (claves ordenadas), list, tuple y None (sin hojas)."""
    if arbol is None:
        return [], ("None",)
    if isinstance(arbol, dict):
        claves = sorted(arbol)
        partes = [aplanar(arbol[k]) for k in claves]
        return [h for p in partes for h in p[0]], ("dict", tuple(claves), tuple(p[1] for p in partes))
    if isinstance(arbol, (list, tuple)):
        partes = [aplanar(x) for x in arbol]
        return [h for p in partes for h in p[0]], (type(arbol).__name__, len(arbol), tuple(p[1] for p in partes))
    return [arbol], ("*",)                                # cualquier otra cosa es una hoja

def contar(est):
    return 1 if est[0] == "*" else 0 if est[0] == "None" else sum(contar(e) for e in est[-1])

def reconstruir(est, hojas):
    it = iter(hojas)
    def r(e):
        if e[0] == "*":
            return next(it)
        if e[0] == "None":
            return None
        hijos = [r(x) for x in e[-1]]
        return dict(zip(e[1], hijos)) if e[0] == "dict" else list(hijos) if e[0] == "list" else tuple(hijos)
    return r(est)

def tree_map(f, arbol, *otros):
    hojas, est = aplanar(arbol)
    resto = []
    for o in otros:
        h, e = aplanar(o)
        if e != est:
            raise ValueError(f"estructuras distintas: {e} frente a {est}")
        resto.append(h)
    return reconstruir(est, [f(*hs) for hs in zip(hojas, *resto)])

params = {"capa2": {"W": np.ones((16, 1)), "b": np.zeros(1)}, "capa1": {"W": np.ones((2, 16)), "b": np.zeros(16)}}
hojas, est = aplanar(params)
print("hojas:", [h.shape for h in hojas])          # capa1 antes que capa2, W antes que b
print("estructura:", est)
print("parámetros:", sum(h.size for h in hojas), " hojas según la estructura:", contar(est))
grads = tree_map(np.ones_like, params)
nuevos = tree_map(lambda p, g: p - 0.1 * g, params, grads)   # SGD sobre todo el árbol en una línea
print("b de capa1 tras un paso:", nuevos["capa1"]["b"][:3])
try:
    tree_map(lambda a, b: a + b, params, {"capa1": params["capa1"]})
except ValueError as e:
    print("ValueError:", str(e)[:70], "...")

Leaf order (capa1 before capa2 even if written in reverse) matches JAX and matters: when jit flattens arguments, leaves are jaxpr’s traced arguments and structure forms part of cache key. Changing parameter structure (add a layer, change list to tuple) recompiles.

Explicit randomness: keys instead of state

A global-state generator like torch.manual_seed or np.random is incompatible with pure functions: every call reads and modifies hidden state. Inside jit, np.random.rand() is evaluated once during tracing and becomes constant; inside vmap, there would be no way to say which number belongs to each batch element. JAX removes state.

clave = jax.random.key(0)                   # Array((), dtype=key<fry>), datos [0 0]
k1, k2 = jax.random.split(clave)            # datos [1797259609 2579123966] y [928981903 3453687069]
jax.random.normal(k1, (3,))                 # [ 1.0040143 -0.9063372 -0.7481722], y otra vez lo mismo
jax.random.fold_in(clave, 1)                # datos [928981903 3453687069]: ¡es k2!
claves = jax.random.split(clave, 4)
jax.vmap(lambda k: jax.random.normal(k, ()))(claves)   # [ 1.0040143 -2.4424558  1.2956359 -0.6219436]

Threefry is a counter-based generator, in the same family as Philox used by PyTorch on GPU: a 64-bit-to-64-bit bijection TkT_k, built like a block cipher with 20 rounds of addition, rotation and XOR, applied to a counter. With JAX’s default configuration (jax_threefry_partitionable), all operations are TkT_k applied to counters (0,i)(0, i), giving exact properties worth knowing because they explain subtler errors.

All three are checked in the following Threefry cell against JAX values. They imply silent errors: mixing split and fold_in on one key repeats keys (fold_in(k, 1) was k2); consuming an already split key produces numbers that are XOR of its children’s words; and reusing a key with two different shapes does not give different numbers but the same stream of another length. None raises an error. Debug check jax.config.update("jax_debug_key_reuse", True) raises KeyReuseError when a key is consumed twice (two random functions, or a split then random function), catching the second and third; it misses the first because the checker does not count fold_in as consumption: split(k) followed by fold_in(k, t) passes silently (checked in JAX 0.12). Against that, only discipline works: dedicate a child key to fold_in and use it for nothing else.

InteractiveThe key tree
clave = jax.random.key(semilla)
k_init, k_datos, k_drop = jax.random.split(clave, 3)
k1, k2, k3 = jax.random.split(k_init, 3)
for t in range(pasos):
k_lote = jax.random.fold_in(k_datos, t)
k_t = jax.random.fold_in(k_drop, t)
kd1 = kd2 = k_t
# the parent key is no longer used
clavekey(0)00000000 00000000
k_initsplit(clave, 3)[0]6b200159 99ba4efe
k1split(k_init, 3)[0]f84e8312 2fef64f3
init W1
k2split(k_init, 3)[1]50afc224 7e1f9c78
init W2
k3split(k_init, 3)[2]a93d9cf0 9315c51c
init W3
k_datossplit(clave, 3)[1]375f238f cddb151d
k_lotefold_in(k_datos, 0)14a3cc6a 157dcf0f
shuffle, step 0
k_lotefold_in(k_datos, 1)ec87e92f e9dec87f
shuffle, step 1
k_dropsplit(clave, 3)[2]f71f4ea9 a20e4081
k_tfold_in(k_drop, 0)a6e4607f 41e28f3e
dropout layer 1, step 0A
dropout layer 2, step 0A
k_tfold_in(k_drop, 1)e129dfaa 08a5d987
dropout layer 1, step 1B
dropout layer 2, step 1B
  • dropout mask (filled = retained)
  • first 8 uniform values from key
  • reused key
0
2
Mistakes
Keys in tree11
Consumptions9
Keys consumed at least twice2
No error or warning, but A: dropout layer 1, step 0, dropout layer 2, step 0; B: dropout layer 1, step 1, dropout layer 2, step 1 receive exactly the same numbers.
Training distributes randomness from one key: initialization of three layers, data shuffling and dropout in two layers at each step. Each row is a derived key (with two 32-bit words) and to its right what each consumer obtains: dropout mask or first eight uniform values. Initial state has an error: both dropout layers use the same key. Find the letter revealing it and fix it by clicking the line. Then enable other errors one by one. With ‘use parent key’, compare the XOR reading with the proposition. Numbers are JAX's.

The initial identical masks are the error nobody sees: dropout keeps “working”, loss falls, and both layers always switch off the same neurons, so dropout regularization loses independence between layers. Without deriving the key by step it is worse: mask is identical throughout training and dropout becomes fixed network pruning. The correct version is error-free state, with a property worth emphasizing: step tt‘s key is fold_in(k_drop, t), a function of tt independent of prior events. Resuming training at step 5000 requires restoring no generator state: just know you are at step 5000. This is exact resumption by construction, and seeding strategy reduces to one root seed and a named derivation tree.

The generator fits in one NumPy cell and reproduces JAX bit for bit:

[ ]Threefry-2x32 from scratch, compared with JAXBrowser
U32 = np.uint32

def rotl(x, r):
    return (x << U32(r)) | (x >> U32(32 - r))

def threefry2x32(clave, x0, x1):
    """Threefry-2x32 con 20 rondas: cifra los contadores (x0, x1) con la clave de 64 bits."""
    k0, k1 = U32(clave[0]), U32(clave[1])
    ks = [k0, k1, k0 ^ k1 ^ U32(0x1BD11BDA)]
    x = [np.asarray(x0, np.uint32) + ks[0], np.asarray(x1, np.uint32) + ks[1]]
    for i in range(5):                                       # 5 bloques de 4 rondas
        for r in ((13, 15, 26, 6), (17, 29, 16, 24))[i % 2]:
            x[0] = x[0] + x[1]
            x[1] = rotl(x[1], r) ^ x[0]
        x[0] = x[0] + ks[(i + 1) % 3]                        # inyección de la clave
        x[1] = x[1] + ks[(i + 2) % 3] + U32(i + 1)
    return x

def key(semilla):
    return np.array([0, semilla], np.uint32)

def split(clave, n=2):
    a, b = threefry2x32(clave, np.zeros(n, np.uint32), np.arange(n, dtype=np.uint32))
    return np.stack([a, b], axis=-1)

def fold_in(clave, dato):
    a, b = threefry2x32(clave, np.zeros(1, np.uint32), np.array([dato], np.uint32))
    return np.array([a[0], b[0]], np.uint32)

def bits(clave, n):
    a, b = threefry2x32(clave, np.zeros(n, np.uint32), np.arange(n, dtype=np.uint32))
    return a ^ b

def uniform(clave, n):
    """Los 23 bits altos como mantisa de un float32 en [1, 2), menos 1."""
    return ((bits(clave, n) >> U32(9)) | U32(0x3F800000)).view(np.float32) - np.float32(1)

# valores que da jax.random en JAX 0.12 con las mismas llamadas
jax_split = [[1832780943, 270669613], [64467757, 2916123636], [2465931498, 255383827]]
jax_fold = [2547012911, 1371500959]
jax_unif = [0.48870957, 0.6797972, 0.6162715, 0.5610161, 0.4506446]
print("split(key(42), 3) como en JAX:", (split(key(42), 3) == np.array(jax_split, np.uint32)).all())
print("fold_in(key(42), 7) como en JAX:", (fold_in(key(42), 7) == np.array(jax_fold, np.uint32)).all())
print("uniform(key(42), 5):", uniform(key(42), 5), np.allclose(uniform(key(42), 5), jax_unif, atol=0, rtol=1e-7))
print("fold_in(k, 1) == split(k)[1]:", (fold_in(key(0), 1) == split(key(0))[1]).all())

# el error más común: la misma clave para el dropout de dos capas
k_t = fold_in(key(0), 3)
m1, m2 = uniform(k_t, 10_000) < 0.5, uniform(k_t, 10_000) < 0.5
print("misma clave: las dos máscaras coinciden en", (m1 == m2).mean(), "de las posiciones")
kd1, kd2 = split(k_t)
m1, m2 = uniform(kd1, 10_000) < 0.5, uniform(kd2, 10_000) < 0.5
print("con split:   coinciden en", (m1 == m2).mean(), "(independientes: 0.5 en media)")

uniform uses a classic trick: with exponent 127 and sign 0, the 23 mantissa bits uniformly traverse [1,2)[1, 2) in 2−232^{-23} steps; subtracting 1 gives [0,1)[0, 1) without division. Counter-based design makes randomness commute with transformations: vmap over a batch of keys yields an independent stream per element, and jit compiles a pure key function like any other.

A pure JAX MLP, and the same in PyTorch

With the four pieces (transformations, jit, pytrees and keys), write complete training without a neural-network library. The task: classify two interleaved spirals of 4096 points with a 2→64→64→12 \to 64 \to 64 \to 1 MLP with tanh⁡\tanh, binary cross-entropy and SGD in minibatches of 256.

import numpy as np
import jax, jax.numpy as jnp
from jax import lax

def espirales(n, ruido=0.08, semilla=0):
    rng = np.random.default_rng(semilla)
    t = np.sqrt(rng.uniform(0, 1, n)) * 3 * np.pi
    y = rng.integers(0, 2, n)
    r, ang = t / (3 * np.pi), t + np.pi * y
    X = np.stack([r * np.cos(ang), r * np.sin(ang)], 1) + ruido * rng.normal(size=(n, 2))
    return X.astype(np.float32), y.astype(np.float32)

X, Y = map(jnp.asarray, espirales(4096))

def init_mlp(clave, tamaños):
    claves = jax.random.split(clave, len(tamaños) - 1)          # una clave por capa
    return [{"W": jax.random.normal(k, (m, n)) * jnp.sqrt(1.0 / m), "b": jnp.zeros(n)}
            for k, m, n in zip(claves, tamaños[:-1], tamaños[1:])]

def logit(params, x):                       # un solo ejemplo: x tiene forma (2,)
    for capa in params[:-1]:
        x = jnp.tanh(x @ capa["W"] + capa["b"])
    return (x @ params[-1]["W"] + params[-1]["b"])[0]

def perdida_ej(params, x, y):               # entropía cruzada binaria, estable
    z = logit(params, x)
    return jnp.logaddexp(0.0, z) - y * z

def perdida(params, X, Y):
    return jax.vmap(perdida_ej, in_axes=(None, 0, 0))(params, X, Y).mean()

@jax.jit
def paso(params, Xb, Yb):
    l, g = jax.value_and_grad(perdida)(params, Xb, Yb)
    return jax.tree.map(lambda p, gp: p - 0.5 * gp, params, g), l

def entrenar(params, clave, pasos, B=256):
    def cuerpo(params, t):
        idx = jax.random.randint(jax.random.fold_in(clave, t), (B,), 0, X.shape[0])
        return paso(params, X[idx], Y[idx])
    return lax.scan(cuerpo, params, jnp.arange(pasos))
entrenar = jax.jit(entrenar, static_argnums=(2, 3))

clave_init, clave_datos = jax.random.split(jax.random.key(0))
params = init_mlp(clave_init, [2, 64, 64, 1])
[h.shape for h in jax.tree.leaves(params)]     # [(2, 64), (64,), (64, 64), (64,), (64, 1), (1,)]: 4417 parámetros
perdida(params, X, Y)                          # 0.7707
params, perdidas = entrenar(params, clave_datos, 3000)
perdidas.block_until_ready()                   # 1.ª llamada: 0.75 s (compila); 2.ª: 0.47 s, unos 160 µs por paso
perdida(params, X, Y)                          # 0.0794, con una exactitud del 97.0 %

g_ej = jax.vmap(jax.grad(perdida_ej), in_axes=(None, 0, 0))(params, X[:8], Y[:8])
[h.shape for h in jax.tree.leaves(g_ej)][:2]   # [(8, 2, 64), (8, 64)]: el árbol de parámetros con un eje de lote
jnp.sqrt(sum(jnp.sum(h.reshape(8, -1) ** 2, axis=1) for h in jax.tree.leaves(g_ej)))
# [0.0431 0.7228 1.4449 0.338  0.0058 0.0828 0.0675 0.4171]: normas de los gradientes por ejemplo

Notice what is absent: no class, mutable state or zero_grad. The model is a function, parameters a pytree, optimization step a function from (parameters, batch) to (new parameters, loss), and entire training a compiled scan. Two runs yield bitwise-identical losses, and the same network trained with a Python loop calling paso yields exactly the same weights. Time changes. On the laptop CPU, with 3000 steps inside a compiled scan, each costs about 160 µs; a Python loop calling a jit function including minibatch selection takes 180 to 240 µs depending on run; and if fold_in, randint and indexing remain outside jit, about 1.3 ms, because each separate JAX operation pays Python dispatch. Absolute numbers change with machine load (other processes can double them); ordering remains: compiled scan, then jit loop, then far behind individual operations.

The course’s PyTorch version, with nn.Module, an optimizer and the usual training loop, and per-example gradients with torch.func:

[ ]The same MLP in PyTorch and per-example gradients with torch.funcLocal GPU
import time, numpy as np, torch
from torch import nn
from torch.func import functional_call, grad, vmap

def espirales(n, ruido=0.08, semilla=0):
    rng = np.random.default_rng(semilla)
    t = np.sqrt(rng.uniform(0, 1, n)) * 3 * np.pi
    y = rng.integers(0, 2, n)
    r, ang = t / (3 * np.pi), t + np.pi * y
    X = np.stack([r * np.cos(ang), r * np.sin(ang)], 1) + ruido * rng.normal(size=(n, 2))
    return X.astype(np.float32), y.astype(np.float32)

def entrenar_torch(dispositivo, pasos=3000, B=256):
    X, Y = (torch.from_numpy(a).to(dispositivo) for a in espirales(4096))
    torch.manual_seed(0)
    modelo = nn.Sequential(nn.Linear(2, 64), nn.Tanh(), nn.Linear(64, 64), nn.Tanh(), nn.Linear(64, 1)).to(dispositivo)
    opt = torch.optim.SGD(modelo.parameters(), lr=0.5)
    gen = torch.Generator(device=dispositivo).manual_seed(0)
    def paso():
        idx = torch.randint(0, X.shape[0], (B,), generator=gen, device=dispositivo)
        perdida = nn.functional.binary_cross_entropy_with_logits(modelo(X[idx]).squeeze(-1), Y[idx])
        opt.zero_grad(set_to_none=True)
        perdida.backward()
        opt.step()
        return perdida
    for _ in range(50):                      # calentamiento
        paso()
    if dispositivo == "cuda":
        torch.cuda.synchronize()
    t0 = time.perf_counter()
    for _ in range(pasos):
        l = paso()
    if dispositivo == "cuda":
        torch.cuda.synchronize()
    dt = (time.perf_counter() - t0) / pasos
    with torch.no_grad():
        acc = ((modelo(X).squeeze(-1) > 0) == (Y > 0.5)).float().mean().item()
    return modelo, X, Y, dt, acc

modelo, X, Y, dt, acc = entrenar_torch("cpu")
print(f"PyTorch eager, CPU: {dt * 1e6:.0f} µs por paso, exactitud {acc:.3f}")
if torch.cuda.is_available():
    *_, dtg, accg = entrenar_torch("cuda")
    print(f"PyTorch eager, GPU: {dtg * 1e6:.0f} µs por paso, exactitud {accg:.3f}")

# gradientes por ejemplo: el mismo vmap(grad(...)) que en JAX
params = {k: v.detach() for k, v in modelo.named_parameters()}
def perdida_ej(params, x, y):
    z = functional_call(modelo, params, (x.unsqueeze(0),)).squeeze()
    return nn.functional.binary_cross_entropy_with_logits(z, y)
por_ejemplo = vmap(grad(perdida_ej), in_dims=(None, 0, 0))
g_ej = por_ejemplo(params, X[:256], Y[:256])
print("formas por ejemplo:", {k: tuple(v.shape) for k, v in list(g_ej.items())[:2]})
normas = torch.sqrt(sum((g.reshape(g.shape[0], -1) ** 2).sum(1) for g in g_ej.values()))
bucle = []
for i in range(4):                           # comprobación: backward ejemplo a ejemplo
    modelo.zero_grad()
    perdida_ej(dict(modelo.named_parameters()), X[i], Y[i]).backward()
    bucle.append(torch.sqrt(sum((p.grad ** 2).sum() for p in modelo.parameters())))
print("normas con vmap:", normas[:4].numpy().round(4), " con un bucle:", torch.stack(bucle).numpy().round(4))
t0 = time.perf_counter()
for _ in range(50):
    por_ejemplo(params, X[:256], Y[:256])
t_vmap = (time.perf_counter() - t0) / 50
t0 = time.perf_counter()
for i in range(256):
    modelo.zero_grad()
    perdida_ej(dict(modelo.named_parameters()), X[i], Y[i]).backward()
print(f"256 gradientes por ejemplo, CPU: vmap {t_vmap * 1e3:.1f} ms, bucle {(time.perf_counter() - t0) * 1e3:.0f} ms")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

On the lab laptop, eager PyTorch step takes 1.1 to 1.4 ms on an unloaded CPU (much longer with other processes), seven to over ten times the JAX scan in the same conditions, with the same final accuracy (the two networks start from different initializations). GPU does not help a 4417-parameter network: step is dominated by tiny kernel launches, not computation. The 256 per-example gradients with vmap cost 5 to 10 ms versus 150 to 300 ms for a backward loop, and in JAX with jit, 1 to 3 ms. The difference is not computation, which is the same, but who organizes it: eager PyTorch dispatches each forward, backward and optimizer operation from Python; JAX compiles the entire step, or all 3000, into one program. torch.compile (the earlier lesson on compilation) closes much of that gap; the programming model remains different.

When each is useful

JAXPyTorch
Modelpure functions and transformationsstateful objects (nn.Module, optimizers) and tensor autograd
Compilationjit whole programs; untraceable code is an erroreager by default; torch.compile with graph breaks and return to Python
Higher-order and per-example derivativesnatural composition of grad, jacfwd, vmaptorch.func with same API, less integrated with rest of ecosystem
Randomnessexplicit keys, reproducible by constructionstateful generators per device
Debuggingharder: inside jit no values (jax.debug.print, jax.disable_jit())print and debugger on any line
EcosystemFlax, optax, orbax, Equinox; dominant on TPU and in some Google researchindustry standard, published models and almost all libraries
Windowsnative CPU; NVIDIA GPU only with WSL2 (experimental)native CPU and GPU

The table’s rule: PyTorch by default, used by the rest of the course and where reusable models live; JAX when the problem is a composition of transformations (higher-order derivatives, vectorizing seeds, environments or hyperparameters, differentiable simulation) or reference code you want to reproduce is written in it. torch.func covers many such cases without changing stack.

For installation in the lab, uv add jax suffices for CPU on native Windows, what this lesson used. For GPU, inside WSL2 with a recent driver, pip install "jax[cuda13]" (or cuda12); according to the installation guide, those packages do not work on native Windows and can silently fail. Above the core, Flax provides network modules (its NNX API restores object style), optax optimizers and Equinox an alternative where models are pytrees.

Common mistakes

Exercises

QuizWhat fails under jit?
Each option is a line inside a function decorated with @jax.jit whose argument x is an array of shape (3,) (and registro = [] is a global list). Which cause the call to fail with an error?

More than one answer may be correct.

NumericCounting compilations
The function @partial(jax.jit, static_argnums=1) def h(x, modo): ... is called many times in an experiment: static argument modo takes 5 distinct integer values and x arrives in 3 distinct shapes (all float32), in any combination. What is the maximum number of compilations?
QuizOne key for two layers
In a training step you write h1 = dropout(k_t, h1, 0.5) and h2 = dropout(k_t, h2, 0.5) with the same key k_t, where dropout uses jax.random.bernoulli(k, 0.5, h.shape). Both activations have shape (256, 512). What happens?
QuizMixing split and fold_in
At the start you do k_init, k_drop = jax.random.split(clave). Later in the loop you write k_paso = jax.random.fold_in(clave, t) for t=0,1,2,…t = 0, 1, 2, \dots What happens?
NumericThe cheaper mode
A function f:R1000→R10f: \R^{1000} \to \R^{10} costs cc to evaluate, and a JVP or VJP costs about 3c3c. You want its full Jacobian. How many products (JVPs or VJPs) does the cheaper option between jacfwd and jacrev perform?
CodePer-example gradients of logistic regression
One example’s logistic regression loss is ℓ(w;x,y)=log⁡(1+ez)−yz\ell(\vb{w}; \vb{x}, y) = \log(1 + e^{z}) - y z with z=x⊤wz = \vb{x}\T\vb{w}. Implement grads_por_ejemplo(w, X, Y), returning a B×dB \times d matrix of each example’s loss gradient with respect to w, and normas(w, X, Y), with each Euclidean norm. Use torch.func, whose API matches JAX (vmap(grad(f), in_dims=...) instead of jax.vmap(jax.grad(f), in_axes=...)). Starter code does the usual PyTorch operation: differentiate mean loss and repeat it in each row. Tests compare with formula (σ(zi)−yi) xi(\sigma(z_i) - y_i)\,\vb{x}_i.
import torch
from torch.func import grad, vmap

def perdida_ej(w, x, y):
  z = x @ w
  return torch.nn.functional.softplus(z) - y * z     # log(1 + e^z) - y z

def grads_por_ejemplo(w, X, Y):
  # gradiente de la pérdida de cada ejemplo respecto a w: forma (B, d)
  g = grad(lambda w: perdida_ej(w, X, Y).mean())(w)
  return g.expand(X.shape[0], -1)

def normas(w, X, Y):
  ...
Shift+Enter to run
CodeBitwise reproducible training with scan
Run the Threefry cell first: this exercise uses its key, fold_in and uniform. Implement scan(f, carry, xs) with lax.scan semantics (return final state and outputs stacked with np.stack) and fix entrenar, linear-regression SGD whose step t chooses a minibatch of 8 indices with uniform. Starter code uses the same key every step, so minibatch never changes. Step t key must be fold_in(clave, t): this makes the trajectory bitwise reproducible and lets it stop and resume at any step without saving generator state.
def scan(f, carry, xs):
  # devuelve (carry final, ys apilados)
  ...

def entrenar(clave, w0, X, Y, ts, eta=0.1, B=8):
  n = X.shape[0]
  def paso(w, t):
      idx = (uniform(clave, B) * n).astype(np.int64)       # ¿qué clave debe usar el paso t?
      Xb, Yb = X[idx], Y[idx]
      r = Xb @ w - Yb
      return w - eta * (2 / B) * (Xb.T @ r), np.mean(r ** 2)
  return scan(paso, w0, ts)
Shift+Enter to run

Summary

  • JAX transforms pure functions. grad, jacfwd, jacrev, vmap and jit take and return functions and compose: vmap(grad(f)) gives per-example gradients, jacfwd(grad(f)) the Hessian. Order matters, and compositions with equal values can have very different costs (jacrev(vmap(f)) is quadratic in batch).
  • Purity. Immutable arrays with .at[], no side effects; what the function does outside arguments and result does not survive transformations.
  • jit traces abstract values. Traced arguments have only shape and dtype; Python control flow on them causes concretization error, while on shapes or statics it resolves during tracing. Cache is indexed by (statics, abstract values): compilation count is distinct keys. lax.cond, fori_loop, while_loop and scan bring control flow into the program.
  • vmap executes the function once with a batch axis and applies each primitive’s batching rule: vectorization manually written in NumPy.
  • Pytrees connect parameters, gradients and optimizer states: same structure, tree.map for everything.
  • Explicit keys. All randomness is a pure key function; split and fold_in derive keys, each key is consumed once and the key folded with fold_in is used for nothing else. With counter-based Threefry, reuse (including mixing split and fold_in) yields identical numbers without warning.
  • JAX versus PyTorch. The same MLP, compiled whole with scan, runs on CPU almost an order of magnitude faster per step than eager PyTorch; PyTorch remains standard, torch.func brings transformations and on Windows JAX is native CPU or GPU with WSL2.
Key idea
In JAX you write one example’s case as a pure function and obtain the rest by transforming it: gradients with grad, batches with vmap, compiled programs with jit. It all works because transformations reinterpret the function with tracers, which also explains every rule: no effects, no control flow on traced values and randomness entering as one more argument, a key used once.