jax
Composable transformations of Python+NumPy programs: differentiate, vectorize, JIT to GPU/TPU, and more
Top Related Projects
Flax is a neural network library for JAX that is designed for flexibility.
Tensors and Dynamic neural networks in Python with strong GPU acceleration
An Open Source Machine Learning Framework for Everyone
DeepSpeed is a deep learning optimization library that makes distributed training and inference easy, efficient, and effective.
Distributed training framework for TensorFlow, Keras, PyTorch, and Apache MXNet.
🤗 Transformers: the model-definition framework for state-of-the-art machine learning models in text, vision, audio, and multimodal models, for both inference and training.
Quick Overview
JAX is a high-performance numerical computing library developed by Google Research. It combines NumPy's familiar API with the benefits of automatic differentiation and GPU/TPU acceleration. JAX is designed for machine learning research and large-scale numerical computations.
Pros
- Automatic differentiation for efficient gradient computations
- Seamless GPU and TPU acceleration
- Just-in-time (JIT) compilation for improved performance
- Functional programming paradigm for better composability and parallelism
Cons
- Steeper learning curve compared to pure NumPy
- Limited support for imperative-style programming
- Smaller ecosystem compared to more established frameworks like TensorFlow or PyTorch
- Some operations may be slower than in other libraries when not JIT-compiled
Code Examples
- Basic array operations:
import jax.numpy as jnp
x = jnp.array([1, 2, 3])
y = jnp.array([4, 5, 6])
z = jnp.dot(x, y)
print(z) # Output: 32
- Automatic differentiation:
from jax import grad
def f(x):
return x ** 2
df = grad(f)
print(df(3.0)) # Output: 6.0
- JIT compilation:
from jax import jit
import jax.numpy as jnp
@jit
def matrix_multiply(a, b):
return jnp.dot(a, b)
a = jnp.array([[1, 2], [3, 4]])
b = jnp.array([[5, 6], [7, 8]])
result = matrix_multiply(a, b)
print(result)
Getting Started
To get started with JAX, follow these steps:
- Install JAX and its dependencies:
pip install --upgrade pip
pip install --upgrade "jax[cuda]" -f https://storage.googleapis.com/jax-releases/jax_cuda_releases.html
- Import JAX in your Python script:
import jax
import jax.numpy as jnp
from jax import grad, jit, vmap
- Start using JAX for numerical computations and machine learning tasks:
# Define a function
def f(x):
return jnp.sum(jnp.sin(x))
# Compute its gradient
grad_f = grad(f)
# Use it on some data
x = jnp.arange(5.0)
print(grad_f(x))
This will get you started with basic JAX functionality. For more advanced usage, refer to the official documentation and examples.
Competitor Comparisons
Flax is a neural network library for JAX that is designed for flexibility.
Pros of Flax
- Higher-level API, making it easier to build and train neural networks
- Includes pre-built modules and layers for common architectures
- Better documentation and tutorials for beginners
Cons of Flax
- Less flexible than JAX for custom, low-level operations
- Smaller community and ecosystem compared to JAX
- May have slightly higher overhead due to abstraction layers
Code Comparison
JAX (low-level):
import jax.numpy as jnp
from jax import grad, jit
def loss(params, x, y):
return jnp.mean((params[0] * x + params[1] - y) ** 2)
grad_loss = jit(grad(loss))
Flax (high-level):
import flax.linen as nn
class LinearModel(nn.Module):
@nn.compact
def __call__(self, x):
return nn.Dense(1)(x)
model = LinearModel()
Both JAX and Flax are powerful libraries for machine learning in Python, with JAX providing a low-level, flexible foundation and Flax offering a higher-level, more user-friendly interface built on top of JAX. The choice between them depends on the specific needs of the project and the developer's experience level.
Tensors and Dynamic neural networks in Python with strong GPU acceleration
Pros of PyTorch
- Easier to debug with eager execution by default
- More extensive ecosystem and community support
- Better support for dynamic computational graphs
Cons of PyTorch
- Generally slower compilation times compared to JAX
- Less efficient automatic differentiation for large models
Code Comparison
PyTorch:
import torch
def model(x):
return torch.nn.functional.relu(x)
x = torch.randn(5)
y = model(x)
JAX:
import jax.numpy as jnp
from jax import grad, jit
def model(x):
return jnp.maximum(x, 0)
x = jnp.randn(5)
y = jit(model)(x)
Both frameworks offer similar syntax for defining and using models, but JAX's jit
compilation can provide performance benefits for repeated computations. PyTorch's eager execution makes debugging easier, while JAX's functional approach and automatic differentiation can lead to more efficient and scalable code for certain use cases.
An Open Source Machine Learning Framework for Everyone
Pros of TensorFlow
- Extensive ecosystem with tools like TensorBoard for visualization
- Robust production deployment options (TensorFlow Serving, TensorFlow Lite)
- Larger community and more extensive documentation
Cons of TensorFlow
- More complex API compared to JAX's simplicity
- Less flexibility for custom gradient computations
- Slower compilation times for large models
Code Comparison
TensorFlow:
import tensorflow as tf
x = tf.constant([[1., 2.], [3., 4.]])
y = tf.matmul(x, x)
JAX:
import jax.numpy as jnp
x = jnp.array([[1., 2.], [3., 4.]])
y = jnp.matmul(x, x)
Both frameworks offer similar syntax for basic operations, but JAX provides a more NumPy-like interface. TensorFlow's API is more verbose, especially for more complex operations. JAX's functional approach and automatic differentiation make it easier to work with custom gradients and transformations, while TensorFlow's object-oriented approach can be more intuitive for some developers. TensorFlow's eager execution mode brings it closer to JAX's immediate execution style, but JAX still maintains an edge in terms of simplicity and flexibility for research-oriented tasks.
DeepSpeed is a deep learning optimization library that makes distributed training and inference easy, efficient, and effective.
Pros of DeepSpeed
- Optimized for distributed training and large-scale models
- Offers ZeRO optimizer for efficient memory usage
- Provides pipeline parallelism for training very large models
Cons of DeepSpeed
- Primarily focused on PyTorch, less flexible across frameworks
- Steeper learning curve for advanced features
- May have more overhead for smaller models or single-GPU setups
Code Comparison
DeepSpeed:
model_engine, optimizer, _, _ = deepspeed.initialize(
args=args,
model=model,
model_parameters=params
)
JAX:
@jax.jit
def train_step(state, batch):
def loss_fn(params):
logits = model.apply(params, batch['x'])
return optax.softmax_cross_entropy_with_integer_labels(logits, batch['y'])
grad_fn = jax.value_and_grad(loss_fn)
loss, grads = grad_fn(state.params)
state = state.apply_gradients(grads=grads)
return state, loss
DeepSpeed excels in distributed training and memory optimization for large models, while JAX offers more flexibility and ease of use for a wider range of applications. DeepSpeed's code focuses on initialization and distributed setup, whereas JAX's code showcases its functional approach and automatic differentiation capabilities.
Distributed training framework for TensorFlow, Keras, PyTorch, and Apache MXNet.
Pros of Horovod
- Designed specifically for distributed deep learning, offering excellent scalability across multiple GPUs and nodes
- Supports multiple deep learning frameworks (TensorFlow, PyTorch, MXNet) with a unified API
- Integrates well with existing codebases, requiring minimal changes to enable distributed training
Cons of Horovod
- Limited to distributed training use cases, not as versatile for general-purpose machine learning tasks
- Requires additional setup and configuration compared to JAX's simpler approach
- May have a steeper learning curve for users not familiar with distributed computing concepts
Code Comparison
Horovod (with TensorFlow):
import horovod.tensorflow as hvd
hvd.init()
optimizer = tf.optimizers.Adam(lr * hvd.size())
optimizer = hvd.DistributedOptimizer(optimizer)
JAX:
from jax import pmap, grad
@pmap
def update(params, x, y):
loss = loss_fn(params, x, y)
return params - learning_rate * grad(loss_fn)(params, x, y)
Both JAX and Horovod offer powerful tools for machine learning, but they serve different purposes. JAX provides a flexible, high-performance framework for numerical computing and machine learning, while Horovod focuses on distributed deep learning across multiple GPUs and nodes.
🤗 Transformers: the model-definition framework for state-of-the-art machine learning models in text, vision, audio, and multimodal models, for both inference and training.
Pros of Transformers
- Extensive pre-trained model library for various NLP tasks
- High-level API for easy model fine-tuning and deployment
- Active community and frequent updates
Cons of Transformers
- Limited to transformer-based architectures
- Heavier dependency footprint
- Less flexibility for custom low-level operations
Code Comparison
Transformers example:
from transformers import BertTokenizer, BertForSequenceClassification
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
model = BertForSequenceClassification.from_pretrained('bert-base-uncased')
JAX example:
import jax.numpy as jnp
from jax import grad, jit
def loss(params, x, y):
return jnp.sum((params * x - y)**2)
grad_loss = jit(grad(loss))
JAX offers more flexibility for custom computations and automatic differentiation, while Transformers provides ready-to-use models for NLP tasks. JAX is better suited for researchers and those needing low-level control, whereas Transformers is ideal for practitioners looking to quickly implement state-of-the-art NLP models.
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME

Transformable numerical computing at scale
Transformations | Scaling | Install guide | Change logs | Reference docs
What is JAX?
JAX is a Python library for accelerator-oriented array computation and program transformation, designed for high-performance numerical computing and large-scale machine learning.
JAX can automatically differentiate native
Python and NumPy functions. It can differentiate through loops, branches,
recursion, and closures, and it can take derivatives of derivatives of
derivatives. It supports reverse-mode differentiation (a.k.a. backpropagation)
via jax.grad
as well as forward-mode differentiation,
and the two can be composed arbitrarily to any order.
JAX uses XLA
to compile and scale your NumPy programs on TPUs, GPUs, and other hardware accelerators.
You can compile your own pure functions with jax.jit
.
Compilation and automatic differentiation can be composed arbitrarily.
Dig a little deeper, and you'll see that JAX is really an extensible system for composable function transformations at scale.
This is a research project, not an official Google product. Expect sharp edges. Please help by trying it out, reporting bugs, and letting us know what you think!
import jax
import jax.numpy as jnp
def predict(params, inputs):
for W, b in params:
outputs = jnp.dot(inputs, W) + b
inputs = jnp.tanh(outputs) # inputs to the next layer
return outputs # no activation on last layer
def loss(params, inputs, targets):
preds = predict(params, inputs)
return jnp.sum((preds - targets)**2)
grad_loss = jax.jit(jax.grad(loss)) # compiled gradient evaluation function
perex_grads = jax.jit(jax.vmap(grad_loss, in_axes=(None, 0, 0))) # fast per-example grads
Contents
- Transformations
- Scaling
- Current gotchas
- Installation
- Neural net libraries
- Citing JAX
- Reference documentation
Transformations
At its core, JAX is an extensible system for transforming numerical functions.
Here are three: jax.grad
, jax.jit
, and jax.vmap
.
Automatic differentiation with grad
Use jax.grad
to efficiently compute reverse-mode gradients:
import jax
import jax.numpy as jnp
def tanh(x):
y = jnp.exp(-2.0 * x)
return (1.0 - y) / (1.0 + y)
grad_tanh = jax.grad(tanh)
print(grad_tanh(1.0))
# prints 0.4199743
You can differentiate to any order with grad
:
print(jax.grad(jax.grad(jax.grad(tanh)))(1.0))
# prints 0.62162673
You're free to use differentiation with Python control flow:
def abs_val(x):
if x > 0:
return x
else:
return -x
abs_val_grad = jax.grad(abs_val)
print(abs_val_grad(1.0)) # prints 1.0
print(abs_val_grad(-1.0)) # prints -1.0 (abs_val is re-evaluated)
See the JAX Autodiff Cookbook and the reference docs on automatic differentiation for more.
Compilation with jit
Use XLA to compile your functions end-to-end with
jit
,
used either as an @jit
decorator or as a higher-order function.
import jax
import jax.numpy as jnp
def slow_f(x):
# Element-wise ops see a large benefit from fusion
return x * x + x * 2.0
x = jnp.ones((5000, 5000))
fast_f = jax.jit(slow_f)
%timeit -n10 -r3 fast_f(x)
%timeit -n10 -r3 slow_f(x)
Using jax.jit
constrains the kind of Python control flow
the function can use; see
the tutorial on Control Flow and Logical Operators with JIT
for more.
Auto-vectorization with vmap
vmap
maps
a function along array axes.
But instead of just looping over function applications, it pushes the loop down
onto the functionâs primitive operations, e.g. turning matrix-vector multiplies into
matrix-matrix multiplies for better performance.
Using vmap
can save you from having to carry around batch dimensions in your
code:
import jax
import jax.numpy as jnp
def l1_distance(x, y):
assert x.ndim == y.ndim == 1 # only works on 1D inputs
return jnp.sum(jnp.abs(x - y))
def pairwise_distances(dist1D, xs):
return jax.vmap(jax.vmap(dist1D, (0, None)), (None, 0))(xs, xs)
xs = jax.random.normal(jax.random.key(0), (100, 3))
dists = pairwise_distances(l1_distance, xs)
dists.shape # (100, 100)
By composing jax.vmap
with jax.grad
and jax.jit
, we can get efficient
Jacobian matrices, or per-example gradients:
per_example_grads = jax.jit(jax.vmap(jax.grad(loss), in_axes=(None, 0, 0)))
Scaling
To scale your computations across thousands of devices, you can use any composition of these:
- Compiler-based automatic parallelization where you program as if using a single global machine, and the compiler chooses how to shard data and partition computation (with some user-provided constraints);
- Explicit sharding and automatic partitioning
where you still have a global view but data shardings are
explicit in JAX types, inspectable using
jax.typeof
; - Manual per-device programming where you have a per-device view of data and computation, and can communicate with explicit collectives.
Mode | View? | Explicit sharding? | Explicit Collectives? |
---|---|---|---|
Auto | Global | â | â |
Explicit | Global | â | â |
Manual | Per-device | â | â |
from jax.sharding import set_mesh, AxisType, PartitionSpec as P
mesh = jax.make_mesh((8,), ('data',), axis_types=(AxisType.Explicit,))
set_mesh(mesh)
# parameters are sharded for FSDP:
for W, b in params:
print(f'{jax.typeof(W)}') # f32[512@data,512]
print(f'{jax.typeof(b)}') # f32[512]
# shard data for batch parallelism:
inputs, targets = jax.device_put((inputs, targets), P('data'))
# evaluate gradients, automatically parallelized!
gradfun = jax.jit(jax.grad(loss))
param_grads = gradfun(params, (inputs, targets))
See the tutorial and advanced guides for more.
Gotchas and sharp bits
See the Gotchas Notebook.
Installation
Supported platforms
Linux x86_64 | Linux aarch64 | Mac aarch64 | Windows x86_64 | Windows WSL2 x86_64 | |
---|---|---|---|---|---|
CPU | yes | yes | yes | yes | yes |
NVIDIA GPU | yes | yes | n/a | no | experimental |
Google TPU | yes | n/a | n/a | n/a | n/a |
AMD GPU | yes | no | n/a | no | no |
Apple GPU | n/a | no | experimental | n/a | n/a |
Intel GPU | experimental | n/a | n/a | no | no |
Instructions
Platform | Instructions |
---|---|
CPU | pip install -U jax |
NVIDIA GPU | pip install -U "jax[cuda12]" |
Google TPU | pip install -U "jax[tpu]" |
AMD GPU (Linux) | Follow AMD's instructions. |
Mac GPU | Follow Apple's instructions. |
Intel GPU | Follow Intel's instructions. |
See the documentation for information on alternative installation strategies. These include compiling from source, installing with Docker, using other versions of CUDA, a community-supported conda build, and answers to some frequently-asked questions.
Citing JAX
To cite this repository:
@software{jax2018github,
author = {James Bradbury and Roy Frostig and Peter Hawkins and Matthew James Johnson and Chris Leary and Dougal Maclaurin and George Necula and Adam Paszke and Jake Vander{P}las and Skye Wanderman-{M}ilne and Qiao Zhang},
title = {{JAX}: composable transformations of {P}ython+{N}um{P}y programs},
url = {http://github.com/jax-ml/jax},
version = {0.3.13},
year = {2018},
}
In the above bibtex entry, names are in alphabetical order, the version number is intended to be that from jax/version.py, and the year corresponds to the project's open-source release.
A nascent version of JAX, supporting only automatic differentiation and compilation to XLA, was described in a paper that appeared at SysML 2018. We're currently working on covering JAX's ideas and capabilities in a more comprehensive and up-to-date paper.
Reference documentation
For details about the JAX API, see the reference documentation.
For getting started as a JAX developer, see the developer documentation.
Top Related Projects
Flax is a neural network library for JAX that is designed for flexibility.
Tensors and Dynamic neural networks in Python with strong GPU acceleration
An Open Source Machine Learning Framework for Everyone
DeepSpeed is a deep learning optimization library that makes distributed training and inference easy, efficient, and effective.
Distributed training framework for TensorFlow, Keras, PyTorch, and Apache MXNet.
🤗 Transformers: the model-definition framework for state-of-the-art machine learning models in text, vision, audio, and multimodal models, for both inference and training.
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot