# How to Think in JAX

## Contents

# How to Think in JAX#

JAX provides a simple and powerful API for writing accelerated numerical code, but working effectively in JAX sometimes requires extra consideration. This document is meant to help build a ground-up understanding of how JAX operates, so that you can use it more effectively.

## JAX vs. NumPy#

**Key Concepts:**

JAX provides a NumPy-inspired interface for convenience.

Through duck-typing, JAX arrays can often be used as drop-in replacements of NumPy arrays.

Unlike NumPy arrays, JAX arrays are always immutable.

NumPy provides a well-known, powerful API for working with numerical data. For convenience, JAX provides `jax.numpy`

which closely mirrors the numpy API and provides easy entry into JAX. Almost anything that can be done with `numpy`

can be done with `jax.numpy`

:

```
import matplotlib.pyplot as plt
import numpy as np
x_np = np.linspace(0, 10, 1000)
y_np = 2 * np.sin(x_np) * np.cos(x_np)
plt.plot(x_np, y_np);
```

```
import jax.numpy as jnp
x_jnp = jnp.linspace(0, 10, 1000)
y_jnp = 2 * jnp.sin(x_jnp) * jnp.cos(x_jnp)
plt.plot(x_jnp, y_jnp);
```

```
WARNING:absl:No GPU/TPU found, falling back to CPU. (Set TF_CPP_MIN_LOG_LEVEL=0 and rerun for more info.)
```

The code blocks are identical aside from replacing `np`

with `jnp`

, and the results are the same. As we can see, JAX arrays can often be used directly in place of NumPy arrays for things like plotting.

The arrays themselves are implemented as different Python types:

```
type(x_np)
```

```
numpy.ndarray
```

```
type(x_jnp)
```

```
jax.interpreters.xla._DeviceArray
```

Pythonâ€™s duck-typing allows JAX arrays and NumPy arrays to be used interchangeably in many places.

However, there is one important difference between JAX and NumPy arrays: JAX arrays are immutable, meaning that once created their contents cannot be changed.

Here is an example of mutating an array in NumPy:

```
# NumPy: mutable arrays
x = np.arange(10)
x[0] = 10
print(x)
```

```
[10 1 2 3 4 5 6 7 8 9]
```

The equivalent in JAX results in an error, as JAX arrays are immutable:

```
# JAX: immutable arrays
x = jnp.arange(10)
x[0] = 10
```

```
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-7-6b90817377fe> in <module>()
1 # JAX: immutable arrays
2 x = jnp.arange(10)
----> 3 x[0] = 10
TypeError: '<class 'jax.interpreters.xla._DeviceArray'>' object does not support item assignment. JAX arrays are immutable; perhaps you want jax.ops.index_update or jax.ops.index_add instead?
```

For updating individual elements, JAX provides an indexed update syntax that returns an updated copy:

```
y = x.at[0].set(10)
print(x)
print(y)
```

```
[0 1 2 3 4 5 6 7 8 9]
[10 1 2 3 4 5 6 7 8 9]
```

## NumPy, lax & XLA: JAX API layering#

**Key Concepts:**

`jax.numpy`

is a high-level wrapper that provides a familiar interface.`jax.lax`

is a lower-level API that is stricter and often more powerful.All JAX operations are implemented in terms of operations in XLA â€“ the Accelerated Linear Algebra compiler.

If you look at the source of `jax.numpy`

, youâ€™ll see that all the operations are eventually expressed in terms of functions defined in `jax.lax`

. You can think of `jax.lax`

as a stricter, but often more powerful, API for working with multi-dimensional arrays.

For example, while `jax.numpy`

will implicitly promote arguments to allow operations between mixed data types, `jax.lax`

will not:

```
import jax.numpy as jnp
jnp.add(1, 1.0) # jax.numpy API implicitly promotes mixed types.
```

```
DeviceArray(2., dtype=float32)
```

```
from jax import lax
lax.add(1, 1.0) # jax.lax API requires explicit type promotion.
```

```
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-10-63245925fccf> in <module>()
1 from jax import lax
----> 2 lax.add(1, 1.0) # jax.lax API requires explicit type promotion.
TypeError: add requires arguments to have the same dtypes, got int32, float32.
```

If using `jax.lax`

directly, youâ€™ll have to do type promotion explicitly in such cases:

```
lax.add(jnp.float32(1), 1.0)
```

```
DeviceArray(2., dtype=float32)
```

Along with this strictness, `jax.lax`

also provides efficient APIs for some more general operations than are supported by NumPy.

For example, consider a 1D convolution, which can be expressed in NumPy this way:

```
x = jnp.array([1, 2, 1])
y = jnp.ones(10)
jnp.convolve(x, y)
```

```
DeviceArray([1., 3., 4., 4., 4., 4., 4., 4., 4., 4., 3., 1.], dtype=float32)
```

Under the hood, this NumPy operation is translated to a much more general convolution implemented by `lax.conv_general_dilated`

:

```
from jax import lax
result = lax.conv_general_dilated(
x.reshape(1, 1, 3).astype(float), # note: explicit promotion
y.reshape(1, 1, 10),
window_strides=(1,),
padding=[(len(y) - 1, len(y) - 1)]) # equivalent of padding='full' in NumPy
result[0, 0]
```

```
DeviceArray([1., 3., 4., 4., 4., 4., 4., 4., 4., 4., 3., 1.], dtype=float32)
```

This is a batched convolution operation designed to be efficient for the types of convolutions often used in deep neural nets. It requires much more boilerplate, but is far more flexible and scalable than the convolution provided by NumPy (See Convolutions in JAX for more detail on JAX convolutions).

At their heart, all `jax.lax`

operations are Python wrappers for operations in XLA; here, for example, the convolution implementation is provided by XLA:ConvWithGeneralPadding.
Every JAX operation is eventually expressed in terms of these fundamental XLA operations, which is what enables just-in-time (JIT) compilation.

## To JIT or not to JIT#

**Key Concepts:**

By default JAX executes operations one at a time, in sequence.

Using a just-in-time (JIT) compilation decorator, sequences of operations can be optimized together and run at once.

Not all JAX code can be JIT compiled, as it requires array shapes to be static & known at compile time.

The fact that all JAX operations are expressed in terms of XLA allows JAX to use the XLA compiler to execute blocks of code very efficiently.

For example, consider this function that normalizes the rows of a 2D matrix, expressed in terms of `jax.numpy`

operations:

```
import jax.numpy as jnp
def norm(X):
X = X - X.mean(0)
return X / X.std(0)
```

A just-in-time compiled version of the function can be created using the `jax.jit`

transform:

```
from jax import jit
norm_compiled = jit(norm)
```

This function returns the same results as the original, up to standard floating-point accuracy:

```
np.random.seed(1701)
X = jnp.array(np.random.rand(10000, 10))
np.allclose(norm(X), norm_compiled(X), atol=1E-6)
```

```
True
```

But due to the compilation (which includes fusing of operations, avoidance of allocating temporary arrays, and a host of other tricks), execution times can be orders of magnitude faster in the JIT-compiled case (note the use of `block_until_ready()`

to account for JAXâ€™s asynchronous dispatch):

```
%timeit norm(X).block_until_ready()
%timeit norm_compiled(X).block_until_ready()
```

```
100 loops, best of 3: 4.3 ms per loop
1000 loops, best of 3: 452 Âµs per loop
```

That said, `jax.jit`

does have limitations: in particular, it requires all arrays to have static shapes. That means that some JAX operations are incompatible with JIT compilation.

For example, this operation can be executed in op-by-op mode:

```
def get_negatives(x):
return x[x < 0]
x = jnp.array(np.random.randn(10))
get_negatives(x)
```

```
DeviceArray([-0.10570311, -0.59403396, -0.8680282 , -0.23489487], dtype=float32)
```

But it returns an error if you attempt to execute it in jit mode:

```
jit(get_negatives)(x)
```

```
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-19-ec8799cf80d7> in <module>()
----> 1 jit(get_negatives)(x)
IndexError: Array boolean indices must be concrete.
```

This is because the function generates an array whose shape is not known at compile time: the size of the output depends on the values of the input array, and so it is not compatible with JIT.

## JIT mechanics: tracing and static variables#

**Key Concepts:**

JIT and other JAX transforms work by

*tracing*a function to determine its effect on inputs of a specific shape and type.Variables that you donâ€™t want to be traced can be marked as

*static*

To use `jax.jit`

effectively, it is useful to understand how it works. Letâ€™s put a few `print()`

statements within a JIT-compiled function and then call the function:

```
@jit
def f(x, y):
print("Running f():")
print(f" x = {x}")
print(f" y = {y}")
result = jnp.dot(x + 1, y + 1)
print(f" result = {result}")
return result
x = np.random.randn(3, 4)
y = np.random.randn(4)
f(x, y)
```

```
Running f():
x = Traced<ShapedArray(float32[3,4])>with<DynamicJaxprTrace(level=0/1)>
y = Traced<ShapedArray(float32[4])>with<DynamicJaxprTrace(level=0/1)>
result = Traced<ShapedArray(float32[3])>with<DynamicJaxprTrace(level=0/1)>
```

```
DeviceArray([0.25773212, 5.3623195 , 5.4032435 ], dtype=float32)
```

Notice that the print statements execute, but rather than printing the data we passed to the function, though, it prints *tracer* objects that stand-in for them.

These tracer objects are what `jax.jit`

uses to extract the sequence of operations specified by the function. Basic tracers are stand-ins that encode the **shape** and **dtype** of the arrays, but are agnostic to the values. This recorded sequence of computations can then be efficiently applied within XLA to new inputs with the same shape and dtype, without having to re-execute the Python code.

When we call the compiled function again on matching inputs, no re-compilation is required and nothing is printed because the result is computed in compiled XLA rather than in Python:

```
x2 = np.random.randn(3, 4)
y2 = np.random.randn(4)
f(x2, y2)
```

```
DeviceArray([1.4344584, 4.3004413, 7.9897013], dtype=float32)
```

The extracted sequence of operations is encoded in a JAX expression, or *jaxpr* for short. You can view the jaxpr using the `jax.make_jaxpr`

transformation:

```
from jax import make_jaxpr
def f(x, y):
return jnp.dot(x + 1, y + 1)
make_jaxpr(f)(x, y)
```

```
{ lambda ; a b.
let c = add a 1.0
d = add b 1.0
e = dot_general[ dimension_numbers=(((1,), (0,)), ((), ()))
precision=None ] c d
in (e,) }
```

Note one consequence of this: because JIT compilation is done *without* information on the content of the array, control flow statements in the function cannot depend on traced values. For example, this fails:

```
@jit
def f(x, neg):
return -x if neg else x
f(1, True)
```

```
---------------------------------------------------------------------------
ConcretizationTypeError Traceback (most recent call last)
<ipython-input-23-acbedba5ce66> in <module>()
3 return -x if neg else x
4
----> 5 f(1, True)
ConcretizationTypeError: Abstract tracer value encountered where concrete value is expected.
The problem arose with the bool function.
While tracing the function f at <ipython-input-23-acbedba5ce66>:1, this concrete value was not available in Python because it depends on the value of the arguments to f at <ipython-input-23-acbedba5ce66>:1 at flattened positions [1], and the computation of these values is being staged out (that is, delayed rather than executed eagerly).
You can use transformation parameters such as static_argnums for jit to avoid tracing particular arguments of transformed functions, though at the cost of more recompiles.
See https://jax.readthedocs.io/en/latest/faq.html#abstract-tracer-value-encountered-where-concrete-value-is-expected-error for more information.
Encountered tracer value: Traced<ShapedArray(bool[], weak_type=True)>with<DynamicJaxprTrace(level=0/1)>
```

If there are variables that you would not like to be traced, they can be marked as static for the purposes of JIT compilation:

```
from functools import partial
@partial(jit, static_argnums=(1,))
def f(x, neg):
return -x if neg else x
f(1, True)
```

```
DeviceArray(-1, dtype=int32)
```

Note that calling a JIT-compiled function with a different static argument results in re-compilation, so the function still works as expected:

```
f(1, False)
```

```
DeviceArray(1, dtype=int32)
```

Understanding which values and operations will be static and which will be traced is a key part of using `jax.jit`

effectively.

## Static vs Traced Operations#

**Key Concepts:**

Just as values can be either static or traced, operations can be static or traced.

Static operations are evaluated at compile-time in Python; traced operations are compiled & evaluated at run-time in XLA.

Use

`numpy`

for operations that you want to be static; use`jax.numpy`

for operations that you want to be traced.

This distinction between static and traced values makes it important to think about how to keep a static value static. Consider this function:

```
import jax.numpy as jnp
from jax import jit
@jit
def f(x):
return x.reshape(jnp.array(x.shape).prod())
x = jnp.ones((2, 3))
f(x)
```

```
---------------------------------------------------------------------------
ConcretizationTypeError Traceback (most recent call last)
<ipython-input-26-5fa933a68063> in <module>()
7
8 x = jnp.ones((2, 3))
----> 9 f(x)
ConcretizationTypeError: Abstract tracer value encountered where concrete value is expected.
The error arose in jax.numpy.reshape.
While tracing the function f at <ipython-input-26-5fa933a68063>:4, this value became a tracer due to JAX operations on these lines:
operation c:int32[] = reduce_prod[ axes=(0,) ] b:int32[2]
from line <ipython-input-26-5fa933a68063>:6 (f)
See https://jax.readthedocs.io/en/latest/faq.html#abstract-tracer-value-encountered-where-concrete-value-is-expected-error for more information.
Encountered tracer value: Traced<ShapedArray(int32[])>with<DynamicJaxprTrace(level=0/1)>
```

This fails with an error specifying that a tracer was found instead of a 1D sequence of concrete values of integer type. Letâ€™s add some print statements to the function to understand why this is happening:

```
@jit
def f(x):
print(f"x = {x}")
print(f"x.shape = {x.shape}")
print(f"jnp.array(x.shape).prod() = {jnp.array(x.shape).prod()}")
# comment this out to avoid the error:
# return x.reshape(jnp.array(x.shape).prod())
f(x)
```

```
x = Traced<ShapedArray(float32[2,3])>with<DynamicJaxprTrace(level=0/1)>
x.shape = (2, 3)
jnp.array(x.shape).prod() = Traced<ShapedArray(int32[])>with<DynamicJaxprTrace(level=0/1)>
```

Notice that although `x`

is traced, `x.shape`

is a static value. However, when we use `jnp.array`

and `jnp.prod`

on this static value, it becomes a traced value, at which point it cannot be used in a function like `reshape()`

that requires a static input (recall: array shapes must be static).

A useful pattern is to use `numpy`

for operations that should be static (i.e. done at compile-time), and use `jax.numpy`

for operations that should be traced (i.e. compiled and executed at run-time). For this function, it might look like this:

```
from jax import jit
import jax.numpy as jnp
import numpy as np
@jit
def f(x):
return x.reshape((np.prod(x.shape),))
f(x)
```

```
DeviceArray([1., 1., 1., 1., 1., 1.], dtype=float32)
```

For this reason, a standard convention in JAX programs is to `import numpy as np`

and `import jax.numpy as jnp`

so that both interfaces are available for finer control over whether operations are performed in a static matter (with `numpy`

, once at compile-time) or a traced manner (with `jax.numpy`

, optimized at run-time).