jax
Composable transformations of Python+NumPy programs: differentiate, vectorize, JIT to GPU/TPU, and more
Top Related Projects
An Open Source Machine Learning Framework for Everyone
Tensors and Dynamic neural networks in Python with strong GPU acceleration
ONNX Runtime: cross-platform, high performance ML inferencing and training accelerator
Open deep learning compiler stack for cpu, gpu and specialized accelerators
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.
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.numpy as jnp
from jax import grad, jit, vmap
- Start using JAX for numerical computations and machine learning tasks:
def f(x):
return jnp.sum(x ** 2)
x = jnp.array([1.0, 2.0, 3.0])
print(f(x)) # Compute function value
print(grad(f)(x)) # Compute gradient
Competitor Comparisons
An Open Source Machine Learning Framework for Everyone
Pros of TensorFlow
- Larger ecosystem with more tools, libraries, and community support
- Better production deployment options, including TensorFlow Serving
- More comprehensive documentation and learning resources
Cons of TensorFlow
- More complex API and steeper learning curve
- Less flexible 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)
Key Differences
- JAX offers a more NumPy-like API, making it easier for researchers familiar with NumPy
- TensorFlow provides better support for distributed training and deployment
- JAX's functional design allows for easier composition of transformations
- TensorFlow has more built-in high-level APIs like Keras for rapid prototyping
- JAX's JIT compilation can lead to faster execution times for certain workloads
Both libraries are powerful tools for machine learning, with TensorFlow being more suitable for production environments and JAX excelling in research and experimentation scenarios.
Tensors and Dynamic neural networks in Python with strong GPU acceleration
Pros of PyTorch
- More mature ecosystem with extensive libraries and pre-trained models
- Dynamic computation graph allows for easier debugging and more intuitive coding
- Better support for deployment in production environments
Cons of PyTorch
- Generally slower than JAX for large-scale computations
- Less efficient memory usage compared to JAX's functional approach
- Limited support for TPUs compared to JAX's native integration
Code Comparison
PyTorch:
import torch
x = torch.randn(3, 3)
y = torch.matmul(x, x.t())
z = torch.relu(y)
JAX:
import jax.numpy as jnp
from jax import random, jit
key = random.PRNGKey(0)
x = random.normal(key, (3, 3))
y = jnp.matmul(x, x.T)
z = jnp.maximum(0, y)
Both frameworks offer similar functionality, but JAX's code is more functional and emphasizes immutability. PyTorch's imperative style may be more familiar to some developers, while JAX's approach can lead to more efficient computations, especially when using JIT compilation.
ONNX Runtime: cross-platform, high performance ML inferencing and training accelerator
Pros of ONNX Runtime
- Broader ecosystem support and compatibility with various ML frameworks
- Optimized for production deployment and inference performance
- Extensive hardware acceleration support (CPU, GPU, FPGA, etc.)
Cons of ONNX Runtime
- Less flexible for custom model development compared to JAX
- Steeper learning curve for researchers and ML practitioners
- Limited support for certain advanced ML techniques like automatic differentiation
Code Comparison
ONNX Runtime example:
import onnxruntime as ort
import numpy as np
session = ort.InferenceSession("model.onnx")
input_name = session.get_inputs()[0].name
output = session.run(None, {input_name: np.random.randn(1, 3, 224, 224).astype(np.float32)})
JAX example:
import jax.numpy as jnp
from jax import grad, jit
def loss_fn(x):
return jnp.sum(x**2)
grad_fn = jit(grad(loss_fn))
result = grad_fn(jnp.array([1.0, 2.0, 3.0]))
Open deep learning compiler stack for cpu, gpu and specialized accelerators
Pros of TVM
- Supports a wider range of hardware targets, including CPUs, GPUs, and specialized AI accelerators
- Offers more advanced graph-level optimizations and code generation capabilities
- Provides a more comprehensive end-to-end deep learning compiler framework
Cons of TVM
- Steeper learning curve due to its more complex architecture and broader scope
- Generally slower compilation times compared to JAX's just-in-time compilation
- Less seamless integration with NumPy-like operations and automatic differentiation
Code Comparison
TVM example:
import tvm
from tvm import te
n = te.var("n")
A = te.placeholder((n,), name="A")
B = te.compute(A.shape, lambda i: A[i] * 2, name="B")
s = te.create_schedule(B.op)
JAX example:
import jax
import jax.numpy as jnp
def double(x):
return x * 2
x = jnp.arange(10)
y = jax.jit(double)(x)
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 easy integration with PyTorch
Cons of DeepSpeed
- Limited to PyTorch ecosystem
- Steeper learning curve for advanced features
- Less flexibility for custom numerical operations
Code Comparison
JAX:
import jax.numpy as jnp
from jax import grad, jit
def loss(x):
return jnp.sum(x**2)
grad_loss = jit(grad(loss))
DeepSpeed:
import torch
import deepspeed
model = MyModel()
optimizer = torch.optim.Adam(model.parameters())
model_engine, optimizer, _, _ = deepspeed.initialize(args=args, model=model, optimizer=optimizer)
JAX focuses on automatic differentiation and compilation, while DeepSpeed emphasizes distributed training and optimization. JAX offers a more flexible approach for numerical computing, whereas DeepSpeed provides ready-to-use solutions for scaling deep learning models. JAX's syntax is closer to NumPy, making it easier for researchers familiar with scientific computing. DeepSpeed, on the other hand, integrates seamlessly with PyTorch, making it more accessible for deep learning practitioners already using the framework.
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 numerical computing
- Requires additional setup and configuration for distributed environments
- May have a steeper learning curve for users not familiar with distributed systems
Code Comparison
Horovod (distributed training):
import horovod.tensorflow as hvd
hvd.init()
optimizer = tf.optimizers.Adam(0.001 * hvd.size())
optimizer = hvd.DistributedOptimizer(optimizer)
JAX (general numerical computing):
import jax.numpy as jnp
from jax import grad, jit
@jit
def loss(params, x, y):
return jnp.mean((params[0] * x + params[1] - y) ** 2)
grad_loss = jit(grad(loss))
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
Quickstart | Transformations | Install guide | Neural net libraries | 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.
With its updated version of Autograd,
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 grad
as well as forward-mode differentiation,
and the two can be composed arbitrarily to any order.
Whatâs new is that JAX uses XLA
to compile and run your NumPy programs on GPUs and TPUs. Compilation happens
under the hood by default, with library calls getting just-in-time compiled and
executed. But JAX also lets you just-in-time compile your own Python functions
into XLA-optimized kernels using a one-function API,
jit
. Compilation and automatic differentiation can be
composed arbitrarily, so you can express sophisticated algorithms and get
maximal performance without leaving Python. You can even program multiple GPUs
or TPU cores at once using pmap
, and
differentiate through the whole thing.
Dig a little deeper, and you'll see that JAX is really an extensible system for
composable function transformations. Both
grad
and jit
are instances of such transformations. Others are
vmap
for automatic vectorization and
pmap
for single-program multiple-data (SPMD)
parallel programming of multiple accelerators, with more to come.
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.numpy as jnp
from jax import grad, jit, vmap
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 = jit(grad(loss)) # compiled gradient evaluation function
perex_grads = jit(vmap(grad_loss, in_axes=(None, 0, 0))) # fast per-example grads
Contents
- Quickstart: Colab in the Cloud
- Transformations
- Current gotchas
- Installation
- Neural net libraries
- Citing JAX
- Reference documentation
Quickstart: Colab in the Cloud
Jump right in using a notebook in your browser, connected to a Google Cloud GPU. Here are some starter notebooks:
- The basics: NumPy on accelerators,
grad
for differentiation,jit
for compilation, andvmap
for vectorization - Training a Simple Neural Network, with TensorFlow Dataset Data Loading
JAX now runs on Cloud TPUs. To try out the preview, see the Cloud TPU Colabs.
For a deeper dive into JAX:
- The Autodiff Cookbook, Part 1: easy and powerful automatic differentiation in JAX
- Common gotchas and sharp edges
- See the full list of notebooks.
Transformations
At its core, JAX is an extensible system for transforming numerical functions.
Here are four transformations of primary interest: grad
, jit
, vmap
, and
pmap
.
Automatic differentiation with grad
JAX has roughly the same API as Autograd.
The most popular function is
grad
for reverse-mode gradients:
from jax import grad
import jax.numpy as jnp
def tanh(x): # Define a function
y = jnp.exp(-2.0 * x)
return (1.0 - y) / (1.0 + y)
grad_tanh = grad(tanh) # Obtain its gradient function
print(grad_tanh(1.0)) # Evaluate it at x = 1.0
# prints 0.4199743
You can differentiate to any order with grad
.
print(grad(grad(grad(tanh)))(1.0))
# prints 0.62162673
For more advanced autodiff, you can use
jax.vjp
for
reverse-mode vector-Jacobian products and
jax.jvp
for
forward-mode Jacobian-vector products. The two can be composed arbitrarily with
one another, and with other JAX transformations. Here's one way to compose those
to make a function that efficiently computes full Hessian
matrices:
from jax import jit, jacfwd, jacrev
def hessian(fun):
return jit(jacfwd(jacrev(fun)))
As with Autograd, you're free to use differentiation with Python control structures:
def abs_val(x):
if x > 0:
return x
else:
return -x
abs_val_grad = 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 reference docs on automatic differentiation and the JAX Autodiff Cookbook for more.
Compilation with jit
You can 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.numpy as jnp
from jax import jit
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 = jit(slow_f)
%timeit -n10 -r3 fast_f(x) # ~ 4.5 ms / loop on Titan X
%timeit -n10 -r3 slow_f(x) # ~ 14.5 ms / loop (also on GPU via JAX)
You can mix jit
and grad
and any other JAX transformation however you like.
Using jit
puts constraints on 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
is
the vectorizing map.
It has the familiar semantics of mapping a function along array axes, but
instead of keeping the loop on the outside, it pushes the loop down into a
functionâs primitive operations for better performance.
Using vmap
can save you from having to carry around batch dimensions in your
code. For example, consider this simple unbatched neural network prediction
function:
def predict(params, input_vec):
assert input_vec.ndim == 1
activations = input_vec
for W, b in params:
outputs = jnp.dot(W, activations) + b # `activations` on the right-hand side!
activations = jnp.tanh(outputs) # inputs to the next layer
return outputs # no activation on last layer
We often instead write jnp.dot(activations, W)
to allow for a batch dimension on the
left side of activations
, but weâve written this particular prediction function to
apply only to single input vectors. If we wanted to apply this function to a
batch of inputs at once, semantically we could just write
from functools import partial
predictions = jnp.stack(list(map(partial(predict, params), input_batch)))
But pushing one example through the network at a time would be slow! Itâs better to vectorize the computation, so that at every layer weâre doing matrix-matrix multiplication rather than matrix-vector multiplication.
The vmap
function does that transformation for us. That is, if we write
from jax import vmap
predictions = vmap(partial(predict, params))(input_batch)
# or, alternatively
predictions = vmap(predict, in_axes=(None, 0))(params, input_batch)
then the vmap
function will push the outer loop inside the function, and our
machine will end up executing matrix-matrix multiplications exactly as if weâd
done the batching by hand.
Itâs easy enough to manually batch a simple neural network without vmap
, but
in other cases manual vectorization can be impractical or impossible. Take the
problem of efficiently computing per-example gradients: that is, for a fixed set
of parameters, we want to compute the gradient of our loss function evaluated
separately at each example in a batch. With vmap
, itâs easy:
per_example_gradients = vmap(partial(grad(loss), params))(inputs, targets)
Of course, vmap
can be arbitrarily composed with jit
, grad
, and any other
JAX transformation! We use vmap
with both forward- and reverse-mode automatic
differentiation for fast Jacobian and Hessian matrix calculations in
jax.jacfwd
, jax.jacrev
, and jax.hessian
.
SPMD programming with pmap
For parallel programming of multiple accelerators, like multiple GPUs, use
pmap
.
With pmap
you write single-program multiple-data (SPMD) programs, including
fast parallel collective communication operations. Applying pmap
will mean
that the function you write is compiled by XLA (similarly to jit
), then
replicated and executed in parallel across devices.
Here's an example on an 8-GPU machine:
from jax import random, pmap
import jax.numpy as jnp
# Create 8 random 5000 x 6000 matrices, one per GPU
keys = random.split(random.key(0), 8)
mats = pmap(lambda key: random.normal(key, (5000, 6000)))(keys)
# Run a local matmul on each device in parallel (no data transfer)
result = pmap(lambda x: jnp.dot(x, x.T))(mats) # result.shape is (8, 5000, 5000)
# Compute the mean on each device in parallel and print the result
print(pmap(jnp.mean)(result))
# prints [1.1566595 1.1805978 ... 1.2321935 1.2015157]
In addition to expressing pure maps, you can use fast collective communication operations between devices:
from functools import partial
from jax import lax
@partial(pmap, axis_name='i')
def normalize(x):
return x / lax.psum(x, 'i')
print(normalize(jnp.arange(4.)))
# prints [0. 0.16666667 0.33333334 0.5 ]
You can even nest pmap
functions for more
sophisticated communication patterns.
It all composes, so you're free to differentiate through parallel computations:
from jax import grad
@pmap
def f(x):
y = jnp.sin(x)
@pmap
def g(z):
return jnp.cos(z) * jnp.tan(y.sum()) * jnp.tanh(x).sum()
return grad(lambda w: jnp.sum(g(w)))(x)
print(f(x))
# [[ 0. , -0.7170853 ],
# [-3.1085174 , -0.4824318 ],
# [10.366636 , 13.135289 ],
# [ 0.22163185, -0.52112055]]
print(grad(lambda x: jnp.sum(f(x)))(x))
# [[ -3.2369726, -1.6356447],
# [ 4.7572474, 11.606951 ],
# [-98.524414 , 42.76499 ],
# [ -1.6007166, -1.2568436]]
When reverse-mode differentiating a pmap
function (e.g. with grad
), the
backward pass of the computation is parallelized just like the forward pass.
See the SPMD Cookbook and the SPMD MNIST classifier from scratch example for more.
Current gotchas
For a more thorough survey of current gotchas, with examples and explanations, we highly recommend reading the Gotchas Notebook. Some standouts:
- JAX transformations only work on pure functions, which don't have side-effects and respect referential transparency (i.e. object identity testing with
is
isn't preserved). If you use a JAX transformation on an impure Python function, you might see an error likeException: Can't lift Traced...
orException: Different traces at same level
. - In-place mutating updates of
arrays, like
x[i] += y
, aren't supported, but there are functional alternatives. Under ajit
, those functional alternatives will reuse buffers in-place automatically. - Random numbers are different, but for good reasons.
- If you're looking for convolution
operators,
they're in the
jax.lax
package. - JAX enforces single-precision (32-bit, e.g.
float32
) values by default, and to enable double-precision (64-bit, e.g.float64
) one needs to set thejax_enable_x64
variable at startup (or set the environment variableJAX_ENABLE_X64=True
). On TPU, JAX uses 32-bit values by default for everything except internal temporary variables in 'matmul-like' operations, such asjax.numpy.dot
andlax.conv
. Those ops have aprecision
parameter which can be used to approximate 32-bit operations via three bfloat16 passes, with a cost of possibly slower runtime. Non-matmul operations on TPU lower to implementations that often emphasize speed over accuracy, so in practice computations on TPU will be less precise than similar computations on other backends. - Some of NumPy's dtype promotion semantics involving a mix of Python scalars
and NumPy types aren't preserved, namely
np.add(1, np.array([2], np.float32)).dtype
isfloat64
rather thanfloat32
. - Some transformations, like
jit
, constrain how you can use Python control flow. You'll always get loud errors if something goes wrong. You might have to usejit
'sstatic_argnums
parameter, structured control flow primitives likelax.scan
, or just usejit
on smaller subfunctions.
Installation
Supported platforms
Linux x86_64 | Linux aarch64 | Mac x86_64 | Mac aarch64 | Windows x86_64 | Windows WSL2 x86_64 | |
---|---|---|---|---|---|---|
CPU | yes | yes | yes | yes | yes | yes |
NVIDIA GPU | yes | yes | no | n/a | no | experimental |
Google TPU | yes | n/a | n/a | n/a | n/a | n/a |
AMD GPU | yes | no | experimental | n/a | no | no |
Apple GPU | n/a | no | n/a | experimental | n/a | n/a |
Intel GPU | experimental | n/a | 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]" -f https://storage.googleapis.com/jax-releases/libtpu_releases.html |
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.
Neural network libraries
Multiple Google research groups at Google DeepMind and Alphabet develop and share libraries for training neural networks in JAX. If you want a fully featured library for neural network training with examples and how-to guides, try Flax and its documentation site.
Check out the JAX Ecosystem section on the JAX documentation site for a list of JAX-based network libraries, which includes Optax for gradient processing and optimization, chex for reliable code and testing, and Equinox for neural networks. (Watch the NeurIPS 2020 JAX Ecosystem at DeepMind talk here for additional details.)
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
An Open Source Machine Learning Framework for Everyone
Tensors and Dynamic neural networks in Python with strong GPU acceleration
ONNX Runtime: cross-platform, high performance ML inferencing and training accelerator
Open deep learning compiler stack for cpu, gpu and specialized accelerators
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.
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