# JAX QuickstartÂ¶

**JAX is NumPy on the CPU, GPU, and TPU, with great automatic differentiation for high-performance machine learning research.**

With its updated version of Autograd, JAX can automatically differentiate native Python and NumPy code. It can differentiate through a large subset of Pythonâ€™s features, including loops, ifs, recursion, and closures, and it can even take derivatives of derivatives of derivatives. It supports reverse-mode 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 code on accelerators, like GPUs and TPUs. Compilation happens under the hood by default, with library calls getting just-in-time compiled and executed. But JAX even lets you just-in-time compile your own Python functions into XLA-optimized kernels using a one-function API. Compilation and automatic differentiation can be composed arbitrarily, so you can express sophisticated algorithms and get maximal performance without having to leave Python.

```
[1]:
```

```
import jax.numpy as np
from jax import grad, jit, vmap
from jax import random
```

## Multiplying MatricesÂ¶

Weâ€™ll be generating random data in the following examples. One big difference between NumPy and JAX is how you generate random numbers. For more details, see the readme.

```
[2]:
```

```
key = random.PRNGKey(0)
x = random.normal(key, (10,))
print(x)
```

```
/home/docs/checkouts/readthedocs.org/user_builds/jax/envs/test-docs/lib/python3.7/site-packages/jax/lib/xla_bridge.py:123: UserWarning: No GPU/TPU found, falling back to CPU.
warnings.warn('No GPU/TPU found, falling back to CPU.')
```

```
[-0.372111 0.26423106 -0.18252774 -0.7368198 -0.44030386 -0.15214427
-0.6713536 -0.5908642 0.73168874 0.5673025 ]
```

Letâ€™s dive right in and multiply two big matrices.

```
[3]:
```

```
size = 3000
x = random.normal(key, (size, size), dtype=np.float32)
%timeit np.dot(x, x.T).block_until_ready() # runs on the GPU
```

```
426 ms Â± 60.8 ms per loop (mean Â± std. dev. of 7 runs, 1 loop each)
```

We added that `block_until_ready`

because JAX uses asynchronous execution by default.

JAX NumPy functions work on regular NumPy arrays.

```
[4]:
```

```
import numpy as onp # original CPU-backed NumPy
x = onp.random.normal(size=(size, size)).astype(onp.float32)
%timeit np.dot(x, x.T).block_until_ready()
```

```
767 ms Â± 110 ms per loop (mean Â± std. dev. of 7 runs, 1 loop each)
```

Thatâ€™s slower because it has to transfer data to the GPU every time. You can ensure that an NDArray is backed by device memory using `device_put`

.

```
[5]:
```

```
from jax import device_put
x = onp.random.normal(size=(size, size)).astype(onp.float32)
x = device_put(x)
%timeit np.dot(x, x.T).block_until_ready()
```

```
350 ms Â± 45.4 ms per loop (mean Â± std. dev. of 7 runs, 1 loop each)
```

The output of `device_put`

still acts like an NDArray, but it only copies values back to the CPU when theyâ€™re needed for printing, plotting, saving to disk, branching, etc. The behavior of `device_put`

is equivalent to the function `jit(lambda x: x)`

, but itâ€™s faster.

If you have a GPU (or TPU!) these calls run on the accelerator and have the potential to be much faster than on CPU.

```
[6]:
```

```
x = onp.random.normal(size=(size, size)).astype(onp.float32)
%timeit onp.dot(x, x.T)
```

```
523 ms Â± 63.6 ms per loop (mean Â± std. dev. of 7 runs, 1 loop each)
```

JAX is much more than just a GPU-backed NumPy. It also comes with a few program transformations that are useful when writing numerical code. For now, thereâ€™s three main ones:

`jit`

, for speeding up your code`grad`

, for taking derivatives`vmap`

, for automatic vectorization or batching.

Letâ€™s go over these, one-by-one. Weâ€™ll also end up composing these in interesting ways.

## Using `jit`

to speed up functionsÂ¶

JAX runs transparently on the GPU (or CPU, if you donâ€™t have one, and TPU coming soon!). However, in the above example, JAX is dispatching kernels to the GPU one operation at a time. If we have a sequence of operations, we can use the `@jit`

decorator to compile multiple operations together using XLA. Letâ€™s try that.

```
[7]:
```

```
def selu(x, alpha=1.67, lmbda=1.05):
return lmbda * np.where(x > 0, x, alpha * np.exp(x) - alpha)
x = random.normal(key, (1000000,))
%timeit selu(x).block_until_ready()
```

```
5.8 ms Â± 1.94 ms per loop (mean Â± std. dev. of 7 runs, 1 loop each)
```

We can speed it up with `@jit`

, which will jit-compile the first time `selu`

is called and will be cached thereafter.

```
[8]:
```

```
selu_jit = jit(selu)
%timeit selu_jit(x).block_until_ready()
```

```
1.06 ms Â± 72.4 Âµs per loop (mean Â± std. dev. of 7 runs, 1000 loops each)
```

## Taking derivatives with `grad`

Â¶

In addition to evaluating numerical functions, we also want to transform them. One transformation is automatic differentiation. In JAX, just like in Autograd, you can compute gradients with the `grad`

function.

```
[9]:
```

```
def sum_logistic(x):
return np.sum(1.0 / (1.0 + np.exp(-x)))
x_small = np.arange(3.)
derivative_fn = grad(sum_logistic)
print(derivative_fn(x_small))
```

```
[0.25 0.19661197 0.10499357]
```

Letâ€™s verify with finite differences that our result is correct.

```
[10]:
```

```
def first_finite_differences(f, x):
eps = 1e-3
return np.array([(f(x + eps * v) - f(x - eps * v)) / (2 * eps)
for v in np.eye(len(x))])
print(first_finite_differences(sum_logistic, x_small))
```

```
[0.24998187 0.1964569 0.10502338]
```

Taking derivatives is as easy as calling `grad`

. `grad`

and `jit`

compose and can be mixed arbitrarily. In the above example we jitted `sum_logistic`

and then took its derivative. We can go further:

```
[11]:
```

```
print(grad(jit(grad(jit(grad(sum_logistic)))))(1.0))
```

```
-0.03532558
```

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 them to make a function that efficiently computes full Hessian matrices:

```
[12]:
```

```
from jax import jacfwd, jacrev
def hessian(fun):
return jit(jacfwd(jacrev(fun)))
```

## Auto-vectorization with `vmap`

Â¶

JAX has one more transformation in its API that you might find useful: `vmap`

, 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. When composed with `jit`

, it can be just as fast as adding the batch dimensions by hand.

Weâ€™re going to work with a simple example, and promote matrix-vector products into matrix-matrix products using `vmap`

. Although this is easy to do by hand in this specific case, the same technique can apply to more complicated functions.

```
[13]:
```

```
mat = random.normal(key, (150, 100))
batched_x = random.normal(key, (10, 100))
def apply_matrix(v):
return np.dot(mat, v)
```

Given a function such as `apply_matrix`

, we can loop over a batch dimension in Python, but usually the performance of doing so is poor.

```
[14]:
```

```
def naively_batched_apply_matrix(v_batched):
return np.stack([apply_matrix(v) for v in v_batched])
print('Naively batched')
%timeit naively_batched_apply_matrix(batched_x).block_until_ready()
```

```
Naively batched
3.79 ms Â± 149 Âµs per loop (mean Â± std. dev. of 7 runs, 100 loops each)
```

We know how to batch this operation manually. In this case, `np.dot`

handles extra batch dimensions transparently.

```
[15]:
```

```
@jit
def batched_apply_matrix(v_batched):
return np.dot(v_batched, mat.T)
print('Manually batched')
%timeit batched_apply_matrix(batched_x).block_until_ready()
```

```
Manually batched
215 Âµs Â± 11.7 Âµs per loop (mean Â± std. dev. of 7 runs, 1000 loops each)
```

However, suppose we had a more complicated function without batching support. We can use `vmap`

to add batching support automatically.

```
[16]:
```

```
@jit
def vmap_batched_apply_matrix(v_batched):
return vmap(apply_matrix)(v_batched)
print('Auto-vectorized with vmap')
%timeit vmap_batched_apply_matrix(batched_x).block_until_ready()
```

```
Auto-vectorized with vmap
248 Âµs Â± 9.93 Âµs per loop (mean Â± std. dev. of 7 runs, 1000 loops each)
```

Of course, `vmap`

can be arbitrarily composed with `jit`

, `grad`

, and any other JAX transformation.

This is just a taste of what JAX can do. Weâ€™re really excited to see what you do with it!