#!/usr/bin/env python # coding: utf-8 # # 🔪 JAX - The Sharp Bits 🔪 # # [](https://colab.research.google.com/github/google/jax/blob/main/docs/notebooks/Common_Gotchas_in_JAX.ipynb) # *levskaya@ mattjj@* # # When walking about the countryside of [Italy](https://iaml.it/blog/jax-intro), the people will not hesitate to tell you that __JAX__ has _"una anima di pura programmazione funzionale"_. # # __JAX__ is a language for __expressing__ and __composing__ __transformations__ of numerical programs. __JAX__ is also able to __compile__ numerical programs for CPU or accelerators (GPU/TPU). # JAX works great for many numerical and scientific programs, but __only if they are written with certain constraints__ that we describe below. # In[1]: import numpy as np from jax import grad, jit from jax import lax from jax import random import jax import jax.numpy as jnp import matplotlib as mpl from matplotlib import pyplot as plt from matplotlib import rcParams rcParams['image.interpolation'] = 'nearest' rcParams['image.cmap'] = 'viridis' rcParams['axes.grid'] = False # ## 🔪 Pure functions # JAX transformation and compilation are designed to work only on Python functions that are functionally pure: all the input data is passed through the function parameters, all the results are output through the function results. A pure function will always return the same result if invoked with the same inputs. # # Here are some examples of functions that are not functionally pure for which JAX behaves differently than the Python interpreter. Note that these behaviors are not guaranteed by the JAX system; the proper way to use JAX is to use it only on functionally pure Python functions. # In[2]: def impure_print_side_effect(x): print("Executing function") # This is a side-effect return x # The side-effects appear during the first run print ("First call: ", jit(impure_print_side_effect)(4.)) # Subsequent runs with parameters of same type and shape may not show the side-effect # This is because JAX now invokes a cached compilation of the function print ("Second call: ", jit(impure_print_side_effect)(5.)) # JAX re-runs the Python function when the type or shape of the argument changes print ("Third call, different type: ", jit(impure_print_side_effect)(jnp.array([5.]))) # In[3]: g = 0. def impure_uses_globals(x): return x + g # JAX captures the value of the global during the first run print ("First call: ", jit(impure_uses_globals)(4.)) g = 10. # Update the global # Subsequent runs may silently use the cached value of the globals print ("Second call: ", jit(impure_uses_globals)(5.)) # JAX re-runs the Python function when the type or shape of the argument changes # This will end up reading the latest value of the global print ("Third call, different type: ", jit(impure_uses_globals)(jnp.array([4.]))) # In[4]: g = 0. def impure_saves_global(x): global g g = x return x # JAX runs once the transformed function with special Traced values for arguments print ("First call: ", jit(impure_saves_global)(4.)) print ("Saved global: ", g) # Saved global has an internal JAX value # A Python function can be functionally pure even if it actually uses stateful objects internally, as long as it does not read or write external state: # In[5]: def pure_uses_internal_state(x): state = dict(even=0, odd=0) for i in range(10): state['even' if i % 2 == 0 else 'odd'] += x return state['even'] + state['odd'] print(jit(pure_uses_internal_state)(5.)) # It is not recommended to use iterators in any JAX function you want to `jit` or in any control-flow primitive. The reason is that an iterator is a python object which introduces state to retrieve the next element. Therefore, it is incompatible with JAX functional programming model. In the code below, there are some examples of incorrect attempts to use iterators with JAX. Most of them return an error, but some give unexpected results. # In[6]: import jax.numpy as jnp import jax.lax as lax from jax import make_jaxpr # lax.fori_loop array = jnp.arange(10) print(lax.fori_loop(0, 10, lambda i,x: x+array[i], 0)) # expected result 45 iterator = iter(range(10)) print(lax.fori_loop(0, 10, lambda i,x: x+next(iterator), 0)) # unexpected result 0 # lax.scan def func11(arr, extra): ones = jnp.ones(arr.shape) def body(carry, aelems): ae1, ae2 = aelems return (carry + ae1 * ae2 + extra, carry) return lax.scan(body, 0., (arr, ones)) make_jaxpr(func11)(jnp.arange(16), 5.) # make_jaxpr(func11)(iter(range(16)), 5.) # throws error # lax.cond array_operand = jnp.array([0.]) lax.cond(True, lambda x: x+1, lambda x: x-1, array_operand) iter_operand = iter(range(10)) # lax.cond(True, lambda x: next(x)+1, lambda x: next(x)-1, iter_operand) # throws error # ## 🔪 In-Place Updates # In Numpy you're used to doing this: # In[7]: numpy_array = np.zeros((3,3), dtype=np.float32) print("original array:") print(numpy_array) # In place, mutating update numpy_array[1, :] = 1.0 print("updated array:") print(numpy_array) # If we try to update a JAX device array in-place, however, we get an __error__! (☉_☉) # In[8]: jax_array = jnp.zeros((3,3), dtype=jnp.float32) # In place update of JAX's array will yield an error! try: jax_array[1, :] = 1.0 except Exception as e: print("Exception {}".format(e)) # Allowing mutation of variables in-place makes program analysis and transformation difficult. JAX requires that programs are pure functions. # # Instead, JAX offers a _functional_ array update using the [`.at` property on JAX arrays](https://jax.readthedocs.io/en/latest/_autosummary/jax.numpy.ndarray.at.html#jax.numpy.ndarray.at). # ️⚠️ inside `jit`'d code and `lax.while_loop` or `lax.fori_loop` the __size__ of slices can't be functions of argument _values_ but only functions of argument _shapes_ -- the slice start indices have no such restriction. See the below __Control Flow__ Section for more information on this limitation. # ### Array updates: `x.at[idx].set(y)` # For example, the update above can be written as: # In[9]: updated_array = jax_array.at[1, :].set(1.0) print("updated array:\n", updated_array) # JAX's array update functions, unlike their NumPy versions, operate out-of-place. That is, the updated array is returned as a new array and the original array is not modified by the update. # In[10]: print("original array unchanged:\n", jax_array) # However, inside __jit__-compiled code, if the __input value__ `x` of `x.at[idx].set(y)` is not reused, the compiler will optimize the array update to occur _in-place_. # ### Array updates with other operations # Indexed array updates are not limited simply to overwriting values. For example, we can perform indexed addition as follows: # In[11]: print("original array:") jax_array = jnp.ones((5, 6)) print(jax_array) new_jax_array = jax_array.at[::2, 3:].add(7.) print("new array post-addition:") print(new_jax_array) # For more details on indexed array updates, see the [documentation for the `.at` property](https://jax.readthedocs.io/en/latest/_autosummary/jax.numpy.ndarray.at.html#jax.numpy.ndarray.at). # ## 🔪 Out-of-Bounds Indexing # In Numpy, you are used to errors being thrown when you index an array outside of its bounds, like this: # In[12]: try: np.arange(10)[11] except Exception as e: print("Exception {}".format(e)) # However, raising an error from code running on an accelerator can be difficult or impossible. Therefore, JAX must choose some non-error behavior for out of bounds indexing (akin to how invalid floating point arithmetic results in `NaN`). When the indexing operation is an array index update (e.g. `index_add` or `scatter`-like primitives), updates at out-of-bounds indices will be skipped; when the operation is an array index retrieval (e.g. NumPy indexing or `gather`-like primitives) the index is clamped to the bounds of the array since __something__ must be returned. For example, the last value of the array will be returned from this indexing operation: # In[13]: jnp.arange(10)[11] # Note that due to this behavior for index retrieval, functions like `jnp.nanargmin` and `jnp.nanargmax` return -1 for slices consisting of NaNs whereas Numpy would throw an error. # # Note also that, as the two behaviors described above are not inverses of each other, reverse-mode automatic differentiation (which turns index updates into index retrievals and vice versa) [will not preserve the semantics of out of bounds indexing](https://github.com/google/jax/issues/5760). Thus it may be a good idea to think of out-of-bounds indexing in JAX as a case of [undefined behavior](https://en.wikipedia.org/wiki/Undefined_behavior). # ## 🔪 Non-array inputs: NumPy vs. JAX # # NumPy is generally happy accepting Python lists or tuples as inputs to its API functions: # In[14]: np.sum([1, 2, 3]) # JAX departs from this, generally returning a helpful error: # In[15]: try: jnp.sum([1, 2, 3]) except TypeError as e: print(f"TypeError: {e}") # This is a deliberate design choice, because passing lists or tuples to traced functions can lead to silent performance degradation that might otherwise be difficult to detect. # # For example, consider the following permissive version of `jnp.sum` that allows list inputs: # In[16]: def permissive_sum(x): return jnp.sum(jnp.array(x)) x = list(range(10)) permissive_sum(x) # The output is what we would expect, but this hides potential performance issues under the hood. In JAX's tracing and JIT compilation model, each element in a Python list or tuple is treated as a separate JAX variable, and individually processed and pushed to device. This can be seen in the jaxpr for the ``permissive_sum`` function above: # In[17]: make_jaxpr(permissive_sum)(x) # Each entry of the list is handled as a separate input, resulting in a tracing & compilation overhead that grows linearly with the size of the list. To prevent surprises like this, JAX avoids implicit conversions of lists and tuples to arrays. # # If you would like to pass a tuple or list to a JAX function, you can do so by first explicitly converting it to an array: # In[18]: jnp.sum(jnp.array(x)) # ## 🔪 Random Numbers # > _If all scientific papers whose results are in doubt because of bad # > `rand()`s were to disappear from library shelves, there would be a # > gap on each shelf about as big as your fist._ - Numerical Recipes # ### RNGs and State # You're used to _stateful_ pseudorandom number generators (PRNGs) from numpy and other libraries, which helpfully hide a lot of details under the hood to give you a ready fountain of pseudorandomness: # In[19]: print(np.random.random()) print(np.random.random()) print(np.random.random()) # Underneath the hood, numpy uses the [Mersenne Twister](https://en.wikipedia.org/wiki/Mersenne_Twister) PRNG to power its pseudorandom functions. The PRNG has a period of $2^{19937}-1$ and at any point can be described by __624 32bit unsigned ints__ and a __position__ indicating how much of this "entropy" has been used up. # In[20]: np.random.seed(0) rng_state = np.random.get_state() #print(rng_state) # --> ('MT19937', array([0, 1, 1812433255, 1900727105, 1208447044, # 2481403966, 4042607538, 337614300, ... 614 more numbers..., # 3048484911, 1796872496], dtype=uint32), 624, 0, 0.0) # This pseudorandom state vector is automagically updated behind the scenes every time a random number is needed, "consuming" 2 of the uint32s in the Mersenne twister state vector: # In[21]: _ = np.random.uniform() rng_state = np.random.get_state() #print(rng_state) # --> ('MT19937', array([2443250962, 1093594115, 1878467924, # ..., 2648828502, 1678096082], dtype=uint32), 2, 0, 0.0) # Let's exhaust the entropy in this PRNG statevector for i in range(311): _ = np.random.uniform() rng_state = np.random.get_state() #print(rng_state) # --> ('MT19937', array([2443250962, 1093594115, 1878467924, # ..., 2648828502, 1678096082], dtype=uint32), 624, 0, 0.0) # Next call iterates the RNG state for a new batch of fake "entropy". _ = np.random.uniform() rng_state = np.random.get_state() # print(rng_state) # --> ('MT19937', array([1499117434, 2949980591, 2242547484, # 4162027047, 3277342478], dtype=uint32), 2, 0, 0.0) # The problem with magic PRNG state is that it's hard to reason about how it's being used and updated across different threads, processes, and devices, and it's _very easy_ to screw up when the details of entropy production and consumption are hidden from the end user. # # The Mersenne Twister PRNG is also known to have a [number](https://cs.stackexchange.com/a/53475) of problems, it has a large 2.5Kb state size, which leads to problematic [initialization issues](https://dl.acm.org/citation.cfm?id=1276928). It [fails](http://www.pcg-random.org/pdf/toms-oneill-pcg-family-v1.02.pdf) modern BigCrush tests, and is generally slow. # ### JAX PRNG # JAX instead implements an _explicit_ PRNG where entropy production and consumption are handled by explicitly passing and iterating PRNG state. JAX uses a modern [Threefry counter-based PRNG](https://github.com/google/jax/blob/main/design_notes/prng.md) that's __splittable__. That is, its design allows us to __fork__ the PRNG state into new PRNGs for use with parallel stochastic generation. # # The random state is described by two unsigned-int32s that we call a __key__: # In[22]: from jax import random key = random.PRNGKey(0) key # JAX's random functions produce pseudorandom numbers from the PRNG state, but __do not__ change the state! # # Reusing the same state will cause __sadness__ and __monotony__, depriving the end user of __lifegiving chaos__: # In[23]: print(random.normal(key, shape=(1,))) print(key) # No no no! print(random.normal(key, shape=(1,))) print(key) # Instead, we __split__ the PRNG to get usable __subkeys__ every time we need a new pseudorandom number: # In[24]: print("old key", key) key, subkey = random.split(key) normal_pseudorandom = random.normal(subkey, shape=(1,)) print(" \---SPLIT --> new key ", key) print(" \--> new subkey", subkey, "--> normal", normal_pseudorandom) # We propagate the __key__ and make new __subkeys__ whenever we need a new random number: # In[25]: print("old key", key) key, subkey = random.split(key) normal_pseudorandom = random.normal(subkey, shape=(1,)) print(" \---SPLIT --> new key ", key) print(" \--> new subkey", subkey, "--> normal", normal_pseudorandom) # We can generate more than one __subkey__ at a time: # In[26]: key, *subkeys = random.split(key, 4) for subkey in subkeys: print(random.normal(subkey, shape=(1,))) # ## 🔪 Control Flow # ### ✔ python control_flow + autodiff ✔ # # If you just want to apply `grad` to your python functions, you can use regular python control-flow constructs with no problems, as if you were using [Autograd](https://github.com/hips/autograd) (or Pytorch or TF Eager). # In[27]: def f(x): if x < 3: return 3. * x ** 2 else: return -4 * x print(grad(f)(2.)) # ok! print(grad(f)(4.)) # ok! # ### python control flow + JIT # # Using control flow with `jit` is more complicated, and by default it has more constraints. # # This works: # In[28]: @jit def f(x): for i in range(3): x = 2 * x return x print(f(3)) # So does this: # In[29]: @jit def g(x): y = 0. for i in range(x.shape[0]): y = y + x[i] return y print(g(jnp.array([1., 2., 3.]))) # But this doesn't, at least by default: # In[30]: @jit def f(x): if x < 3: return 3. * x ** 2 else: return -4 * x # This will fail! try: f(2) except Exception as e: print("Exception {}".format(e)) # __What gives!?__ # # When we `jit`-compile a function, we usually want to compile a version of the function that works for many different argument values, so that we can cache and reuse the compiled code. That way we don't have to re-compile on each function evaluation. # # For example, if we evaluate an `@jit` function on the array `jnp.array([1., 2., 3.], jnp.float32)`, we might want to compile code that we can reuse to evaluate the function on `jnp.array([4., 5., 6.], jnp.float32)` to save on compile time. # # To get a view of your Python code that is valid for many different argument values, JAX traces it on _abstract values_ that represent sets of possible inputs. There are [multiple different levels of abstraction](https://github.com/google/jax/blob/main/jax/_src/abstract_arrays.py), and different transformations use different abstraction levels. # # By default, `jit` traces your code on the `ShapedArray` abstraction level, where each abstract value represents the set of all array values with a fixed shape and dtype. For example, if we trace using the abstract value `ShapedArray((3,), jnp.float32)`, we get a view of the function that can be reused for any concrete value in the corresponding set of arrays. That means we can save on compile time. # # But there's a tradeoff here: if we trace a Python function on a `ShapedArray((), jnp.float32)` that isn't committed to a specific concrete value, when we hit a line like `if x < 3`, the expression `x < 3` evaluates to an abstract `ShapedArray((), jnp.bool_)` that represents the set `{True, False}`. When Python attempts to coerce that to a concrete `True` or `False`, we get an error: we don't know which branch to take, and can't continue tracing! The tradeoff is that with higher levels of abstraction we gain a more general view of the Python code (and thus save on re-compilations), but we require more constraints on the Python code to complete the trace. # # The good news is that you can control this tradeoff yourself. By having `jit` trace on more refined abstract values, you can relax the traceability constraints. For example, using the `static_argnums` argument to `jit`, we can specify to trace on concrete values of some arguments. Here's that example function again: # In[31]: def f(x): if x < 3: return 3. * x ** 2 else: return -4 * x f = jit(f, static_argnums=(0,)) print(f(2.)) # Here's another example, this time involving a loop: # In[32]: def f(x, n): y = 0. for i in range(n): y = y + x[i] return y f = jit(f, static_argnums=(1,)) f(jnp.array([2., 3., 4.]), 2) # In effect, the loop gets statically unrolled. JAX can also trace at _higher_ levels of abstraction, like `Unshaped`, but that's not currently the default for any transformation # ️⚠️ **functions with argument-__value__ dependent shapes** # # These control-flow issues also come up in a more subtle way: numerical functions we want to __jit__ can't specialize the shapes of internal arrays on argument _values_ (specializing on argument __shapes__ is ok). As a trivial example, let's make a function whose output happens to depend on the input variable `length`. # In[33]: def example_fun(length, val): return jnp.ones((length,)) * val # un-jit'd works fine print(example_fun(5, 4)) bad_example_jit = jit(example_fun) # this will fail: try: print(bad_example_jit(10, 4)) except Exception as e: print("Exception {}".format(e)) # static_argnums tells JAX to recompile on changes at these argument positions: good_example_jit = jit(example_fun, static_argnums=(0,)) # first compile print(good_example_jit(10, 4)) # recompiles print(good_example_jit(5, 4)) # `static_argnums` can be handy if `length` in our example rarely changes, but it would be disastrous if it changed a lot! # # Lastly, if your function has global side-effects, JAX's tracer can cause weird things to happen. A common gotcha is trying to print arrays inside __jit__'d functions: # In[34]: @jit def f(x): print(x) y = 2 * x print(y) return y f(2) # ### Structured control flow primitives # # There are more options for control flow in JAX. Say you want to avoid re-compilations but still want to use control flow that's traceable, and that avoids un-rolling large loops. Then you can use these 4 structured control flow primitives: # # - `lax.cond` _differentiable_ # - `lax.while_loop` __fwd-mode-differentiable__ # - `lax.fori_loop` __fwd-mode-differentiable__ # - `lax.scan` _differentiable_ # #### cond # python equivalent: # # ```python # def cond(pred, true_fun, false_fun, operand): # if pred: # return true_fun(operand) # else: # return false_fun(operand) # ``` # In[35]: from jax import lax operand = jnp.array([0.]) lax.cond(True, lambda x: x+1, lambda x: x-1, operand) # --> array([1.], dtype=float32) lax.cond(False, lambda x: x+1, lambda x: x-1, operand) # --> array([-1.], dtype=float32) # #### while_loop # # python equivalent: # ``` # def while_loop(cond_fun, body_fun, init_val): # val = init_val # while cond_fun(val): # val = body_fun(val) # return val # ``` # In[36]: init_val = 0 cond_fun = lambda x: x<10 body_fun = lambda x: x+1 lax.while_loop(cond_fun, body_fun, init_val) # --> array(10, dtype=int32) # #### fori_loop # python equivalent: # ``` # def fori_loop(start, stop, body_fun, init_val): # val = init_val # for i in range(start, stop): # val = body_fun(i, val) # return val # ``` # In[37]: init_val = 0 start = 0 stop = 10 body_fun = lambda i,x: x+i lax.fori_loop(start, stop, body_fun, init_val) # --> array(45, dtype=int32) # #### Summary # # $$ # \begin{array} {r|rr} # \hline \ # \textrm{construct} # & \textrm{jit} # & \textrm{grad} \\ # \hline \ # \textrm{if} & ❌ & ✔ \\ # \textrm{for} & ✔* & ✔\\ # \textrm{while} & ✔* & ✔\\ # \textrm{lax.cond} & ✔ & ✔\\ # \textrm{lax.while_loop} & ✔ & \textrm{fwd}\\ # \textrm{lax.fori_loop} & ✔ & \textrm{fwd}\\ # \textrm{lax.scan} & ✔ & ✔\\ # \hline # \end{array} # $$ # #