{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 0
   },
   "source": [
    "# Compilers and Interpreters\n",
    ":label:`sec_hybridize`\n",
    "\n",
    "So far, this book has focused on imperative programming, which makes use of statements such as `print`, `+`, and `if` to change a program's state. Consider the following example of a simple imperative program.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "origin_pos": 1,
    "tab": [
     "tensorflow"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "10\n"
     ]
    }
   ],
   "source": [
    "def add(a, b):\n",
    "    return a + b\n",
    "\n",
    "def fancy_func(a, b, c, d):\n",
    "    e = add(a, b)\n",
    "    f = add(c, d)\n",
    "    g = add(e, f)\n",
    "    return g\n",
    "\n",
    "print(fancy_func(1, 2, 3, 4))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 2
   },
   "source": [
    "Python is an *interpreted language*. When evaluating the above `fancy_func` function it performs the operations making up the function's body *in sequence*. That is, it will evaluate `e = add(a, b)` and store the results as variable `e`, thereby changing the program's state. The next two statements `f = add(c, d)` and `g = add(e, f)` will be executed similarly, performing additions and storing the results as variables. :numref:`fig_compute_graph` illustrates the flow of data.\n",
    "\n",
    "![Data flow in an imperative program.](../img/computegraph.svg)\n",
    ":label:`fig_compute_graph`\n",
    "\n",
    "Although imperative programming is convenient, it may be inefficient. On one hand, even if the `add` function is repeatedly called throughout `fancy_func`, Python will execute the three function calls individually. If these are executed, say, on a GPU (or even on multiple GPUs), the overhead arising from the Python interpreter can become overwhelming. Moreover, it will need to save the variable values of `e` and `f` until all the statements in `fancy_func` have been executed. This is because we do not know whether the variables `e` and `f` will be used by other parts of the program after the statements `e = add(a, b)` and `f = add(c, d)` are executed.\n",
    "\n",
    "## Symbolic Programming\n",
    "\n",
    "Consider the alternative, *symbolic programming*, where computation is usually performed only once the process has been fully defined. This strategy is used by multiple deep learning frameworks, including Theano and TensorFlow (the latter has acquired imperative extensions). It usually involves the following steps:\n",
    "\n",
    "1. Define the operations to be executed.\n",
    "1. Compile the operations into an executable program.\n",
    "1. Provide the required inputs and call the compiled program for execution.\n",
    "\n",
    "This allows for a significant amount of optimization. First, we can skip the Python interpreter in many cases, thus removing a performance bottleneck that can become significant on multiple fast GPUs paired with a single Python thread on a CPU. \n",
    "Second, a compiler might optimize and rewrite the above code into `print((1 + 2) + (3 + 4))` or even `print(10)`. This is possible since a compiler gets to see the full code before turning it into machine instructions. For instance, it can release memory (or never allocate it) whenever a variable is no longer needed. Or it can transform the code entirely into an equivalent piece.\n",
    "To get a better idea, consider the following simulation of imperative programming (it is Python after all) below.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "origin_pos": 3,
    "tab": [
     "tensorflow"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "def add(a, b):\n",
      "    return a + b\n",
      "\n",
      "def fancy_func(a, b, c, d):\n",
      "    e = add(a, b)\n",
      "    f = add(c, d)\n",
      "    g = add(e, f)\n",
      "    return g\n",
      "print(fancy_func(1, 2, 3, 4))\n",
      "10\n"
     ]
    }
   ],
   "source": [
    "def add_():\n",
    "    return '''\n",
    "def add(a, b):\n",
    "    return a + b\n",
    "'''\n",
    "\n",
    "def fancy_func_():\n",
    "    return '''\n",
    "def fancy_func(a, b, c, d):\n",
    "    e = add(a, b)\n",
    "    f = add(c, d)\n",
    "    g = add(e, f)\n",
    "    return g\n",
    "'''\n",
    "\n",
    "def evoke_():\n",
    "    return add_() + fancy_func_() + 'print(fancy_func(1, 2, 3, 4))'\n",
    "\n",
    "prog = evoke_()\n",
    "print(prog)\n",
    "y = compile(prog, '', 'exec')\n",
    "exec(y)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 4
   },
   "source": [
    "The differences between imperative (interpreted) programming and symbolic programming are as follows:\n",
    "\n",
    "* Imperative programming is easier. When imperative programming is used in Python, the majority of the code is straightforward and easy to write. It is also easier to debug imperative programming code. This is because it is easier to obtain and print all relevant intermediate variable values, or use Python's built-in debugging tools.\n",
    "* Symbolic programming is more efficient and easier to port. Symbolic programming makes it easier to optimize the code during compilation, while also having the ability to port the program into a format independent of Python. This allows the program to be run in a non-Python environment, thus avoiding any potential performance issues related to the Python interpreter.\n",
    "\n",
    "\n",
    "## Hybrid Programming\n",
    "\n",
    "Historically most deep learning frameworks choose between an imperative or a symbolic approach. For example, Theano, TensorFlow (inspired by the former), Keras, and CNTK formulate models symbolically. Conversely, Chainer and PyTorch take an imperative approach. An imperative mode was added to TensorFlow 2.0 and Keras in later revisions.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 7,
    "tab": [
     "tensorflow"
    ]
   },
   "source": [
    "The imperative programming paradigm is now the default in Tensorflow 2, a welcoming change for those new to the language. However, the same symbolic programming techniques and subsequent computational graphs still exist in TensorFlow, and can be accessed by the easy-to-use `tf.function` decorator. This brought the imperative programming paradigm to TensorFlow, allowed users to define more intuitive functions, then wrap them and compile them into computational graphs automatically using a feature the TensorFlow team refers to as [autograph](https://www.tensorflow.org/api_docs/python/tf/autograph).\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 8
   },
   "source": [
    "## Hybridizing the `Sequential` Class\n",
    "\n",
    "The easiest way to get a feel for how hybridization works is to consider deep networks with multiple layers. Conventionally the Python interpreter will need to execute the code for all layers to generate an instruction that can then be forwarded to a CPU or a GPU. For a single (fast) computing device this does not cause any major issues. On the other hand, if we use an advanced 8-GPU server such as an AWS P3dn.24xlarge instance Python will struggle to keep all GPUs busy. The single-threaded Python interpreter becomes the bottleneck here. Let us see how we can address this for significant parts of the code by replacing `Sequential` with `HybridSequential`. We begin by defining a simple MLP.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "origin_pos": 11,
    "tab": [
     "tensorflow"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<tf.Tensor: shape=(1, 2), dtype=float32, numpy=array([[ 0.19465998, -0.44404456]], dtype=float32)>"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import tensorflow as tf\n",
    "from tensorflow.keras.layers import Dense\n",
    "from d2l import tensorflow as d2l\n",
    "\n",
    "\n",
    "# Factory for networks\n",
    "def get_net():\n",
    "    net = tf.keras.Sequential()\n",
    "    net.add(Dense(256, input_shape = (512,), activation = \"relu\"))\n",
    "    net.add(Dense(128, activation = \"relu\"))\n",
    "    net.add(Dense(2, activation = \"linear\"))\n",
    "    return net\n",
    "\n",
    "x = tf.random.normal([1,512])\n",
    "net = get_net()\n",
    "net(x)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 14,
    "tab": [
     "tensorflow"
    ]
   },
   "source": [
    "Formerly, all functions built in TensorFlow were built as a computational graph, and therefore JIT compiled by default. However, with the release of TensorFlow 2.X and EagerTensor, this is no longer the default behavor. \n",
    "We cen re-enable this functionality with tf.function. tf.function is more commonly used as a function decorator, however it is possible to call it direcly as a normal python function, shown below. The model's computation result remains unchanged.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "origin_pos": 17,
    "tab": [
     "tensorflow"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<tf.Tensor: shape=(1, 2), dtype=float32, numpy=array([[ 0.19465998, -0.44404456]], dtype=float32)>"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "net = tf.function(net)\n",
    "net(x)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 20,
    "tab": [
     "tensorflow"
    ]
   },
   "source": [
    "This seems almost too good to be true: write the same code as before and simply convert the model using `tf.function`. Once this happens the network is built as a computational graph in TensorFlow's MLIR intermediate representation and is heavily optimized at the compiler level for rapid execution (we will benchmark the performance below).\n",
    "Explicitly adding the `jit_compile = True` flag to the `tf.function()` call enables XLA (Accelerated Linear Algebra) functionality in TensorFlow. XLA can further optimize JIT compiled code in certain instances. Graph-mode execution is enabled without this explicit definition, however XLA can make certain large linear algebra operations (in the vein of those we see in deep learning applications) much faster, particularly in a GPU environment.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 21
   },
   "source": [
    "### Acceleration by Hybridization\n",
    "\n",
    "To demonstrate the performance improvement gained by compilation we compare the time needed to evaluate `net(x)` before and after hybridization. Let us define a class to measure this time first. It will come handy throughout the chapter as we set out to measure (and improve) performance.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "origin_pos": 22,
    "tab": [
     "tensorflow"
    ]
   },
   "outputs": [],
   "source": [
    "#@save\n",
    "class Benchmark:\n",
    "    \"\"\"For measuring running time.\"\"\"\n",
    "    def __init__(self, description='Done'):\n",
    "        self.description = description\n",
    "\n",
    "    def __enter__(self):\n",
    "        self.timer = d2l.Timer()\n",
    "        return self\n",
    "\n",
    "    def __exit__(self, *args):\n",
    "        print(f'{self.description}: {self.timer.stop():.4f} sec')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 25,
    "tab": [
     "tensorflow"
    ]
   },
   "source": [
    "Now we can invoke the network three times, once executed eagerly, once with graph-mode execution, and again using JIT compiled XLA.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "origin_pos": 28,
    "tab": [
     "tensorflow"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Eager Mode: 1.3419 sec\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Graph Mode: 0.4598 sec\n"
     ]
    }
   ],
   "source": [
    "net = get_net()\n",
    "with Benchmark('Eager Mode'):\n",
    "    for i in range(1000): net(x)\n",
    "\n",
    "net = tf.function(net)\n",
    "with Benchmark('Graph Mode'):\n",
    "    for i in range(1000): net(x)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 31,
    "tab": [
     "tensorflow"
    ]
   },
   "source": [
    "As is observed in the above results, after a `tf.keras.Sequential` instance is scripted using the `tf.function` function, computing performance is improved through the use of symbolic programming via graph-mode execution in tensorflow.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 32
   },
   "source": [
    "### Serialization\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 35,
    "tab": [
     "tensorflow"
    ]
   },
   "source": [
    "One of the benefits of compiling the models is that we can serialize (save) the model and its parameters to disk. This allows us to store a model in a manner that is independent of the front-end language of choice. This allows us to deploy trained models to other devices and easily use other front-end programming languages or execute a trained model on a server. At the same time the code is often faster than what can be achieved in imperative programming. \n",
    "The low-level API that allows us to save in tensorflow is `tf.saved_model`. \n",
    "Let's see the `saved_model` instance in action.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "origin_pos": 38,
    "tab": [
     "tensorflow"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "INFO:tensorflow:Assets written to: my_mlp/assets\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "total 68K\r\n",
      "drwxr-xr-x 2 d2l-worker d2l-worker 4.0K Mar 24 13:09 assets\r\n",
      "-rw-rw-r-- 1 d2l-worker d2l-worker  60K Mar 24 13:09 saved_model.pb\r\n",
      "drwxr-xr-x 2 d2l-worker d2l-worker 4.0K Mar 24 13:09 variables\r\n"
     ]
    }
   ],
   "source": [
    "net = get_net()\n",
    "tf.saved_model.save(net, 'my_mlp')\n",
    "!ls -lh my_mlp*"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 50
   },
   "source": [
    "## Summary\n",
    "\n",
    "\n",
    "* Imperative programming makes it easy to design new models since it is possible to write code with control flow and the ability to use a large amount of the Python software ecosystem.\n",
    "* Symbolic programming requires that we specify the program and compile it before executing it. The benefit is improved performance.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 52
   },
   "source": [
    "## Exercises\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 54,
    "tab": [
     "tensorflow"
    ]
   },
   "source": [
    "1. Review the models that interest you in the previous chapters. Can you improve their computational performance by reimplementing them?\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 57,
    "tab": [
     "tensorflow"
    ]
   },
   "source": [
    "[Discussions](https://discuss.d2l.ai/t/2492)\n"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}