# One Decorator, 6x Faster: JAX Basics for Inference in 30 Minutes

> Source: <https://dev.to/danielsamfdo/one-decorator-6x-faster-jax-basics-for-inference-in-30-minutes-46n4>
> Published: 2026-11-29 17:07:34+00:00

**Recommendation:** Apply jit to functions called repeatedly in a loop, pad varying sequence lengths into buckets to avoid recompiles, and keep Python side effects and traced-value branching out of jitted code.
More in the playbook "Inference and self-hosting": <https://wpnews.pro/playbooks/inference-serving>

JAX is the library behind most of Google's AI stack — the same numerical core that trains Gemma and runs on TPUs — and it fits in three ideas: `jit` compiles your function, `grad` differentiates it, and sharding splits it across devices. This is GDE post #11, the first post in Lane B, and it is the one the rest of the lane stands on: every Gemma, Keras, and TPU post that follows assumes you can read these three transformations. The good news is that thirty minutes is enough, because JAX is not a framework you learn — it is three function transformations you compose.

The numbers below are measured, not quoted: every figure in this post comes from the companion notebook, run on this machine with JAX 0.12.1 (released November 18, 2026) on a single CPU. The headline: a fused elementwise chain runs 6.13x faster under `jit` — 416.1 ms eager, 67.9 ms compiled — while a bare 4096×4096 matmul only improves 1.21x, because a single BLAS call is already fast and there is nothing to fuse. That split is the whole lesson about when `jit` pays.

Think of NumPy as a chef who cooks one ingredient at a time and washes the pan between each step. `jax.jit` is the same chef with a prep list: it watches the whole recipe first, then cooks everything in one pass, in one pan, without the trips back to the sink. The recipe is your Python function; the watching is called *tracing*; the one-pass cooking is XLA compiling the traced operations into a single fused kernel.

`jax.grad` is the same trick applied backwards. You write the forward computation — a loss, a score, a simulation — and JAX hands you a function that computes its gradient, exactly, by differentiating the traced operations. No finite differences, no hand-written backward pass, and it composes: `grad(grad(f))` is the second derivative, `jit(grad(f))` is a compiled gradient step, and `vmap(grad(f))` is per-example gradients for a whole batch in one call.

Sharding is the third idea and the simplest to state: when one device cannot hold the model, you cut the model up and put the pieces on different devices. JAX 0.12 makes this explicit — `pmap` is now implemented as `jit(shard_map)` and is in maintenance mode, so new code should use `shard_map` and `NamedSharding` directly.

`jit` traces your function with abstract values — shapes and dtypes, not data — lowers the trace to XLA, and compiles it. The first call pays the compile tax: 1.22 seconds on this box for the chain above, versus 67.9 ms per steady-state call. That tax is why `jit` is a serving decision, not a free lunch: if you call the function once, eager is faster. If you call it in a loop — and inference is a loop — the tax amortizes fast. The break-even for the chain is call 4.

The gradient-step number deserves a careful read, because it is the most dramatic and the easiest to misread. A 512×64 linear-loss gradient step takes 17.80 ms eager and 0.01 ms jitted — a 1,780x ratio — but the compute is two million FLOPs, which is microseconds either way. What `jit` removed is Python dispatch: the eager version pays interpreter overhead on every small op, and the jitted version pays it once, at trace time. In a training loop that runs that step ten thousand times, the eager version spends three minutes on dispatch; the jitted version spends a tenth of a second. That is why `jax.jit(jax.grad(loss))` is the standard recipe, straight from the JAX docs.

Three rules keep `jit` predictable. First, shapes are part of the compiled program: call a jitted function with a new shape and it recompiles — 0.13 s on this box, cheap, but a loop over varying sequence lengths recompiles on every length, so pad to buckets. Second, Python side effects do not survive tracing: a `print` inside a jitted function fires once, at trace time, and never again; a global counter stays at its traced value. Third, control flow on traced values needs `lax.cond` / `lax.scan` — a plain Python `if` on an array branches at trace time on the abstract value, which is not what you want.

The notebook checks `grad` against the analytic answer for `sum(sin(x)^2)`, whose derivative is `sin(2x)`. Maximum absolute error: 5.96e-08 — below float32 epsilon (1.19e-07), i.e. exact to the precision of the arithmetic. The second derivative of x³ at 2.0 comes back as exactly 12.0. These are not party tricks; they are the reason JAX is trusted for the backward pass in the first place.

For inference, `grad` matters in two places. The first is evaluation: per-example gradients — `jax.vmap(jax.grad(loss), in_axes=(None, 0, 0))` — give you a (128, 8) gradient matrix for 128 examples in one call, which is how you measure influence, debug a bad example, or build a gradient-based data filter without a Python loop. The second is the new `with_logs` option in 0.12.1: `jax.grad(f, with_logs=True)` returns the gradient plus backward-pass logs, so you can see what the backward pass did without dropping down to `jax.vjp`.

Sharding is decided by arithmetic, not by fashion. Gemma 3 4B is 8.6 GB in bf16 — it fits on one device with room for a KV cache, and sharding it would only add communication. Gemma 3 27B is 54.4 GB in bf16 — it does not fit a 40 GB A100, and in fp32 (108.8 GB) it does not fit an 80 GB H100 either. That is when you shard: two-way tensor parallelism for the 27B in bf16, three or more ways in fp32. The notebook shows the mechanism on one CPU device — a `Mesh`, a `NamedSharding` with `PartitionSpec("x")`, and `jit` with explicit `in_shardings`/` out_shardings` — and the same code runs unchanged on eight TPU cores, which is the point: you declare the placement, XLA does the communication.

Two 0.12 changes to know. The legacy GSPMD partitioner is gone — JAX now always uses the Shardy partitioner, which has been the default for about a year. And `jax.pmap` is now a wrapper around `jit(shard_map)`, with the old C++ pmap infrastructure removed entirely, along with `device_put_sharded` and `device_put_replicated`. If your code still calls `pmap`, it works, but the migration guide says to move to `shard_map` — and this post's notebook is written that way.

Three situations. First, a single call: the 1.22 s compile tax beats any per-call saving, so one-off scripts should stay eager. Second, shape-varying loops with no bucketing: every new shape recompiles, and the tax can exceed the saving. Third, code that is mostly Python — string processing, dict juggling, I/O — gains nothing from XLA and loses readability to tracing rules. JAX is a numerical-computing library that happens to run models; it is not a general-purpose accelerator for arbitrary Python.

`jit(grad(loss))` is the standard training-step recipe, and `vmap(grad)` gives per-example gradients in one call.`NamedSharding`; XLA handles the communication.` pmap` is now `jit(shard_map)`, the Shardy partitioner is the only partitioner, and `grad` gains a `with_logs` option.
*Honesty note: all timing figures are this notebook's measurements on one CPU with JAX 0.12.1 — TPU/GPU speedups differ, and the 1,780x gradient-step ratio is Python dispatch overhead disappearing, not compute. Gemma 3 parameter counts are the published 4.3B/27.2B figures; memory is weights only, before KV cache and activations. JAX 0.12.1 changelog details verified against docs.jax.dev on Nov 29, 2026. No Meta content per the standing exclusion.*

*Companion notebook: `jax_basics_inference.ipynb` — jit speedup measurement, compile tax and break-even, grad accuracy and grad-of-grad, vmap per-example gradients, NamedSharding with jit, all exec-tested on JAX 0.12.1.*

**Companion notebook:** the runnable tutorial for this post — [download it here](https://danielsamfdo.github.io/blog/assets/jax_basics_inference.ipynb) (open in Colab/Jupyter).
