cd /news/machine-learning/one-decorator-6x-faster-jax-basics-f… Β· home β€Ί topics β€Ί machine-learning β€Ί article
[ARTICLE Β· art-178204] src=dev.to β†— pub= topic=machine-learning verified=true sentiment=↑ positive

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

A developer benchmarked JAX 0.12.1 on a single CPU and found that a fused elementwise chain runs 6.13x faster under jax.jit (416.1 ms eager versus 67.9 ms compiled), while a bare 4096Γ—4096 matmul improves only 1.21x because a single BLAS call has nothing to fuse. The writeup also measured a 512Γ—64 linear-loss gradient step dropping from 17.80 ms eager to 0.01 ms jitted, attributing the gap to eliminated Python dispatch rather than compute, and noted that jit's 1.22-second compile tax breaks even at the fourth call. The post frames JAX as three composable transformations β€” jit, grad and sharding β€” and flags that pmap is now implemented as jit(shard_map) and in maintenance mode, with new code directed to shard_map and NamedSharding.

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 playbook: Inference and self-hosting
by read6 min views5 publishedNov 29, 2026

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 (open in Colab/Jupyter).

── more in #machine-learning 4 stories Β· sorted by recency
── more on @jax 3 stories trending now
sponsored brought to you by zahid.host 4,200+ EU-deployed projects
reading about agents? ship yours in a single git push.

Run your AI side-project on zahid.host

EU-based hosting, git-push deploys, automatic HTTPS, no cold starts. Free tier with a custom domain β€” perfect for shipping the agent you just read about.

$git push zahid main
β†’ Live at https://your-agent.zahid.host βœ“
Get free account β†’ Pricing
from €0/mo Β· no card required
LIVE [news/one-decorator-6x-fas…] indexed:0 read:6min 2026-11-29 Β· β€”