JAX: A Comprehensive Guide for Python Developers (2026)

Mistral Vibe
Mistral Vibe

JAX has become the de‑facto standard for high‑performance, differentiable scientific computing in Python, offering NumPy‑compatible syntax while delivering automatic differentiation, just‑in‑time compilation, and seamless multi‑device scaling. This guide walks experienced Python developers through every core concept, from basic array creation to production‑grade deployment, using reproducible code snippets that can be run on a laptop or a TPU pod.

Introduction to JAX

What is JAX and why use it

JAX is an open‑source library that extends NumPy with composable function transformations: grad for reverse‑mode autodiff, vmap for vectorized mapping, jit for XLA compilation, and pmap for SPMD parallelism. It lets you write pure Python functions that automatically run on CPUs, GPUs, or TPUs without changing the code.

JAX vs NumPy vs TensorFlow

While NumPy provides eager execution on the host CPU, JAX adds a functional transformation layer that can compile the same code to accelerated hardware. TensorFlow offers similar capabilities but with a heavier graph‑construction API; JAX keeps the API minimal and NumPy‑centric, making it easier to prototype and then scale.

Key features

  • Autograd – reverse‑mode differentiation via jax.grad.
  • vmap – automatic batching without explicit loops.
  • jit – XLA‑based compilation for sub‑millisecond latency.
  • pmap – single‑program multiple‑data execution across many devices.

Installation and setup

pip install --upgrade "jax[cpu]"          # CPU only
pip install --upgrade "jax[cuda]"==0.4.13+cuda12.cudnn89   # GPU
pip install --upgrade "jax[tpu]"          # on Google Cloud TPUs

After installation, verify the backend:

import jax
print(jax.default_backend())  # cpu, gpu, or tpu

JAX Fundamentals

Arrays and creation methods

JAX arrays are immutable DeviceArray objects. Creation mirrors NumPy:

import jax.numpy as jnp

a = jnp.arange(12).reshape(3, 4)
b = jnp.ones((2, 2))
c = jnp.linspace(0, 1, 5)

Random number generation

JAX uses a functional PRNG. A key is split to produce independent streams.

key = jax.random.PRNGKey(42)
key, subkey = jax.random.split(key)
samples = jax.random.normal(subkey, (3, 3))

Array operations and broadcasting

All NumPy broadcasting rules apply, and most ufuncs are available under jax.numpy. Example:

c = a @ b.T + 0.5   # matrix multiplication + broadcasting scalar

Device management

Explicitly move data with jax.device_put or query devices via jax.devices(). The runtime automatically places arrays on the device where the first operation occurs.

Automatic Differentiation with autograd

How autograd works

JAX records a trace of primitive operations and applies the chain rule backward. This is transparent to the user: wrap any pure function with jax.grad.

Computing gradients

def loss(w, x, y):
    pred = jnp.dot(x, w)
    return jnp.mean((pred - y) ** 2)

grad_loss = jax.grad(loss)  # gradient w.r.t. first argument

Higher‑order derivatives

hessian = jax.jacfwd(jax.grad(loss))   # ∂²loss/∂w²

Custom gradients with custom_vjp

When a primitive lacks a stable gradient, define forward and backward passes manually.

@jax.custom_vjp
def stable_log(x):
    return jnp.log(jnp.clip(x, a_min=1e-7))

def stable_log_fwd(x):
    y = stable_log(x)
    return y, y

def stable_log_bwd(res, g):
    y = res
    return (g / jnp.clip(y, a_min=1e-7),)

stable_log.defvjp(stable_log_fwd, stable_log_bwd)

Example: Gradient descent from scratch

def step(w, x, y, lr=0.01):
    g = grad_loss(w, x, y)
    return w - lr * g

w = jnp.zeros(x.shape[1])
for i in range(200):
    w = step(w, x, y)

Vectorization with vmap

What is vmap and why it matters

vmap lifts a scalar‑or‑batch function to operate over an extra dimension, eliminating Python loops and enabling XLA to fuse operations.

Automatic batching

def single_forward(params, x):
    return jnp.tanh(jnp.dot(x, params))

batched_forward = jax.vmap(single_forward, in_axes=(None, 0))
out = batched_forward(params, batch_x)   # batch_x: (batch, dim)

Performance benefits

Benchmarking on a V100 shows a 3× speedup for a 10k‑sample batch compared to a manual loop.

Example: Batched matrix multiplication

def matmul(A, B):
    return jnp.dot(A, B)

batched_matmul = jax.vmap(matmul, in_axes=(0, 0))
C = batched_matmul(A_batch, B_batch)   # shapes (N, M, K) and (N, K, P)

Just‑In‑Time Compilation with jit

What JIT compilation does

jax.jit traces a Python function, lowers it to XLA HLO, and caches the compiled executable for subsequent calls.

Tracing and compilation

@jax.jit
def compute(x):
    return jnp.sin(x) * jnp.exp(x)

y = compute(jnp.arange(1e6))

When to use jit

Apply jit to functions that are called many times with the same shape and dtype. Avoid JIT‑ing tiny functions or those that change shape frequently.

Performance considerations

First call incurs compilation overhead (≈10‑30 ms on GPU). Subsequent calls are typically memory‑bound and run at native XLA speed.

Example: Speeding up functions

def naive(x):
    return jnp.sum(jnp.sin(x) ** 2 + jnp.cos(x) ** 2)

naive_jit = jax.jit(naive)

%timeit naive(jnp.arange(1_000_000))
%timeit naive_jit(jnp.arange(1_000_000))

Parallel Computation with pmap

Single‑program multiple‑data (SPMD)

pmap replicates a function across multiple devices, automatically handling sharding of inputs and aggregation of outputs.

Using pmap for multi‑device computation

def loss_on_device(params, x, y):
    pred = jnp.dot(x, params)
    return jnp.mean((pred - y) ** 2)

parallel_loss = jax.pmap(loss_on_device, in_axes=(None, 0, 0))

# Assume 8‑GPU host, split data accordingly
x_sharded = x.reshape(8, -1, x.shape[1])
y_sharded = y.reshape(8, -1)

losses = parallel_loss(params, x_sharded, y_sharded)
print(jnp.mean(losses))

Sharding and replication

Use jax.sharding (JAX 0.4+) for fine‑grained control: NamedSharding or Mesh to describe device topology.

Example: Distributed training

def step(params, opt_state, x, y):
    grads = jax.grad(loss_on_device)(params, x, y)
    updates, opt_state = optimizer.update(grads, opt_state)
    return optax.apply_updates(params, updates), opt_state

p_step = jax.pmap(step, in_axes=(None, None, 0, 0))

for epoch in range(10):
    params, opt_state = p_step(params, opt_state, x_sharded, y_sharded)

Functional Programming in JAX

Pure functions in JAX

All JAX transformations assume functions are side‑effect free: no mutation of inputs, no global state, and deterministic outputs for a given PRNG key.

Functional transformations

Combine jit, vmap, and grad to build pipelines:

train_step = jax.jit(jax.grad(loss))
batched_step = jax.vmap(train_step, in_axes=(None, 0, 0))

Avoiding side effects

Use jax.lax.scan for loops that need to carry state without Python iteration.

def scan_body(carry, x):
    w = carry
    grad = jax.grad(loss)(w, x, y)
    return w - 0.01 * grad, None

final_w, _ = jax.lax.scan(scan_body, init_w, data_batch)

Building Neural Networks with JAX

Layer patterns in JAX

Without a high‑level library, define layers as pure functions returning (output, new_params).

def dense(params, x):
    w, b = params
    return jnp.dot(x, w) + b

def init_dense(key, in_dim, out_dim):
    k1, k2 = jax.random.split(key)
    w = jax.random.normal(k1, (in_dim, out_dim)) * jnp.sqrt(2 / in_dim)
    b = jnp.zeros(out_dim)
    return (w, b)

Parameter initialization

Leverage the functional PRNG pattern shown above to keep randomness reproducible.

Training loops

def mlp(params, x):
    for w, b in params[:-1]:
        x = jax.nn.relu(dense((w, b), x))
    w, b = params[-1]
    return dense((w, b), x)

@jax.jit
def loss(params, x, y):
    preds = mlp(params, x)
    return jnp.mean((preds - y) ** 2)

grad_loss = jax.jit(jax.grad(loss))

def train(params, data, epochs=100, lr=1e-3):
    opt_state = optax.adam(lr).init(params)
    for epoch in range(epochs):
        grads = grad_loss(params, data.x, data.y)
        updates, opt_state = optax.adam(lr).update(grads, opt_state)
        params = optax.apply_updates(params, updates)
    return params

JAX Ecosystem

Flax for neural networks

Flax provides a module system, mutable collections, and checkpoint utilities while preserving JAX’s functional core.

Haiku for modular models

Haiku, from DeepMind, offers a lightweight object‑oriented wrapper that still respects functional purity via hk.transform.

Orbax for checkpointing

Orbax integrates with both Flax and Haiku, supporting async writes and sharded checkpoints on multi‑node clusters.

Optax for optimization

Optax supplies a composable set of gradient transformations (Adam, SGD, weight decay, learning‑rate schedules) that work directly with JAX’s grad output.

Other libraries

  • Chex – testing utilities for JAX code.
  • Equinox – PyTree‑friendly object‑oriented models.
  • t5x, alpa – large‑scale training frameworks built on top of JAX.

Performance Optimization

Common performance pitfalls

  • Python loops inside JIT‑compiled functions – replace with lax.scan or vmap.
  • Dynamic shape changes – keep shapes static across calls.
  • Unnecessary data transfer between host and device – use jax.device_get sparingly.

Profiler usage

Run jax.profiler.start_trace("logs/") before the workload and jax.profiler.stop_trace() after; view results in TensorBoard.

Memory management

Leverage jax.experimental.enable_x64() only when needed; otherwise stay in 32‑bit to halve memory footprint. Use jax.checkpoint (remat) to trade compute for memory on deep networks.

Best practices for fast code

  • Batch inputs to fully saturate accelerators.
  • Place large constants as static_argnums in jit to avoid recompilation.
  • Prefer in‑place‑like updates via jax.lax.scatter when mutating large arrays.

JAX for Production

Serialization with Orbax

ckpt = orbax.checkpoint.CheckpointManager("ckpts/")
ckpt.save(step, {"params": params})
restored = ckpt.restore(step, items={"params": orbax.checkpoint.PyTreeCheckpointHandler()})

Deployment considerations

Export JIT‑compiled functions as XLA binaries for serving, or use jax2tf to convert to TensorFlow SavedModel for TensorFlow Serving.

Debugging JAX code

Use jax.debug.print inside JIT functions, and jax.make_jaxpr to inspect the traced computation graph.

Testing strategies

Leverage chex.assert_shape and chex.assert_type in unit tests; run tests with jax.disable_jit() to isolate logic from compilation artifacts.

Comparing JAX to Other Frameworks

JAX vs TensorFlow

TensorFlow provides a mature ecosystem for production pipelines, but JAX offers tighter NumPy compatibility, easier composability of transformations, and often superior single‑node performance.

JAX vs PyTorch

PyTorch’s eager mode is intuitive, yet JAX’s functional approach yields more predictable compilation and scaling; both now support GPU/TPU, but JAX’s pmap is more straightforward for SPMD.

When to choose JAX

Select JAX for research that demands rapid prototyping of novel gradients, large‑scale parallelism, or when you need XLA‑level performance without sacrificing NumPy familiarity.

Hybrid approaches

Combine JAX for core numerics with PyTorch or TensorFlow for data pipelines, leveraging jax.dlpack

Mistral Vibe
  • Mistral Vibe CLI is an open-source, terminal-based AI coding agent developed by Mistral AI. Unlike traditional IDE plugins or web-based assistants, it operates directly in your command line, allowing developers to interact with their codebase using natural language. It is designed to autonomously explore, modify, and execute changes across multiple files while keeping the developer in control.

    The tool is built for agentic software engineering, meaning it doesn't just suggest code snippets but can plan, execute, verify, and iterate on complex tasks like refactoring, debugging, and implementing features. It is released under the Apache 2.0 license, making it fully auditable and extensible.

Blog

Leave a Comment

Your email address will not be published. Required fields are marked *