rocm_jax/docs/notebooks/quickstart.ipynb
2022-03-21 09:41:10 -07:00

500 lines
14 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "xtWX4x9DCF5_"
},
"source": [
"# JAX Quickstart\n",
"\n",
"[![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/google/jax/blob/main/docs/notebooks/quickstart.ipynb)\n",
"\n",
"**JAX is NumPy on the CPU, GPU, and TPU, with great automatic differentiation for high-performance machine learning research.**\n",
"\n",
"With its updated version of [Autograd](https://github.com/hips/autograd), JAX\n",
"can automatically differentiate native Python and NumPy code. It can\n",
"differentiate through a large subset of Pythons features, including loops, ifs,\n",
"recursion, and closures, and it can even take derivatives of derivatives of\n",
"derivatives. It supports reverse-mode as well as forward-mode differentiation, and the two can be composed arbitrarily\n",
"to any order.\n",
"\n",
"Whats new is that JAX uses\n",
"[XLA](https://www.tensorflow.org/xla)\n",
"to compile and run your NumPy code on accelerators, like GPUs and TPUs.\n",
"Compilation happens under the hood by default, with library calls getting\n",
"just-in-time compiled and executed. But JAX even lets you just-in-time compile\n",
"your own Python functions into XLA-optimized kernels using a one-function API.\n",
"Compilation and automatic differentiation can be composed arbitrarily, so you\n",
"can express sophisticated algorithms and get maximal performance without having\n",
"to leave Python."
]
},
{
"cell_type": "code",
"execution_count": 0,
"metadata": {
"id": "SY8mDvEvCGqk"
},
"outputs": [],
"source": [
"import jax.numpy as jnp\n",
"from jax import grad, jit, vmap\n",
"from jax import random"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "FQ89jHCYfhpg"
},
"source": [
"## Multiplying Matrices"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "Xpy1dSgNqCP4"
},
"source": [
"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 [Common Gotchas in JAX].\n",
"\n",
"[Common Gotchas in JAX]: https://jax.readthedocs.io/en/latest/notebooks/Common_Gotchas_in_JAX.html#%F0%9F%94%AA-Random-Numbers"
]
},
{
"cell_type": "code",
"execution_count": 0,
"metadata": {
"id": "u0nseKZNqOoH"
},
"outputs": [],
"source": [
"key = random.PRNGKey(0)\n",
"x = random.normal(key, (10,))\n",
"print(x)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "hDJF0UPKnuqB"
},
"source": [
"Let's dive right in and multiply two big matrices."
]
},
{
"cell_type": "code",
"execution_count": 0,
"metadata": {
"id": "eXn8GUl6CG5N"
},
"outputs": [],
"source": [
"size = 3000\n",
"x = random.normal(key, (size, size), dtype=jnp.float32)\n",
"%timeit jnp.dot(x, x.T).block_until_ready() # runs on the GPU"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "0AlN7EbonyaR"
},
"source": [
"We added that `block_until_ready` because JAX uses asynchronous execution by default (see {ref}`async-dispatch`).\n",
"\n",
"JAX NumPy functions work on regular NumPy arrays."
]
},
{
"cell_type": "code",
"execution_count": 0,
"metadata": {
"id": "ZPl0MuwYrM7t"
},
"outputs": [],
"source": [
"import numpy as np\n",
"x = np.random.normal(size=(size, size)).astype(np.float32)\n",
"%timeit jnp.dot(x, x.T).block_until_ready()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "_SrcB2IurUuE"
},
"source": [
"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 {func}`~jax.device_put`."
]
},
{
"cell_type": "code",
"execution_count": 0,
"metadata": {
"id": "Jj7M7zyRskF0"
},
"outputs": [],
"source": [
"from jax import device_put\n",
"\n",
"x = np.random.normal(size=(size, size)).astype(np.float32)\n",
"x = device_put(x)\n",
"%timeit jnp.dot(x, x.T).block_until_ready()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "clO9djnen8qi"
},
"source": [
"The output of {func}`~jax.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 {func}`~jax.device_put` is equivalent to the function `jit(lambda x: x)`, but it's faster."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "ghkfKNQttDpg"
},
"source": [
"If you have a GPU (or TPU!) these calls run on the accelerator and have the potential to be much faster than on CPU.\n",
"See {ref}`faq-jax-vs-numpy` for more comparison of performance characteristics of NumPy and JAX"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "iOzp0P_GoJhb"
},
"source": [
"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 are three main ones:\n",
"\n",
" - {func}`~jax.jit`, for speeding up your code\n",
" - {func}`~jax.grad`, for taking derivatives\n",
" - {func}`~jax.vmap`, for automatic vectorization or batching.\n",
"\n",
"Let's go over these, one-by-one. We'll also end up composing these in interesting ways."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "bTTrTbWvgLUK"
},
"source": [
"## Using {func}`~jax.jit` to speed up functions"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "YrqE32mvE3b7"
},
"source": [
"JAX runs transparently on the GPU or TPU (falling back to CPU if you don't have one). 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](https://www.tensorflow.org/xla). Let's try that."
]
},
{
"cell_type": "code",
"execution_count": 0,
"metadata": {
"id": "qLGdCtFKFLOR"
},
"outputs": [],
"source": [
"def selu(x, alpha=1.67, lmbda=1.05):\n",
" return lmbda * jnp.where(x > 0, x, alpha * jnp.exp(x) - alpha)\n",
"\n",
"x = random.normal(key, (1000000,))\n",
"%timeit selu(x).block_until_ready()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "a_V8SruVHrD_"
},
"source": [
"We can speed it up with `@jit`, which will jit-compile the first time `selu` is called and will be cached thereafter."
]
},
{
"cell_type": "code",
"execution_count": 0,
"metadata": {
"id": "fh4w_3NpFYTp"
},
"outputs": [],
"source": [
"selu_jit = jit(selu)\n",
"%timeit selu_jit(x).block_until_ready()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "HxpBc4WmfsEU"
},
"source": [
"## Taking derivatives with {func}`~jax.grad`\n",
"\n",
"In addition to evaluating numerical functions, we also want to transform them. One transformation is [automatic differentiation](https://en.wikipedia.org/wiki/Automatic_differentiation). In JAX, just like in [Autograd](https://github.com/HIPS/autograd), you can compute gradients with the {func}`~jax.grad` function."
]
},
{
"cell_type": "code",
"execution_count": 0,
"metadata": {
"id": "IMAgNJaMJwPD"
},
"outputs": [],
"source": [
"def sum_logistic(x):\n",
" return jnp.sum(1.0 / (1.0 + jnp.exp(-x)))\n",
"\n",
"x_small = jnp.arange(3.)\n",
"derivative_fn = grad(sum_logistic)\n",
"print(derivative_fn(x_small))"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "PtNs881Ohioc"
},
"source": [
"Let's verify with finite differences that our result is correct."
]
},
{
"cell_type": "code",
"execution_count": 0,
"metadata": {
"id": "JXI7_OZuKZVO"
},
"outputs": [],
"source": [
"def first_finite_differences(f, x):\n",
" eps = 1e-3\n",
" return jnp.array([(f(x + eps * v) - f(x - eps * v)) / (2 * eps)\n",
" for v in jnp.eye(len(x))])\n",
"\n",
"\n",
"print(first_finite_differences(sum_logistic, x_small))"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "Q2CUZjOWNZ-3"
},
"source": [
"Taking derivatives is as easy as calling {func}`~jax.grad`. {func}`~jax.grad` and {func}`~jax.jit` compose and can be mixed arbitrarily. In the above example we jitted `sum_logistic` and then took its derivative. We can go further:"
]
},
{
"cell_type": "code",
"execution_count": 0,
"metadata": {
"id": "TO4g8ny-OEi4"
},
"outputs": [],
"source": [
"print(grad(jit(grad(jit(grad(sum_logistic)))))(1.0))"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "yCJ5feKvhnBJ"
},
"source": [
"For more advanced autodiff, you can use {func}`jax.vjp` for reverse-mode vector-Jacobian products and {func}`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:"
]
},
{
"cell_type": "code",
"execution_count": 0,
"metadata": {
"id": "Z-JxbiNyhxEW"
},
"outputs": [],
"source": [
"from jax import jacfwd, jacrev\n",
"def hessian(fun):\n",
" return jit(jacfwd(jacrev(fun)))"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "TI4nPsGafxbL"
},
"source": [
"## Auto-vectorization with {func}`~jax.vmap`"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "PcxkONy5aius"
},
"source": [
"JAX has one more transformation in its API that you might find useful: {func}`~jax.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 functions primitive operations for better performance. When composed with {func}`~jax.jit`, it can be just as fast as adding the batch dimensions by hand."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "TPiX4y-bWLFS"
},
"source": [
"We're going to work with a simple example, and promote matrix-vector products into matrix-matrix products using {func}`~jax.vmap`. Although this is easy to do by hand in this specific case, the same technique can apply to more complicated functions."
]
},
{
"cell_type": "code",
"execution_count": 0,
"metadata": {
"id": "8w0Gpsn8WYYj"
},
"outputs": [],
"source": [
"mat = random.normal(key, (150, 100))\n",
"batched_x = random.normal(key, (10, 100))\n",
"\n",
"def apply_matrix(v):\n",
" return jnp.dot(mat, v)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "0zWsc0RisQWx"
},
"source": [
"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."
]
},
{
"cell_type": "code",
"execution_count": 0,
"metadata": {
"id": "KWVc9BsZv0Ki"
},
"outputs": [],
"source": [
"def naively_batched_apply_matrix(v_batched):\n",
" return jnp.stack([apply_matrix(v) for v in v_batched])\n",
"\n",
"print('Naively batched')\n",
"%timeit naively_batched_apply_matrix(batched_x).block_until_ready()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "qHfKaLE9stbA"
},
"source": [
"We know how to batch this operation manually. In this case, `jnp.dot` handles extra batch dimensions transparently."
]
},
{
"cell_type": "code",
"execution_count": 0,
"metadata": {
"id": "ipei6l8nvrzH"
},
"outputs": [],
"source": [
"@jit\n",
"def batched_apply_matrix(v_batched):\n",
" return jnp.dot(v_batched, mat.T)\n",
"\n",
"print('Manually batched')\n",
"%timeit batched_apply_matrix(batched_x).block_until_ready()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "1eF8Nhb-szAb"
},
"source": [
"However, suppose we had a more complicated function without batching support. We can use {func}`~jax.vmap` to add batching support automatically."
]
},
{
"cell_type": "code",
"execution_count": 0,
"metadata": {
"id": "67Oeknf5vuCl"
},
"outputs": [],
"source": [
"@jit\n",
"def vmap_batched_apply_matrix(v_batched):\n",
" return vmap(apply_matrix)(v_batched)\n",
"\n",
"print('Auto-vectorized with vmap')\n",
"%timeit vmap_batched_apply_matrix(batched_x).block_until_ready()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "pYVl3Z2nbZhO"
},
"source": [
"Of course, {func}`~jax.vmap` can be arbitrarily composed with {func}`~jax.jit`, {func}`~jax.grad`, and any other JAX transformation."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "WwNnjaI4th_8"
},
"source": [
"This is just a taste of what JAX can do. We're really excited to see what you do with it!"
]
}
],
"metadata": {
"accelerator": "GPU",
"colab": {
"collapsed_sections": [],
"name": "JAX Quickstart.ipynb",
"provenance": [],
"toc_visible": true,
"version": "0.3.2"
},
"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.6"
}
},
"nbformat": 4,
"nbformat_minor": 0
}