{
 "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 AoT cold start compilation time with regional compilation\n",
    "\n",
    "**Author:** [Sayak Paul](https://huggingface.co/sayakpaul), [Charles\n",
    "Bensimon](https://huggingface.co/cbensimon), [Angela\n",
    "Yi](https://github.com/angelayi)\n",
    "\n",
    "In the [regional compilation\n",
    "recipe](https://docs.pytorch.org/tutorials/recipes/regional_compilation.html),\n",
    "we showed how to reduce cold start compilation times while retaining\n",
    "(almost) full compilation benefits. This was demonstrated for\n",
    "just-in-time (JIT) compilation.\n",
    "\n",
    "This recipe shows how to apply similar principles when compiling a model\n",
    "ahead-of-time (AoT). If you are not familiar with AOTInductor and\n",
    "`torch.export`, we recommend you to check out [this\n",
    "tutorial](https://docs.pytorch.org/tutorials/recipes/torch_export_aoti_python.html).\n",
    "\n",
    "## Prerequisites\n",
    "\n",
    "-   Pytorch 2.6 or later\n",
    "-   Familiarity with regional compilation\n",
    "-   Familiarity with AOTInductor and `torch.export`\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"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Steps\n",
    "\n",
    "In this recipe, we will follow the same steps as the regional\n",
    "compilation recipe mentioned above:\n",
    "\n",
    "1.  Import all necessary libraries.\n",
    "2.  Define and initialize a neural network with repeated regions.\n",
    "3.  Measure the compilation time of the full model and the regional\n",
    "    compilation with AoT.\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",
    "torch.set_grad_enabled(False)\n",
    "\n",
    "from time import perf_counter"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Defining the Neural Network\n",
    "\n",
    "We will use the same neural network structure as the regional\n",
    "compilation recipe.\n",
    "\n",
    "We will use a network, composed of repeated layers. This mimics a large\n",
    "language model, that typically is composed of many Transformer blocks.\n",
    "In this recipe, we will create a `Layer` using the `nn.Module` class as\n",
    "a proxy for a repeated region. We will then create a `Model` which is\n",
    "composed 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):\n",
    "        super().__init__()\n",
    "        self.linear = torch.nn.Linear(10, 10)\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": [
    "# Compiling the model ahead-of-time\n",
    "\n",
    "Since we\\'re compiling the model ahead-of-time, we need to prepare\n",
    "representative input examples, that we expect the model to see during\n",
    "actual deployments.\n",
    "\n",
    "Let\\'s create an instance of `Model` and pass it some sample input data.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "model = Model().cuda()\n",
    "input = torch.randn(10, 10, device=\"cuda\")\n",
    "output = model(input)\n",
    "print(f\"{output.shape=}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now, let\\'s compile our model ahead-of-time. We will use `input` created\n",
    "above to pass to `torch.export`. This will yield a\n",
    "`torch.export.ExportedProgram` which we can compile.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "path = torch._inductor.aoti_compile_and_package(\n",
    "    torch.export.export(model, args=(input,))\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can load from this `path` and use it to perform inference.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "compiled_binary = torch._inductor.aoti_load_package(path)\n",
    "output_compiled = compiled_binary(input)\n",
    "print(f\"{output_compiled.shape=}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Compiling \\_[regions]() of the model ahead-of-time\n",
    "\n",
    "Compiling model regions ahead-of-time, on the other hand, requires a few\n",
    "key changes.\n",
    "\n",
    "Since the compute pattern is shared by all the blocks that are repeated\n",
    "in a model (`Layer` instances in this cases), we can just compile a\n",
    "single block and let the inductor reuse it.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "model = Model().cuda()\n",
    "path = torch._inductor.aoti_compile_and_package(\n",
    "    torch.export.export(model.layers[0], args=(input,)),\n",
    "    inductor_configs={\n",
    "        # compile artifact w/o saving params in the artifact\n",
    "        \"aot_inductor.package_constants_in_so\": False,\n",
    "    }\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "An exported program (`torch.export.ExportedProgram`) contains the Tensor\n",
    "computation, a `state_dict` containing tensor values of all lifted\n",
    "parameters and buffer alongside other metadata. We specify the\n",
    "`aot_inductor.package_constants_in_so` to be `False` to not serialize\n",
    "the model parameters in the generated artifact.\n",
    "\n",
    "Now, when loading the compiled binary, we can reuse the existing\n",
    "parameters of each block. This lets us take advantage of the compiled\n",
    "binary obtained above.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "for layer in model.layers:\n",
    "    compiled_layer = torch._inductor.aoti_load_package(path)\n",
    "    compiled_layer.load_constants(\n",
    "        layer.state_dict(), check_full_update=True, user_managed=True\n",
    "    )\n",
    "    layer.forward = compiled_layer\n",
    "\n",
    "output_regional_compiled = model(input)\n",
    "print(f\"{output_regional_compiled.shape=}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Just like JIT regional compilation, compiling regions within a model\n",
    "ahead-of-time leads to significantly reduced cold start times. The\n",
    "actual number will vary from model to model.\n",
    "\n",
    "Even though full model compilation offers the fullest scope of\n",
    "optimizations, for practical purposes and depending on the type of\n",
    "model, we have seen regional compilation (both JiT and AoT) providing\n",
    "similar speed benefits, while drastically reducing the cold start times.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Measuring compilation time\n",
    "\n",
    "Next, let\\'s measure the compilation time of the full model and the\n",
    "regional compilation.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": false
   },
   "outputs": [],
   "source": [
    "def measure_compile_time(input, regional=False):\n",
    "    start = perf_counter()\n",
    "    model = aot_compile_load_model(regional=regional)\n",
    "    torch.cuda.synchronize()\n",
    "    end = perf_counter()\n",
    "    # make sure the model works.\n",
    "    _ = model(input)\n",
    "    return end - start\n",
    "\n",
    "def aot_compile_load_model(regional=False) -> torch.nn.Module:\n",
    "    input = torch.randn(10, 10, device=\"cuda\")\n",
    "    model = Model().cuda()\n",
    "\n",
    "    inductor_configs = {}\n",
    "    if regional:\n",
    "        inductor_configs = {\"aot_inductor.package_constants_in_so\": False}\n",
    "\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",
    "        path = torch._inductor.aoti_compile_and_package(\n",
    "            torch.export.export(\n",
    "                model.layers[0] if regional else model,\n",
    "                args=(input,)\n",
    "            ),\n",
    "            inductor_configs=inductor_configs,\n",
    "        )\n",
    "\n",
    "        if regional:\n",
    "            for layer in model.layers:\n",
    "                compiled_layer = torch._inductor.aoti_load_package(path)\n",
    "                compiled_layer.load_constants(\n",
    "                    layer.state_dict(), check_full_update=True, user_managed=True\n",
    "                )\n",
    "                layer.forward = compiled_layer\n",
    "        else:\n",
    "            model = torch._inductor.aoti_load_package(path)\n",
    "    return model\n",
    "\n",
    "input = torch.randn(10, 10, device=\"cuda\")\n",
    "full_model_compilation_latency = measure_compile_time(input, regional=False)\n",
    "print(f\"Full model compilation time = {full_model_compilation_latency:.2f} seconds\")\n",
    "\n",
    "regional_compilation_latency = measure_compile_time(input, regional=True)\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": [
    "There may also be layers in a model incompatible with compilation. So,\n",
    "full compilation will result in a fragmented computation graph resulting\n",
    "in potential latency degradation. In these case, regional compilation\n",
    "can be beneficial.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Conclusion\n",
    "\n",
    "This recipe shows how to control the cold start time when compiling your\n",
    "model ahead-of-time. This becomes effective when your model has repeated\n",
    "blocks, which is typically seen in large generative models. We used this\n",
    "recipe on various models to speed up real-time performance. Learn more\n",
    "[here](https://huggingface.co/blog/zerogpu-aoti).\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
}
