#!/usr/bin/env python # coding: utf-8 # # 🔪 JAX - The Sharp Bits 🔪 # *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. As such it needs to control the _unwanted proliferation_ of __side-effects__ in its programs so that analysis and transformation of its computations remain tractable! # # This requires us to write code in a _functional_ style with _explicit_ descriptions of how the state of a program changes, which results in __several important differences__ to how you might be used to programming in Numpy, Tensorflow or Pytorch. # # Herein we try to cover the most frequent points of trouble that users encounter when starting out in __JAX__. # In[ ]: import numpy as onp from jax import grad, jit from jax import lax from jax import random import jax import jax.numpy as np 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 # ## 🔪 In-Place Updates # In Numpy you're used to doing this: # In[ ]: numpy_array = onp.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[ ]: jax_array = np.zeros((3,3), dtype=np.float32) # In place update of JAX's array will yield an error! jax_array[1, :] = 1.0 # __What gives?!__ # # Allowing mutation of variables in-place makes program analysis and transformation very difficult. JAX requires a pure functional expression of a numerical program. # # Instead, JAX offers the _functional_ update functions: __index_update__, __index_add__, __index_min__, __index_max__, and the __index__ helper. # # __NB__: _Fancy Indexing_ is __not__ yet supported, but will likely be added to JAX soon. # # ️⚠️ 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. # In[ ]: from jax.ops import index, index_add, index_update # ### index_update # If the __input values__ of __index_update__ aren't reused, __jit__-compiled code will perform these operations _in-place_. # In[ ]: jax_array = np.zeros((3, 3)) print("original array:") print(jax_array) new_jax_array = index_update(jax_array, index[1, :], 1.) print("old array unchanged:") print(jax_array) print("new array:") print(new_jax_array) # ### index_add # If the __input values__ of __index_update__ aren't reused, __jit__-compiled code will perform these operations _in-place_. # In[ ]: print("original array:") jax_array = np.ones((5, 6)) print(jax_array) new_jax_array = index_add(jax_array, index[::2, 3:], 7.) print("new array post-addition:") print(new_jax_array) # ## 🔪 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[ ]: print(onp.random.random()) print(onp.random.random()) print(onp.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[ ]: onp.random.seed(0) rng_state = onp.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[ ]: _ = onp.random.uniform() rng_state = onp.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): _ = onp.random.uniform() rng_state = onp.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". _ = onp.random.uniform() rng_state = onp.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 [Three-fry counter-based PRNG](https://github.com/google/jax/blob/master/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[ ]: 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 enduser of __lifegiving chaos__: # In[ ]: 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[ ]: 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[ ]: 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[ ]: 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[ ]: 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[ ]: @jit def f(x): for i in range(3): x = 2 * x return x print(f(3)) # So does this: # In[ ]: @jit def g(x): y = 0. for i in range(x.shape[0]): y = y + x[i] return y print(g(np.array([1., 2., 3.]))) # But this doesn't, at least by default: # In[ ]: @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("ERROR:", 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 `np.array([1., 2., 3.], np.float32)`, we might want to compile code that we can reuse to evaluate the function on `np.array([4., 5., 6.], np.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/master/jax/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,), np.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((), np.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((), np.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[ ]: 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[ ]: def f(x, n): y = 0. for i in range(n): y = y + x[i] return y f = jit(f, static_argnums=(1,)) f(np.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[ ]: def example_fun(length, val): return np.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("error!", 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[ ]: @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` _will be differentiable soon_ # - `lax.while_loop` __non-differentiable__* # - `lax.fori_loop` __non-differentiable__* # - `lax.scan` _will be differentiable soon_ # # *_these can in principle be made to be __forward__-differentiable, but this isn't on the current roadmap._ # #### cond # python equivalent: # # ``` # def cond(pred, true_operand, true_fun, false_operand, false_fun): # if pred: # return true_fun(true_operand) # else: # return false_fun(false_operand) # ``` # In[ ]: from jax import lax operand = np.array([0.]) lax.cond(True, operand, lambda x: x+1, operand, lambda x: x-1) # --> array([1.], dtype=float32) lax.cond(False, operand, lambda x: x+1, operand, lambda x: x-1) # --> 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[ ]: 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[ ]: 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{soon!}\\ # \textrm{lax.while_loop} & ✔ & ❌\\ # \textrm{lax.fori_loop} & ✔ & ❌\\ # \textrm{lax.scan} & \textrm{soon!} & \textrm{soon!}\\ # \hline # \end{array} # $$ #