{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "f4TSNCvpENrW"
      },
      "source": [
        "##### Copyright 2019 The TensorFlow Authors."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "cellView": "form",
        "id": "vamNSA0vEP-m"
      },
      "outputs": [],
      "source": [
        "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n",
        "# you may not use this file except in compliance with the License.\n",
        "# You may obtain a copy of the License at\n",
        "#\n",
        "# https://www.apache.org/licenses/LICENSE-2.0\n",
        "#\n",
        "# Unless required by applicable law or agreed to in writing, software\n",
        "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
        "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
        "# See the License for the specific language governing permissions and\n",
        "# limitations under the License."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "e1oSi4lHFt3z"
      },
      "source": [
        "# Use XLA with tf.function"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "b7noD9NjFRL-"
      },
      "source": [
        "<table class=\"tfo-notebook-buttons\" align=\"left\">\n",
        "  <td>\n",
        "    <a target=\"_blank\" href=\"https://www.tensorflow.org/xla/tutorials/compile\"><img src=\"https://www.tensorflow.org/images/tf_logo_32px.png\" />View on TensorFlow.org</a>\n",
        "  </td>\n",
        "  <td>\n",
        "    <a target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/tensorflow/blob/master/tensorflow/compiler/xla/g3doc/tutorials/jit_compile.ipynb\"><img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" />Run in Google Colab</a>\n",
        "  </td>\n",
        "  <td>\n",
        "    <a href=\"https://storage.googleapis.com/tensorflow_docs/tensorflow/tensorflow/compiler/xla/g3doc/tutorials/jit_compile.ipynb\"><img src=\"https://www.tensorflow.org/images/download_logo_32px.png\" />Download notebook</a>\n",
        "  </td>\n",
        "  <td>\n",
        "    <a target=\"_blank\" href=\"https://github.com/tensorflow/tensorflow/blob/master/tensorflow/compiler/xla/g3doc/tutorials/jit_compile.ipynb\"><img src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" />View source on GitHub</a>\n",
        "  </td>\n",
        "</table>"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "sDy5lSBd4BDE"
      },
      "source": [
        "This tutorial trains a TensorFlow model to classify the MNIST dataset, where the training function is compiled using XLA.\n",
        "\n",
        "First, load TensorFlow and enable eager execution."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "45kUPj5ZFrRa"
      },
      "outputs": [],
      "source": [
        "import tensorflow as tf\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "GZVNiRmTDV-5"
      },
      "source": [
        "Then define some necessary constants and prepare the MNIST dataset."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "f37TSEGvGX4_"
      },
      "outputs": [],
      "source": [
        "# Size of each input image, 28 x 28 pixels\n",
        "IMAGE_SIZE = 28 * 28\n",
        "# Number of distinct number labels, [0..9]\n",
        "NUM_CLASSES = 10\n",
        "# Number of examples in each training batch (step)\n",
        "TRAIN_BATCH_SIZE = 100\n",
        "# Number of training steps to run\n",
        "TRAIN_STEPS = 1000\n",
        "\n",
        "# Loads MNIST dataset.\n",
        "train, test = tf.keras.datasets.mnist.load_data()\n",
        "train_ds = tf.data.Dataset.from_tensor_slices(train).batch(TRAIN_BATCH_SIZE).repeat()\n",
        "\n",
        "# Casting from raw data to the required datatypes.\n",
        "def cast(images, labels):\n",
        "  images = tf.cast(\n",
        "      tf.reshape(images, [-1, IMAGE_SIZE]), tf.float32)\n",
        "  labels = tf.cast(labels, tf.int64)\n",
        "  return (images, labels)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "lv7I-u_82v1S"
      },
      "source": [
        "Finally, define the model and the optimizer. The model uses a single dense layer."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "7O2NcEfG206Q"
      },
      "outputs": [],
      "source": [
        "layer = tf.keras.layers.Dense(NUM_CLASSES)\n",
        "optimizer = tf.keras.optimizers.Adam()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "x_ZehpZP-SfS"
      },
      "source": [
        "# Define the training function\n",
        "\n",
        "In the training function, you get the predicted labels using the layer defined above, and then minimize the gradient of the loss using the optimizer. In order to compile the computation using XLA, place it inside `tf.function` with `jit_compile=True`."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "ZbhJl_WvGa3g"
      },
      "outputs": [],
      "source": [
        "@tf.function(jit_compile=True)\n",
        "def train_mnist(images, labels):\n",
        "    images, labels = cast(images, labels)\n",
        "\n",
        "    with tf.GradientTape() as tape:\n",
        "      predicted_labels = layer(images)\n",
        "      loss = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(\n",
        "          logits=predicted_labels, labels=labels\n",
        "      ))\n",
        "    layer_variables = layer.trainable_variables\n",
        "    grads = tape.gradient(loss, layer_variables)\n",
        "    optimizer.apply_gradients(zip(grads, layer_variables))"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "EZD1m_n1DxAF"
      },
      "source": [
        "# Train and test the model"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "gukC2Hol3sFZ"
      },
      "source": [
        "Once you have defined the training function, define the model."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "qe28bAHNHUG2"
      },
      "outputs": [],
      "source": [
        "for images, labels in train_ds:\n",
        "  if optimizer.iterations > TRAIN_STEPS:\n",
        "    break\n",
        "  train_mnist(images, labels)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "qgsKmz3n2UiW"
      },
      "source": [
        "And, finally, check the accuracy:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "_GxF6jTRHVuA"
      },
      "outputs": [],
      "source": [
        "images, labels = cast(test[0], test[1])\n",
        "predicted_labels = layer(images)\n",
        "correct_prediction = tf.equal(tf.argmax(predicted_labels, 1), labels)\n",
        "accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n",
        "print(\"Prediction accuracy after training: %s\" % accuracy)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "PXoOjJnuZRaV"
      },
      "source": [
        "Behind the scenes, the XLA compiler has compiled the entire TF function to HLO, which has enabled fusion optimizations. Using the introspection facilities, we can see the HLO code (other interesting possible values for \"stage\" are `optimized_hlo` for HLO after optimizations and `optimized_hlo_dot` for a Graphviz graph):"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "_a8GsNLVaLSQ"
      },
      "outputs": [],
      "source": [
        "print(train_mnist.experimental_get_compiler_ir(images, labels)(stage='hlo'))"
      ]
    }
  ],
  "metadata": {
    "colab": {
      "collapsed_sections": [],
      "name": "jit_compile.ipynb",
      "provenance": [],
      "toc_visible": true
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
