[
  {
    "path": "Dockerfile",
    "content": "FROM nvidia/cuda:12.1.0-runtime-ubuntu20.04\n\nENV DEBIAN_FRONTEND=noninteractive\n\nRUN apt update && \\\n    apt install -y bash \\\n    build-essential \\\n    git \\\n    git-lfs \\\n    curl \\\n    ca-certificates \\\n    libsndfile1-dev \\\n    libgl1 \\\n    python3.8 \\\n    python3-pip \\\n    python3.8-venv && \\\n    rm -rf /var/lib/apt/lists\n\nRUN python3 -m venv /opt/venv\nENV PATH=\"/opt/venv/bin:$PATH\"\n\nRUN python3 -m pip install --no-cache-dir --upgrade pip && \\\n    python3 -m pip install --no-cache-dir --pre torch==2.3.0.dev20231218+cu121 --index-url https://download.pytorch.org/whl/nightly/cu121 && \\\n    python3 -m pip install --no-cache-dir \\\n    accelerate \\\n    transformers \\\n    peft \n\nRUN python3 -m pip install  --no-cache-dir diffusers==0.25.0\nRUN python3 -m pip install --no-cache-dir git+https://github.com/pytorch-labs/ao@54bcd5a10d0abbe7b0c045052029257099f83fd9\n\nCMD [\"/bin/bash\"]"
  },
  {
    "path": "LICENSE",
    "content": "                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"[]\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright Hugging Face\n\n   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       http://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.\n"
  },
  {
    "path": "Makefile",
    "content": "check_dirs := .\n\nquality:\n\truff check $(check_dirs)\n\truff format --check $(check_dirs)\n\nstyle:\n\truff check $(check_dirs) --fix\n\truff format $(check_dirs)\n\n"
  },
  {
    "path": "README.md",
    "content": "# Diffusion, fast\n\nRepository for the blog post: [**Accelerating Generative AI Part III: Diffusion, Fast**](https://pytorch.org/blog/accelerating-generative-ai-3/). You can find a run down of the techniques on the [🤗 Diffusers website](https://huggingface.co/docs/diffusers/main/en/optimization/fp16) too. \n\n<div align=\"center\">\n\n<img src=\"https://huggingface.co/datasets/sayakpaul/sample-datasets/resolve/main/final-results-diffusion-fast/SDXL%2C_Batch_Size%3A_1%2C_Steps%3A_30.png\" width=500>\n\n</div><br>\n\nCheck out the Flux edition here: [huggingface/flux-fast](https://github.com/huggingface/flux-fast/).\n\n> [!WARNING]  \n> This repository relies on the `torchao` package for all things quantization. Since the first version of this repo, the `torchao` package has changed its APIs significantly. More specifically, [this](https://github.com/huggingface/diffusion-fast/blob/f4fa861422d9819226eb2ceac247c85c3547130d/Dockerfile#L30) version was used to obtain the numbers in this repository. For more updated usage of `torchao`, please refer to the [`diffusers-torchao`](https://github.com/sayakpaul/diffusers-torchao) repository.\n\nSummary of the optimizations:\n\n* Running with the bfloat16 precision\n* `scaled_dot_product_attention` (SDPA)\n* `torch.compile`\n* Combining q,k,v projections for attention computation\n* Dynamic int8 quantization \n\nThese techniques are fairly generalizable to other pipelines too, as we show below.\n\nTable of contents:\n\n* [Setup](#setup-🛠️)\n* [Running benchmarking experiments](#running-a-benchmarking-experiment-🏎️)\n* [Code](#improvements-progressively-📈-📊)\n* [Results from other pipelines](#results-from-other-pipelines-🌋)\n\n## Setup 🛠️\n\nWe rely on pure PyTorch for the optimizations. You can refer to the [Dockerfile](./Dockerfile) to get the complete development environment setup. \n\nFor hardware, we used an 80GB 400W A100 GPU with its memory clock set to the maximum rate (1593 in our case).\n\nMeanwhile, these optimizations (BFloat16, SDPA, torch.compile, Combining q,k,v projections) can run on CPU platforms as well, and bring 4x latency improvement to Stable Diffusion XL (SDXL) on 4th Gen Intel® Xeon® Scalable processors.\n\n## Running a benchmarking experiment 🏎️\n\n[`run_benchmark.py`](./run_benchmark.py) is the main script for benchmarking the different optimization techniques. After an experiment has been done, you should expect to see two files:\n\n* A `.csv` file with all the benchmarking numbers.\n* A `.jpeg` image file corresponding to the experiment. \n\nRefer to the [`experiment-scripts/run_sd.sh`](./experiment-scripts/run_sd.sh) for some reference experiment commands. \n\n**Notes on running PixArt-Alpha experiments**:\n\n* Use the [`run_experiment_pixart.py`](./run_benchmark_pixart.py) for this.\n* Uninstall the current installation of `diffusers` and re-install it again like so: `pip install git+https://github.com/huggingface/diffusers@fuse-projections-pixart`.\n* Refer to the [`experiment-scripts/run_pixart.sh`](./experiment-scripts/run_pixart.sh) script for some reference experiment commands.\n\n_(Support for PixArt-Alpha is experimental.)_\n\nYou can use the [`prepare_results.py`](./prepare_results.py) script to generate a consolidated CSV file and a plot to visualize the results from it. This is best used after you have run a couple of benchmarking experiments already and have their corresponding CSV files.\n\nThe script also supports CPU platforms, you can refer to the [`experiment-scripts/run_sd_cpu.sh`](./experiment-scripts/run_sd_cpu.sh) for some reference experiment commands. \n\nTo run the script, you need the following dependencies:\n\n* pandas\n* matplotlib\n* seaborn\n\n## Improvements, progressively 📈 📊\n\n<details>\n  <summary>Baseline</summary>\n\n```python\nfrom diffusers import StableDiffusionXLPipeline\n\n# Load the pipeline in full-precision and place its model components on CUDA.\npipe = StableDiffusionXLPipeline.from_pretrained(\n    \"stabilityai/stable-diffusion-xl-base-1.0\"\n).to(\"cuda\")\n\n# Run the attention ops without efficiency.\npipe.unet.set_default_attn_processor()\npipe.vae.set_default_attn_processor()\n\nprompt = \"Astronaut in a jungle, cold color palette, muted colors, detailed, 8k\"\nimage = pipe(prompt, num_inference_steps=30).images[0]\n```\n\nWith this, we're at:\n\n<div align=\"center\">\n\n<img src=\"https://huggingface.co/datasets/sayakpaul/sample-datasets/resolve/main/progressive-acceleration-sdxl/SDXL%2C_Batch_Size%3A_1%2C_Steps%3A_30_0.png\" width=500>\n\n</div>\n\n</details>\n\n<details>\n  <summary>Bfloat16</summary>\n\n```python\nfrom diffusers import StableDiffusionXLPipeline\nimport torch\n\npipe = StableDiffusionXLPipeline.from_pretrained(\n\t\"stabilityai/stable-diffusion-xl-base-1.0\", torch_dtype=torch.bfloat16\n).to(\"cuda\")\n\n# Run the attention ops without efficiency.\npipe.unet.set_default_attn_processor()\npipe.vae.set_default_attn_processor()\n\nprompt = \"Astronaut in a jungle, cold color palette, muted colors, detailed, 8k\"\nimage = pipe(prompt, num_inference_steps=30).images[0]\n```\n\n<div align=\"center\">\n\n<img src=\"https://huggingface.co/datasets/sayakpaul/sample-datasets/resolve/main/progressive-acceleration-sdxl/SDXL%2C_Batch_Size%3A_1%2C_Steps%3A_30_1.png\" width=500>\n\n</div>\n\n> 💡 We later ran the experiments in float16 and found out that the recent versions of `torchao` do not incur numerical problems from float16.\n\n</details>\n\n<details>\n  <summary>scaled_dot_product_attention</summary>\n\n```python\nfrom diffusers import StableDiffusionXLPipeline\nimport torch\n\npipe = StableDiffusionXLPipeline.from_pretrained(\n\t\"stabilityai/stable-diffusion-xl-base-1.0\", torch_dtype=torch.bfloat16\n).to(\"cuda\")\n\nprompt = \"Astronaut in a jungle, cold color palette, muted colors, detailed, 8k\"\nimage = pipe(prompt, num_inference_steps=30).images[0]\n```\n\n<div align=\"center\">\n\n<img src=\"https://huggingface.co/datasets/sayakpaul/sample-datasets/resolve/main/progressive-acceleration-sdxl/SDXL%2C_Batch_Size%3A_1%2C_Steps%3A_30_2.png\" width=500>\n\n</div>\n\n</details>\n\n<details>\n  <summary>torch.compile</summary><br>\n\nFirst, configure some compiler flags:\n\n```python\nfrom diffusers import StableDiffusionXLPipeline\nimport torch\n\n# Set the following compiler flags to make things go brrr.\ntorch._inductor.config.conv_1x1_as_mm = True\ntorch._inductor.config.coordinate_descent_tuning = True\ntorch._inductor.config.epilogue_fusion = False\ntorch._inductor.config.coordinate_descent_check_all_directions = True\n```\n\nThen load the pipeline:\n\n```python\npipe = StableDiffusionXLPipeline.from_pretrained(\n    \"stabilityai/stable-diffusion-xl-base-1.0\", torch_dtype=torch.bfloat16\n).to(\"cuda\")\n```\n\nCompile and perform inference:\n\n```python\n# Compile the UNet and VAE.\npipe.unet.to(memory_format=torch.channels_last)\npipe.vae.to(memory_format=torch.channels_last)\npipe.unet = torch.compile(pipe.unet, mode=\"max-autotune\", fullgraph=True)\npipe.vae.decode = torch.compile(pipe.vae.decode, mode=\"max-autotune\", fullgraph=True)\n\nprompt = \"Astronaut in a jungle, cold color palette, muted colors, detailed, 8k\"\n\n# First call to `pipe` will be slow, subsequent ones will be faster.\nimage = pipe(prompt, num_inference_steps=30).images[0]\n```\n\n<div align=\"center\">\n\n<img src=\"https://huggingface.co/datasets/sayakpaul/sample-datasets/resolve/main/progressive-acceleration-sdxl/SDXL%2C_Batch_Size%3A_1%2C_Steps%3A_30_3.png\" width=500>\n\n</div>\n\n</details>\n\n<details>\n  <summary>Combining attention projection matrices</summary><br>\n\n```python\nfrom diffusers import StableDiffusionXLPipeline\nimport torch\n\n# Configure the compiler flags.\ntorch._inductor.config.conv_1x1_as_mm = True\ntorch._inductor.config.coordinate_descent_tuning = True\ntorch._inductor.config.epilogue_fusion = False\ntorch._inductor.config.coordinate_descent_check_all_directions = True\n\npipe = StableDiffusionXLPipeline.from_pretrained(\n    \"stabilityai/stable-diffusion-xl-base-1.0\", torch_dtype=torch.bfloat16\n).to(\"cuda\")\n\n# Combine attention projection matrices.\npipe.fuse_qkv_projections()\n\n# Compile the UNet and VAE.\npipe.unet.to(memory_format=torch.channels_last)\npipe.vae.to(memory_format=torch.channels_last)\npipe.unet = torch.compile(pipe.unet, mode=\"max-autotune\", fullgraph=True)\npipe.vae.decode = torch.compile(pipe.vae.decode, mode=\"max-autotune\", fullgraph=True)\n\nprompt = \"Astronaut in a jungle, cold color palette, muted colors, detailed, 8k\"\n\n# First call to `pipe` will be slow, subsequent ones will be faster.\nimage = pipe(prompt, num_inference_steps=30).images[0]\n```\n\n<div align=\"center\">\n\n<img src=\"https://huggingface.co/datasets/sayakpaul/sample-datasets/resolve/main/progressive-acceleration-sdxl/SDXL%2C_Batch_Size%3A_1%2C_Steps%3A_30_4.png\" width=500>\n\n</div>\n\n</details>\n\n<details>\n  <summary>Dynamic quantization</summary><br>\n\nStart by setting the compiler flags (this time, we have two new):\n\n```python\nfrom diffusers import StableDiffusionXLPipeline\nimport torch\n\nfrom torchao.quantization import apply_dynamic_quant, swap_conv2d_1x1_to_linear\n\n# Compiler flags. There are two new.\ntorch._inductor.config.conv_1x1_as_mm = True\ntorch._inductor.config.coordinate_descent_tuning = True\ntorch._inductor.config.epilogue_fusion = False\ntorch._inductor.config.coordinate_descent_check_all_directions = True\ntorch._inductor.config.force_fuse_int_mm_with_mul = True\ntorch._inductor.config.use_mixed_mm = True\n```\n\nThen write the filtering functions to apply dynamic quantization:\n\n```python\ndef dynamic_quant_filter_fn(mod, *args):\n    return (\n        isinstance(mod, torch.nn.Linear)\n        and mod.in_features > 16\n        and (mod.in_features, mod.out_features)\n        not in [\n            (1280, 640),\n            (1920, 1280),\n            (1920, 640),\n            (2048, 1280),\n            (2048, 2560),\n            (2560, 1280),\n            (256, 128),\n            (2816, 1280),\n            (320, 640),\n            (512, 1536),\n            (512, 256),\n            (512, 512),\n            (640, 1280),\n            (640, 1920),\n            (640, 320),\n            (640, 5120),\n            (640, 640),\n            (960, 320),\n            (960, 640),\n        ]\n    )\n\n\ndef conv_filter_fn(mod, *args):\n    return (\n        isinstance(mod, torch.nn.Conv2d) and mod.kernel_size == (1, 1) and 128 in [mod.in_channels, mod.out_channels]\n    )\n```\n\nThen we're rwady for inference:\n\n```python\npipe = StableDiffusionXLPipeline.from_pretrained(\n\t\"stabilityai/stable-diffusion-xl-base-1.0\", torch_dtype=torch.bfloat16\n).to(\"cuda\")\n\n# Combine attention projection matrices.\npipe.fuse_qkv_projections()\n\n# Change the memory layout.\npipe.unet.to(memory_format=torch.channels_last)\npipe.vae.to(memory_format=torch.channels_last)\n\n# Swap the pointwise convs with linears.\nswap_conv2d_1x1_to_linear(pipe.unet, conv_filter_fn)\nswap_conv2d_1x1_to_linear(pipe.vae, conv_filter_fn)\n\n# Apply dynamic quantization.\napply_dynamic_quant(pipe.unet, dynamic_quant_filter_fn)\napply_dynamic_quant(pipe.vae, dynamic_quant_filter_fn)\n\n# Compile.\npipe.unet = torch.compile(pipe.unet, mode=\"max-autotune\", fullgraph=True)\npipe.vae.decode = torch.compile(pipe.vae.decode, mode=\"max-autotune\", fullgraph=True)\n\nprompt = \"Astronaut in a jungle, cold color palette, muted colors, detailed, 8k\"\nimage = pipe(prompt, num_inference_steps=30).images[0]\n```\n\n<div align=\"center\">\n\n<img src=\"https://huggingface.co/datasets/sayakpaul/sample-datasets/resolve/main/progressive-acceleration-sdxl/SDXL%2C_Batch_Size%3A_1%2C_Steps%3A_30_5.png\" width=500>\n\n</div>\n\n</details>\n\n## Results from other pipelines 🌋\n\n<details>\n  <summary>SSD-1B</summary>\n\n<div align=\"center\">\n\n<img src=\"https://huggingface.co/datasets/sayakpaul/sample-datasets/resolve/main/final-results-diffusion-fast/SSD-1B%2C_Batch_Size%3A_1%2C_Steps%3A_30.png\" width=500>\n<br><sup><a href=\"https://huggingface.co/segmind/SSD-1B\">segmind/SSD-1B</a></sup>\n\n</div>\n\n</details>\n\n<details>\n  <summary>SD v1-5</summary>\n\n<div align=\"center\">\n\n<img src=\"https://huggingface.co/datasets/sayakpaul/sample-datasets/resolve/main/final-results-diffusion-fast/SD_v1-5%2C_Batch_Size%3A_1%2C_Steps%3A_30.png\" width=500>\n<br><sup><a href=\"https://huggingface.co/runwayml/stable-diffusion-v1-5\">runwayml/stable-diffusion-v1-5</a></sup>\n\n</div>\n\n</details>\n\n<details>\n  <summary>Pixart-Alpha</summary>\n\n<div align=\"center\">\n\n<img src=\"https://huggingface.co/datasets/sayakpaul/sample-datasets/resolve/main/final-results-diffusion-fast/PixArt-%24%5Calpha%24%2C_Batch_Size%3A_1%2C_Steps%3A_30.png\" width=500>\n<br><sup><a href=\"https://huggingface.co/PixArt-alpha/PixArt-XL-2-1024-MS\">PixArt-alpha/PixArt-XL-2-1024-MS</a></sup>\n\n</div>\n\n</details>\n"
  },
  {
    "path": "experiment-scripts/run_pixart.sh",
    "content": "#!/bin/bash\n\n# From diffusion-fast source directory.\n\npython run_benchmark_pixart.py --ckpt \"PixArt-alpha/PixArt-XL-2-1024-MS\" --no_sdpa --no_bf16 && \\\npython run_benchmark_pixart.py --ckpt \"PixArt-alpha/PixArt-XL-2-1024-MS\" --compile_transformer --compile_mode=max-autotune --compile_vae --change_comp_config && \\\npython run_benchmark_pixart.py --ckpt \"PixArt-alpha/PixArt-XL-2-1024-MS\" --compile_transformer --compile_mode=max-autotune --compile_vae --change_comp_config --enable_fused_projections && \\\npython run_benchmark_pixart.py --ckpt \"PixArt-alpha/PixArt-XL-2-1024-MS\" --compile_transformer --compile_mode=max-autotune --compile_vae --enable_fused_projections --do_quant \"int8dynamic\" --change_comp_config && \\\npython prepare_results.py --plot_title \"PixArt-Alpha, Batch Size: 1, Steps: 30\" --final_csv_filename \"collated_results.csv\"\n"
  },
  {
    "path": "experiment-scripts/run_sd.sh",
    "content": "#!/bin/bash\n\n# From diffusion-fast source directory.\n\npython run_benchmark.py --no_sdpa --no_bf16 && \\\npython run_benchmark.py --compile_unet --compile_mode=max-autotune --compile_vae --change_comp_config && \\\npython run_benchmark.py --compile_unet --compile_mode=max-autotune --compile_vae --change_comp_config --enable_fused_projections && \\\npython run_benchmark.py --compile_unet --compile_mode=max-autotune --compile_vae --enable_fused_projections --do_quant \"int8dynamic\" --change_comp_config && \\\npython prepare_results.py --plot_title \"SDXL, Batch Size: 1, Steps: 30\" --final_csv_filename \"collated_results.csv\"\n"
  },
  {
    "path": "experiment-scripts/run_sd_cpu.sh",
    "content": "#!/bin/bash\n\n# From diffusion-fast source directory.\n\n# Run Diffusion benchmark on CPU platforms.\n\npython run_benchmark.py --no_sdpa --no_bf16 --device=cpu\npython run_benchmark.py --compile_unet --compile_vae --device=cpu\npython run_benchmark.py --compile_unet --compile_vae --enable_fused_projections --device=cpu\n"
  },
  {
    "path": "prepare_results.py",
    "content": "import argparse\nimport glob\nimport os\nimport sys\n\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport seaborn as sns\nfrom huggingface_hub import upload_file\n\n\nsys.path.append(\".\")\nfrom utils.benchmarking_utils import collate_csv  # noqa: E402\n\n\nREPO_ID = \"sayakpaul/sample-datasets\"\n\n\ndef prepare_plot(df, args):\n    # Drop the columns that are not needed\n    columns_to_drop = [\n        \"batch_size\",\n        \"num_inference_steps\",\n        \"pipeline_cls\",\n        \"ckpt_id\",\n        \"upcast_vae\",\n        \"memory (gbs)\",\n        \"actual_gpu_memory (gbs)\",\n        \"tag\",\n    ]\n    df_filtered = df.drop(columns=columns_to_drop)\n    df_filtered[[\"quant\"]] = df_filtered[[\"do_quant\"]].fillna(\"None\")\n    df_filtered.drop(columns=[\"do_quant\"], inplace=True)\n\n    # Create a new column to consolidate settings into a readable format\n    df_filtered[\"settings\"] = df_filtered.apply(\n        lambda row: \", \".join([f\"{col}-{row[col]}\" for col in df_filtered.columns if col != \"time (secs)\"]), axis=1\n    )\n    df_filtered[\"formatted_settings\"] = df_filtered[\"settings\"].str.replace(\", \", \"\\n\", regex=False)\n    df_filtered.loc[0, \"formatted_settings\"] = \"default\"\n\n    # Generating the plot with matplotlib directly for better control\n    plt.figure(figsize=(12, 10))\n    sns.set_style(\"whitegrid\")\n\n    # Calculate the number of unique settings for bar positions\n    n_settings = len(df_filtered[\"formatted_settings\"].unique())\n    bar_positions = range(n_settings)\n\n    # Choose a color palette\n    palette = sns.color_palette(\"husl\", n_settings)\n\n    # Plot each bar manually\n    bar_width = 0.25  # Width of the bars\n    for i, setting in enumerate(df_filtered[\"formatted_settings\"].unique()):\n        # Filter the dataframe for each setting and get the mean time\n        mean_time = df_filtered[df_filtered[\"formatted_settings\"] == setting][\"time (secs)\"].mean()\n        plt.bar(i, mean_time, width=bar_width, align=\"center\", color=palette[i])\n\n        # Add the text above the bars\n        plt.text(i, mean_time + 0.01, f\"{mean_time:.2f}\", ha=\"center\", va=\"bottom\", fontsize=14, fontweight=\"bold\")\n\n    # Set the x-ticks to correspond to the settings\n    plt.xticks(bar_positions, df_filtered[\"formatted_settings\"].unique(), rotation=45, ha=\"right\", fontsize=10)\n\n    plt.ylabel(\"Time in Seconds\", fontsize=14, labelpad=15)\n    plt.xlabel(\"Settings\", fontsize=14, labelpad=15)\n    plt.title(args.plot_title, fontsize=18, fontweight=\"bold\", pad=20)\n\n    # Adding horizontal gridlines for better readability\n    plt.grid(axis=\"y\", linestyle=\"--\", linewidth=0.7, alpha=0.7)\n\n    plt.tight_layout()\n    plt.subplots_adjust(top=0.9, bottom=0.2)  # Adjust the top and bottom\n\n    plot_path = args.plot_title.replace(\" \", \"_\") + \".png\"\n    plt.savefig(plot_path, bbox_inches=\"tight\", dpi=300)\n\n    if args.push_to_hub:\n        upload_file(repo_id=REPO_ID, path_in_repo=plot_path, path_or_fileobj=plot_path, repo_type=\"dataset\")\n        print(\n            f\"Plot successfully uploaded. Find it here: https://huggingface.co/datasets/{REPO_ID}/blob/main/{args.plot_file_path}\"\n        )\n\n    # Show the plot\n    plt.show()\n\n\ndef main(args):\n    all_csvs = sorted(glob.glob(f\"{args.base_path}/*.csv\"))\n    all_csvs = [os.path.join(args.base_path, x) for x in all_csvs]\n    is_pixart = \"PixArt-alpha\" in all_csvs[0]\n    collate_csv(all_csvs, args.final_csv_filename, is_pixart=is_pixart)\n\n    if args.push_to_hub:\n        upload_file(\n            repo_id=REPO_ID,\n            path_in_repo=args.final_csv_filename,\n            path_or_fileobj=args.final_csv_filename,\n            repo_type=\"dataset\",\n        )\n        print(\n            f\"CSV successfully uploaded. Find it here: https://huggingface.co/datasets/{REPO_ID}/blob/main/{args.final_csv_filename}\"\n        )\n\n    if args.plot_title is not None:\n        df = pd.read_csv(args.final_csv_filename)\n        prepare_plot(df, args)\n\n\nif __name__ == \"__main__\":\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\"--base_path\", type=str, default=\".\")\n    parser.add_argument(\"--final_csv_filename\", type=str, default=\"collated_results.csv\")\n    parser.add_argument(\"--plot_title\", type=str, default=None)\n    parser.add_argument(\"--push_to_hub\", action=\"store_true\")\n    args = parser.parse_args()\n\n    main(args)\n"
  },
  {
    "path": "pyproject.toml",
    "content": "[tool.ruff]\n# Never enforce `E501` (line length violations).\nignore = [\"C901\", \"E501\", \"E741\", \"F402\", \"F823\"]\nselect = [\"C\", \"E\", \"F\", \"I\", \"W\"]\nline-length = 119\n\n# Ignore import violations in all `__init__.py` files.\n[tool.ruff.per-file-ignores]\n\"__init__.py\" = [\"E402\", \"F401\", \"F403\", \"F811\"]\n\"src/diffusers/utils/dummy_*.py\" = [\"F401\"]\n\n[tool.ruff.isort]\nlines-after-imports = 2\nknown-first-party = [\"diffusers\"]\n\n[tool.ruff.format]\n# Like Black, use double quotes for strings.\nquote-style = \"double\"\n\n# Like Black, indent with spaces, rather than tabs.\nindent-style = \"space\"\n\n# Like Black, respect magic trailing commas.\nskip-magic-trailing-comma = false\n\n# Like Black, automatically detect the appropriate line ending.\nline-ending = \"auto\""
  },
  {
    "path": "run_benchmark.py",
    "content": "import torch\n\n\ntorch.set_float32_matmul_precision(\"high\")\n\nimport sys  # noqa: E402\n\n\nsys.path.append(\".\")\nfrom utils.benchmarking_utils import (  # noqa: E402\n    benchmark_fn,\n    create_parser,\n    generate_csv_dict,\n    write_to_csv,\n)\nfrom utils.pipeline_utils import load_pipeline  # noqa: E402\n\n\ndef run_inference(pipe, args):\n    _ = pipe(\n        prompt=args.prompt,\n        num_inference_steps=args.num_inference_steps,\n        num_images_per_prompt=args.batch_size,\n    )\n\n\ndef main(args) -> dict:\n    pipeline = load_pipeline(\n        ckpt=args.ckpt,\n        compile_unet=args.compile_unet,\n        compile_vae=args.compile_vae,\n        no_sdpa=args.no_sdpa,\n        no_bf16=args.no_bf16,\n        upcast_vae=args.upcast_vae,\n        enable_fused_projections=args.enable_fused_projections,\n        do_quant=args.do_quant,\n        compile_mode=args.compile_mode,\n        change_comp_config=args.change_comp_config,\n        device=args.device,\n    )\n\n    # Warmup.\n    run_inference(pipeline, args)\n    run_inference(pipeline, args)\n    run_inference(pipeline, args)\n\n    time = benchmark_fn(run_inference, pipeline, args)  # in seconds.\n\n    data_dict = generate_csv_dict(\n        pipeline_cls=str(pipeline.__class__.__name__),\n        args=args,\n        time=time,\n    )\n    img = pipeline(\n        prompt=args.prompt,\n        num_inference_steps=args.num_inference_steps,\n        num_images_per_prompt=args.batch_size,\n    ).images[0]\n\n    return data_dict, img\n\n\nif __name__ == \"__main__\":\n    parser = create_parser()\n    args = parser.parse_args()\n    print(args)\n\n    data_dict, img = main(args)\n\n    name = (\n        args.ckpt.replace(\"/\", \"_\")\n        + f\"bf16@{not args.no_bf16}-sdpa@{not args.no_sdpa}-bs@{args.batch_size}-fuse@{args.enable_fused_projections}-upcast_vae@{args.upcast_vae}-steps@{args.num_inference_steps}-unet@{args.compile_unet}-vae@{args.compile_vae}-mode@{args.compile_mode}-change_comp_config@{args.change_comp_config}-do_quant@{args.do_quant}-tag@{args.tag}-device@{args.device}.csv\"\n    )\n    img.save(f'{name.replace(\".csv\", \"\")}.jpeg')\n    write_to_csv(name, data_dict)\n"
  },
  {
    "path": "run_benchmark_pixart.py",
    "content": "import torch\n\n\ntorch.set_float32_matmul_precision(\"high\")\n\nimport sys  # noqa: E402\n\n\nsys.path.append(\".\")\nfrom utils.benchmarking_utils import (  # noqa: E402\n    benchmark_fn,\n    create_parser,\n    generate_csv_dict,\n    write_to_csv,\n)\nfrom utils.pipeline_utils_pixart import load_pipeline  # noqa: E402\n\n\ndef run_inference(pipe, args):\n    _ = pipe(\n        prompt=args.prompt,\n        num_inference_steps=args.num_inference_steps,\n        num_images_per_prompt=args.batch_size,\n    )\n\n\ndef main(args) -> dict:\n    pipeline = load_pipeline(\n        ckpt=args.ckpt,\n        compile_transformer=args.compile_transformer,\n        compile_vae=args.compile_vae,\n        no_sdpa=args.no_sdpa,\n        no_bf16=args.no_bf16,\n        enable_fused_projections=args.enable_fused_projections,\n        do_quant=args.do_quant,\n        compile_mode=args.compile_mode,\n        change_comp_config=args.change_comp_config,\n        device=args.device,\n    )\n\n    # Warmup.\n    run_inference(pipeline, args)\n    run_inference(pipeline, args)\n    run_inference(pipeline, args)\n\n    time = benchmark_fn(run_inference, pipeline, args)  # in seconds.\n\n    data_dict = generate_csv_dict(\n        pipeline_cls=str(pipeline.__class__.__name__),\n        args=args,\n        time=time,\n    )\n    img = pipeline(\n        prompt=args.prompt,\n        num_inference_steps=args.num_inference_steps,\n        num_images_per_prompt=args.batch_size,\n    ).images[0]\n\n    return data_dict, img\n\n\nif __name__ == \"__main__\":\n    parser = create_parser(is_pixart=True)\n    args = parser.parse_args()\n    print(args)\n\n    data_dict, img = main(args)\n\n    name = (\n        args.ckpt.replace(\"/\", \"_\")\n        + f\"bf16@{not args.no_bf16}-sdpa@{not args.no_sdpa}-bs@{args.batch_size}-fuse@{args.enable_fused_projections}-upcast_vae@NA-steps@{args.num_inference_steps}-transformer@{args.compile_transformer}-vae@{args.compile_vae}-mode@{args.compile_mode}-change_comp_config@{args.change_comp_config}-do_quant@{args.do_quant}-tag@{args.tag}-device@{args.device}.csv\"\n    )\n    img.save(f\"{name}.jpeg\")\n    write_to_csv(name, data_dict, is_pixart=True)\n"
  },
  {
    "path": "run_profile.py",
    "content": "import torch\n\n\ntorch.set_float32_matmul_precision(\"high\")\n\nfrom torch._inductor import config as inductorconfig  # noqa: E402\n\n\ninductorconfig.triton.unique_kernel_names = True\n\nimport functools  # noqa: E402\nimport sys  # noqa: E402\n\n\nsys.path.append(\".\")\nfrom utils.benchmarking_utils import create_parser  # noqa: E402\nfrom utils.pipeline_utils import load_pipeline  # noqa: E402\n\n\ndef profiler_runner(path, fn, *args, **kwargs):\n    with torch.profiler.profile(\n        activities=[torch.profiler.ProfilerActivity.CPU, torch.profiler.ProfilerActivity.CUDA], record_shapes=True\n    ) as prof:\n        result = fn(*args, **kwargs)\n    prof.export_chrome_trace(path)\n    return result\n\n\ndef run_inference(pipe, args):\n    _ = pipe(\n        prompt=args.prompt,\n        num_inference_steps=args.num_inference_steps,\n        num_images_per_prompt=args.batch_size,\n    )\n\n\ndef main(args) -> dict:\n    pipeline = load_pipeline(\n        ckpt=args.ckpt,\n        compile_unet=args.compile_unet,\n        compile_vae=args.compile_vae,\n        no_sdpa=args.no_sdpa,\n        no_bf16=args.no_bf16,\n        upcast_vae=args.upcast_vae,\n        enable_fused_projections=args.enable_fused_projections,\n        do_quant=args.do_quant,\n        compile_mode=args.compile_mode,\n        change_comp_config=args.change_comp_config,\n        device=args.device,\n    )\n\n    # warmup.\n    run_inference(pipeline, args)\n    run_inference(pipeline, args)\n\n    trace_path = (\n        args.ckpt.replace(\"/\", \"_\")\n        + f\"bf16@{not args.no_bf16}-sdpa@{not args.no_sdpa}-bs@{args.batch_size}-fuse@{args.enable_fused_projections}-upcast_vae@{args.upcast_vae}-steps@{args.num_inference_steps}-unet@{args.compile_unet}-vae@{args.compile_vae}-mode@{args.compile_mode}-change_comp_config@{args.change_comp_config}-do_quant@{args.do_quant}-device@{args.device}.json\"\n    )\n    runner = functools.partial(profiler_runner, trace_path)\n    with torch.autograd.profiler.record_function(\"sdxl-brrr\"):\n        runner(run_inference, pipeline, args)\n    return trace_path\n\n\nif __name__ == \"__main__\":\n    parser = create_parser()\n    args = parser.parse_args()\n\n    if not args.compile_unet:\n        args.compile_mode = \"NA\"\n\n    trace_path = main(args)\n    print(f\"Trace generated at: {trace_path}\")\n"
  },
  {
    "path": "utils/benchmarking_utils.py",
    "content": "import argparse\nimport copy\nimport csv\nimport gc\nfrom typing import Dict, List, Union\n\nimport torch\nimport torch.utils.benchmark as benchmark\n\n\nBENCHMARK_FIELDS = [\n    \"pipeline_cls\",\n    \"ckpt_id\",\n    \"bf16\",\n    \"sdpa\",\n    \"fused_qkv_projections\",\n    \"upcast_vae\",\n    \"batch_size\",\n    \"num_inference_steps\",\n    \"compile_unet\",\n    \"compile_vae\",\n    \"compile_mode\",\n    \"change_comp_config\",\n    \"do_quant\",\n    \"time (secs)\",\n    \"memory (gbs)\",\n    \"actual_gpu_memory (gbs)\",\n    \"tag\",\n]\n\n\ndef create_parser(is_pixart=False):\n    \"\"\"Creates CLI args parser.\"\"\"\n    parser = argparse.ArgumentParser()\n\n    parser.add_argument(\"--ckpt\", type=str, default=\"stabilityai/stable-diffusion-xl-base-1.0\")\n    parser.add_argument(\"--prompt\", type=str, default=\"ghibli style, a fantasy landscape with castles\")\n    parser.add_argument(\"--no_bf16\", action=\"store_true\")\n    parser.add_argument(\"--no_sdpa\", action=\"store_true\")\n    parser.add_argument(\"--batch_size\", type=int, default=1)\n    parser.add_argument(\"--num_inference_steps\", type=int, default=30)\n    parser.add_argument(\"--enable_fused_projections\", action=\"store_true\")\n\n    if not is_pixart:\n        parser.add_argument(\"--upcast_vae\", action=\"store_true\")\n\n    if is_pixart:\n        parser.add_argument(\"--compile_transformer\", action=\"store_true\")\n    else:\n        parser.add_argument(\"--compile_unet\", action=\"store_true\")\n\n    parser.add_argument(\"--compile_vae\", action=\"store_true\")\n    parser.add_argument(\"--compile_mode\", type=str, default=None, choices=[\"reduce-overhead\", \"max-autotune\"])\n    parser.add_argument(\"--change_comp_config\", action=\"store_true\")\n    parser.add_argument(\"--do_quant\", type=str, default=None)\n    parser.add_argument(\"--tag\", type=str, default=\"\")\n    parser.add_argument(\"--device\", type=str, choices=[\"cuda\", \"cpu\"], default=\"cuda\")\n    return parser\n\n\ndef flush():\n    \"\"\"Wipes off memory.\"\"\"\n    gc.collect()\n    torch.cuda.empty_cache()\n    torch.cuda.reset_max_memory_allocated()\n    torch.cuda.reset_peak_memory_stats()\n\n\ndef bytes_to_giga_bytes(bytes):\n    return f\"{(bytes / 1024 / 1024 / 1024):.3f}\"\n\n\ndef benchmark_fn(f, *args, **kwargs):\n    t0 = benchmark.Timer(\n        stmt=\"f(*args, **kwargs)\",\n        globals={\"args\": args, \"kwargs\": kwargs, \"f\": f},\n        num_threads=torch.get_num_threads(),\n    )\n    return f\"{(t0.blocked_autorange().mean):.3f}\"\n\n\ndef generate_csv_dict(pipeline_cls: str, args, time: float) -> Dict[str, Union[str, bool, float]]:\n    \"\"\"Packs benchmarking data into a dictionary for latter serialization.\"\"\"\n    data_dict = {\n        \"pipeline_cls\": pipeline_cls,\n        \"ckpt_id\": args.ckpt,\n        \"bf16\": not args.no_bf16,\n        \"sdpa\": not args.no_sdpa,\n        \"fused_qkv_projections\": args.enable_fused_projections,\n        \"upcast_vae\": \"NA\" if \"PixArt\" in pipeline_cls else args.upcast_vae,\n        \"batch_size\": args.batch_size,\n        \"num_inference_steps\": args.num_inference_steps,\n        \"compile_unet\": args.compile_transformer if \"PixArt\" in pipeline_cls else args.compile_unet,\n        \"compile_vae\": args.compile_vae,\n        \"compile_mode\": args.compile_mode,\n        \"change_comp_config\": args.change_comp_config,\n        \"do_quant\": args.do_quant,\n        \"time (secs)\": time,\n        \"tag\": args.tag,\n    }\n    if args.device == \"cuda\":\n        memory = bytes_to_giga_bytes(torch.cuda.max_memory_allocated())  # in GBs.\n        TOTAL_GPU_MEMORY = torch.cuda.get_device_properties(0).total_memory / (1024**3)\n        data_dict[\"memory (gbs)\"] = memory\n        data_dict[\"actual_gpu_memory (gbs)\"] = f\"{(TOTAL_GPU_MEMORY):.3f}\"\n    if \"PixArt\" in pipeline_cls:\n        data_dict[\"compile_transformer\"] = data_dict.pop(\"compile_unet\")\n    return data_dict\n\n\ndef write_to_csv(file_name: str, data_dict: Dict[str, Union[str, bool, float]], is_pixart=False):\n    \"\"\"Serializes a dictionary into a CSV file.\"\"\"\n    fields_copy = copy.deepcopy(BENCHMARK_FIELDS)\n    fields = BENCHMARK_FIELDS\n    if is_pixart:\n        i = BENCHMARK_FIELDS.index(\"compile_unet\")\n        fields_copy[i] = \"compile_transformer\"\n        fields = fields_copy\n    with open(file_name, mode=\"w\", newline=\"\") as csvfile:\n        writer = csv.DictWriter(csvfile, fieldnames=fields)\n        writer.writeheader()\n        writer.writerow(data_dict)\n\n\ndef collate_csv(input_files: List[str], output_file: str, is_pixart=False):\n    \"\"\"Collates multiple identically structured CSVs into a single CSV file.\"\"\"\n    fields_copy = copy.deepcopy(BENCHMARK_FIELDS)\n    fields = BENCHMARK_FIELDS\n    if is_pixart:\n        i = BENCHMARK_FIELDS.index(\"compile_unet\")\n        fields_copy[i] = \"compile_transformer\"\n        fields = fields_copy\n    with open(output_file, mode=\"w\", newline=\"\") as outfile:\n        writer = csv.DictWriter(outfile, fieldnames=fields)\n        writer.writeheader()\n\n        for file in input_files:\n            with open(file, mode=\"r\") as infile:\n                reader = csv.DictReader(infile)\n                for row in reader:\n                    writer.writerow(row)\n"
  },
  {
    "path": "utils/pipeline_utils.py",
    "content": "import torch\nfrom torchao.quantization import (\n    apply_dynamic_quant,\n    change_linear_weights_to_int4_woqtensors,\n    change_linear_weights_to_int8_woqtensors,\n    swap_conv2d_1x1_to_linear,\n)\n\nfrom diffusers import AutoencoderKL, DiffusionPipeline, DPMSolverMultistepScheduler\n\n\nPROMPT = \"ghibli style, a fantasy landscape with castles\"\n\n\ndef dynamic_quant_filter_fn(mod, *args):\n    return (\n        isinstance(mod, torch.nn.Linear)\n        and mod.in_features > 16\n        and (mod.in_features, mod.out_features)\n        not in [\n            (1280, 640),\n            (1920, 1280),\n            (1920, 640),\n            (2048, 1280),\n            (2048, 2560),\n            (2560, 1280),\n            (256, 128),\n            (2816, 1280),\n            (320, 640),\n            (512, 1536),\n            (512, 256),\n            (512, 512),\n            (640, 1280),\n            (640, 1920),\n            (640, 320),\n            (640, 5120),\n            (640, 640),\n            (960, 320),\n            (960, 640),\n        ]\n    )\n\n\ndef conv_filter_fn(mod, *args):\n    return (\n        isinstance(mod, torch.nn.Conv2d) and mod.kernel_size == (1, 1) and 128 in [mod.in_channels, mod.out_channels]\n    )\n\n\ndef load_pipeline(\n    ckpt: str,\n    compile_unet: bool,\n    compile_vae: bool,\n    no_sdpa: bool,\n    no_bf16: bool,\n    upcast_vae: bool,\n    enable_fused_projections: bool,\n    do_quant: bool,\n    compile_mode: str,\n    change_comp_config: bool,\n    device: str,\n):\n    \"\"\"Loads the SDXL pipeline.\"\"\"\n\n    if do_quant and not compile_unet:\n        raise ValueError(\"Compilation for UNet must be enabled when quantizing.\")\n    if do_quant and not compile_vae:\n        raise ValueError(\"Compilation for VAE must be enabled when quantizing.\")\n\n    dtype = torch.float32 if no_bf16 else torch.bfloat16\n    print(f\"Using dtype: {dtype}\")\n\n    if ckpt != \"runwayml/stable-diffusion-v1-5\":\n        pipe = DiffusionPipeline.from_pretrained(ckpt, torch_dtype=dtype, use_safetensors=True)\n    else:\n        pipe = DiffusionPipeline.from_pretrained(ckpt, torch_dtype=dtype, use_safetensors=True, safety_checker=None)\n        # As the default scheduler of SD v1-5 doesn't have sigmas device placement\n        # (https://github.com/huggingface/diffusers/pull/6173)\n        pipe.scheduler = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)\n\n    if not upcast_vae and ckpt != \"runwayml/stable-diffusion-v1-5\":\n        print(\"Using a more numerically stable VAE.\")\n        pipe.vae = AutoencoderKL.from_pretrained(\"madebyollin/sdxl-vae-fp16-fix\", torch_dtype=dtype)\n\n    if enable_fused_projections:\n        print(\"Enabling fused QKV projections for both UNet and VAE.\")\n        pipe.fuse_qkv_projections()\n\n    if upcast_vae and ckpt != \"runwayml/stable-diffusion-v1-5\":\n        print(\"Upcasting VAE.\")\n        pipe.upcast_vae()\n\n    if no_sdpa:\n        print(\"Using vanilla attention.\")\n        pipe.unet.set_default_attn_processor()\n        pipe.vae.set_default_attn_processor()\n\n    if device == \"cuda\":\n        pipe = pipe.to(\"cuda\")\n\n    if compile_unet:\n        pipe.unet.to(memory_format=torch.channels_last)\n        print(\"Compile UNet.\")\n        swap_conv2d_1x1_to_linear(pipe.unet, conv_filter_fn)\n        if compile_mode == \"max-autotune\" and change_comp_config:\n            torch._inductor.config.conv_1x1_as_mm = True\n            torch._inductor.config.coordinate_descent_tuning = True\n            torch._inductor.config.epilogue_fusion = False\n            torch._inductor.config.coordinate_descent_check_all_directions = True\n\n        if do_quant:\n            print(\"Apply quantization to UNet.\")\n            if do_quant == \"int4weightonly\":\n                change_linear_weights_to_int4_woqtensors(pipe.unet)\n            elif do_quant == \"int8weightonly\":\n                change_linear_weights_to_int8_woqtensors(pipe.unet)\n            elif do_quant == \"int8dynamic\":\n                apply_dynamic_quant(pipe.unet, dynamic_quant_filter_fn)\n            else:\n                raise ValueError(f\"Unknown do_quant value: {do_quant}.\")\n            torch._inductor.config.force_fuse_int_mm_with_mul = True\n            torch._inductor.config.use_mixed_mm = True\n\n        pipe.unet = torch.compile(pipe.unet, mode=compile_mode, fullgraph=True)\n\n    if compile_vae:\n        pipe.vae.to(memory_format=torch.channels_last)\n        print(\"Compile VAE.\")\n        swap_conv2d_1x1_to_linear(pipe.vae, conv_filter_fn)\n\n        if compile_mode == \"max-autotune\" and change_comp_config:\n            torch._inductor.config.conv_1x1_as_mm = True\n            torch._inductor.config.coordinate_descent_tuning = True\n            torch._inductor.config.epilogue_fusion = False\n            torch._inductor.config.coordinate_descent_check_all_directions = True\n\n        if do_quant:\n            print(\"Apply quantization to VAE.\")\n            if do_quant == \"int4weightonly\":\n                change_linear_weights_to_int4_woqtensors(pipe.vae)\n            elif do_quant == \"int8weightonly\":\n                change_linear_weights_to_int8_woqtensors(pipe.vae)\n            elif do_quant == \"int8dynamic\":\n                apply_dynamic_quant(pipe.vae, dynamic_quant_filter_fn)\n            else:\n                raise ValueError(f\"Unknown do_quant value: {do_quant}.\")\n            torch._inductor.config.force_fuse_int_mm_with_mul = True\n            torch._inductor.config.use_mixed_mm = True\n\n        pipe.vae.decode = torch.compile(pipe.vae.decode, mode=compile_mode, fullgraph=True)\n\n    pipe.set_progress_bar_config(disable=True)\n    return pipe\n"
  },
  {
    "path": "utils/pipeline_utils_pixart.py",
    "content": "import torch\nfrom torchao.quantization import (\n    apply_dynamic_quant,\n    change_linear_weights_to_int4_woqtensors,\n    change_linear_weights_to_int8_woqtensors,\n    swap_conv2d_1x1_to_linear,\n)\n\nfrom diffusers import DiffusionPipeline\n\n\ndef dynamic_quant_filter_fn(mod, *args):\n    return (\n        isinstance(mod, torch.nn.Linear)\n        and mod.in_features > 16\n        and (mod.in_features, mod.out_features)\n        not in [\n            (1280, 640),\n            (1920, 1280),\n            (1920, 640),\n            (2048, 1280),\n            (2048, 2560),\n            (2560, 1280),\n            (256, 128),\n            (2816, 1280),\n            (320, 640),\n            (512, 1536),\n            (512, 256),\n            (512, 512),\n            (640, 1280),\n            (640, 1920),\n            (640, 320),\n            (640, 5120),\n            (640, 640),\n            (960, 320),\n            (960, 640),\n        ]\n    )\n\n\ndef conv_filter_fn(mod, *args):\n    return (\n        isinstance(mod, torch.nn.Conv2d) and mod.kernel_size == (1, 1) and 128 in [mod.in_channels, mod.out_channels]\n    )\n\n\ndef load_pipeline(\n    ckpt: str,\n    compile_transformer: bool,\n    compile_vae: bool,\n    no_sdpa: bool,\n    no_bf16: bool,\n    enable_fused_projections: bool,\n    do_quant: bool,\n    compile_mode: str,\n    change_comp_config: bool,\n    device: str,\n):\n    \"\"\"Loads the PixArt-Alpha pipeline.\"\"\"\n\n    if do_quant and not compile_transformer:\n        raise ValueError(\"Compilation for Transformer must be enabled when quantizing.\")\n    if do_quant and not compile_vae:\n        raise ValueError(\"Compilation for VAE must be enabled when quantizing.\")\n\n    dtype = torch.float32 if no_bf16 else torch.bfloat16\n    print(f\"Using dtype: {dtype}\")\n    pipe = DiffusionPipeline.from_pretrained(ckpt, torch_dtype=dtype)\n\n    if enable_fused_projections:\n        print(\"Enabling fused QKV projections for both Transformer and VAE.\")\n        pipe.fuse_qkv_projections()\n\n    if no_sdpa:\n        print(\"Using vanilla attention.\")\n        pipe.transformer.set_default_attn_processor()\n        pipe.vae.set_default_attn_processor()\n\n    if device == \"cuda\":\n        pipe = pipe.to(\"cuda\")\n\n    if compile_transformer:\n        pipe.transformer.to(memory_format=torch.channels_last)\n        print(\"Compile Transformer\")\n        swap_conv2d_1x1_to_linear(pipe.transformer, conv_filter_fn)\n        if compile_mode == \"max-autotune\" and change_comp_config:\n            torch._inductor.config.conv_1x1_as_mm = True\n            torch._inductor.config.coordinate_descent_tuning = True\n            torch._inductor.config.epilogue_fusion = False\n            torch._inductor.config.coordinate_descent_check_all_directions = True\n\n        if do_quant:\n            print(\"Apply quantization to Transformer\")\n            if do_quant == \"int4weightonly\":\n                change_linear_weights_to_int4_woqtensors(pipe.transformer)\n            elif do_quant == \"int8weightonly\":\n                change_linear_weights_to_int8_woqtensors(pipe.transformer)\n            elif do_quant == \"int8dynamic\":\n                apply_dynamic_quant(pipe.transformer, dynamic_quant_filter_fn)\n            else:\n                raise ValueError(f\"Unknown do_quant value: {do_quant}.\")\n            torch._inductor.config.force_fuse_int_mm_with_mul = True\n            torch._inductor.config.use_mixed_mm = True\n\n        pipe.transformer = torch.compile(pipe.transformer, mode=compile_mode, fullgraph=True)\n\n    if compile_vae:\n        pipe.vae.to(memory_format=torch.channels_last)\n        print(\"Compile VAE\")\n        swap_conv2d_1x1_to_linear(pipe.vae, conv_filter_fn)\n\n        if compile_mode == \"max-autotune\" and change_comp_config:\n            torch._inductor.config.conv_1x1_as_mm = True\n            torch._inductor.config.coordinate_descent_tuning = True\n            torch._inductor.config.epilogue_fusion = False\n            torch._inductor.config.coordinate_descent_check_all_directions = True\n\n        if do_quant:\n            print(\"Apply quantization to VAE\")\n            if do_quant == \"int4weightonly\":\n                change_linear_weights_to_int4_woqtensors(pipe.vae)\n            elif do_quant == \"int8weightonly\":\n                change_linear_weights_to_int8_woqtensors(pipe.vae)\n            elif do_quant == \"int8dynamic\":\n                apply_dynamic_quant(pipe.vae, dynamic_quant_filter_fn)\n            else:\n                raise ValueError(f\"Unknown do_quant value: {do_quant}.\")\n            torch._inductor.config.force_fuse_int_mm_with_mul = True\n            torch._inductor.config.use_mixed_mm = True\n\n        pipe.vae.decode = torch.compile(pipe.vae.decode, mode=compile_mode, fullgraph=True)\n\n    pipe.set_progress_bar_config(disable=True)\n    return pipe\n"
  }
]