mirror of
https://github.com/ROCm/jax.git
synced 2025-04-14 19:06:07 +00:00
550 lines
17 KiB
Plaintext
550 lines
17 KiB
Plaintext
{
|
|
"cells": [
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {
|
|
"id": "M-hPMKlwXjMr"
|
|
},
|
|
"source": [
|
|
"# Writing custom Jaxpr interpreters in JAX\n",
|
|
"\n",
|
|
"<!--* freshness: { reviewed: '2024-04-08' } *-->\n",
|
|
"\n",
|
|
"[](https://colab.research.google.com/github/jax-ml/jax/blob/main/docs/notebooks/Writing_custom_interpreters_in_Jax.ipynb) [](https://kaggle.com/kernels/welcome?src=https://github.com/jax-ml/jax/blob/main/docs/notebooks/Writing_custom_interpreters_in_Jax.ipynb)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {
|
|
"id": "r-3vMiKRYXPJ"
|
|
},
|
|
"source": [
|
|
"JAX offers several composable function transformations (`jit`, `grad`, `vmap`,\n",
|
|
"etc.) that enable writing concise, accelerated code. \n",
|
|
"\n",
|
|
"Here we show how to add your own function transformations to the system, by writing a custom Jaxpr interpreter. And we'll get composability with all the other transformations for free.\n",
|
|
"\n",
|
|
"**This example uses internal JAX APIs, which may break at any time. Anything not in [the API Documentation](https://jax.readthedocs.io/en/latest/jax.html) should be assumed internal.**"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {
|
|
"id": "s27RDKvKXFL8"
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"import jax\n",
|
|
"import jax.numpy as jnp\n",
|
|
"from jax import jit, grad, vmap\n",
|
|
"from jax import random"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {
|
|
"id": "jb_8mEsJboVM"
|
|
},
|
|
"source": [
|
|
"## What is JAX doing?"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {
|
|
"id": "KxR2WK0Ubs0R"
|
|
},
|
|
"source": [
|
|
"JAX provides a NumPy-like API for numerical computing which can be used as is, but JAX's true power comes from composable function transformations. Take the `jit` function transformation, which takes in a function and returns a semantically identical function but is lazily compiled by XLA for accelerators."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {
|
|
"id": "HmlMcICOcSXR"
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"x = random.normal(random.key(0), (5000, 5000))\n",
|
|
"def f(w, b, x):\n",
|
|
" return jnp.tanh(jnp.dot(x, w) + b)\n",
|
|
"fast_f = jit(f)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {
|
|
"id": "gA8V51wZdsjh"
|
|
},
|
|
"source": [
|
|
"When we call `fast_f`, what happens? JAX traces the function and constructs an XLA computation graph. The graph is then JIT-compiled and executed. Other transformations work similarly in that they first trace the function and handle the output trace in some way. To learn more about Jax's tracing machinery, you can refer to the [\"How it works\"](https://github.com/jax-ml/jax#how-it-works) section in the README."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {
|
|
"id": "2Th1vYLVaFBz"
|
|
},
|
|
"source": [
|
|
"## Jaxpr tracer\n",
|
|
"\n",
|
|
"A tracer of special importance in Jax is the Jaxpr tracer, which records ops into a Jaxpr (Jax expression). A Jaxpr is a data structure that can be evaluated like a mini functional programming language and \n",
|
|
"thus Jaxprs are a useful intermediate representation\n",
|
|
"for function transformation."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {
|
|
"id": "pH7s63lpaHJO"
|
|
},
|
|
"source": [
|
|
"To get a first look at Jaxprs, consider the `make_jaxpr` transformation. `make_jaxpr` is essentially a \"pretty-printing\" transformation:\n",
|
|
"it transforms a function into one that, given example arguments, produces a Jaxpr representation of its computation.\n",
|
|
"`make_jaxpr` is useful for debugging and introspection.\n",
|
|
"Let's use it to look at how some example Jaxprs are structured."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {
|
|
"id": "RSxEiWi-EeYW"
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"def examine_jaxpr(closed_jaxpr):\n",
|
|
" jaxpr = closed_jaxpr.jaxpr\n",
|
|
" print(\"invars:\", jaxpr.invars)\n",
|
|
" print(\"outvars:\", jaxpr.outvars)\n",
|
|
" print(\"constvars:\", jaxpr.constvars)\n",
|
|
" for eqn in jaxpr.eqns:\n",
|
|
" print(\"equation:\", eqn.invars, eqn.primitive, eqn.outvars, eqn.params)\n",
|
|
" print()\n",
|
|
" print(\"jaxpr:\", jaxpr)\n",
|
|
"\n",
|
|
"def foo(x):\n",
|
|
" return x + 1\n",
|
|
"print(\"foo\")\n",
|
|
"print(\"=====\")\n",
|
|
"examine_jaxpr(jax.make_jaxpr(foo)(5))\n",
|
|
"\n",
|
|
"print()\n",
|
|
"\n",
|
|
"def bar(w, b, x):\n",
|
|
" return jnp.dot(w, x) + b + jnp.ones(5), x\n",
|
|
"print(\"bar\")\n",
|
|
"print(\"=====\")\n",
|
|
"examine_jaxpr(jax.make_jaxpr(bar)(jnp.ones((5, 10)), jnp.ones(5), jnp.ones(10)))"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {
|
|
"id": "k-HxK9iagnH6"
|
|
},
|
|
"source": [
|
|
"* `jaxpr.invars` - the `invars` of a Jaxpr are a list of the input variables to Jaxpr, analogous to arguments in Python functions.\n",
|
|
"* `jaxpr.outvars` - the `outvars` of a Jaxpr are the variables that are returned by the Jaxpr. Every Jaxpr has multiple outputs.\n",
|
|
"* `jaxpr.constvars` - the `constvars` are a list of variables that are also inputs to the Jaxpr, but correspond to constants from the trace (we'll go over these in more detail later).\n",
|
|
"* `jaxpr.eqns` - a list of equations, which are essentially let-bindings. Each equation is a list of input variables, a list of output variables, and a *primitive*, which is used to evaluate inputs to produce outputs. Each equation also has a `params`, a dictionary of parameters.\n",
|
|
"\n",
|
|
"Altogether, a Jaxpr encapsulates a simple program that can be evaluated with inputs to produce an output. We'll go over how exactly to do this later. The important thing to note now is that a Jaxpr is a data structure that can be manipulated and evaluated in whatever way we want."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {
|
|
"id": "NwY7TurYn6sr"
|
|
},
|
|
"source": [
|
|
"### Why are Jaxprs useful?"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {
|
|
"id": "UEy6RorCgdYt"
|
|
},
|
|
"source": [
|
|
"Jaxprs are simple program representations that are easy to transform. And because Jax lets us stage out Jaxprs from Python functions, it gives us a way to transform numerical programs written in Python."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {
|
|
"id": "qizTKpbno_ua"
|
|
},
|
|
"source": [
|
|
"## Your first interpreter: `invert`"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {
|
|
"id": "OIto-KX4pD7j"
|
|
},
|
|
"source": [
|
|
"Let's try to implement a simple function \"inverter\", which takes in the output of the original function and returns the inputs that produced those outputs. For now, let's focus on simple, unary functions which are composed of other invertible unary functions.\n",
|
|
"\n",
|
|
"Goal:\n",
|
|
"```python\n",
|
|
"def f(x):\n",
|
|
" return jnp.exp(jnp.tanh(x))\n",
|
|
"f_inv = inverse(f)\n",
|
|
"assert jnp.allclose(f_inv(f(1.0)), 1.0)\n",
|
|
"```\n",
|
|
"\n",
|
|
"The way we'll implement this is by (1) tracing `f` into a Jaxpr, then (2) interpreting the Jaxpr *backwards*. While interpreting the Jaxpr backwards, for each equation we'll look up the primitive's inverse in a table and apply it.\n",
|
|
"\n",
|
|
"### 1. Tracing a function\n",
|
|
"\n",
|
|
"Let's use `make_jaxpr` to trace a function into a Jaxpr."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {
|
|
"id": "BHkg_3P1pXJj"
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"# Importing Jax functions useful for tracing/interpreting.\n",
|
|
"from functools import wraps\n",
|
|
"\n",
|
|
"from jax import core\n",
|
|
"from jax import lax\n",
|
|
"from jax._src.util import safe_map"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {
|
|
"id": "CpTml2PTrzZ4"
|
|
},
|
|
"source": [
|
|
"`jax.make_jaxpr` returns a *closed* Jaxpr, which is a Jaxpr that has been bundled with\n",
|
|
"the constants (`literals`) from the trace."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {
|
|
"id": "Tc1REN5aq_fH"
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"def f(x):\n",
|
|
" return jnp.exp(jnp.tanh(x))\n",
|
|
"\n",
|
|
"closed_jaxpr = jax.make_jaxpr(f)(jnp.ones(5))\n",
|
|
"print(closed_jaxpr.jaxpr)\n",
|
|
"print(closed_jaxpr.literals)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {
|
|
"id": "WmZ3BcmZsbfR"
|
|
},
|
|
"source": [
|
|
"### 2. Evaluating a Jaxpr\n",
|
|
"\n",
|
|
"\n",
|
|
"Before we write a custom Jaxpr interpreter, let's first implement the \"default\" interpreter, `eval_jaxpr`, which evaluates the Jaxpr as-is, computing the same values that the original, un-transformed Python function would. \n",
|
|
"\n",
|
|
"To do this, we first create an environment to store the values for each of the variables, and update the environment with each equation we evaluate in the Jaxpr."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {
|
|
"id": "ACMxjIHStHwD"
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"def eval_jaxpr(jaxpr, consts, *args):\n",
|
|
" # Mapping from variable -> value\n",
|
|
" env = {}\n",
|
|
"\n",
|
|
" def read(var):\n",
|
|
" # Literals are values baked into the Jaxpr\n",
|
|
" if type(var) is core.Literal:\n",
|
|
" return var.val\n",
|
|
" return env[var]\n",
|
|
"\n",
|
|
" def write(var, val):\n",
|
|
" env[var] = val\n",
|
|
"\n",
|
|
" # Bind args and consts to environment\n",
|
|
" safe_map(write, jaxpr.invars, args)\n",
|
|
" safe_map(write, jaxpr.constvars, consts)\n",
|
|
"\n",
|
|
" # Loop through equations and evaluate primitives using `bind`\n",
|
|
" for eqn in jaxpr.eqns:\n",
|
|
" # Read inputs to equation from environment\n",
|
|
" invals = safe_map(read, eqn.invars)\n",
|
|
" # `bind` is how a primitive is called\n",
|
|
" outvals = eqn.primitive.bind(*invals, **eqn.params)\n",
|
|
" # Primitives may return multiple outputs or not\n",
|
|
" if not eqn.primitive.multiple_results:\n",
|
|
" outvals = [outvals]\n",
|
|
" # Write the results of the primitive into the environment\n",
|
|
" safe_map(write, eqn.outvars, outvals)\n",
|
|
" # Read the final result of the Jaxpr from the environment\n",
|
|
" return safe_map(read, jaxpr.outvars)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {
|
|
"id": "mGHPc3NruCFV"
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"closed_jaxpr = jax.make_jaxpr(f)(jnp.ones(5))\n",
|
|
"eval_jaxpr(closed_jaxpr.jaxpr, closed_jaxpr.literals, jnp.ones(5))"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {
|
|
"id": "XhZhzbVBvAiT"
|
|
},
|
|
"source": [
|
|
"Notice that `eval_jaxpr` will always return a flat list even if the original function does not.\n",
|
|
"\n",
|
|
"Furthermore, this interpreter does not handle higher-order primitives (like `jit` and `pmap`), which we will not cover in this guide. You can refer to `core.eval_jaxpr` ([link](https://github.com/jax-ml/jax/blob/main/jax/core.py)) to see the edge cases that this interpreter does not cover."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {
|
|
"id": "0vb2ZoGrCMM4"
|
|
},
|
|
"source": [
|
|
"### Custom `inverse` Jaxpr interpreter\n",
|
|
"\n",
|
|
"An `inverse` interpreter doesn't look too different from `eval_jaxpr`. We'll first set up the registry which will map primitives to their inverses. We'll then write a custom interpreter that looks up primitives in the registry.\n",
|
|
"\n",
|
|
"It turns out that this interpreter will also look similar to the \"transpose\" interpreter used in reverse-mode autodifferentiation [found here](https://github.com/jax-ml/jax/blob/main/jax/interpreters/ad.py#L164-L234)."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {
|
|
"id": "gSMIT2z1vUpO"
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"inverse_registry = {}"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {
|
|
"id": "JgrpMgDyCrC7"
|
|
},
|
|
"source": [
|
|
"We'll now register inverses for some of the primitives. By convention, primitives in Jax end in `_p` and a lot of the popular ones live in `lax`."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {
|
|
"id": "fUerorGkCqhw"
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"inverse_registry[lax.exp_p] = jnp.log\n",
|
|
"inverse_registry[lax.tanh_p] = jnp.arctanh"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {
|
|
"id": "mDtH_lYDC5WK"
|
|
},
|
|
"source": [
|
|
"`inverse` will first trace the function, then custom-interpret the Jaxpr. Let's set up a simple skeleton."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {
|
|
"id": "jGNfV6JJC1B3"
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"def inverse(fun):\n",
|
|
" @wraps(fun)\n",
|
|
" def wrapped(*args, **kwargs):\n",
|
|
" # Since we assume unary functions, we won't worry about flattening and\n",
|
|
" # unflattening arguments.\n",
|
|
" closed_jaxpr = jax.make_jaxpr(fun)(*args, **kwargs)\n",
|
|
" out = inverse_jaxpr(closed_jaxpr.jaxpr, closed_jaxpr.literals, *args)\n",
|
|
" return out[0]\n",
|
|
" return wrapped"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {
|
|
"id": "g6v6wV7SDM7g"
|
|
},
|
|
"source": [
|
|
"Now we just need to define `inverse_jaxpr`, which will walk through the Jaxpr backward and invert primitives when it can."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {
|
|
"id": "uUAd-L-BDKT5"
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"def inverse_jaxpr(jaxpr, consts, *args):\n",
|
|
" env = {}\n",
|
|
"\n",
|
|
" def read(var):\n",
|
|
" if type(var) is core.Literal:\n",
|
|
" return var.val\n",
|
|
" return env[var]\n",
|
|
"\n",
|
|
" def write(var, val):\n",
|
|
" env[var] = val\n",
|
|
" # Args now correspond to Jaxpr outvars\n",
|
|
" safe_map(write, jaxpr.outvars, args)\n",
|
|
" safe_map(write, jaxpr.constvars, consts)\n",
|
|
"\n",
|
|
" # Looping backward\n",
|
|
" for eqn in jaxpr.eqns[::-1]:\n",
|
|
" # outvars are now invars\n",
|
|
" invals = safe_map(read, eqn.outvars)\n",
|
|
" if eqn.primitive not in inverse_registry:\n",
|
|
" raise NotImplementedError(\n",
|
|
" f\"{eqn.primitive} does not have registered inverse.\")\n",
|
|
" # Assuming a unary function\n",
|
|
" outval = inverse_registry[eqn.primitive](*invals)\n",
|
|
" safe_map(write, eqn.invars, [outval])\n",
|
|
" return safe_map(read, jaxpr.invars)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {
|
|
"id": "M8i3wGbVERhA"
|
|
},
|
|
"source": [
|
|
"That's it!"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {
|
|
"id": "cjEKWso-D5Bu"
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"def f(x):\n",
|
|
" return jnp.exp(jnp.tanh(x))\n",
|
|
"\n",
|
|
"f_inv = inverse(f)\n",
|
|
"assert jnp.allclose(f_inv(f(1.0)), 1.0)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {
|
|
"id": "Ny7Oo4WLHdXt"
|
|
},
|
|
"source": [
|
|
"Importantly, you can trace through a Jaxpr interpreter."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {
|
|
"id": "j6ov_rveHmTb"
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"jax.make_jaxpr(inverse(f))(f(1.))"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {
|
|
"id": "yfWVBsKwH0j6"
|
|
},
|
|
"source": [
|
|
"That's all it takes to add a new transformation to a system, and you get composition with all the others for free! For example, we can use `jit`, `vmap`, and `grad` with `inverse`!"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"metadata": {
|
|
"id": "3tjNk21CH4yZ"
|
|
},
|
|
"outputs": [],
|
|
"source": [
|
|
"jit(vmap(grad(inverse(f))))((jnp.arange(5) + 1.) / 5.)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"metadata": {
|
|
"id": "APtG-u_6E4tK"
|
|
},
|
|
"source": [
|
|
"## Exercises for the reader\n",
|
|
"\n",
|
|
"* Handle primitives with multiple arguments where inputs are partially known, for example `lax.add_p`, `lax.mul_p`.\n",
|
|
"* Handle `xla_call` and `xla_pmap` primitives, which will not work with both `eval_jaxpr` and `inverse_jaxpr` as written."
|
|
]
|
|
}
|
|
],
|
|
"metadata": {
|
|
"colab": {
|
|
"collapsed_sections": [],
|
|
"name": "Writing custom interpreters in Jax",
|
|
"provenance": []
|
|
},
|
|
"jupytext": {
|
|
"formats": "ipynb,md:myst"
|
|
},
|
|
"kernelspec": {
|
|
"display_name": "Python 3",
|
|
"language": "python",
|
|
"name": "python3"
|
|
},
|
|
"language_info": {
|
|
"codemirror_mode": {
|
|
"name": "ipython",
|
|
"version": 3
|
|
},
|
|
"file_extension": ".py",
|
|
"mimetype": "text/x-python",
|
|
"name": "python",
|
|
"nbconvert_exporter": "python",
|
|
"pygments_lexer": "ipython3",
|
|
"version": "3.7.3"
|
|
}
|
|
},
|
|
"nbformat": 4,
|
|
"nbformat_minor": 0
|
|
}
|