{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "# For tips on running notebooks in Google Colab, see\n",
    "# https://docs.pytorch.org/tutorials/beginner/colab\n",
    "%matplotlib inline"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Reducing torch.compile cold start compilation time with regional compilation\n",
    "\n",
    "**Author:** [Animesh Jain](https://github.com/anijain2305)\n",
    "\n",
    "As deep learning models get larger, the compilation time of these models\n",
    "also increases. This extended compilation time can result in a large\n",
    "startup time in inference services or wasted resources in large-scale\n",
    "training. This recipe shows an example of how to reduce the cold start\n",
    "compilation time by choosing to compile a repeated region of the model\n",
    "instead of the entire model.\n",
    "\n",
    "## Prerequisites\n",
    "\n",
    "-   Pytorch 2.5 or later\n",
    "\n",
    "## Setup\n",
    "\n",
    "Before we begin, we need to install `torch` if it is not already\n",
    "available.\n",
    "\n",
    "``` sh\n",
    "pip install torch\n",
    "```\n",
    "\n",
    "<div style=\"background-color: #54c7ec; color: #fff; font-weight: 700; padding-left: 10px; padding-top: 5px; padding-bottom: 5px\"><strong>NOTE:</strong></div>\n",
    "\n",
    "<div style=\"background-color: #f3f4f7; padding-left: 10px; padding-top: 10px; padding-bottom: 10px; padding-right: 10px\">\n",
    "\n",
    "<p>This feature is available starting with the 2.5 release. If you are using version 2.4,you can enable the configuration flag <code>torch._dynamo.config.inline_inbuilt_nn_modules=True</code>to prevent recompilations during regional compilation. In version 2.5, this flag is enabled by default.</p>\n",
    "\n",
    "</div>\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "from time import perf_counter"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Steps\n",
    "\n",
    "In this recipe, we will follow these steps:\n",
    "\n",
    "1.  Import all necessary libraries.\n",
    "2.  Define and initialize a neural network with repeated regions.\n",
    "3.  Understand the difference between the full model and the regional\n",
    "    compilation.\n",
    "4.  Measure the compilation time of the full model and the regional\n",
    "    compilation.\n",
    "\n",
    "First, let\\'s import the necessary libraries for loading our data:\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "import torch\n",
    "import torch.nn as nn"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Next, let\\'s define and initialize a neural network with repeated\n",
    "regions.\n",
    "\n",
    "Typically, neural networks are composed of repeated layers. For example,\n",
    "a large language model is composed of many Transformer blocks. In this\n",
    "recipe, we will create a `Layer` using the `nn.Module` class as a proxy\n",
    "for a repeated region. We will then create a `Model` which is composed\n",
    "of 64 instances of this `Layer` class.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "class Layer(torch.nn.Module):\n",
    "    def __init__(self):\n",
    "        super().__init__()\n",
    "        self.linear1 = torch.nn.Linear(10, 10)\n",
    "        self.relu1 = torch.nn.ReLU()\n",
    "        self.linear2 = torch.nn.Linear(10, 10)\n",
    "        self.relu2 = torch.nn.ReLU()\n",
    "\n",
    "    def forward(self, x):\n",
    "        a = self.linear1(x)\n",
    "        a = self.relu1(a)\n",
    "        a = torch.sigmoid(a)\n",
    "        b = self.linear2(a)\n",
    "        b = self.relu2(b)\n",
    "        return b\n",
    "\n",
    "\n",
    "class Model(torch.nn.Module):\n",
    "    def __init__(self, apply_regional_compilation):\n",
    "        super().__init__()\n",
    "        self.linear = torch.nn.Linear(10, 10)\n",
    "        # Apply compile only to the repeated layers.\n",
    "        if apply_regional_compilation:\n",
    "            self.layers = torch.nn.ModuleList(\n",
    "                [torch.compile(Layer()) for _ in range(64)]\n",
    "            )\n",
    "        else:\n",
    "            self.layers = torch.nn.ModuleList([Layer() for _ in range(64)])\n",
    "\n",
    "    def forward(self, x):\n",
    "        # In regional compilation, the self.linear is outside of the scope of `torch.compile`.\n",
    "        x = self.linear(x)\n",
    "        for layer in self.layers:\n",
    "            x = layer(x)\n",
    "        return x"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Next, let\\'s review the difference between the full model and the\n",
    "regional compilation.\n",
    "\n",
    "In full model compilation, the entire model is compiled as a whole. This\n",
    "is the common approach most users take with `torch.compile`. In this\n",
    "example, we apply `torch.compile` to the `Model` object. This will\n",
    "effectively inline the 64 layers, producing a large graph to compile.\n",
    "You can look at the full graph by running this recipe with\n",
    "`TORCH_LOGS=graph_code`.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "model = Model(apply_regional_compilation=False).cuda()\n",
    "full_compiled_model = torch.compile(model)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The regional compilation, on the other hand, compiles a region of the\n",
    "model. By strategically choosing to compile a repeated region of the\n",
    "model, we can compile a much smaller graph and then reuse the compiled\n",
    "graph for all the regions. In the example, `torch.compile` is applied\n",
    "only to the `layers` and not the full model.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "regional_compiled_model = Model(apply_regional_compilation=True).cuda()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Applying compilation to a repeated region, instead of full model, leads\n",
    "to large savings in compile time. Here, we will just compile a layer\n",
    "instance and then reuse it 64 times in the `Model` object.\n",
    "\n",
    "Note that with repeated regions, some part of the model might not be\n",
    "compiled. For example, the `self.linear` in the `Model` is outside of\n",
    "the scope of regional compilation.\n",
    "\n",
    "Also, note that there is a tradeoff between performance speedup and\n",
    "compile time. Full model compilation involves a larger graph and,\n",
    "theoretically, offers more scope for optimizations. However, for\n",
    "practical purposes and depending on the model, we have observed many\n",
    "cases with minimal speedup differences between the full model and\n",
    "regional compilation.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Next, let\\'s measure the compilation time of the full model and the\n",
    "regional compilation.\n",
    "\n",
    "`torch.compile` is a JIT compiler, which means that it compiles on the\n",
    "first invocation. In the code below, we measure the total time spent in\n",
    "the first invocation. While this method is not precise, it provides a\n",
    "good estimate since the majority of the time is spent in compilation.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "def measure_latency(fn, input):\n",
    "    # Reset the compiler caches to ensure no reuse between different runs\n",
    "    torch.compiler.reset()\n",
    "    with torch._inductor.utils.fresh_inductor_cache():\n",
    "        start = perf_counter()\n",
    "        fn(input)\n",
    "        torch.cuda.synchronize()\n",
    "        end = perf_counter()\n",
    "        return end - start\n",
    "\n",
    "\n",
    "input = torch.randn(10, 10, device=\"cuda\")\n",
    "full_model_compilation_latency = measure_latency(full_compiled_model, input)\n",
    "print(f\"Full model compilation time = {full_model_compilation_latency:.2f} seconds\")\n",
    "\n",
    "regional_compilation_latency = measure_latency(regional_compiled_model, input)\n",
    "print(f\"Regional compilation time = {regional_compilation_latency:.2f} seconds\")\n",
    "\n",
    "assert regional_compilation_latency < full_model_compilation_latency"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Conclusion\n",
    "\n",
    "This recipe shows how to control the cold start compilation time if your\n",
    "model has repeated regions. This approach requires user modifications to\n",
    "apply [torch.compile]{.title-ref} to the repeated regions instead of\n",
    "more commonly used full model compilation. We are continually working on\n",
    "reducing cold start compilation time.\n"
   ]
  }
 ],
 "metadata": {
  "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.12.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
