Thinking in JAX

You write a function for one number. JAX hands back its slope, a batched copy and a compiled copy. On our laptop CPU the slope cost 0.52 ms per call op by op, and 0.003 ms once compiled.

Learn the four transforms (jit, grad, vmap, sharding) and the one contract that makes them work: a pure function.

Switch on grad, then vmap, then jit, and press Call twice after each. Watch what each switch changes: the numbers, the shape or the time. Then we build each transform from zero, and the rules that keep it honest.

You need Python and a little NumPy (arrays, shapes, a dot product). We build the rest from zero.

Built on the JAX documentation: Quickstart: How to think in JAX and Common gotchas. Every snippet on this page ran on JAX 0.10.1.

Stack the transforms on f

f(x) = sin(x)² + x. The outputs are what JAX 0.10.1 returns. The times are medians we measured on one laptop CPU (Apple M5 Max). Your machine will give other times, but the same pattern: grad and vmap change what is computed, jit changes how fast.

Chapter 0

Why JAX

See the three things NumPy cannot do for a training loop, and how JAX gets them from one idea

You wrote a small neural network in NumPy. You derived the gradients by hand, and it trains. Now you want a model a thousand times larger, on a GPU. Three things stop you.

  1. Speed. NumPy runs one operation at a time. Each one reads its input from memory and writes its output back.
  2. Gradients. Every new layer means new derivatives by hand.
  3. Batches. Your code handles one example. A batch of 64 means you rewrite it with an extra axis.

JAX is a library that looks like NumPy (jax.numpy.dot, jax.numpy.sum) and adds transforms. A transform takes your function and returns a new function. jit returns a compiled copy. grad returns its derivative. vmap returns a batched copy. Sharding spreads the work over many devices.

All four rest on one trick. JAX calls your function once with stand-in values, records every operation, and works on that record. The record goes to XLA (Accelerated Linear Algebra), a compiler that fuses many small operations into a few large ones. The device below counts what fusion saves.

Count the trips to memory

Each block is one operation on a big array. Drag the chain length, then switch between op by op and fused.

10

The trip count is a simplified model: XLA may not fuse every operation. We timed a chain of 50 elementwise operations on one million float32 values (JAX 0.10.1, laptop CPU). It took about 11 ms op by op and about 4 ms under jit.

Op by op, a chain of 50 operations moves the array through memory 100 times. Fused, it moves twice: one read, one write. On our CPU that took the chain from about 11 ms to about 4 ms. On a GPU the gap is often larger, because there memory is the slow part.

The price is a contract. Your function must be pure: its output depends only on its inputs, and it changes nothing outside itself. Chapter 2 shows what breaks when you forget.

The failure: JAX that is no faster than NumPy

Symptom: you port code to JAX and it runs no faster. Measure: time the second call, not the first, and end the timer with .block_until_ready(). JAX returns before the device finishes, so a bare timer measures almost nothing. Fix: wrap the whole training step in one jit, not many small pieces.

The road

  1. Arrays: what changes from NumPy (no in-place writes, float32, silent bounds).
  2. Pure functions: the contract, and the stale value you get when you break it.
  3. jit: tracing, the jaxpr, and when JAX compiles again. The hero's jit switch.
  4. Control flow: why if fails under jit and what to use instead.
  5. grad: exact slopes from the recorded operations. The hero's grad switch.
  6. vmap: one function, a whole batch. The hero's vmap switch.
  7. PyTrees and the training step: nested parameters, and a live training loop.
  8. Random keys: randomness without hidden state.
  9. Many devices: meshes, shardings and gradient averaging.
  10. Field guide: terms, numbers, the checklist and the core code.
What lets JAX compile, differentiate and batch the same function?

Chapter 1

Arrays: What Changes from NumPy

Replace in-place writes with new arrays, and learn the three quiet defaults that surprise NumPy users

In NumPy you write x[0] = 99 and the array changes. In JAX the same line raises a TypeError. A JAX array (jax.Array) is immutable: once made, it never changes. To "change" it, you ask for a new array.

pythonimport jax.numpy as jnp
x = jnp.array([10, 20, 30])
y = x.at[0].set(99)     # y = [99 20 30], x is still [10 20 30]
z = x.at[1].add(5)      # z = [10 25 30]

Why? The compiler must see every change as an output of the function. A hidden write would be invisible to it. Under jit, XLA can do the update in place anyway, so the copy usually costs nothing.

Out of range indices behave differently too. A compiled program cannot raise a Python error halfway through, so JAX picks a safe answer. A read clamps to the nearest valid index. JAX drops a write to a bad index. Try it.

Index past the end

The array is [10, 20, 30]. Choose read or write, then drag the index past either end.

1

The JAX results are what JAX 0.10.1 returns: x[10] gives 30, x[-10] gives 10, and x.at[10].set(7) returns the array unchanged. For writes, the NumPy row shows x[i] = 99.

Two more defaults

JAX makes float32 arrays by default, where NumPy makes float64. GPUs and TPUs are much faster at 32 bits. If you need 64 bits, set jax.config.update("jax_enable_x64", True) at startup.

JAX also divides by zero in silence. NumPy prints a warning and returns inf or nan. JAX returns the same values with no warning, so a NaN can spread through a whole training run.

How small a step can float32 see?

A float32 number keeps 24 significant bits. So there is a gap between a weight and the next number float32 can store. Call the weight w. Call the gap Δ (delta). It grows with the size of w, by a fixed fraction called ε (epsilon).

Say it aloud

Delta is about epsilon times the size of w, and epsilon is two to the minus twenty-three.

Δ
delta the gap between w and the next float32 number above it.
ε
epsilon the float32 machine epsilon: the gap just above 1.
|w|
the size of w the weight without its sign.
2−23
two to the minus twenty-three about 0.000000119. It comes from the 23 stored fraction bits.
In plain words

Multiply the size of w by epsilon to get the gap delta. An update smaller than half of delta rounds away, and w does not move.

With numbers

At w = 1, delta = 2−23 ≈ 0.000000119, so half of delta is 0.0000000596. An update of 0.00000005 is smaller, and float32 gives 1.0 back. At w = 1024, delta = 0.000122, so updates below 0.000061 vanish.

The failure: a weight that will not move

Symptom: loss stalls although gradients are not zero. Measure: compare each update with half the gap delta for its weight. Fix: raise the learning rate or rescale the weights, or turn on 64 bits for that run. For NaNs, set jax_debug_nans to True: JAX then raises a FloatingPointError at the first NaN.

Why can you not write x[0] = 99 on a JAX array?

Chapter 2

Pure Functions: The Contract

Learn what JAX asks of your function, and watch a compiled function keep a stale value

Every transform makes the same deal. Give it a pure function, and it gives you speed, slopes and batches. Break the deal, and you get wrong answers with no error.

A pure function has two properties.

  1. The same inputs always give the same output. It reads no global variable, no file and no hidden random state.
  2. It has no side effects: it prints nothing, writes no global and changes none of its arguments.

Why does JAX care? The first time you call a jitted function, JAX does not run it on your numbers. It runs it on tracers: stand-in values that carry only a shape and a type, and record each operation done to them. Anything that is not an operation on a tracer happens once, at trace time, and then never again.

A global variable is the classic case. JAX reads it while tracing and bakes its value into the compiled program as a constant.

pythonbias = 1.0
def add_bias(x):
    return x + bias          # bias is read at trace time
f = jax.jit(add_bias)
f(5.0)                       # 6.0
bias = 2.0
f(5.0)                       # still 6.0: the compiled program kept 1.0
f(jnp.array(5, dtype=jnp.int32))  # 7.0: a new dtype forced a new trace

The last line is the nasty part. The stale value lasts only until something forces a new trace. So the same call can return 6 one minute and 7 the next. Step through it.

Catch the stale global

Press the buttons in any order. Purple is trace time. Blue is the compiled program. Red marks a wrong answer.

The behaviour matches JAX 0.10.1 on the code above: f(5.0) gives 6.0 before and after bias changes, and an int32 call retraces and gives 7.0.

print follows the same rule. Inside a jitted function it runs once, at trace time, and shows a tracer such as JitTracer(~float32[]). To print the real value on every call, use jax.debug.print("x = {}", x). It puts a print step into the compiled program.

The failure, and the fix

Symptom: a setting changes in your code but the results do not. Measure: call the function after the change and compare with a hand calculation. Fix: pass everything the function reads as an argument. Then bias is a traced input, and f(5.0, 2.0) gives 7.0 at once.

You put print(x) inside a jitted function and call it three times with float32 scalars. What do you see?

Chapter 3

jit: Trace Once, Compile, Run Many Times

Follow one call from tracers to a jaxpr to XLA, and count what a new shape costs

Call jax.jit(f) and nothing runs yet. On the first call, three steps happen.

  1. Trace. JAX calls f on tracers and records each operation.
  2. Compile. XLA turns the record into one program for your device.
  3. Run. The program runs on your real numbers. Later calls skip to this step.

The record is a jaxpr (JAX expression). Every value in it has a name, a type and a shape, and nothing in it has side effects. jax.make_jaxpr shows it.

pythondef f(x):
    return jnp.sin(x) ** 2 + jnp.cos(x) ** 2
print(jax.make_jaxpr(f)(jnp.array(1.0)))
# { lambda ; a:f32[]. let
#     b:f32[] = sin a
#     c:f32[] = integer_pow[y=2] b
#     d:f32[] = cos a
#     e:f32[] = integer_pow[y=2] d
#     f:f32[] = add c e
#   in (f,) }

f32[] means a float32 with no axes, a scalar. The tracer never saw the number 1.0. It saw only "a float32 scalar". So the compiled program works for any float32 scalar, and JAX keeps it in a cache keyed by the shapes and dtypes of the inputs.

What changes between callsNew trace?Why
Array valuesNoSame shape and dtype: a cache hit.
Array shapeYesA different program.
Array dtypeYesDifferent machine types.
A Python float's valueNoIt becomes a traced float32 scalar.
Python int in place of a floatYesThe dtype changes.
An argument in static_argnumsWhen its value changesIts value is part of the cache key.

How much does a new shape cost? Call the number of compiles C and the time of one compile Tc. Call the number of calls N and the run time of one cached call Tr. The total time is T.

Say it aloud

T equals C times T-c, plus N times T-r.

T
T the total time of all the calls, in ms.
C
C how many times JAX traced and compiled: once per new shape and dtype.
Tc
T-c the time of one trace and compile, in ms.
N
N how many calls you make.
T-r
T-r the run time of one call to the compiled program, in ms.
In plain words

Pay T-c once for every compile C. Pay T-r for every call N. Add the two.

With numbers

From our CPU, a chain of 50 operations: T-c ≈ 25 ms and T-r ≈ 0.1 ms on 1,000 values. Twenty calls at one shape: T = 1 × 25 + 20 × 0.1 = 27 ms. Twenty calls at twenty shapes: T = 20 × 25 + 2 = 502 ms. We measured 494 ms. Compiles are almost the whole bill.

Feed the cache

Each call adds a bar. Purple and blue mean trace and compile. Teal means a cached run. Try the same shape twice, then a new shape every call.

We rounded T-c = 25 ms and T-r = 0.1 ms from our measurement (JAX 0.10.1, laptop CPU, 50 elementwise operations). Bar heights use a square-root scale so that both fit.

The failure: shape churn

Symptom: every step is slow, though the second call should be fast. Measure: count traces, for example with a counter inside the function, or set jax_log_compiles to True. Fix: pad inputs to a few fixed sizes (buckets), so the cache stays small.

You call a jitted function with a (4, 3) array, then with another (4, 3) float32 array of different values. Does JAX trace again?

Chapter 4

Control Flow Under jit

See why a Python if fails on a tracer, why a Python loop unrolls, and pick the lax primitive that fixes each

Write if x > 0: inside a jitted function and call it. JAX raises a TracerBoolConversionError (a kind of ConcretizationTypeError). The tracer knows that x is a float32 scalar. It does not know whether x is positive, so Python cannot pick a branch.

Python for loops run too, but at trace time. A loop of 10 steps records 10 copies of its body. The jaxpr grows with the loop, and so does the compile time. Drag the loop length below.

Unroll a loop, or keep it rolled

The loop body is x = x × 1.01 + 1, two operations. Drag the step count and compare the two ways to write it.

10

Measured with JAX 0.10.1 on our laptop CPU. The Python loop records 20, 200 and 2,000 operations for 10, 100 and 1,000 steps. Its first call takes about 15, 27 and 159 ms. fori_loop records one operation (a scan), and its first call takes 11 to 12 ms at every length.

The fix is the structured control flow in jax.lax. Each one takes your branch or loop body as a function, traces it once, and hands XLA a real branch or a real loop.

PythonUnder jit, useWhen
if / elselax.cond(pred, f_true, f_false, x)Branch on a traced value.
a value picked elementwisejnp.where(x > 0, x, -x)Both sides are cheap.
for with a fixed countlax.fori_loop(0, n, body, x)Many steps.
whilelax.while_loop(cond, body, x)The stop depends on values.
for that collects outputslax.scan(step, carry, xs)An RNN, a running sum.
python@jax.jit
def good_abs(x):
    return jax.lax.cond(x > 0, lambda x: x, lambda x: -x, x)
good_abs(-3.0)                                     # 3.0
jax.lax.scan(lambda c, x: (c + x, c + x), 0.0, jnp.array([1., 2., 3., 4.]))
# (10.0, [1. 3. 6. 10.]): the final carry, and every step's output

A third way: if you know a value before the call, such as a layer count, mark it with static_argnums. A Python if on it then works, and each new value gets its own compile.

The failure: a compile that takes minutes

Symptom: the first call of a training step takes far longer than later calls. Measure: print len(jax.make_jaxpr(f)(x).jaxpr.eqns). Thousands of operations point to an unrolled loop. Fix: move the loop into lax.fori_loop or lax.scan.

Inside a jitted function you need a loop of 10,000 steps that carries a state. What should you write?

Chapter 5

grad: Exact Slopes from the Recorded Operations

See why nudging the input fails, then walk the trace backwards and add the slopes

Take f(x) = sin(x)² + x. You want its slope at x = 0.5. The obvious way is to nudge the input. Call the nudge h, and the slope estimate f′(x) (f-prime of x).

Say it aloud

f-prime of x is about f of x plus h, minus f of x, all over h.

f′(x)
f-prime of x the slope of f at the point x.
f(x + h)
f of x plus h the function at the nudged input.
f(x)
f of x the function at the input.
h
h the nudge, a small positive number.
In plain words

Run f at x and at x plus h. Subtract the two outputs. Divide by h.

With numbers

At x = 0.5 the true slope is sin(1) + 1 = 1.8415. In float32 with h = 0.0001 the estimate is about 1.84. With h = 0.0000001, rounding takes over and the estimate falls to about 1.79. And a model with 100 million weights needs 100 million extra runs of f.

So nudging is slow and fragile. Automatic differentiation gives the exact slope of all inputs at once. It costs a small, fixed multiple of one run of f, whether f has one input or a million. JAX records f as a chain of primitives (sin, square, add), each with a known slope. Then it walks the record backwards. This is reverse mode.

Write the chain with names: y = sin(x), z = y², L = z + x. The backward walk gives every value an adjoint: how much the output L changes per unit change of that value. Call the adjoint of x x̄ (x-bar). x feeds two operations, so it collects one term from each.

Say it aloud

x-bar equals the sum over every use u of x, of u-bar times the partial of u with respect to x.

x̄
x-bar the adjoint of x: the slope of L with respect to x. This is what grad returns.
Σu
the sum over u one term for each operation u that reads x.
ū
u-bar the adjoint of u, already known because the walk goes backwards.
∂u/∂x
the partial of u with respect to x the local slope of one primitive, such as cos(x) for sin.
In plain words

Start with L-bar = 1. Walk the record from the end. For each value, take every operation u that read it, multiply u-bar by that operation's local slope, and add the products.

With numbers

At x = 1: y = 0.8415, z = 0.7081, L = 1.7081. L-bar = 1, z-bar = 1. y-bar = z-bar × 2y = 1.6829. x is read by sin and by the add, so x-bar = 1.6829 × cos(1) + 1 × 1 = 0.9093 + 1 = 1.9093. jax.grad(f)(1.0) returns 1.9092973.

Exact slope against the nudge

Teal is f. Warm is the tangent from grad. Drag x, then shrink the nudge h and watch the estimate break.

0.50
1e-4

The exact slope is 2 sin(x) cos(x) + 1, the value grad returns. The nudged estimate rounds x + h and each f value to float32, as JAX's default dtype would.

jax.grad(f) returns a function, not a number. Call it like f. Three habits follow.

The failure: grad of an integer

Symptom: jax.grad(f)(3) raises a TypeError. Measure: read the dtype of the input. Fix: pass a float, 3.0. A slope needs real numbers.

What does jax.grad(f) return?

Chapter 6

vmap: One Function, a Whole Batch

Write the code for one example, choose which inputs carry the batch, and get per-example gradients in one line

Your predict(params, x) takes one example: weights of shape (10, 784) and an image of shape (784,). It returns (10,) scores. Now you have 64 images. A Python loop is slow. Rewriting with an extra axis invites bugs.

jax.vmap does the rewrite for you. It traces the function once and adds a batch axis to every operation. The result runs as one batched operation, with no Python loop.

pythondef predict(params, x):        # params (10, 784), x (784,)
    return jnp.dot(params, x)      # (10,)
batched = jax.vmap(predict, in_axes=(None, 0))
batched(params, images).shape      # images (64, 784) -> (64, 10)

in_axes says, for each argument, which axis is the batch. None means "not batched: share it with every example". 0 means "the first axis is the batch". Try the three common choices.

Choose the batch axis

Pink rows carry the batch. Every example shares the grey blocks. Pick in_axes and watch which pieces meet for each example.

Toy shapes, batch of 4: a = a vector of length 3 or a batch (4, 3), b likewise. The function is dot(a, b). The output shapes match what JAX 0.10.1 returns.

Per-example gradients

Transforms compose. Take the loss of one example, ℓ (ell), with weights θ (theta) and an example (xi, yi). Its gradient for that example alone is gi. Privacy methods and data audits need every gi, not their average.

Say it aloud

g-i equals the gradient with respect to theta of ell of theta, x-i, y-i, for i from one to B.

gi
g-i the gradient for example i alone. Same shape as theta.
∇θ
the gradient with respect to theta the direction that raises the loss fastest: jax.grad on argument 0.
ℓ(θ, xi, yi)
ell of theta, x-i, y-i the loss of one example: here (theta · x-i minus y-i) squared.
i = 1 … B
i from one to B one gradient per example in a batch of B.
In plain words

For each example i, take the slope of its own loss ell with respect to theta. vmap does this for all B examples at once: jax.vmap(jax.grad(loss), in_axes=(None, 0, 0)).

With numbers

With made-up numbers: theta = (1, 2). Example 1: x = (1, 0), y = 0, prediction 1, so g-1 = 2 × (1 − 0) × (1, 0) = (2, 0). Example 3: x = (1, 1), y = 5, prediction 3, so g-3 = 2 × (3 − 5) × (1, 1) = (−4, −4). JAX returns these rows exactly.

The failure: mismatched batch sizes

Symptom: ValueError: vmap got inconsistent sizes for array axes to be mapped. Measure: print the shape of each argument and its batch axis. Fix: mark shared arguments, such as weights, with None.

In vmap(f, in_axes=(None, 0)), what does None mean for the first argument?

Chapter 7

PyTrees and the Training Step

Hold every weight in one nested structure, update all of it with one line, and train a model live

A network's weights are not one array. They are a dict of layers, each a dict of arrays. JAX calls any nesting of lists, tuples and dicts a PyTree. The arrays at the bottom are its leaves.

pythonparams = {'layer1': {'w': jnp.zeros((784, 256)), 'b': jnp.zeros(256)},
          'layer2': {'w': jnp.zeros((256, 10)),  'b': jnp.zeros(10)}}
leaves, treedef = jax.tree.flatten(params)
[l.shape for l in leaves]   # [(256,), (784, 256), (10,), (256, 10)]: dict keys in sorted order
grads = jax.grad(loss)(params, x)   # the same tree: grads['layer1']['w'] has shape (784, 256)

Every transform takes PyTrees. It flattens the tree into a list of leaves plus a treedef (the shape of the nesting), works on the list, and rebuilds the tree. So grad hands back gradients in the same tree as the weights.

Now the update. Call a weight θ (theta), its gradient g, and the learning rate η (eta).

Say it aloud

Theta becomes theta minus eta times g.

θ ←
theta becomes the new value of one leaf. In JAX this is a new array, not an overwrite.
θ
theta the old value of that leaf.
η
eta the learning rate: how big a step to take.
g
g the gradient leaf in the same place of the grads tree.
In plain words

For every leaf, multiply its gradient g by eta and subtract it from theta. jax.tree.map(lambda p, g: p - lr * g, params, grads) does this for all leaves and keeps the tree.

With numbers

In the device below, at the start: w = 0, b = 0, loss 3.0, gradients g-w = −2 and g-b = 2. With eta = 0.05: w = 0 − 0.05 × (−2) = 0.1 and b = 0 − 0.05 × 2 = −0.1. The loss falls to 2.615. JAX gives the same numbers.

Run the training step

Teal dots are data on the line y = 2x − 1. The teal line is the model. Warm boxes hold the gradients of w and b. Step, or run 40 steps, then push the learning rate past 1.

0.05

Five points x = −1, −0.5, 0, 0.5, 1 with y = 2x − 1, mean squared error. The browser computes the gradient by hand; the first step matches jax.value_and_grad on the same data. The steps diverge for a learning rate above 1, because the loss curves twice as fast along b as along w.

This is the whole pattern of JAX training code. All state lives in a PyTree. The step function takes it in and returns the new one. One jit wraps the step, and value_and_grad gives the loss and the gradients together.

python@jax.jit
def train_step(params, x, y, lr):
    loss, grads = jax.value_and_grad(loss_fn)(params, x, y)
    params = jax.tree.map(lambda p, g: p - lr * g, params, grads)
    return params, loss

The failure: a learning rate that explodes

Symptom: the loss grows each step, then becomes NaN. Measure: log the loss every step and watch the sign of each update flip. Fix: lower eta below 2 divided by the steepest curvature of the loss. Here that limit is 2 / 2 = 1.

What structure does jax.grad(loss)(params, x) return?

Chapter 8

Random Numbers Without Hidden State

Carry randomness as a key you split, and see the bug a reused key makes

Each call to np.random.randn() changes a hidden counter inside NumPy. That is a side effect. Under jit, the counter would be read once at trace time, and every call would get the same "random" numbers.

JAX makes the state visible. A PRNG key (pseudo-random number generator key) is a small array you pass in. The same key always gives the same numbers. To get new numbers, you split a key into fresh keys.

pythonimport jax.random as jr
key = jr.key(42)                   # the root key from a seed
key, sub = jr.split(key)           # keep one key for later, use the other now
noise = jr.normal(sub, (3, 3))
keys = jr.split(key, 10)            # ten keys at once, for example one per layer

Keys work under jit and vmap, because a key is an ordinary input. The rule is short: use each key once. Split before you draw, and keep one child to split again. The keys form a tree. The same root always grows the same tree, so a run is reproducible. Different branches give independent numbers.

Grow the key tree

Yellow keys are fresh. Grey keys are spent. Split, draw, then press Reuse to draw twice from one key.

The numbers come from a toy hash of each key's path in the tree, not from JAX's generator. What is real: one key always gives one sequence, which JAX 0.10.1 confirms for jr.normal.

In a training loop, split at the top of every step.

pythonkey = jr.key(0)
for step in range(1000):
    key, drop_key = jr.split(key)          # a fresh key for this step's dropout
    params, loss = train_step(params, batch, drop_key)

The failure: the same dropout mask every step

Symptom: dropout does not regularise, and two "random" initial layers come out equal. Measure: draw twice with the keys you pass and compare: equal draws mean a reused key. Fix: split inside the loop and never pass the same key to two draws.

You pass the same key to two calls of jr.normal. What happens?

Chapter 9

Many Devices: Meshes, Shardings and pmean

Say where each piece of an array lives, let jit place the work, and average gradients across copies

One GPU has finite memory and finite speed. To train on eight, you must say where each piece of each array lives. In JAX you do not write "run this on GPU 3". You describe the layout, and the compiler places the work.

Three objects describe a layout. A mesh is a grid of devices with named axes, such as 2 × 4 named ('data', 'model'). A PartitionSpec says which array axis splits along which mesh axis. A NamedSharding joins the two.

pythonfrom jax.sharding import NamedSharding, PartitionSpec as P
mesh = jax.make_mesh((2, 4), ('data', 'model'))
w = jax.device_put(w, NamedSharding(mesh, P(None, 'model')))   # columns split 4 ways
x = jax.device_put(x, NamedSharding(mesh, P('data')))          # batch split 2 ways
y = jax.jit(lambda w, x: x @ w)(w, x)   # w (4, 8), x (16, 4): y (16, 8), split on both axes

The simplest layout is data parallel. Every device holds a full copy of the weights and a slice of the batch. Each device computes the gradient on its slice. Then the devices average their gradients, so every copy takes the same step.

Call the number of devices D, the gradient on device d gd, and the averaged gradient g.

Say it aloud

g equals one over D, times the sum over d of g-d.

g
g the averaged gradient. Every device ends with this same value.
D
D the number of devices on the mesh axis.
Σd
the sum over d one term per device, from 1 to D.
gd
g-d the gradient device d computed on its slice of the batch.
In plain words

Each device computes g-d on its own slice. Add the D gradients and divide by D. jax.lax.pmean(g, 'data') does both and gives every device the result.

With numbers

With made-up numbers on 4 devices: g-d = 1, 2, 3 and 6. Sum 12, D = 4, so g = 3 on every device. With equal slices this equals the gradient of the whole batch. JAX 0.10.1 returns [3, 3, 3, 3] for this case.

Average the gradients

A batch of 32 examples in pink. Choose a device count, then run one step: split, compute, average.

Illustrative: each example has a made-up gradient value. The average is exact: the mean of the device means equals the mean of all 32 values when slices are equal.

For code that must see its own slice, jax.shard_map runs your function once per device, and collectives such as pmean move data between them. The older jax.pmap still works, but its own docs call it the old way and point to shard_map.

LayoutWhat you splitWhen
Data parallelThe batchThe model fits on one device.
Model (tensor) parallelWeight matricesOne layer is too big for one device.
Pipeline parallelGroups of layersThe model has many layers.
FSDPWeights and optimizer state, gathered on useData parallel that runs out of memory.

The failure: copies that drift apart

Symptom: loss differs between devices and gets worse over time. Measure: compare a weight across devices after a few steps. Fix: average the gradients (or the loss) across the data axis before the update.

What does jax.lax.pmean(g, 'data') do?

Chapter 10

Field Guide

Keep the terms, the numbers, the checklist and the core code in one place

JAX gives you four transforms of a pure function: jit compiles it, grad differentiates it, vmap batches it, and shardings spread it over devices. They work because JAX traces your function into a jaxpr. Every rule on this page protects that trace.

Terms and numbers

TermWhat it isNumber to remember
TracerA stand-in value with a shape and a dtype onlyPrints as JitTracer(~float32[])
jaxprThe recorded list of primitivessin² + cos²: 5 operations
Compile cacheOne program per input shape and dtypeAbout 25 ms per compile against 0.1 ms per run (our CPU)
Python loop under jitUnrolled at trace time1,000 steps: 2,000 operations, 159 ms first call
gradReverse mode on the jaxprgrad(sin²x + x) at 1 = 1.9093
vmapAdds a batch axis to each operation(None, 0): (10, 784) and (64, 784) give (64, 10)
float32JAX's default dtypeε = 2−23 ≈ 1.19 × 10−7
PRNG keyExplicit random state, split before useOne key, one sequence
pmeanAverage across a mesh axis1, 2, 3, 6 on 4 devices: 3 everywhere

The checklist

  1. Pass every input as an argument. No globals inside jit.
  2. Make new arrays with x.at[i].set(v). No in-place writes.
  3. Use lax.cond, fori_loop, while_loop or scan for branches and long loops on traced values.
  4. Keep input shapes fixed, or pad them to a few buckets.
  5. Split a PRNG key before every draw. Never reuse one.
  6. Time the second call, with .block_until_ready().
  7. Debug with jax.debug.print and jax_debug_nans.

The core as code

pythonimport jax, jax.numpy as jnp, jax.random as jr

def init_params(key):
    k1, k2 = jr.split(key)
    return {'w1': jr.normal(k1, (8, 16)) * 0.3, 'b1': jnp.zeros(16),
            'w2': jr.normal(k2, (16, 1)) * 0.3, 'b2': jnp.zeros(1)}

def predict(p, x):                                  # x (batch, 8) -> (batch, 1)
    h = jnp.tanh(x @ p['w1'] + p['b1'])
    return h @ p['w2'] + p['b2']

def loss_fn(p, x, y):
    return jnp.mean((predict(p, x) - y) ** 2)

@jax.jit
def train_step(p, x, y, lr):
    loss, grads = jax.value_and_grad(loss_fn)(p, x, y)
    return jax.tree.map(lambda a, g: a - lr * g, p, grads), loss

key = jr.key(42)
key, pk, xk = jr.split(key, 3)
params = init_params(pk)
x = jr.normal(xk, (256, 8))
y = jnp.sin(x.sum(axis=1, keepdims=True))
for step in range(500):
    params, loss = train_step(params, x, y, 0.1)   # one compile, then 499 cached runs
print(float(loss))                                   # 0.84 at the start, about 0.086 after 500 steps
per_example = jax.vmap(jax.grad(loss_fn), in_axes=(None, 0, 0))(params, x[:, None], y[:, None])
print(per_example['w1'].shape)                        # (256, 8, 16): one gradient tree per example

JAX next to PyTorch

IdeaPyTorchJAX
StyleObjects, runs as it goesFunctions, trace then compile
WeightsInside nn.Module objectsA PyTree you pass in and get back
Gradientsloss.backward() fills .gradgrad(f) returns a function
BatchingWrite the batch axis by handvmap adds it
Compilingtorch.compile, opt injit, the normal way
RandomnessGlobal seedKeys you split

Keep going

The takeaway. Write a pure function for one example. Let grad give the slope, vmap the batch, jit the speed and a sharding the devices. Keep shapes fixed, loops in lax, and keys split.
In a JAX training loop, where does all the changing state live?

Now press Present or Teach and explain from memory: the pure function contract, what a trace records, when JAX compiles again, and how grad, vmap and keys work. Then go back to the hero, switch on all three transforms, and say which one changed the numbers, the shape and the time.

Credit and source

This lesson follows the JAX team's documentation, chiefly Quickstart: How to think in JAX and Common gotchas in JAX. The explanations, toys and timings are our own; every snippet ran on JAX 0.10.1.

Thinking in JAX
How to think in JAX · Common gotchas · Back to Gleams