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.
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
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.
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.
Each block is one operation on a big array. Drag the chain length, then switch between op by op and fused.
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.
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.
if fails under jit and what to use instead.Chapter 1
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.
The array is [10, 20, 30]. Choose read or write, then drag the index past either end.
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.
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.
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).
Delta is about epsilon times the size of w, and epsilon is two to the minus twenty-three.
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.
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.
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.
Chapter 2
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.
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.
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.
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.
Chapter 3
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.
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 calls | New trace? | Why |
|---|---|---|
| Array values | No | Same shape and dtype: a cache hit. |
| Array shape | Yes | A different program. |
| Array dtype | Yes | Different machine types. |
| A Python float's value | No | It becomes a traced float32 scalar. |
| Python int in place of a float | Yes | The dtype changes. |
An argument in static_argnums | When its value changes | Its 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.
T equals C times T-c, plus N times T-r.
Pay T-c once for every compile C. Pay T-r for every call N. Add the two.
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.
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.
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.
Chapter 4
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.
The loop body is x = x × 1.01 + 1, two operations. Drag the step count and compare the two ways to write it.
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.
| Python | Under jit, use | When |
|---|---|---|
if / else | lax.cond(pred, f_true, f_false, x) | Branch on a traced value. |
| a value picked elementwise | jnp.where(x > 0, x, -x) | Both sides are cheap. |
for with a fixed count | lax.fori_loop(0, n, body, x) | Many steps. |
while | lax.while_loop(cond, body, x) | The stop depends on values. |
for that collects outputs | lax.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.
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.
Chapter 5
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).
f-prime of x is about f of x plus h, minus f of x, all over h.
Run f at x and at x plus h. Subtract the two outputs. Divide by h.
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.
x-bar equals the sum over every use u of x, of u-bar times the partial of u with respect to x.
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.
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.
Teal is f. Warm is the tangent from grad. Drag x, then shrink the nudge h and watch the estimate break.
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.
grad needs a scalar output. A vector output raises a TypeError.argnums=(0, 1) gives slopes for the first two arguments. The default is the first only.jax.value_and_grad(loss) returns the loss and its gradient from one pass.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.
Chapter 6
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.
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.
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.
g-i equals the gradient with respect to theta of ell of theta, x-i, y-i, for i from one to B.
jax.grad on argument 0.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 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.
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.
Chapter 7
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).
Theta becomes theta minus eta times g.
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.
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.
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.
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
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.
Chapter 8
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.
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)
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.
Chapter 9
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.
g equals one over D, times the sum over d of g-d.
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 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.
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.
| Layout | What you split | When |
|---|---|---|
| Data parallel | The batch | The model fits on one device. |
| Model (tensor) parallel | Weight matrices | One layer is too big for one device. |
| Pipeline parallel | Groups of layers | The model has many layers. |
| FSDP | Weights and optimizer state, gathered on use | Data parallel that runs out of memory. |
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.
Chapter 10
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.
| Term | What it is | Number to remember |
|---|---|---|
| Tracer | A stand-in value with a shape and a dtype only | Prints as JitTracer(~float32[]) |
| jaxpr | The recorded list of primitives | sin² + cos²: 5 operations |
| Compile cache | One program per input shape and dtype | About 25 ms per compile against 0.1 ms per run (our CPU) |
| Python loop under jit | Unrolled at trace time | 1,000 steps: 2,000 operations, 159 ms first call |
| grad | Reverse mode on the jaxpr | grad(sin²x + x) at 1 = 1.9093 |
| vmap | Adds a batch axis to each operation | (None, 0): (10, 784) and (64, 784) give (64, 10) |
| float32 | JAX's default dtype | ε = 2−23 ≈ 1.19 × 10−7 |
| PRNG key | Explicit random state, split before use | One key, one sequence |
| pmean | Average across a mesh axis | 1, 2, 3, 6 on 4 devices: 3 everywhere |
x.at[i].set(v). No in-place writes.lax.cond, fori_loop, while_loop or scan for branches and long loops on traced values..block_until_ready().jax.debug.print and jax_debug_nans.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
| Idea | PyTorch | JAX |
|---|---|---|
| Style | Objects, runs as it goes | Functions, trace then compile |
| Weights | Inside nn.Module objects | A PyTree you pass in and get back |
| Gradients | loss.backward() fills .grad | grad(f) returns a function |
| Batching | Write the batch axis by hand | vmap adds it |
| Compiling | torch.compile, opt in | jit, the normal way |
| Randomness | Global seed | Keys you split |
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.
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.