[
  {
    "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 [yyyy] [name of copyright owner]\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": "README.md",
    "content": "# DepthLab: From Partial to Complete\n\nThis repository represents the official implementation of the paper titled \"DepthLab: From Partial to Complete\".\n\n[![Website](docs/badge-website.svg)](https://johanan528.github.io/depthlab_web/)\n[![Paper](https://img.shields.io/badge/arXiv-PDF-b31b1b)](https://arxiv.org/abs/2412.18153)\n[![License](https://img.shields.io/badge/License-Apache--2.0-929292)](https://www.apache.org/licenses/LICENSE-2.0)\n[![Hugging Face Model](https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Spaces-blue')](https://huggingface.co/Johanan0528/DepthLab/tree/main)\n\n<p align=\"center\">\n    <a href=\"https://johanan528.github.io/\"><strong>Zhiheng Liu*</strong></a>\n    ·\n    <a href=\"https://felixcheng97.github.io/\"><strong>Ka Leong Cheng*</strong></a>\n    ·\n    <a href=\"https://github.com/qiuyu96\"><strong>Qiuyu Wang</strong></a>\n    ·\n    <a href=\"https://ffrivera0.github.io/\"><strong>Shuzhe Wang</strong></a>\n    ·\n    <a href=\"https://ken-ouyang.github.io/\"><strong>Hao Ouyang</strong></a>\n    ·\n    <a href=\"https://icetttb.github.io/\"><strong>Bin Tan</strong></a>\n    ·\n    <a href=\"https://scholar.google.com/citations?user=Mo_2YsgAAAAJ&hl=zh-CN\"><strong>Kai Zhu</strong></a>\n    ·\n    <a href=\"https://shenyujun.github.io/\"><strong>Yujun Shen</strong></a>\n    ·\n    <a href=\"https://cqf.io/\"><strong>Qifeng Chen</strong></a>\n    ·\n    <a href=\"http://luoping.me/\"><strong>Ping Luo</strong></a>\n    <br>\n  </p>\n\nWe present **DepthLab**, a robust depth inpainting foundation model that can be applied to various downstream tasks to enhance performance. Many tasks naturally contain partial depth information, such as (1) *3D Gaussian inpainting*, (2) *LiDAR depth completion*, (3) *sparse-view reconstruction with DUSt3R*, and (4) *text-to-scene generation*. Our model leverages this known information to achieve improved depth estimation, enhancing performance in downstream tasks. We hope to motivate more related tasks to adopt DepthLab.\n\n![teaser](docs/teaser_new.webp)\n\n## 📢 News\n* 2024-12-25: Inference code and paper is released.\n* [To-do]: Release the training code to facilitate fine-tuning, allowing adaptation to different mask types in your downstream tasks.\n\n## 🛠️ Setup\n\n### 📦 Repository\n\nClone the repository (requires git):\n\n```bash\ngit clone https://github.com/Johanan528/DepthLab.git\ncd DepthLab\n```\n\n### 💻 Dependencies\n\nInstall with `conda`: \n```bash\nconda env create -f environment.yaml\nconda activate DepthLab\n```\n\n### 📦 Checkpoints\nDownload the Marigold checkpoint [here](https://huggingface.co/prs-eth/marigold-depth-v1-0), the image encoder checkpoint [here](https://huggingface.co/laion/CLIP-ViT-H-14-laion2B-s32B-b79K), and our checkpoints at [Hugging Face](https://huggingface.co/Johanan0528/DepthLab/tree/main). The downloaded checkpoint directory has the following structure:\n```\n.\n`-- checkpoints\n    |-- marigold-depth-v1-0\n    |-- CLIP-ViT-H-14-laion2B-s32B-b79K\n    `-- DepthLab\n        |-- denoising_unet.pth\n        |-- reference_unet.pth\n        `-- mapping_layer.pth\n```\n\n## 🏃 Testing on your cases\n\n### 📷 Prepare images, masks, known depths\nMasks: PNG/JPG or Numpy, where black (0) represents the known regions, and white (1) indicates the predicted areas.\n\nKnown depths: Numpy\n\nImages: PNG/JPG\n\n#### We provide a case in 'test_cases' folder.\n### 🎮 Run inference\n\n```bash\ncd scripts\nbash infer.sh\n```\n\nYou can find all results in `output/in-the-wild_example`. Enjoy!\n\n### ⚙️ Inference settings\n\nThe default settings are optimized for the best result. However, the behavior of the code can be customized:\n  - `--denoise_steps`: Number of denoising steps of each inference pass. For the original (DDIM) version, it's recommended to use 20-50 steps.\n  - `--processing_res`: The processing resolution. **For cases where the mask is sparse, such as in depth completion scenarios, it is advisable to set the 'processing_res' and the mask size to be the same in order to avoid accuracy loss in the mask due to resizing. For non-sparse completion tasks, we recommend using a resolution of 640 or 768 for inference.**\n  - `--normalize_scale`: When the known depth scale cannot encompass the global scale, it is possible to reduce the normalization scale, allowing the model to better predict the depth of distant objects.\n  - `--strength`: When set to 1, the prediction is entirely based on the model itself. When set to a value less than 1, the model is partially assisted by interpolated masked depth to some extent.\n  - `--blend`: Whether to use Blend Diffusion, a commonly used technique in image inpainting.\n  - `--refine`: If you want to refine depthmap of DUSt3R, or you have a full initial depthmap, turn this option on.\n## 🌺 Acknowledgements\nThis project is developped on the codebase of [Marigold](https://github.com/prs-eth/Marigold) and [MagicAnimate](https://github.com/magic-research/magic-animate). We appreciate their great works! \n\n## 🎓 Citation\nPlease cite our paper:\n```bibtex\n@article{liu2024depthlab,\n  title={DepthLab: From Partial to Complete},\n  author={Liu, Zhiheng and Cheng, Ka Leong and Wang, Qiuyu and Wang, Shuzhe and Ouyang, Hao and Tan, Bin and Zhu, Kai and Shen, Yujun and Chen, Qifeng and Luo, Ping},\n  journal={arXiv preprint arXiv:2412.18153},\n  year={2024}\n}\n```\n"
  },
  {
    "path": "checkpoints/place_checkpoints_here.txt",
    "content": ""
  },
  {
    "path": "environment.yaml",
    "content": "name: DepthLab\nchannels:\n  - defaults\ndependencies:\n  - pip=24.2=py39h06a4308_0\n  - python=3.9.19=h955ad1f_1\n  - pip:\n      - accelerate==0.34.2\n      - diffusers==0.27.2\n      - dill==0.3.8\n      - einops==0.8.0\n      - huggingface-hub==0.24.7\n      - imageio==2.35.1\n      - importlib-metadata==8.5.0\n      - importlib-resources==6.4.5\n      - ipython==8.18.1\n      - ipywidgets==8.1.5\n      - matplotlib==3.5.2\n      - numpy==1.26.4\n      - open3d==0.18.0\n      - opencv-python==4.10.0.84\n      - packaging==24.1\n      - pandas==2.2.2\n      - pillow==10.4.0\n      - prompt-toolkit==3.0.48\n      - pyyaml==6.0.2\n      - requests==2.32.3\n      - safetensors==0.4.5\n      - scikit-image==0.24.0\n      - scikit-learn==1.5.2\n      - scipy==1.13.1\n      - torch==2.1.0\n      - torchaudio==2.1.0\n      - torchvision==0.16.0\n      - tqdm==4.66.5\n      - transformers==4.44.2\n      - trimesh==4.4.9\n      - zipp==3.20.2\n"
  },
  {
    "path": "infer.py",
    "content": "import argparse\nimport logging\nimport os\nimport random\nimport numpy as np\nimport torch\nfrom PIL import Image\nfrom tqdm.auto import tqdm\nfrom diffusers import (\n    DDIMScheduler,\n    AutoencoderKL,\n)\nimport cv2\nimport torch.nn as nn\nfrom transformers import CLIPTextModel, CLIPTokenizer\nfrom src.models.unet_2d_condition import UNet2DConditionModel\nfrom src.models.unet_2d_condition_main import UNet2DConditionModel_main\nfrom src.models.projection import My_proj\nfrom transformers import CLIPVisionModelWithProjection\nfrom inference.depthlab_pipeline import DepthLabPipeline\nfrom utils.seed_all import seed_all\nfrom utils.image_util import get_filled_for_latents\n\ndef load_and_process_mask(mask_path):\n    image = Image.open(mask_path).convert('L')\n    mask = np.array(image)\n    mask = mask / 255.0\n    mask[mask > 0.5] = 1\n    mask[mask <= 0.5] = 0\n    \n    return mask\nif \"__main__\" == __name__:\n    logging.basicConfig(level=logging.INFO)\n\n    # -------------------- Arguments --------------------\n    parser = argparse.ArgumentParser(\n        description=\"Run single-image depth estimation using Marigold.\"\n    )\n    parser.add_argument(\n        \"--output_dir\", type=str, required=True, help=\"Output directory.\"\n    )\n\n    # inference setting\n    parser.add_argument(\n        \"--denoise_steps\",\n        type=int,\n        default=50,  # quantitative evaluation uses 50 steps\n        help=\"Diffusion denoising steps, more steps results in higher accuracy but slower inference speed.\",\n    )\n\n    # resolution setting\n    parser.add_argument(\n        \"--processing_res\",\n        type=int,\n        default=0,\n        help=\"Maximum resolution of processing. 0 for using input image resolution. Default: 0.\",\n    )\n    parser.add_argument(\n        \"--normalize_scale\",\n        type=float,\n        default=1,\n        help=\"Maximum resolution of processing. 0 for using input image resolution. Default: 0.\",\n    )\n    parser.add_argument(\n        \"--strength\",\n        type=float,\n        default=0.8,\n        help=\"Maximum resolution of processing. 0 for using input image resolution. Default: 0.\",\n    )\n    parser.add_argument(\"--seed\", type=int, default=None, help=\"Random seed.\")\n\n    parser.add_argument(\n        \"--pretrained_model_name_or_path\",\n        type=str,\n        default=None,\n        required=True,\n        help=\"Path to pretrained model or model identifier from huggingface.co/models.\",\n    )\n    parser.add_argument(\n        \"--image_encoder_path\",\n        type=str,\n        default=None,\n        required=True,\n        help=\"Path to pretrained model or model identifier from huggingface.co/models.\",\n    )\n    parser.add_argument(\n        \"--denoising_unet_path\", type=str, required=True, help=\"Path to depth inpainting model.\"\n    )\n    parser.add_argument(\n        \"--mapping_path\", type=str, required=True, help=\"Path to depth inpainting model.\"\n    )\n    parser.add_argument(\n        \"--reference_unet_path\", type=str, required=True, help=\"Path to depth inpainting model.\"\n    )\n    parser.add_argument(\n        \"--input_image_paths\",\n        nargs='+',\n        default=None,\n        help=\"input_image_paths\",\n    )\n    parser.add_argument(\n        \"--known_depth_paths\",\n        nargs='+',\n        default=None,\n        help=\"known_depth_paths\",\n    )\n    parser.add_argument(\n        \"--blend\",\n        action=\"store_true\",\n        help=\"Whether or not to use gradient checkpointing to save memory at the expense of slower backward pass.\",\n    )\n    parser.add_argument(\n        \"--refine\",\n        action=\"store_true\",\n        help=\"Whether or not to use gradient checkpointing to save memory at the expense of slower backward pass.\",\n    )\n    parser.add_argument(\n        \"--masks_paths\",\n        nargs='+',\n        default=None,\n        help=\"masks_paths\",\n    )\n    args = parser.parse_args()\n    output_dir = args.output_dir\n    denoise_steps = args.denoise_steps\n    processing_res = args.processing_res\n    seed = args.seed\n    output_dir_color = os.path.join(output_dir, \"depth_colored\")\n    output_dir_npy = os.path.join(output_dir, \"depth_npy\")\n    os.makedirs(output_dir, exist_ok=True)\n    os.makedirs(output_dir_color, exist_ok=True)\n    os.makedirs(output_dir_npy, exist_ok=True)\n    logging.info(f\"output dir = {output_dir}\")\n    if args.input_image_paths is not None:\n        assert len(args.input_image_paths) == len(args.known_depth_paths)\n        assert len(args.input_image_paths) == len(args.masks_paths)\n    input_image_paths = args.input_image_paths\n    known_depth_paths = args.known_depth_paths\n    masks_paths = args.masks_paths\n    print(f\"arguments: {args}\")\n    if seed is None:\n        import time\n\n        seed = int(time.time())\n    seed_all(seed)\n\n    # -------------------- Device --------------------\n    if torch.cuda.is_available():\n        device = torch.device(\"cuda\")\n    else:\n        device = torch.device(\"cpu\")\n        logging.warning(\"CUDA is not available. Running on CPU will be slow.\")\n    logging.info(f\"device = {device}\")\n\n    # -------------------- Model --------------------\n\n    vae = AutoencoderKL.from_pretrained(args.pretrained_model_name_or_path,\n                                                     subfolder='vae')\n    text_encoder = CLIPTextModel.from_pretrained(args.pretrained_model_name_or_path,\n                                                     subfolder='text_encoder')\n    denoising_unet = UNet2DConditionModel_main.from_pretrained(args.pretrained_model_name_or_path,subfolder=\"unet\",\n                                                    in_channels=12, sample_size=96,\n                                                    low_cpu_mem_usage=False,\n                                                    ignore_mismatched_sizes=True)\n    reference_unet = UNet2DConditionModel.from_pretrained(args.pretrained_model_name_or_path,subfolder=\"unet\",\n                                                    in_channels=4, sample_size=96,\n                                                    low_cpu_mem_usage=False,\n                                                    ignore_mismatched_sizes=True)\n    image_enc = CLIPVisionModelWithProjection.from_pretrained(args.image_encoder_path)\n    mapping_layer=My_proj()\n\n\n    mapping_layer.load_state_dict(\n        torch.load(args.mapping_path, map_location=\"cpu\"),\n        strict=False,\n        )\n    mapping_device = torch.device(\"cuda\")\n    mapping_layer.to(mapping_device )\n    reference_unet.load_state_dict(\n                torch.load(args.reference_unet_path, map_location=\"cpu\"),\n        )\n    denoising_unet.load_state_dict(\n        torch.load(args.denoising_unet_path, map_location=\"cpu\"),\n        strict=False,\n        )\n    tokenizer = CLIPTokenizer.from_pretrained(args.pretrained_model_name_or_path,subfolder='tokenizer')\n    scheduler = DDIMScheduler.from_pretrained(args.pretrained_model_name_or_path,subfolder='scheduler')\n    pipe = DepthLabPipeline(reference_unet=reference_unet,\n                                       denoising_unet = denoising_unet,  \n                                       mapping_layer=mapping_layer,\n                                       vae=vae,\n                                       text_encoder=text_encoder,\n                                       tokenizer=tokenizer,\n                                       image_enc=image_enc,\n                                       scheduler=scheduler,\n                                       ).to('cuda')\n    try:\n        pipe.enable_xformers_memory_efficient_attention()\n    except ImportError:\n        logging.debug(\"run without xformers\")\n\n    # -------------------- Inference and saving --------------------\n    with torch.no_grad():\n        for i in range(len(input_image_paths)):\n            input_image_path = input_image_paths[i]\n            mask_path = masks_paths[i]\n            known_depth_path = known_depth_paths[i]\n\n            # save path\n            rgb_name_base = os.path.splitext(os.path.basename(input_image_path))[0]\n            pred_name_base = rgb_name_base + \"_pred\"\n            npy_save_path = os.path.join(output_dir_npy, f\"{pred_name_base}.npy\")\n            colored_save_path = os.path.join(\n                output_dir_color, f\"{pred_name_base}_colored.png\"\n            )\n\n            input_image = Image.open(input_image_path)\n            try:\n                mask = np.load(mask_path)\n                mask[mask>0.5]=1\n                mask[mask<0.5]=0\n            except:\n                mask = load_and_process_mask(mask_path)\n            depth_numpy=np.load(known_depth_path)\n\n            if args.refine is not True:\n                depth_numpy=get_filled_for_latents(mask,depth_numpy)\n            pipe_out = pipe(\n                input_image,\n                denosing_steps = denoise_steps,\n                processing_res = processing_res,\n                match_input_res = True,\n                batch_size =1,\n                color_map = \"Spectral\",\n                show_progress_bar = True,\n                depth_numpy_origin = depth_numpy,\n                mask_origin = mask,\n                guidance_scale = 1,\n                normalize_scale = args.normalize_scale,\n                strength = args.strength,\n                blend = args.blend)\n\n            depth_pred: np.ndarray = pipe_out.depth_np\n            if os.path.exists(colored_save_path):\n                logging.warning(f\"Existing file: '{colored_save_path}' will be overwritten\")\n\n            np.save(npy_save_path,depth_pred)\n            pipe_out.depth_colored.save(colored_save_path)"
  },
  {
    "path": "inference/depthlab_pipeline.py",
    "content": "import os, sys\nparent_dir = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))\nif parent_dir not in sys.path:\n    sys.path.insert(0, parent_dir)\n\nfrom typing import Any, Dict, Union\nimport torch.nn.functional as F\nimport torch\nfrom torch.utils.data import DataLoader, TensorDataset\nimport numpy as np\nfrom tqdm.auto import tqdm\nfrom PIL import Image\nimport torch.nn as nn\nfrom diffusers import (\n    DiffusionPipeline,\n    DDIMScheduler,\n    AutoencoderKL,\n)\nfrom transformers import CLIPImageProcessor\nfrom transformers import CLIPVisionModelWithProjection\nfrom src.models.mutual_self_attention import ReferenceAttentionControl\nfrom src.models.unet_2d_condition import UNet2DConditionModel\nfrom src.models.unet_2d_condition_main import UNet2DConditionModel_main\nfrom src.models.projection import My_proj\nimport cv2\nfrom diffusers.utils import BaseOutput\nfrom transformers import CLIPTextModel, CLIPTokenizer\nfrom utils.image_util import resize_max_res, resize_max_res_cv2, colorize_depth_maps, chw2hwc, Disparity_Normalization_mask_scale,get_filled_depth\nfrom scipy.interpolate import griddata\nsys.path.pop(0)\nclass DepthPipelineOutput(BaseOutput):\n    \"\"\"\n    Output class for Marigold monocular depth prediction pipeline.\n\n    Args:\n        depth_np (`np.ndarray`):\n            Predicted depth map, with depth values in the range of [0, 1].\n        depth_colored (`PIL.Image.Image`):\n            Colorized depth map, with the shape of [3, H, W] and values in [0, 1].\n        uncertainty (`None` or `np.ndarray`):\n            Uncalibrated uncertainty(MAD, median absolute deviation) coming from ensembling.\n    \"\"\"\n    depth_np: np.ndarray\n    depth_norm: Image.Image\n    depth_colored: Image.Image\n    depth_pred_numpy_origin:np.ndarray\n\nclass DepthLabPipeline(DiffusionPipeline):\n    # two hyper-parameters\n    rgb_latent_scale_factor = 0.18215\n    depth_latent_scale_factor = 0.18215\n    \n    def __init__(self,\n        reference_unet:UNet2DConditionModel,\n        denoising_unet:UNet2DConditionModel_main,\n        mapping_layer:My_proj,\n        vae:AutoencoderKL,\n        text_encoder:CLIPTextModel,\n        tokenizer:CLIPTokenizer,\n        image_enc:CLIPVisionModelWithProjection,\n        scheduler:DDIMScheduler,\n    ):\n        super().__init__()\n            \n        self.register_modules(\n            reference_unet=reference_unet,\n            denoising_unet=denoising_unet, \n            mapping_layer=mapping_layer,      \n            vae=vae,\n            image_enc=image_enc,\n            scheduler=scheduler,\n            tokenizer=tokenizer,\n            text_encoder=text_encoder\n\n        )\n        self.empty_text_embed = None\n        self.clip_image_processor = CLIPImageProcessor()\n        \n    @torch.no_grad()\n    def __call__(self,\n        input_image: str,\n        denosing_steps: int = 20,\n        processing_res: int = 768,\n        match_input_res: bool = True,\n        batch_size: int = 0,\n        color_map: str=\"Spectral\",\n        show_progress_bar: bool = True,\n        ensemble_kwargs: Dict = None,\n        depth_numpy_origin = None,\n        mask_origin = None,\n        guidance_scale = 1,\n        normalize_scale = 1,\n        strength=0.8,\n        blend=True\n        ) -> DepthPipelineOutput:\n        \n        # inherit from thea Diffusion Pipeline\n        device = self.image_enc.device\n\n        clip_image_unresize = input_image\n\n        try:\n            depth_origin = depth_numpy_origin\n        except:\n            raise NotImplementedError\n        assert depth_origin.min() >= 0.\n        \n        mask_origin = np.array(mask_origin)\n        mask_origin [mask_origin <0.5] = 0.\n        mask_origin [mask_origin >0.5] = 1.\n        \n        clip_image = self.clip_image_processor.preprocess(\n            clip_image_unresize, return_tensors=\"pt\"\n        ).pixel_values\n        clip_image_embeds = self.image_enc(\n            clip_image.to(device, dtype=self.image_enc.dtype)\n        ).image_embeds\n        encoder_hidden_states = clip_image_embeds.unsqueeze(1)\n        encoder_hidden_states =self.mapping_layer(encoder_hidden_states )\n        prompt = \"\"\n        text_inputs =self.tokenizer(\n            prompt,\n            padding=\"do_not_pad\",\n            max_length=self.tokenizer.model_max_length,\n            truncation=True,\n            return_tensors=\"pt\",\n        )\n        text_input_ids = text_inputs.input_ids.to(device) \n        empty_text_embed = self.text_encoder(text_input_ids)[0].to(self.dtype)\n        uncond_encoder_hidden_states = empty_text_embed.repeat((1, 1, 1))[:,0,:].unsqueeze(0)\n\n        do_classifier_free_guidance = True\n\n        # adjust the input resolution.\n        if not match_input_res:\n            assert (\n                processing_res is not None                \n            ),\" Value Error: `resize_output_back` is only valid with \"\n        \n        assert processing_res >= 0\n        assert denosing_steps >= 1\n        \n        # --------------- Image Processing ------------------------\n        # Resize image\n        original_H, original_W = depth_origin.shape\n        if processing_res > 0:\n            image = resize_max_res(\n                input_image, max_edge_resolution=processing_res, resample=Image.BICUBIC\n            )\n            depth = resize_max_res_cv2(\n                depth_origin, max_edge_resolution=processing_res, interpolation=cv2.INTER_LINEAR\n            )\n            mask = resize_max_res_cv2(\n                mask_origin , max_edge_resolution=processing_res, interpolation=cv2.INTER_NEAREST\n            )\n        # Convert the image to RGB, to 1. reomve the alpha channel.\n        image = np.array(image)\n        \n        # Normalize RGB Values.\n        rgb = np.transpose(image,(2,0,1))\n        rgb_norm = rgb / 255.0 * 2.0 - 1.0\n        rgb_norm = torch.from_numpy(rgb_norm).to(self.dtype).to(device)\n        assert rgb_norm.min() >= -1.0 and rgb_norm.max() <= 1.0\n\n        # depth\n        depth = torch.from_numpy(depth).to(self.dtype).to(device)[None]\n        assert depth.min() >= 0.\n\n        # mask\n        mask = torch.from_numpy(mask).to(self.dtype).to(device)[None]\n        assert mask.min() >= 0. and mask.max() <= 1.\n        \n        # ----------------- predicting depth -----------------\n        single_rgb_dataset = TensorDataset(rgb_norm[None], depth[None], mask[None])\n        \n        # find the batch size\n        if batch_size>0:\n            _bs = batch_size\n        else:\n            _bs = 1\n        \n        single_rgb_loader = DataLoader(single_rgb_dataset,batch_size=_bs,shuffle=False)\n\n        # classifier guidance\n        if do_classifier_free_guidance:\n            encoder_hidden_states = torch.cat(\n                [uncond_encoder_hidden_states, encoder_hidden_states], dim=0\n            )\n\n        reference_control_writer = ReferenceAttentionControl(\n            self.reference_unet,\n            do_classifier_free_guidance=do_classifier_free_guidance,\n            mode=\"write\",\n            batch_size=batch_size,\n            fusion_blocks=\"full\",\n        )\n        reference_control_reader = ReferenceAttentionControl(\n            self.denoising_unet,\n            do_classifier_free_guidance=do_classifier_free_guidance,\n            mode=\"read\",\n            batch_size=batch_size,\n            fusion_blocks=\"full\",\n        )\n\n        if show_progress_bar:\n            iterable_bar = tqdm(\n                single_rgb_loader, desc=\" \" * 2 + \"Inference batches\", leave=False\n            )\n        else:\n            iterable_bar = single_rgb_loader\n        for batch in iterable_bar:\n            (image, depth, mask)= batch  \n            depth_pred_raw, max_value, min_value = self.single_infer(\n                image = image,\n                depth = depth,\n                mask = mask,\n                num_inference_steps = denosing_steps,\n                show_pbar = show_progress_bar,\n                guidance_scale = guidance_scale,\n                encoder_hidden_states = encoder_hidden_states,\n                reference_control_writer = reference_control_writer,\n                reference_control_reader = reference_control_reader,\n                strength = strength,\n                blend = blend,\n                normalize_scale = normalize_scale,\n                generator = None,\n            )\n        \n        depth_pred = depth_pred_raw\n        torch.cuda.empty_cache()     \n\n        # ----------------- Post processing -----------------\n        depth_pred = (depth_pred * (max_value - min_value) + min_value)\n        depth_pred_numpy = depth_pred.detach().cpu().numpy().squeeze()\n        depth_pred_numpy = cv2.resize(depth_pred_numpy.astype(float), (original_W, original_H))\n        depth_pred_numpy = depth_pred_numpy.clip(min=0.)\n        depth_pred_numpy_origin=depth_pred_numpy.copy()\n        depth_pred_norm = (depth_pred_numpy - depth_pred_numpy.min()) / (depth_pred_numpy.max() - depth_pred_numpy.min())\n        depth_pred_colored = colorize_depth_maps(\n            depth_pred_norm, 0, 1, cmap=\"Spectral\"\n        ).squeeze()  # [3, H, W], value in (0, 1)\n        depth_pred_colored = (depth_pred_colored * 255).astype(np.uint8)\n        depth_pred_colored = Image.fromarray(chw2hwc(depth_pred_colored))\n\n        return DepthPipelineOutput(\n            depth_np = depth_pred_numpy,\n            depth_norm = depth_pred_norm,\n            depth_colored = depth_pred_colored,\n            depth_pred_numpy_origin=depth_pred_numpy_origin\n        )\n\n    def get_timesteps(self, num_inference_steps, strength, device):\n        # get the original timestep using init_timestep\n        init_timestep = min(int(num_inference_steps * strength), num_inference_steps)\n        t_start = max(num_inference_steps - init_timestep, 0)\n\n        timesteps = self.scheduler.timesteps[t_start * self.scheduler.order :]\n\n        return timesteps, num_inference_steps - t_start\n        \n    @torch.no_grad()\n    def single_infer(self,\n        image: torch.Tensor,\n        depth: torch.Tensor,\n        mask: torch.Tensor,\n        num_inference_steps: int,\n        show_pbar: bool,\n        guidance_scale: float,\n        encoder_hidden_states: torch.Tensor,\n        reference_control_writer: ReferenceAttentionControl,\n        reference_control_reader: ReferenceAttentionControl,\n        strength: float,\n        blend: bool,\n        normalize_scale: float,\n        generator=None,\n    ):\n        do_classifier_free_guidance = True\n        try:\n            device = self.image_enc.device\n        except:\n            import pdb; pdb.set_trace()\n        h, w = image.shape[-2:]\n\n        # Set timesteps: inherit from the diffuison pipeline\n        self.scheduler.set_timesteps(num_inference_steps, device=device)\n        timesteps, _ = self.get_timesteps(num_inference_steps, strength, device)\n        \n        # Encode image\n        rgb_latent = self.encode_RGB(image) #\n\n\n        min_value = depth[mask == 0].min()\n        max_value = depth[mask == 0].max()\n\n        depth = Disparity_Normalization_mask_scale(depth, min_value, max_value, scale=normalize_scale)\n        masked_depth = depth.clone()\n        masked_depth[mask == 1] = 0\n\n        masked_depth = get_filled_depth(masked_depth.squeeze().cpu().numpy(), mask.squeeze().cpu().numpy(),method='linear')\n        masked_depth = torch.from_numpy(masked_depth).unsqueeze(0).unsqueeze(0).float().to(device)\n        masked_depth = masked_depth.repeat(1,3,1,1)\n        masked_depth_latent = self.encode_depth(masked_depth)\n        depth = depth.repeat(1,3,1,1)\n        depth_latent = self.encode_depth(depth)\n\n        # process mask\n        mask_latents=self.encode_RGB(mask.repeat(1,3,1,1).to(rgb_latent.dtype) * 2 - 1)\n        mask_down = torch.nn.functional.interpolate(mask, size=(h//8, w//8),mode='nearest')\n        noise = torch.randn_like(depth_latent)\n  \n        if strength < 1.:\n            noisy_depth_latent = self.scheduler.add_noise(depth_latent, noise, timesteps[:1])\n        else:\n            noisy_depth_latent = torch.randn(\n                depth_latent.shape,\n                device=device,\n                dtype=depth_latent.dtype,\n                generator=generator,\n            )\n        \n        # Denoising loop\n        if show_pbar:\n            iterable = tqdm(\n                enumerate(timesteps),\n                total=len(timesteps),\n                leave=False,\n                desc=\" \" * 4 + \"Diffusion denoising\",\n            )\n        else:\n            iterable = enumerate(timesteps)\n        \n        for i, t in iterable:\n            if i == 0:\n                self.reference_unet(\n                    rgb_latent.repeat(\n                        (2 if do_classifier_free_guidance else 1), 1, 1, 1\n                    ),\n                    torch.zeros_like(t),\n                    encoder_hidden_states=encoder_hidden_states,\n                    return_dict=False,\n                )\n                reference_control_reader.update(reference_control_writer)\n            unet_input = torch.cat([noisy_depth_latent, mask_latents, masked_depth_latent], dim=1)\n            noise_pred = self.denoising_unet(\n                unet_input.repeat(\n                        (2 if do_classifier_free_guidance else 1), 1, 1, 1\n                    ).to(dtype=self.denoising_unet.dtype), t, encoder_hidden_states=encoder_hidden_states\n            ).sample  # [B, 4, h, w]\n            if do_classifier_free_guidance:\n                noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)\n                noise_pred = noise_pred_uncond + guidance_scale * (\n                            noise_pred_text - noise_pred_uncond\n                        )\n            # compute the previous noisy sample x_t -> x_t-1\n            noisy_depth_latent = self.scheduler.step(noise_pred, t, noisy_depth_latent).prev_sample.to(self.dtype)\n            if blend:\n            # Blend diffusion https://arxiv.org/abs/2111.14818\n                if i < len(timesteps) - 1:\n                    noise_timestep = timesteps[i + 1]\n                    depth_latent_step = self.scheduler.add_noise(\n                        depth_latent, noise, torch.tensor([noise_timestep])\n                    )\n                    mask_blend = mask_down.repeat(1,4,1,1).float()\n                    noisy_depth_latent = (1 - mask_blend) * depth_latent_step + mask_blend * noisy_depth_latent\n\n        reference_control_reader.clear()\n        reference_control_writer.clear()\n        torch.cuda.empty_cache()\n        depth = self.decode_depth(noisy_depth_latent)\n        # depth = torch.clip(depth, -1.0, 1.0)\n\n        # shift\n        depth = (depth + normalize_scale) / (normalize_scale*2)\n        return depth, max_value, min_value\n        \n    \n    def encode_RGB(self, rgb_in: torch.Tensor) -> torch.Tensor:\n        \"\"\"\n        Encode RGB image into latent.\n\n        Args:\n            rgb_in (`torch.Tensor`):\n                Input RGB image to be encoded.\n\n        Returns:\n            `torch.Tensor`: Image latent.\n        \"\"\"\n\n        \n        # encode\n        h = self.vae.encoder(rgb_in)\n\n        moments = self.vae.quant_conv(h)\n        mean, logvar = torch.chunk(moments, 2, dim=1)\n        rgb_latent = mean * self.rgb_latent_scale_factor\n        \n        return rgb_latent\n    \n    def decode_depth(self, depth_latent: torch.Tensor) -> torch.Tensor:\n        \"\"\"\n        Decode depth latent into depth map.\n\n        Args:\n            depth_latent (`torch.Tensor`):\n                Depth latent to be decoded.\n\n        Returns:\n            `torch.Tensor`: Decoded depth map.\n        \"\"\"\n        depth_latent = depth_latent / self.depth_latent_scale_factor\n        \n        depth_latent = depth_latent\n        try:\n            z = self.vae.post_quant_conv(depth_latent)\n            stacked = self.vae.decoder(z)\n        except:\n            stacked = self.vae.decode(depth_latent)\n        # mean of output channels\n        depth_mean = stacked.mean(dim=1, keepdim=True)\n        return depth_mean\n\n\n    def encode_depth(self, depth_latent: torch.Tensor) -> torch.Tensor:\n        \"\"\"\n        Decode depth latent into depth map.\n\n        Args:\n            depth_latent (`torch.Tensor`):\n                Depth latent to be decoded.\n\n        Returns:\n            `torch.Tensor`: Decoded depth map.\n        \"\"\"\n        # scale latent\n        h_disp = self.vae.encoder(depth_latent)\n        moments_disp = self.vae.quant_conv(h_disp)\n        mean_disp, logvar_disp = torch.chunk(moments_disp, 2, dim=1)\n        disp_latents = mean_disp *self.depth_latent_scale_factor\n        return disp_latents\n\n\n\n"
  },
  {
    "path": "scripts/infer.sh",
    "content": "#!/usr/bin/env bash\nset -e\nset -x\npretrained_model_name_or_path='./checkpoints/marigold-depth-v1-0'\nimage_encoder_path='./checkpoints/CLIP-ViT-H-14-laion2B-s32B-b79K'\ndenoising_unet_path='./checkpoints/DepthLab/denoising_unet.pth'\nreference_unet_path='./checkpoints/DepthLab/reference_unet.pth'\nmapping_path='./checkpoints/DepthLab/mapping_layer.pth'\n\nexport CUDA_VISIBLE_DEVICES=0\ncd ..\npython infer.py  \\\n    --seed 1234 \\\n    --denoise_steps 50 \\\n    --processing_res 768 \\\n    --normalize_scale 1 \\\n    --strength 0.8 \\\n    --pretrained_model_name_or_path $pretrained_model_name_or_path --image_encoder_path $image_encoder_path \\\n    --denoising_unet_path $denoising_unet_path \\\n    --reference_unet_path $reference_unet_path \\\n    --mapping_path $mapping_path \\\n    --output_dir 'output/in-the-wild_example' \\\n    --input_image_paths test_cases/RGB.JPG \\\n    --known_depth_paths test_cases/know_depth.npy \\\n    --masks_paths test_cases/mask.npy \\\n    --blend"
  },
  {
    "path": "src/models/attention.py",
    "content": "# Adapted from https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention.py\n\nfrom typing import Any, Dict, Optional\n\nimport torch\nfrom diffusers.models.attention import AdaLayerNorm, Attention, FeedForward\nfrom diffusers.models.embeddings import SinusoidalPositionalEmbedding\nfrom einops import rearrange\nfrom torch import nn\n\n\nclass BasicTransformerBlock(nn.Module):\n    r\"\"\"\n    A basic Transformer block.\n\n    Parameters:\n        dim (`int`): The number of channels in the input and output.\n        num_attention_heads (`int`): The number of heads to use for multi-head attention.\n        attention_head_dim (`int`): The number of channels in each head.\n        dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.\n        cross_attention_dim (`int`, *optional*): The size of the encoder_hidden_states vector for cross attention.\n        activation_fn (`str`, *optional*, defaults to `\"geglu\"`): Activation function to be used in feed-forward.\n        num_embeds_ada_norm (:\n            obj: `int`, *optional*): The number of diffusion steps used during training. See `Transformer2DModel`.\n        attention_bias (:\n            obj: `bool`, *optional*, defaults to `False`): Configure if the attentions should contain a bias parameter.\n        only_cross_attention (`bool`, *optional*):\n            Whether to use only cross-attention layers. In this case two cross attention layers are used.\n        double_self_attention (`bool`, *optional*):\n            Whether to use two self-attention layers. In this case no cross attention layers are used.\n        upcast_attention (`bool`, *optional*):\n            Whether to upcast the attention computation to float32. This is useful for mixed precision training.\n        norm_elementwise_affine (`bool`, *optional*, defaults to `True`):\n            Whether to use learnable elementwise affine parameters for normalization.\n        norm_type (`str`, *optional*, defaults to `\"layer_norm\"`):\n            The normalization layer to use. Can be `\"layer_norm\"`, `\"ada_norm\"` or `\"ada_norm_zero\"`.\n        final_dropout (`bool` *optional*, defaults to False):\n            Whether to apply a final dropout after the last feed-forward layer.\n        attention_type (`str`, *optional*, defaults to `\"default\"`):\n            The type of attention to use. Can be `\"default\"` or `\"gated\"` or `\"gated-text-image\"`.\n        positional_embeddings (`str`, *optional*, defaults to `None`):\n            The type of positional embeddings to apply to.\n        num_positional_embeddings (`int`, *optional*, defaults to `None`):\n            The maximum number of positional embeddings to apply.\n    \"\"\"\n\n    def __init__(\n        self,\n        dim: int,\n        num_attention_heads: int,\n        attention_head_dim: int,\n        dropout=0.0,\n        cross_attention_dim: Optional[int] = None,\n        activation_fn: str = \"geglu\",\n        num_embeds_ada_norm: Optional[int] = None,\n        attention_bias: bool = False,\n        only_cross_attention: bool = False,\n        double_self_attention: bool = False,\n        upcast_attention: bool = False,\n        norm_elementwise_affine: bool = True,\n        norm_type: str = \"layer_norm\",  # 'layer_norm', 'ada_norm', 'ada_norm_zero', 'ada_norm_single'\n        norm_eps: float = 1e-5,\n        final_dropout: bool = False,\n        attention_type: str = \"default\",\n        positional_embeddings: Optional[str] = None,\n        num_positional_embeddings: Optional[int] = None,\n    ):\n        super().__init__()\n        self.only_cross_attention = only_cross_attention\n\n        self.use_ada_layer_norm_zero = (\n            num_embeds_ada_norm is not None\n        ) and norm_type == \"ada_norm_zero\"\n        self.use_ada_layer_norm = (\n            num_embeds_ada_norm is not None\n        ) and norm_type == \"ada_norm\"\n        self.use_ada_layer_norm_single = norm_type == \"ada_norm_single\"\n        self.use_layer_norm = norm_type == \"layer_norm\"\n\n        if norm_type in (\"ada_norm\", \"ada_norm_zero\") and num_embeds_ada_norm is None:\n            raise ValueError(\n                f\"`norm_type` is set to {norm_type}, but `num_embeds_ada_norm` is not defined. Please make sure to\"\n                f\" define `num_embeds_ada_norm` if setting `norm_type` to {norm_type}.\"\n            )\n\n        if positional_embeddings and (num_positional_embeddings is None):\n            raise ValueError(\n                \"If `positional_embedding` type is defined, `num_positition_embeddings` must also be defined.\"\n            )\n\n        if positional_embeddings == \"sinusoidal\":\n            self.pos_embed = SinusoidalPositionalEmbedding(\n                dim, max_seq_length=num_positional_embeddings\n            )\n        else:\n            self.pos_embed = None\n\n        # Define 3 blocks. Each block has its own normalization layer.\n        # 1. Self-Attn\n        if self.use_ada_layer_norm:\n            self.norm1 = AdaLayerNorm(dim, num_embeds_ada_norm)\n        elif self.use_ada_layer_norm_zero:\n            self.norm1 = AdaLayerNormZero(dim, num_embeds_ada_norm)\n        else:\n            self.norm1 = nn.LayerNorm(\n                dim, elementwise_affine=norm_elementwise_affine, eps=norm_eps\n            )\n\n        self.attn1 = Attention(\n            query_dim=dim,\n            heads=num_attention_heads,\n            dim_head=attention_head_dim,\n            dropout=dropout,\n            bias=attention_bias,\n            cross_attention_dim=cross_attention_dim if only_cross_attention else None,\n            upcast_attention=upcast_attention,\n        )\n\n        # 2. Cross-Attn\n        if cross_attention_dim is not None or double_self_attention:\n            # We currently only use AdaLayerNormZero for self attention where there will only be one attention block.\n            # I.e. the number of returned modulation chunks from AdaLayerZero would not make sense if returned during\n            # the second cross attention block.\n            self.norm2 = (\n                AdaLayerNorm(dim, num_embeds_ada_norm)\n                if self.use_ada_layer_norm\n                else nn.LayerNorm(\n                    dim, elementwise_affine=norm_elementwise_affine, eps=norm_eps\n                )\n            )\n            self.attn2 = Attention(\n                query_dim=dim,\n                cross_attention_dim=cross_attention_dim\n                if not double_self_attention\n                else None,\n                heads=num_attention_heads,\n                dim_head=attention_head_dim,\n                dropout=dropout,\n                bias=attention_bias,\n                upcast_attention=upcast_attention,\n            )  # is self-attn if encoder_hidden_states is none\n        else:\n            self.norm2 = None\n            self.attn2 = None\n\n        # 3. Feed-forward\n        if not self.use_ada_layer_norm_single:\n            self.norm3 = nn.LayerNorm(\n                dim, elementwise_affine=norm_elementwise_affine, eps=norm_eps\n            )\n\n        self.ff = FeedForward(\n            dim,\n            dropout=dropout,\n            activation_fn=activation_fn,\n            final_dropout=final_dropout,\n        )\n\n        # 4. Fuser\n        if attention_type == \"gated\" or attention_type == \"gated-text-image\":\n            self.fuser = GatedSelfAttentionDense(\n                dim, cross_attention_dim, num_attention_heads, attention_head_dim\n            )\n\n        # 5. Scale-shift for PixArt-Alpha.\n        if self.use_ada_layer_norm_single:\n            self.scale_shift_table = nn.Parameter(torch.randn(6, dim) / dim**0.5)\n\n        # let chunk size default to None\n        self._chunk_size = None\n        self._chunk_dim = 0\n\n    def set_chunk_feed_forward(self, chunk_size: Optional[int], dim: int = 0):\n        # Sets chunk feed-forward\n        self._chunk_size = chunk_size\n        self._chunk_dim = dim\n\n    def forward(\n        self,\n        hidden_states: torch.FloatTensor,\n        attention_mask: Optional[torch.FloatTensor] = None,\n        encoder_hidden_states: Optional[torch.FloatTensor] = None,\n        encoder_attention_mask: Optional[torch.FloatTensor] = None,\n        timestep: Optional[torch.LongTensor] = None,\n        cross_attention_kwargs: Dict[str, Any] = None,\n        class_labels: Optional[torch.LongTensor] = None,\n    ) -> torch.FloatTensor:\n        # Notice that normalization is always applied before the real computation in the following blocks.\n        # 0. Self-Attention\n        batch_size = hidden_states.shape[0]\n\n        if self.use_ada_layer_norm:\n            norm_hidden_states = self.norm1(hidden_states, timestep)\n        elif self.use_ada_layer_norm_zero:\n            norm_hidden_states, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.norm1(\n                hidden_states, timestep, class_labels, hidden_dtype=hidden_states.dtype\n            )\n        elif self.use_layer_norm:\n            norm_hidden_states = self.norm1(hidden_states)\n        elif self.use_ada_layer_norm_single:\n            shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = (\n                self.scale_shift_table[None] + timestep.reshape(batch_size, 6, -1)\n            ).chunk(6, dim=1)\n            norm_hidden_states = self.norm1(hidden_states)\n            norm_hidden_states = norm_hidden_states * (1 + scale_msa) + shift_msa\n            norm_hidden_states = norm_hidden_states.squeeze(1)\n        else:\n            raise ValueError(\"Incorrect norm used\")\n\n        if self.pos_embed is not None:\n            norm_hidden_states = self.pos_embed(norm_hidden_states)\n\n        # 1. Retrieve lora scale.\n        lora_scale = (\n            cross_attention_kwargs.get(\"scale\", 1.0)\n            if cross_attention_kwargs is not None\n            else 1.0\n        )\n\n        # 2. Prepare GLIGEN inputs\n        cross_attention_kwargs = (\n            cross_attention_kwargs.copy() if cross_attention_kwargs is not None else {}\n        )\n        gligen_kwargs = cross_attention_kwargs.pop(\"gligen\", None)\n\n        attn_output = self.attn1(\n            norm_hidden_states,\n            encoder_hidden_states=encoder_hidden_states\n            if self.only_cross_attention\n            else None,\n            attention_mask=attention_mask,\n            **cross_attention_kwargs,\n        )\n        if self.use_ada_layer_norm_zero:\n            attn_output = gate_msa.unsqueeze(1) * attn_output\n        elif self.use_ada_layer_norm_single:\n            attn_output = gate_msa * attn_output\n\n        hidden_states = attn_output + hidden_states\n        if hidden_states.ndim == 4:\n            hidden_states = hidden_states.squeeze(1)\n\n        # 2.5 GLIGEN Control\n        if gligen_kwargs is not None:\n            hidden_states = self.fuser(hidden_states, gligen_kwargs[\"objs\"])\n\n        # 3. Cross-Attention\n        if self.attn2 is not None:\n            if self.use_ada_layer_norm:\n                norm_hidden_states = self.norm2(hidden_states, timestep)\n            elif self.use_ada_layer_norm_zero or self.use_layer_norm:\n                norm_hidden_states = self.norm2(hidden_states)\n            elif self.use_ada_layer_norm_single:\n                # For PixArt norm2 isn't applied here:\n                # https://github.com/PixArt-alpha/PixArt-alpha/blob/0f55e922376d8b797edd44d25d0e7464b260dcab/diffusion/model/nets/PixArtMS.py#L70C1-L76C103\n                norm_hidden_states = hidden_states\n            else:\n                raise ValueError(\"Incorrect norm\")\n\n            if self.pos_embed is not None and self.use_ada_layer_norm_single is False:\n                norm_hidden_states = self.pos_embed(norm_hidden_states)\n\n            attn_output = self.attn2(\n                norm_hidden_states,\n                encoder_hidden_states=encoder_hidden_states,\n                attention_mask=encoder_attention_mask,\n                **cross_attention_kwargs,\n            )\n            hidden_states = attn_output + hidden_states\n\n        # 4. Feed-forward\n        if not self.use_ada_layer_norm_single:\n            norm_hidden_states = self.norm3(hidden_states)\n\n        if self.use_ada_layer_norm_zero:\n            norm_hidden_states = (\n                norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None]\n            )\n\n        if self.use_ada_layer_norm_single:\n            norm_hidden_states = self.norm2(hidden_states)\n            norm_hidden_states = norm_hidden_states * (1 + scale_mlp) + shift_mlp\n\n        ff_output = self.ff(norm_hidden_states, scale=lora_scale)\n\n        if self.use_ada_layer_norm_zero:\n            ff_output = gate_mlp.unsqueeze(1) * ff_output\n        elif self.use_ada_layer_norm_single:\n            ff_output = gate_mlp * ff_output\n\n        hidden_states = ff_output + hidden_states\n        if hidden_states.ndim == 4:\n            hidden_states = hidden_states.squeeze(1)\n\n        return hidden_states\n\n\nclass TemporalBasicTransformerBlock(nn.Module):\n    def __init__(\n        self,\n        dim: int,\n        num_attention_heads: int,\n        attention_head_dim: int,\n        dropout=0.0,\n        cross_attention_dim: Optional[int] = None,\n        activation_fn: str = \"geglu\",\n        num_embeds_ada_norm: Optional[int] = None,\n        attention_bias: bool = False,\n        only_cross_attention: bool = False,\n        upcast_attention: bool = False,\n        unet_use_cross_frame_attention=None,\n        unet_use_temporal_attention=None,\n    ):\n        super().__init__()\n        self.only_cross_attention = only_cross_attention\n        self.use_ada_layer_norm = num_embeds_ada_norm is not None\n        self.unet_use_cross_frame_attention = unet_use_cross_frame_attention\n        self.unet_use_temporal_attention = unet_use_temporal_attention\n\n        # SC-Attn\n        self.attn1 = Attention(\n            query_dim=dim,\n            heads=num_attention_heads,\n            dim_head=attention_head_dim,\n            dropout=dropout,\n            bias=attention_bias,\n            upcast_attention=upcast_attention,\n        )\n        self.norm1 = (\n            AdaLayerNorm(dim, num_embeds_ada_norm)\n            if self.use_ada_layer_norm\n            else nn.LayerNorm(dim)\n        )\n\n        # Cross-Attn\n        if cross_attention_dim is not None:\n            self.attn2 = Attention(\n                query_dim=dim,\n                cross_attention_dim=cross_attention_dim,\n                heads=num_attention_heads,\n                dim_head=attention_head_dim,\n                dropout=dropout,\n                bias=attention_bias,\n                upcast_attention=upcast_attention,\n            )\n        else:\n            self.attn2 = None\n\n        if cross_attention_dim is not None:\n            self.norm2 = (\n                AdaLayerNorm(dim, num_embeds_ada_norm)\n                if self.use_ada_layer_norm\n                else nn.LayerNorm(dim)\n            )\n        else:\n            self.norm2 = None\n\n        # Feed-forward\n        self.ff = FeedForward(dim, dropout=dropout, activation_fn=activation_fn)\n        self.norm3 = nn.LayerNorm(dim)\n        self.use_ada_layer_norm_zero = False\n\n        # Temp-Attn\n        assert unet_use_temporal_attention is not None\n        if unet_use_temporal_attention:\n            self.attn_temp = Attention(\n                query_dim=dim,\n                heads=num_attention_heads,\n                dim_head=attention_head_dim,\n                dropout=dropout,\n                bias=attention_bias,\n                upcast_attention=upcast_attention,\n            )\n            nn.init.zeros_(self.attn_temp.to_out[0].weight.data)\n            self.norm_temp = (\n                AdaLayerNorm(dim, num_embeds_ada_norm)\n                if self.use_ada_layer_norm\n                else nn.LayerNorm(dim)\n            )\n\n    def forward(\n        self,\n        hidden_states,\n        encoder_hidden_states=None,\n        timestep=None,\n        attention_mask=None,\n        video_length=None,\n    ):\n        norm_hidden_states = (\n            self.norm1(hidden_states, timestep)\n            if self.use_ada_layer_norm\n            else self.norm1(hidden_states)\n        )\n\n        if self.unet_use_cross_frame_attention:\n            hidden_states = (\n                self.attn1(\n                    norm_hidden_states,\n                    attention_mask=attention_mask,\n                    video_length=video_length,\n                )\n                + hidden_states\n            )\n        else:\n            hidden_states = (\n                self.attn1(norm_hidden_states, attention_mask=attention_mask)\n                + hidden_states\n            )\n\n        if self.attn2 is not None:\n            # Cross-Attention\n            norm_hidden_states = (\n                self.norm2(hidden_states, timestep)\n                if self.use_ada_layer_norm\n                else self.norm2(hidden_states)\n            )\n            hidden_states = (\n                self.attn2(\n                    norm_hidden_states,\n                    encoder_hidden_states=encoder_hidden_states,\n                    attention_mask=attention_mask,\n                )\n                + hidden_states\n            )\n\n        # Feed-forward\n        hidden_states = self.ff(self.norm3(hidden_states)) + hidden_states\n\n        # Temporal-Attention\n        if self.unet_use_temporal_attention:\n            d = hidden_states.shape[1]\n            hidden_states = rearrange(\n                hidden_states, \"(b f) d c -> (b d) f c\", f=video_length\n            )\n            norm_hidden_states = (\n                self.norm_temp(hidden_states, timestep)\n                if self.use_ada_layer_norm\n                else self.norm_temp(hidden_states)\n            )\n            hidden_states = self.attn_temp(norm_hidden_states) + hidden_states\n            hidden_states = rearrange(hidden_states, \"(b d) f c -> (b f) d c\", d=d)\n\n        return hidden_states\n"
  },
  {
    "path": "src/models/mutual_self_attention.py",
    "content": "# Adapted from https://github.com/magic-research/magic-animate/blob/main/magicanimate/models/mutual_self_attention.py\nfrom typing import Any, Dict, Optional\n\nimport torch\nfrom einops import rearrange\n\nfrom .attention import TemporalBasicTransformerBlock\n\nfrom .attention import BasicTransformerBlock\n\n\ndef torch_dfs(model: torch.nn.Module):\n    result = [model]\n    for child in model.children():\n        result += torch_dfs(child)\n    return result\n\n\nclass ReferenceAttentionControl:\n    def __init__(\n        self,\n        unet,\n        mode=\"write\",\n        do_classifier_free_guidance=False,\n        attention_auto_machine_weight=float(\"inf\"),\n        gn_auto_machine_weight=1.0,\n        style_fidelity=1.0,\n        reference_attn=True,\n        reference_adain=False,\n        fusion_blocks=\"midup\",\n        batch_size=1,\n    ) -> None:\n        # 10. Modify self attention and group norm\n        self.unet = unet\n        assert mode in [\"read\", \"write\"]\n        assert fusion_blocks in [\"midup\", \"full\"]\n        self.reference_attn = reference_attn\n        self.reference_adain = reference_adain\n        self.fusion_blocks = fusion_blocks\n        self.register_reference_hooks(\n            mode,\n            do_classifier_free_guidance,\n            attention_auto_machine_weight,\n            gn_auto_machine_weight,\n            style_fidelity,\n            reference_attn,\n            reference_adain,\n            fusion_blocks,\n            batch_size=batch_size,\n        )\n\n    def register_reference_hooks(\n        self,\n        mode,\n        do_classifier_free_guidance,\n        attention_auto_machine_weight,\n        gn_auto_machine_weight,\n        style_fidelity,\n        reference_attn,\n        reference_adain,\n        dtype=torch.float16,\n        batch_size=1,\n        num_images_per_prompt=1,\n        device=torch.device(\"cpu\"),\n        fusion_blocks=\"midup\",\n    ):\n        MODE = mode\n        do_classifier_free_guidance = do_classifier_free_guidance\n        attention_auto_machine_weight = attention_auto_machine_weight\n        gn_auto_machine_weight = gn_auto_machine_weight\n        style_fidelity = style_fidelity\n        reference_attn = reference_attn\n        reference_adain = reference_adain\n        fusion_blocks = fusion_blocks\n        num_images_per_prompt = num_images_per_prompt\n        dtype = dtype\n        if do_classifier_free_guidance:\n            uc_mask = (\n                torch.Tensor(\n                    [1] * batch_size * num_images_per_prompt * 16\n                    + [0] * batch_size * num_images_per_prompt * 16\n                )\n                .to(device)\n                .bool()\n            )\n        else:\n            uc_mask = (\n                torch.Tensor([0] * batch_size * num_images_per_prompt * 2)\n                .to(device)\n                .bool()\n            )\n\n        def hacked_basic_transformer_inner_forward(\n            self,\n            hidden_states: torch.FloatTensor,\n            attention_mask: Optional[torch.FloatTensor] = None,\n            encoder_hidden_states: Optional[torch.FloatTensor] = None,\n            encoder_attention_mask: Optional[torch.FloatTensor] = None,\n            timestep: Optional[torch.LongTensor] = None,\n            cross_attention_kwargs: Dict[str, Any] = None,\n            class_labels: Optional[torch.LongTensor] = None,\n            video_length=None,\n        ):\n            if self.use_ada_layer_norm:  # False\n                norm_hidden_states = self.norm1(hidden_states, timestep)\n            elif self.use_ada_layer_norm_zero:\n                (\n                    norm_hidden_states,\n                    gate_msa,\n                    shift_mlp,\n                    scale_mlp,\n                    gate_mlp,\n                ) = self.norm1(\n                    hidden_states,\n                    timestep,\n                    class_labels,\n                    hidden_dtype=hidden_states.dtype,\n                )\n            else:\n                norm_hidden_states = self.norm1(hidden_states)\n\n            # 1. Self-Attention\n            # self.only_cross_attention = False\n            cross_attention_kwargs = (\n                cross_attention_kwargs if cross_attention_kwargs is not None else {}\n            )\n            if self.only_cross_attention:\n                attn_output = self.attn1(\n                    norm_hidden_states,\n                    encoder_hidden_states=encoder_hidden_states\n                    if self.only_cross_attention\n                    else None,\n                    attention_mask=attention_mask,\n                    **cross_attention_kwargs,\n                )\n            else:\n                if MODE == \"write\":\n                    self.bank.append(norm_hidden_states.clone())\n                    attn_output = self.attn1(\n                        norm_hidden_states,\n                        encoder_hidden_states=encoder_hidden_states\n                        if self.only_cross_attention\n                        else None,\n                        attention_mask=attention_mask,\n                        **cross_attention_kwargs,\n                    )\n                if MODE == \"read\":\n                    # if len(self.bank)>0:\n                    # import ipdb;ipdb.set_trace()\n                    # bank_fea = [ d for d in self.bank]\n                    bank_fea = [\n                        rearrange(\n                            d.unsqueeze(1).repeat(1, 1, 1, 1),\n                            \"b t l c -> (b t) l c\",\n                        )\n                        for d in self.bank\n                    ]\n                    modify_norm_hidden_states = torch.cat(\n                        [norm_hidden_states] + bank_fea, dim=1\n                    )\n                    hidden_states_uc = (\n                        self.attn1(\n                            norm_hidden_states,\n                            encoder_hidden_states=modify_norm_hidden_states,\n                            attention_mask=attention_mask,\n                        )\n                        + hidden_states\n                    )\n                    if do_classifier_free_guidance:\n                        hidden_states_c = hidden_states_uc.clone()\n                        _uc_mask = uc_mask.clone()\n                        if hidden_states.shape[0] != _uc_mask.shape[0]:\n                            _uc_mask = (\n                                torch.Tensor(\n                                    [1] * (hidden_states.shape[0] // 2)\n                                    + [0] * (hidden_states.shape[0] // 2)\n                                )\n                                .to(device)\n                                .bool()\n                            )\n                        hidden_states_c[_uc_mask] = (\n                            self.attn1(\n                                norm_hidden_states[_uc_mask],\n                                encoder_hidden_states=norm_hidden_states[_uc_mask],\n                                attention_mask=attention_mask,\n                            )\n                            + hidden_states[_uc_mask]\n                        )\n                        hidden_states = hidden_states_c.clone()\n                    else:\n                        hidden_states = hidden_states_uc\n                    if self.attn2 is not None:\n                        # Cross-Attention\n                        norm_hidden_states = (\n                            self.norm2(hidden_states, timestep)\n                            if self.use_ada_layer_norm\n                            else self.norm2(hidden_states)\n                        )\n                        hidden_states = (\n                            self.attn2(\n                                norm_hidden_states,\n                                encoder_hidden_states=encoder_hidden_states,\n                                attention_mask=attention_mask,\n                            )\n                            + hidden_states\n                        )\n\n                    # Feed-forward\n                    hidden_states = self.ff(self.norm3(hidden_states)) + hidden_states\n                    return hidden_states\n            # import ipdb;ipdb.set_trace()\n            if self.use_ada_layer_norm_zero:\n                attn_output = gate_msa.unsqueeze(1) * attn_output\n            try:\n                hidden_states = attn_output + hidden_states\n            except:\n                import ipdb;ipdb.set_trace()\n            if self.attn2 is not None:\n                norm_hidden_states = (\n                    self.norm2(hidden_states, timestep)\n                    if self.use_ada_layer_norm\n                    else self.norm2(hidden_states)\n                )\n\n                # 2. Cross-Attention\n                attn_output = self.attn2(\n                    norm_hidden_states,\n                    encoder_hidden_states=encoder_hidden_states,\n                    attention_mask=encoder_attention_mask,\n                    **cross_attention_kwargs,\n                )\n                hidden_states = attn_output + hidden_states\n\n            # 3. Feed-forward\n            norm_hidden_states = self.norm3(hidden_states)\n\n            if self.use_ada_layer_norm_zero:\n                norm_hidden_states = (\n                    norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None]\n                )\n\n            ff_output = self.ff(norm_hidden_states)\n\n            if self.use_ada_layer_norm_zero:\n                ff_output = gate_mlp.unsqueeze(1) * ff_output\n\n            hidden_states = ff_output + hidden_states\n\n            return hidden_states\n\n        if self.reference_attn:\n            if self.fusion_blocks == \"midup\":\n                attn_modules = [\n                    module\n                    for module in (\n                        torch_dfs(self.unet.mid_block) + torch_dfs(self.unet.up_blocks)\n                    )\n                    if isinstance(module, BasicTransformerBlock)\n                    or isinstance(module, TemporalBasicTransformerBlock)\n                ]\n            elif self.fusion_blocks == \"full\":\n                attn_modules = [\n                    module\n                    for module in torch_dfs(self.unet)\n                    if isinstance(module, BasicTransformerBlock)\n                    or isinstance(module, TemporalBasicTransformerBlock)\n                ]\n            attn_modules = sorted(\n                attn_modules, key=lambda x: -x.norm1.normalized_shape[0]\n            )\n\n            for i, module in enumerate(attn_modules):\n                module._original_inner_forward = module.forward\n                if isinstance(module, BasicTransformerBlock):\n                    module.forward = hacked_basic_transformer_inner_forward.__get__(\n                        module, BasicTransformerBlock\n                    )\n                if isinstance(module, TemporalBasicTransformerBlock):\n                    module.forward = hacked_basic_transformer_inner_forward.__get__(\n                        module, TemporalBasicTransformerBlock\n                    )\n\n                module.bank = []\n                module.attn_weight = float(i) / float(len(attn_modules))\n\n    def update(self, writer, dtype=torch.float16):\n        if self.reference_attn:\n            if self.fusion_blocks == \"midup\":\n                reader_attn_modules = [\n                    module\n                    for module in (\n                        torch_dfs(self.unet.mid_block) + torch_dfs(self.unet.up_blocks)\n                    )\n                    if isinstance(module, TemporalBasicTransformerBlock)\n                ]\n                writer_attn_modules = [\n                    module\n                    for module in (\n                        torch_dfs(writer.unet.mid_block)\n                        + torch_dfs(writer.unet.up_blocks)\n                    )\n                    if isinstance(module, BasicTransformerBlock)\n                ]\n            elif self.fusion_blocks == \"full\":\n                reader_attn_modules = [\n                    module\n                    for module in torch_dfs(self.unet)\n                    if isinstance(module, BasicTransformerBlock)\n                ]\n                writer_attn_modules = [\n                    module\n                    for module in torch_dfs(writer.unet)\n                    if isinstance(module, BasicTransformerBlock)\n                ]\n            reader_attn_modules = sorted(\n                reader_attn_modules, key=lambda x: -x.norm1.normalized_shape[0]\n            )\n            writer_attn_modules = sorted(\n                writer_attn_modules, key=lambda x: -x.norm1.normalized_shape[0]\n            )\n            for r, w in zip(reader_attn_modules, writer_attn_modules):\n                r.bank = [v.clone().to(dtype) for v in w.bank]\n                # w.bank.clear()\n\n    def clear(self):\n        if self.reference_attn:\n            if self.fusion_blocks == \"midup\":\n                reader_attn_modules = [\n                    module\n                    for module in (\n                        torch_dfs(self.unet.mid_block) + torch_dfs(self.unet.up_blocks)\n                    )\n                    if isinstance(module, BasicTransformerBlock)\n                    or isinstance(module, TemporalBasicTransformerBlock)\n                ]\n            elif self.fusion_blocks == \"full\":\n                reader_attn_modules = [\n                    module\n                    for module in torch_dfs(self.unet)\n                    if isinstance(module, BasicTransformerBlock)\n                    or isinstance(module, TemporalBasicTransformerBlock)\n                ]\n            reader_attn_modules = sorted(\n                reader_attn_modules, key=lambda x: -x.norm1.normalized_shape[0]\n            )\n            for r in reader_attn_modules:\n                r.bank.clear()\n"
  },
  {
    "path": "src/models/projection.py",
    "content": "import torch\nimport torch.nn as nn\n\nclass My_proj(nn.Module):\n    def __init__(self, input=1024, dtype=torch.float32):\n        super(My_proj, self).__init__()\n        self.mapping_layer = nn.Linear(input, 1024)\n        self.dtype = dtype\n    \n    def forward(self, x):\n        x = self.mapping_layer(x)\n        return x"
  },
  {
    "path": "src/models/transformer_2d.py",
    "content": "# Adapted from https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/transformer_2d.py\nfrom dataclasses import dataclass\nfrom typing import Any, Dict, Optional\n\nimport torch\nfrom diffusers.configuration_utils import ConfigMixin, register_to_config\n# from diffusers.models.embeddings import CaptionProjection\nfrom diffusers.models.lora import LoRACompatibleConv, LoRACompatibleLinear\nfrom diffusers.models.modeling_utils import ModelMixin\nfrom diffusers.models.normalization import AdaLayerNormSingle\nfrom diffusers.utils import USE_PEFT_BACKEND, BaseOutput, deprecate, is_torch_version\nfrom torch import nn\n\nfrom .attention import BasicTransformerBlock\n\n\n@dataclass\nclass Transformer2DModelOutput(BaseOutput):\n    \"\"\"\n    The output of [`Transformer2DModel`].\n\n    Args:\n        sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` or `(batch size, num_vector_embeds - 1, num_latent_pixels)` if [`Transformer2DModel`] is discrete):\n            The hidden states output conditioned on the `encoder_hidden_states` input. If discrete, returns probability\n            distributions for the unnoised latent pixels.\n    \"\"\"\n\n    sample: torch.FloatTensor\n    ref_feature: torch.FloatTensor\n\n\nclass Transformer2DModel(ModelMixin, ConfigMixin):\n    \"\"\"\n    A 2D Transformer model for image-like data.\n\n    Parameters:\n        num_attention_heads (`int`, *optional*, defaults to 16): The number of heads to use for multi-head attention.\n        attention_head_dim (`int`, *optional*, defaults to 88): The number of channels in each head.\n        in_channels (`int`, *optional*):\n            The number of channels in the input and output (specify if the input is **continuous**).\n        num_layers (`int`, *optional*, defaults to 1): The number of layers of Transformer blocks to use.\n        dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.\n        cross_attention_dim (`int`, *optional*): The number of `encoder_hidden_states` dimensions to use.\n        sample_size (`int`, *optional*): The width of the latent images (specify if the input is **discrete**).\n            This is fixed during training since it is used to learn a number of position embeddings.\n        num_vector_embeds (`int`, *optional*):\n            The number of classes of the vector embeddings of the latent pixels (specify if the input is **discrete**).\n            Includes the class for the masked latent pixel.\n        activation_fn (`str`, *optional*, defaults to `\"geglu\"`): Activation function to use in feed-forward.\n        num_embeds_ada_norm ( `int`, *optional*):\n            The number of diffusion steps used during training. Pass if at least one of the norm_layers is\n            `AdaLayerNorm`. This is fixed during training since it is used to learn a number of embeddings that are\n            added to the hidden states.\n\n            During inference, you can denoise for up to but not more steps than `num_embeds_ada_norm`.\n        attention_bias (`bool`, *optional*):\n            Configure if the `TransformerBlocks` attention should contain a bias parameter.\n    \"\"\"\n\n    _supports_gradient_checkpointing = True\n\n    @register_to_config\n    def __init__(\n        self,\n        num_attention_heads: int = 16,\n        attention_head_dim: int = 88,\n        in_channels: Optional[int] = None,\n        out_channels: Optional[int] = None,\n        num_layers: int = 1,\n        dropout: float = 0.0,\n        norm_num_groups: int = 32,\n        cross_attention_dim: Optional[int] = None,\n        attention_bias: bool = False,\n        sample_size: Optional[int] = None,\n        num_vector_embeds: Optional[int] = None,\n        patch_size: Optional[int] = None,\n        activation_fn: str = \"geglu\",\n        num_embeds_ada_norm: Optional[int] = None,\n        use_linear_projection: bool = False,\n        only_cross_attention: bool = False,\n        double_self_attention: bool = False,\n        upcast_attention: bool = False,\n        norm_type: str = \"layer_norm\",\n        norm_elementwise_affine: bool = True,\n        norm_eps: float = 1e-5,\n        attention_type: str = \"default\",\n        caption_channels: int = None,\n    ):\n        super().__init__()\n        self.use_linear_projection = use_linear_projection\n        self.num_attention_heads = num_attention_heads\n        self.attention_head_dim = attention_head_dim\n        inner_dim = num_attention_heads * attention_head_dim\n\n        conv_cls = nn.Conv2d if USE_PEFT_BACKEND else LoRACompatibleConv\n        linear_cls = nn.Linear if USE_PEFT_BACKEND else LoRACompatibleLinear\n\n        # 1. Transformer2DModel can process both standard continuous images of shape `(batch_size, num_channels, width, height)` as well as quantized image embeddings of shape `(batch_size, num_image_vectors)`\n        # Define whether input is continuous or discrete depending on configuration\n        self.is_input_continuous = (in_channels is not None) and (patch_size is None)\n        self.is_input_vectorized = num_vector_embeds is not None\n        self.is_input_patches = in_channels is not None and patch_size is not None\n\n        if norm_type == \"layer_norm\" and num_embeds_ada_norm is not None:\n            deprecation_message = (\n                f\"The configuration file of this model: {self.__class__} is outdated. `norm_type` is either not set or\"\n                \" incorrectly set to `'layer_norm'`.Make sure to set `norm_type` to `'ada_norm'` in the config.\"\n                \" Please make sure to update the config accordingly as leaving `norm_type` might led to incorrect\"\n                \" results in future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it\"\n                \" would be very nice if you could open a Pull request for the `transformer/config.json` file\"\n            )\n            deprecate(\n                \"norm_type!=num_embeds_ada_norm\",\n                \"1.0.0\",\n                deprecation_message,\n                standard_warn=False,\n            )\n            norm_type = \"ada_norm\"\n\n        if self.is_input_continuous and self.is_input_vectorized:\n            raise ValueError(\n                f\"Cannot define both `in_channels`: {in_channels} and `num_vector_embeds`: {num_vector_embeds}. Make\"\n                \" sure that either `in_channels` or `num_vector_embeds` is None.\"\n            )\n        elif self.is_input_vectorized and self.is_input_patches:\n            raise ValueError(\n                f\"Cannot define both `num_vector_embeds`: {num_vector_embeds} and `patch_size`: {patch_size}. Make\"\n                \" sure that either `num_vector_embeds` or `num_patches` is None.\"\n            )\n        elif (\n            not self.is_input_continuous\n            and not self.is_input_vectorized\n            and not self.is_input_patches\n        ):\n            raise ValueError(\n                f\"Has to define `in_channels`: {in_channels}, `num_vector_embeds`: {num_vector_embeds}, or patch_size:\"\n                f\" {patch_size}. Make sure that `in_channels`, `num_vector_embeds` or `num_patches` is not None.\"\n            )\n\n        # 2. Define input layers\n        self.in_channels = in_channels\n\n        self.norm = torch.nn.GroupNorm(\n            num_groups=norm_num_groups,\n            num_channels=in_channels,\n            eps=1e-6,\n            affine=True,\n        )\n        if use_linear_projection:\n            self.proj_in = linear_cls(in_channels, inner_dim)\n        else:\n            self.proj_in = conv_cls(\n                in_channels, inner_dim, kernel_size=1, stride=1, padding=0\n            )\n\n        # 3. Define transformers blocks\n        self.transformer_blocks = nn.ModuleList(\n            [\n                BasicTransformerBlock(\n                    inner_dim,\n                    num_attention_heads,\n                    attention_head_dim,\n                    dropout=dropout,\n                    cross_attention_dim=cross_attention_dim,\n                    activation_fn=activation_fn,\n                    num_embeds_ada_norm=num_embeds_ada_norm,\n                    attention_bias=attention_bias,\n                    only_cross_attention=only_cross_attention,\n                    double_self_attention=double_self_attention,\n                    upcast_attention=upcast_attention,\n                    norm_type=norm_type,\n                    norm_elementwise_affine=norm_elementwise_affine,\n                    norm_eps=norm_eps,\n                    attention_type=attention_type,\n                )\n                for d in range(num_layers)\n            ]\n        )\n\n        # 4. Define output layers\n        self.out_channels = in_channels if out_channels is None else out_channels\n        # TODO: should use out_channels for continuous projections\n        if use_linear_projection:\n            self.proj_out = linear_cls(inner_dim, in_channels)\n        else:\n            self.proj_out = conv_cls(\n                inner_dim, in_channels, kernel_size=1, stride=1, padding=0\n            )\n\n        # 5. PixArt-Alpha blocks.\n        self.adaln_single = None\n        self.use_additional_conditions = False\n        if norm_type == \"ada_norm_single\":\n            self.use_additional_conditions = self.config.sample_size == 128\n            # TODO(Sayak, PVP) clean this, for now we use sample size to determine whether to use\n            # additional conditions until we find better name\n            self.adaln_single = AdaLayerNormSingle(\n                inner_dim, use_additional_conditions=self.use_additional_conditions\n            )\n\n        self.caption_projection = None\n        # if caption_channels is not None:\n        #     self.caption_projection = CaptionProjection(\n        #         in_features=caption_channels, hidden_size=inner_dim\n        #     )\n\n        self.gradient_checkpointing = False\n\n    def _set_gradient_checkpointing(self, module, value=False):\n        if hasattr(module, \"gradient_checkpointing\"):\n            module.gradient_checkpointing = value\n\n    def forward(\n        self,\n        hidden_states: torch.Tensor,\n        encoder_hidden_states: Optional[torch.Tensor] = None,\n        timestep: Optional[torch.LongTensor] = None,\n        added_cond_kwargs: Dict[str, torch.Tensor] = None,\n        class_labels: Optional[torch.LongTensor] = None,\n        cross_attention_kwargs: Dict[str, Any] = None,\n        attention_mask: Optional[torch.Tensor] = None,\n        encoder_attention_mask: Optional[torch.Tensor] = None,\n        return_dict: bool = True,\n    ):\n        \"\"\"\n        The [`Transformer2DModel`] forward method.\n\n        Args:\n            hidden_states (`torch.LongTensor` of shape `(batch size, num latent pixels)` if discrete, `torch.FloatTensor` of shape `(batch size, channel, height, width)` if continuous):\n                Input `hidden_states`.\n            encoder_hidden_states ( `torch.FloatTensor` of shape `(batch size, sequence len, embed dims)`, *optional*):\n                Conditional embeddings for cross attention layer. If not given, cross-attention defaults to\n                self-attention.\n            timestep ( `torch.LongTensor`, *optional*):\n                Used to indicate denoising step. Optional timestep to be applied as an embedding in `AdaLayerNorm`.\n            class_labels ( `torch.LongTensor` of shape `(batch size, num classes)`, *optional*):\n                Used to indicate class labels conditioning. Optional class labels to be applied as an embedding in\n                `AdaLayerZeroNorm`.\n            cross_attention_kwargs ( `Dict[str, Any]`, *optional*):\n                A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under\n                `self.processor` in\n                [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).\n            attention_mask ( `torch.Tensor`, *optional*):\n                An attention mask of shape `(batch, key_tokens)` is applied to `encoder_hidden_states`. If `1` the mask\n                is kept, otherwise if `0` it is discarded. Mask will be converted into a bias, which adds large\n                negative values to the attention scores corresponding to \"discard\" tokens.\n            encoder_attention_mask ( `torch.Tensor`, *optional*):\n                Cross-attention mask applied to `encoder_hidden_states`. Two formats supported:\n\n                    * Mask `(batch, sequence_length)` True = keep, False = discard.\n                    * Bias `(batch, 1, sequence_length)` 0 = keep, -10000 = discard.\n\n                If `ndim == 2`: will be interpreted as a mask, then converted into a bias consistent with the format\n                above. This bias will be added to the cross-attention scores.\n            return_dict (`bool`, *optional*, defaults to `True`):\n                Whether or not to return a [`~models.unet_2d_condition.UNet2DConditionOutput`] instead of a plain\n                tuple.\n\n        Returns:\n            If `return_dict` is True, an [`~models.transformer_2d.Transformer2DModelOutput`] is returned, otherwise a\n            `tuple` where the first element is the sample tensor.\n        \"\"\"\n        # ensure attention_mask is a bias, and give it a singleton query_tokens dimension.\n        #   we may have done this conversion already, e.g. if we came here via UNet2DConditionModel#forward.\n        #   we can tell by counting dims; if ndim == 2: it's a mask rather than a bias.\n        # expects mask of shape:\n        #   [batch, key_tokens]\n        # adds singleton query_tokens dimension:\n        #   [batch,                    1, key_tokens]\n        # this helps to broadcast it as a bias over attention scores, which will be in one of the following shapes:\n        #   [batch,  heads, query_tokens, key_tokens] (e.g. torch sdp attn)\n        #   [batch * heads, query_tokens, key_tokens] (e.g. xformers or classic attn)\n        if attention_mask is not None and attention_mask.ndim == 2:\n            # assume that mask is expressed as:\n            #   (1 = keep,      0 = discard)\n            # convert mask into a bias that can be added to attention scores:\n            #       (keep = +0,     discard = -10000.0)\n            attention_mask = (1 - attention_mask.to(hidden_states.dtype)) * -10000.0\n            attention_mask = attention_mask.unsqueeze(1)\n\n        # convert encoder_attention_mask to a bias the same way we do for attention_mask\n        if encoder_attention_mask is not None and encoder_attention_mask.ndim == 2:\n            encoder_attention_mask = (\n                1 - encoder_attention_mask.to(hidden_states.dtype)\n            ) * -10000.0\n            encoder_attention_mask = encoder_attention_mask.unsqueeze(1)\n\n        # Retrieve lora scale.\n        lora_scale = (\n            cross_attention_kwargs.get(\"scale\", 1.0)\n            if cross_attention_kwargs is not None\n            else 1.0\n        )\n\n        # 1. Input\n        batch, _, height, width = hidden_states.shape\n        residual = hidden_states\n\n        hidden_states = self.norm(hidden_states)\n        if not self.use_linear_projection:\n            hidden_states = (\n                self.proj_in(hidden_states, scale=lora_scale)\n                if not USE_PEFT_BACKEND\n                else self.proj_in(hidden_states)\n            )\n            inner_dim = hidden_states.shape[1]\n            hidden_states = hidden_states.permute(0, 2, 3, 1).reshape(\n                batch, height * width, inner_dim\n            )\n        else:\n            inner_dim = hidden_states.shape[1]\n            hidden_states = hidden_states.permute(0, 2, 3, 1).reshape(\n                batch, height * width, inner_dim\n            )\n            hidden_states = (\n                self.proj_in(hidden_states, scale=lora_scale)\n                if not USE_PEFT_BACKEND\n                else self.proj_in(hidden_states)\n            )\n\n        # 2. Blocks\n        if self.caption_projection is not None:\n            batch_size = hidden_states.shape[0]\n            encoder_hidden_states = self.caption_projection(encoder_hidden_states)\n            encoder_hidden_states = encoder_hidden_states.view(\n                batch_size, -1, hidden_states.shape[-1]\n            )\n\n        ref_feature = hidden_states.reshape(batch, height, width, inner_dim)\n        for block in self.transformer_blocks:\n            if self.training and self.gradient_checkpointing:\n\n                def create_custom_forward(module, return_dict=None):\n                    def custom_forward(*inputs):\n                        if return_dict is not None:\n                            return module(*inputs, return_dict=return_dict)\n                        else:\n                            return module(*inputs)\n\n                    return custom_forward\n\n                ckpt_kwargs: Dict[str, Any] = (\n                    {\"use_reentrant\": False} if is_torch_version(\">=\", \"1.11.0\") else {}\n                )\n                hidden_states = torch.utils.checkpoint.checkpoint(\n                    create_custom_forward(block),\n                    hidden_states,\n                    attention_mask,\n                    encoder_hidden_states,\n                    encoder_attention_mask,\n                    timestep,\n                    cross_attention_kwargs,\n                    class_labels,\n                    **ckpt_kwargs,\n                )\n            else:\n                hidden_states = block(\n                    hidden_states,\n                    attention_mask=attention_mask,\n                    encoder_hidden_states=encoder_hidden_states,\n                    encoder_attention_mask=encoder_attention_mask,\n                    timestep=timestep,\n                    cross_attention_kwargs=cross_attention_kwargs,\n                    class_labels=class_labels,\n                )\n\n        # 3. Output\n        if self.is_input_continuous:\n            if not self.use_linear_projection:\n                hidden_states = (\n                    hidden_states.reshape(batch, height, width, inner_dim)\n                    .permute(0, 3, 1, 2)\n                    .contiguous()\n                )\n                hidden_states = (\n                    self.proj_out(hidden_states, scale=lora_scale)\n                    if not USE_PEFT_BACKEND\n                    else self.proj_out(hidden_states)\n                )\n            else:\n                hidden_states = (\n                    self.proj_out(hidden_states, scale=lora_scale)\n                    if not USE_PEFT_BACKEND\n                    else self.proj_out(hidden_states)\n                )\n                hidden_states = (\n                    hidden_states.reshape(batch, height, width, inner_dim)\n                    .permute(0, 3, 1, 2)\n                    .contiguous()\n                )\n\n            output = hidden_states + residual\n        if not return_dict:\n            return (output, ref_feature)\n\n        return Transformer2DModelOutput(sample=output, ref_feature=ref_feature)\n"
  },
  {
    "path": "src/models/unet_2d_blocks.py",
    "content": "# Adapted from https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/unet_2d_blocks.py\nfrom typing import Any, Dict, Optional, Tuple, Union\n\nimport numpy as np\nimport torch\nimport torch.nn.functional as F\nfrom diffusers.models.activations import get_activation\nfrom diffusers.models.attention_processor import Attention\nfrom diffusers.models.dual_transformer_2d import DualTransformer2DModel\nfrom diffusers.models.resnet import Downsample2D, ResnetBlock2D, Upsample2D\nfrom diffusers.utils import is_torch_version, logging\nfrom diffusers.utils.torch_utils import apply_freeu\nfrom torch import nn\n\nfrom .transformer_2d import Transformer2DModel\n\nlogger = logging.get_logger(__name__)  # pylint: disable=invalid-name\n\n\ndef get_down_block(\n    down_block_type: str,\n    num_layers: int,\n    in_channels: int,\n    out_channels: int,\n    temb_channels: int,\n    add_downsample: bool,\n    resnet_eps: float,\n    resnet_act_fn: str,\n    transformer_layers_per_block: int = 1,\n    num_attention_heads: Optional[int] = None,\n    resnet_groups: Optional[int] = None,\n    cross_attention_dim: Optional[int] = None,\n    downsample_padding: Optional[int] = None,\n    dual_cross_attention: bool = False,\n    use_linear_projection: bool = False,\n    only_cross_attention: bool = False,\n    upcast_attention: bool = False,\n    resnet_time_scale_shift: str = \"default\",\n    attention_type: str = \"default\",\n    resnet_skip_time_act: bool = False,\n    resnet_out_scale_factor: float = 1.0,\n    cross_attention_norm: Optional[str] = None,\n    attention_head_dim: Optional[int] = None,\n    downsample_type: Optional[str] = None,\n    dropout: float = 0.0,\n):\n    # If attn head dim is not defined, we default it to the number of heads\n    if attention_head_dim is None:\n        logger.warn(\n            f\"It is recommended to provide `attention_head_dim` when calling `get_down_block`. Defaulting `attention_head_dim` to {num_attention_heads}.\"\n        )\n        attention_head_dim = num_attention_heads\n\n    down_block_type = (\n        down_block_type[7:]\n        if down_block_type.startswith(\"UNetRes\")\n        else down_block_type\n    )\n    if down_block_type == \"DownBlock2D\":\n        return DownBlock2D(\n            num_layers=num_layers,\n            in_channels=in_channels,\n            out_channels=out_channels,\n            temb_channels=temb_channels,\n            dropout=dropout,\n            add_downsample=add_downsample,\n            resnet_eps=resnet_eps,\n            resnet_act_fn=resnet_act_fn,\n            resnet_groups=resnet_groups,\n            downsample_padding=downsample_padding,\n            resnet_time_scale_shift=resnet_time_scale_shift,\n        )\n    elif down_block_type == \"CrossAttnDownBlock2D\":\n        if cross_attention_dim is None:\n            raise ValueError(\n                \"cross_attention_dim must be specified for CrossAttnDownBlock2D\"\n            )\n        return CrossAttnDownBlock2D(\n            num_layers=num_layers,\n            transformer_layers_per_block=transformer_layers_per_block,\n            in_channels=in_channels,\n            out_channels=out_channels,\n            temb_channels=temb_channels,\n            dropout=dropout,\n            add_downsample=add_downsample,\n            resnet_eps=resnet_eps,\n            resnet_act_fn=resnet_act_fn,\n            resnet_groups=resnet_groups,\n            downsample_padding=downsample_padding,\n            cross_attention_dim=cross_attention_dim,\n            num_attention_heads=num_attention_heads,\n            dual_cross_attention=dual_cross_attention,\n            use_linear_projection=use_linear_projection,\n            only_cross_attention=only_cross_attention,\n            upcast_attention=upcast_attention,\n            resnet_time_scale_shift=resnet_time_scale_shift,\n            attention_type=attention_type,\n        )\n    raise ValueError(f\"{down_block_type} does not exist.\")\n\n\ndef get_up_block(\n    up_block_type: str,\n    num_layers: int,\n    in_channels: int,\n    out_channels: int,\n    prev_output_channel: int,\n    temb_channels: int,\n    add_upsample: bool,\n    resnet_eps: float,\n    resnet_act_fn: str,\n    resolution_idx: Optional[int] = None,\n    transformer_layers_per_block: int = 1,\n    num_attention_heads: Optional[int] = None,\n    resnet_groups: Optional[int] = None,\n    cross_attention_dim: Optional[int] = None,\n    dual_cross_attention: bool = False,\n    use_linear_projection: bool = False,\n    only_cross_attention: bool = False,\n    upcast_attention: bool = False,\n    resnet_time_scale_shift: str = \"default\",\n    attention_type: str = \"default\",\n    resnet_skip_time_act: bool = False,\n    resnet_out_scale_factor: float = 1.0,\n    cross_attention_norm: Optional[str] = None,\n    attention_head_dim: Optional[int] = None,\n    upsample_type: Optional[str] = None,\n    dropout: float = 0.0,\n) -> nn.Module:\n    # If attn head dim is not defined, we default it to the number of heads\n    if attention_head_dim is None:\n        logger.warn(\n            f\"It is recommended to provide `attention_head_dim` when calling `get_up_block`. Defaulting `attention_head_dim` to {num_attention_heads}.\"\n        )\n        attention_head_dim = num_attention_heads\n\n    up_block_type = (\n        up_block_type[7:] if up_block_type.startswith(\"UNetRes\") else up_block_type\n    )\n    if up_block_type == \"UpBlock2D\":\n        return UpBlock2D(\n            num_layers=num_layers,\n            in_channels=in_channels,\n            out_channels=out_channels,\n            prev_output_channel=prev_output_channel,\n            temb_channels=temb_channels,\n            resolution_idx=resolution_idx,\n            dropout=dropout,\n            add_upsample=add_upsample,\n            resnet_eps=resnet_eps,\n            resnet_act_fn=resnet_act_fn,\n            resnet_groups=resnet_groups,\n            resnet_time_scale_shift=resnet_time_scale_shift,\n        )\n    elif up_block_type == \"CrossAttnUpBlock2D\":\n        if cross_attention_dim is None:\n            raise ValueError(\n                \"cross_attention_dim must be specified for CrossAttnUpBlock2D\"\n            )\n        return CrossAttnUpBlock2D(\n            num_layers=num_layers,\n            transformer_layers_per_block=transformer_layers_per_block,\n            in_channels=in_channels,\n            out_channels=out_channels,\n            prev_output_channel=prev_output_channel,\n            temb_channels=temb_channels,\n            resolution_idx=resolution_idx,\n            dropout=dropout,\n            add_upsample=add_upsample,\n            resnet_eps=resnet_eps,\n            resnet_act_fn=resnet_act_fn,\n            resnet_groups=resnet_groups,\n            cross_attention_dim=cross_attention_dim,\n            num_attention_heads=num_attention_heads,\n            dual_cross_attention=dual_cross_attention,\n            use_linear_projection=use_linear_projection,\n            only_cross_attention=only_cross_attention,\n            upcast_attention=upcast_attention,\n            resnet_time_scale_shift=resnet_time_scale_shift,\n            attention_type=attention_type,\n        )\n\n    raise ValueError(f\"{up_block_type} does not exist.\")\ndef get_mid_block(\n    mid_block_type: str,\n    temb_channels: int,\n    in_channels: int,\n    resnet_eps: float,\n    resnet_act_fn: str,\n    resnet_groups: int,\n    output_scale_factor: float = 1.0,\n    transformer_layers_per_block: int = 1,\n    num_attention_heads: Optional[int] = None,\n    cross_attention_dim: Optional[int] = None,\n    dual_cross_attention: bool = False,\n    use_linear_projection: bool = False,\n    mid_block_only_cross_attention: bool = False,\n    upcast_attention: bool = False,\n    resnet_time_scale_shift: str = \"default\",\n    attention_type: str = \"default\",\n    resnet_skip_time_act: bool = False,\n    cross_attention_norm: Optional[str] = None,\n    attention_head_dim: Optional[int] = 1,\n    dropout: float = 0.0,\n):\n    if mid_block_type == \"UNetMidBlock2DCrossAttn\":\n        return UNetMidBlock2DCrossAttn(\n            transformer_layers_per_block=transformer_layers_per_block,\n            in_channels=in_channels,\n            temb_channels=temb_channels,\n            dropout=dropout,\n            resnet_eps=resnet_eps,\n            resnet_act_fn=resnet_act_fn,\n            output_scale_factor=output_scale_factor,\n            resnet_time_scale_shift=resnet_time_scale_shift,\n            cross_attention_dim=cross_attention_dim,\n            num_attention_heads=num_attention_heads,\n            resnet_groups=resnet_groups,\n            dual_cross_attention=dual_cross_attention,\n            use_linear_projection=use_linear_projection,\n            upcast_attention=upcast_attention,\n            attention_type=attention_type,\n        )\n    elif mid_block_type == \"UNetMidBlock2D\":\n        return UNetMidBlock2D(\n            in_channels=in_channels,\n            temb_channels=temb_channels,\n            dropout=dropout,\n            num_layers=0,\n            resnet_eps=resnet_eps,\n            resnet_act_fn=resnet_act_fn,\n            output_scale_factor=output_scale_factor,\n            resnet_groups=resnet_groups,\n            resnet_time_scale_shift=resnet_time_scale_shift,\n            add_attention=False,\n        )\n    elif mid_block_type is None:\n        return None\n    else:\n        raise ValueError(f\"unknown mid_block_type : {mid_block_type}\")\n\n\nclass AutoencoderTinyBlock(nn.Module):\n    \"\"\"\n    Tiny Autoencoder block used in [`AutoencoderTiny`]. It is a mini residual module consisting of plain conv + ReLU\n    blocks.\n\n    Args:\n        in_channels (`int`): The number of input channels.\n        out_channels (`int`): The number of output channels.\n        act_fn (`str`):\n            ` The activation function to use. Supported values are `\"swish\"`, `\"mish\"`, `\"gelu\"`, and `\"relu\"`.\n\n    Returns:\n        `torch.FloatTensor`: A tensor with the same shape as the input tensor, but with the number of channels equal to\n        `out_channels`.\n    \"\"\"\n\n    def __init__(self, in_channels: int, out_channels: int, act_fn: str):\n        super().__init__()\n        act_fn = get_activation(act_fn)\n        self.conv = nn.Sequential(\n            nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1),\n            act_fn,\n            nn.Conv2d(out_channels, out_channels, kernel_size=3, padding=1),\n            act_fn,\n            nn.Conv2d(out_channels, out_channels, kernel_size=3, padding=1),\n        )\n        self.skip = (\n            nn.Conv2d(in_channels, out_channels, kernel_size=1, bias=False)\n            if in_channels != out_channels\n            else nn.Identity()\n        )\n        self.fuse = nn.ReLU()\n\n    def forward(self, x: torch.FloatTensor) -> torch.FloatTensor:\n        return self.fuse(self.conv(x) + self.skip(x))\n\n\nclass UNetMidBlock2D(nn.Module):\n    \"\"\"\n    A 2D UNet mid-block [`UNetMidBlock2D`] with multiple residual blocks and optional attention blocks.\n\n    Args:\n        in_channels (`int`): The number of input channels.\n        temb_channels (`int`): The number of temporal embedding channels.\n        dropout (`float`, *optional*, defaults to 0.0): The dropout rate.\n        num_layers (`int`, *optional*, defaults to 1): The number of residual blocks.\n        resnet_eps (`float`, *optional*, 1e-6 ): The epsilon value for the resnet blocks.\n        resnet_time_scale_shift (`str`, *optional*, defaults to `default`):\n            The type of normalization to apply to the time embeddings. This can help to improve the performance of the\n            model on tasks with long-range temporal dependencies.\n        resnet_act_fn (`str`, *optional*, defaults to `swish`): The activation function for the resnet blocks.\n        resnet_groups (`int`, *optional*, defaults to 32):\n            The number of groups to use in the group normalization layers of the resnet blocks.\n        attn_groups (`Optional[int]`, *optional*, defaults to None): The number of groups for the attention blocks.\n        resnet_pre_norm (`bool`, *optional*, defaults to `True`):\n            Whether to use pre-normalization for the resnet blocks.\n        add_attention (`bool`, *optional*, defaults to `True`): Whether to add attention blocks.\n        attention_head_dim (`int`, *optional*, defaults to 1):\n            Dimension of a single attention head. The number of attention heads is determined based on this value and\n            the number of input channels.\n        output_scale_factor (`float`, *optional*, defaults to 1.0): The output scale factor.\n\n    Returns:\n        `torch.FloatTensor`: The output of the last residual block, which is a tensor of shape `(batch_size,\n        in_channels, height, width)`.\n\n    \"\"\"\n\n    def __init__(\n        self,\n        in_channels: int,\n        temb_channels: int,\n        dropout: float = 0.0,\n        num_layers: int = 1,\n        resnet_eps: float = 1e-6,\n        resnet_time_scale_shift: str = \"default\",  # default, spatial\n        resnet_act_fn: str = \"swish\",\n        resnet_groups: int = 32,\n        attn_groups: Optional[int] = None,\n        resnet_pre_norm: bool = True,\n        add_attention: bool = True,\n        attention_head_dim: int = 1,\n        output_scale_factor: float = 1.0,\n    ):\n        super().__init__()\n        resnet_groups = (\n            resnet_groups if resnet_groups is not None else min(in_channels // 4, 32)\n        )\n        self.add_attention = add_attention\n\n        if attn_groups is None:\n            attn_groups = (\n                resnet_groups if resnet_time_scale_shift == \"default\" else None\n            )\n\n        # there is always at least one resnet\n        resnets = [\n            ResnetBlock2D(\n                in_channels=in_channels,\n                out_channels=in_channels,\n                temb_channels=temb_channels,\n                eps=resnet_eps,\n                groups=resnet_groups,\n                dropout=dropout,\n                time_embedding_norm=resnet_time_scale_shift,\n                non_linearity=resnet_act_fn,\n                output_scale_factor=output_scale_factor,\n                pre_norm=resnet_pre_norm,\n            )\n        ]\n        attentions = []\n\n        if attention_head_dim is None:\n            logger.warn(\n                f\"It is not recommend to pass `attention_head_dim=None`. Defaulting `attention_head_dim` to `in_channels`: {in_channels}.\"\n            )\n            attention_head_dim = in_channels\n\n        for _ in range(num_layers):\n            if self.add_attention:\n                attentions.append(\n                    Attention(\n                        in_channels,\n                        heads=in_channels // attention_head_dim,\n                        dim_head=attention_head_dim,\n                        rescale_output_factor=output_scale_factor,\n                        eps=resnet_eps,\n                        norm_num_groups=attn_groups,\n                        spatial_norm_dim=temb_channels\n                        if resnet_time_scale_shift == \"spatial\"\n                        else None,\n                        residual_connection=True,\n                        bias=True,\n                        upcast_softmax=True,\n                        _from_deprecated_attn_block=True,\n                    )\n                )\n            else:\n                attentions.append(None)\n\n            resnets.append(\n                ResnetBlock2D(\n                    in_channels=in_channels,\n                    out_channels=in_channels,\n                    temb_channels=temb_channels,\n                    eps=resnet_eps,\n                    groups=resnet_groups,\n                    dropout=dropout,\n                    time_embedding_norm=resnet_time_scale_shift,\n                    non_linearity=resnet_act_fn,\n                    output_scale_factor=output_scale_factor,\n                    pre_norm=resnet_pre_norm,\n                )\n            )\n\n        self.attentions = nn.ModuleList(attentions)\n        self.resnets = nn.ModuleList(resnets)\n\n    def forward(\n        self, hidden_states: torch.FloatTensor, temb: Optional[torch.FloatTensor] = None\n    ) -> torch.FloatTensor:\n        hidden_states = self.resnets[0](hidden_states, temb)\n        for attn, resnet in zip(self.attentions, self.resnets[1:]):\n            if attn is not None:\n                hidden_states = attn(hidden_states, temb=temb)\n            hidden_states = resnet(hidden_states, temb)\n\n        return hidden_states\n\n\nclass UNetMidBlock2DCrossAttn(nn.Module):\n    def __init__(\n        self,\n        in_channels: int,\n        temb_channels: int,\n        dropout: float = 0.0,\n        num_layers: int = 1,\n        transformer_layers_per_block: Union[int, Tuple[int]] = 1,\n        resnet_eps: float = 1e-6,\n        resnet_time_scale_shift: str = \"default\",\n        resnet_act_fn: str = \"swish\",\n        resnet_groups: int = 32,\n        resnet_pre_norm: bool = True,\n        num_attention_heads: int = 1,\n        output_scale_factor: float = 1.0,\n        cross_attention_dim: int = 1280,\n        dual_cross_attention: bool = False,\n        use_linear_projection: bool = False,\n        upcast_attention: bool = False,\n        attention_type: str = \"default\",\n    ):\n        super().__init__()\n\n        self.has_cross_attention = True\n        self.num_attention_heads = num_attention_heads\n        resnet_groups = (\n            resnet_groups if resnet_groups is not None else min(in_channels // 4, 32)\n        )\n\n        # support for variable transformer layers per block\n        if isinstance(transformer_layers_per_block, int):\n            transformer_layers_per_block = [transformer_layers_per_block] * num_layers\n\n        # there is always at least one resnet\n        resnets = [\n            ResnetBlock2D(\n                in_channels=in_channels,\n                out_channels=in_channels,\n                temb_channels=temb_channels,\n                eps=resnet_eps,\n                groups=resnet_groups,\n                dropout=dropout,\n                time_embedding_norm=resnet_time_scale_shift,\n                non_linearity=resnet_act_fn,\n                output_scale_factor=output_scale_factor,\n                pre_norm=resnet_pre_norm,\n            )\n        ]\n        attentions = []\n\n        for i in range(num_layers):\n            if not dual_cross_attention:\n                attentions.append(\n                    Transformer2DModel(\n                        num_attention_heads,\n                        in_channels // num_attention_heads,\n                        in_channels=in_channels,\n                        num_layers=transformer_layers_per_block[i],\n                        cross_attention_dim=cross_attention_dim,\n                        norm_num_groups=resnet_groups,\n                        use_linear_projection=use_linear_projection,\n                        upcast_attention=upcast_attention,\n                        attention_type=attention_type,\n                    )\n                )\n            else:\n                attentions.append(\n                    DualTransformer2DModel(\n                        num_attention_heads,\n                        in_channels // num_attention_heads,\n                        in_channels=in_channels,\n                        num_layers=1,\n                        cross_attention_dim=cross_attention_dim,\n                        norm_num_groups=resnet_groups,\n                    )\n                )\n            resnets.append(\n                ResnetBlock2D(\n                    in_channels=in_channels,\n                    out_channels=in_channels,\n                    temb_channels=temb_channels,\n                    eps=resnet_eps,\n                    groups=resnet_groups,\n                    dropout=dropout,\n                    time_embedding_norm=resnet_time_scale_shift,\n                    non_linearity=resnet_act_fn,\n                    output_scale_factor=output_scale_factor,\n                    pre_norm=resnet_pre_norm,\n                )\n            )\n\n        self.attentions = nn.ModuleList(attentions)\n        self.resnets = nn.ModuleList(resnets)\n\n        self.gradient_checkpointing = False\n\n    def forward(\n        self,\n        hidden_states: torch.FloatTensor,\n        temb: Optional[torch.FloatTensor] = None,\n        encoder_hidden_states: Optional[torch.FloatTensor] = None,\n        attention_mask: Optional[torch.FloatTensor] = None,\n        cross_attention_kwargs: Optional[Dict[str, Any]] = None,\n        encoder_attention_mask: Optional[torch.FloatTensor] = None,\n    ) -> torch.FloatTensor:\n        lora_scale = (\n            cross_attention_kwargs.get(\"scale\", 1.0)\n            if cross_attention_kwargs is not None\n            else 1.0\n        )\n        hidden_states = self.resnets[0](hidden_states, temb, scale=lora_scale)\n        for attn, resnet in zip(self.attentions, self.resnets[1:]):\n            if self.training and self.gradient_checkpointing:\n\n                def create_custom_forward(module, return_dict=None):\n                    def custom_forward(*inputs):\n                        if return_dict is not None:\n                            return module(*inputs, return_dict=return_dict)\n                        else:\n                            return module(*inputs)\n\n                    return custom_forward\n\n                ckpt_kwargs: Dict[str, Any] = (\n                    {\"use_reentrant\": False} if is_torch_version(\">=\", \"1.11.0\") else {}\n                )\n                hidden_states, ref_feature = attn(\n                    hidden_states,\n                    encoder_hidden_states=encoder_hidden_states,\n                    cross_attention_kwargs=cross_attention_kwargs,\n                    attention_mask=attention_mask,\n                    encoder_attention_mask=encoder_attention_mask,\n                    return_dict=False,\n                )\n                hidden_states = torch.utils.checkpoint.checkpoint(\n                    create_custom_forward(resnet),\n                    hidden_states,\n                    temb,\n                    **ckpt_kwargs,\n                )\n            else:\n                hidden_states, ref_feature = attn(\n                    hidden_states,\n                    encoder_hidden_states=encoder_hidden_states,\n                    cross_attention_kwargs=cross_attention_kwargs,\n                    attention_mask=attention_mask,\n                    encoder_attention_mask=encoder_attention_mask,\n                    return_dict=False,\n                )\n                hidden_states = resnet(hidden_states, temb, scale=lora_scale)\n\n        return hidden_states\n\n\nclass CrossAttnDownBlock2D(nn.Module):\n    def __init__(\n        self,\n        in_channels: int,\n        out_channels: int,\n        temb_channels: int,\n        dropout: float = 0.0,\n        num_layers: int = 1,\n        transformer_layers_per_block: Union[int, Tuple[int]] = 1,\n        resnet_eps: float = 1e-6,\n        resnet_time_scale_shift: str = \"default\",\n        resnet_act_fn: str = \"swish\",\n        resnet_groups: int = 32,\n        resnet_pre_norm: bool = True,\n        num_attention_heads: int = 1,\n        cross_attention_dim: int = 1280,\n        output_scale_factor: float = 1.0,\n        downsample_padding: int = 1,\n        add_downsample: bool = True,\n        dual_cross_attention: bool = False,\n        use_linear_projection: bool = False,\n        only_cross_attention: bool = False,\n        upcast_attention: bool = False,\n        attention_type: str = \"default\",\n    ):\n        super().__init__()\n        resnets = []\n        attentions = []\n\n        self.has_cross_attention = True\n        self.num_attention_heads = num_attention_heads\n        if isinstance(transformer_layers_per_block, int):\n            transformer_layers_per_block = [transformer_layers_per_block] * num_layers\n\n        for i in range(num_layers):\n            in_channels = in_channels if i == 0 else out_channels\n            resnets.append(\n                ResnetBlock2D(\n                    in_channels=in_channels,\n                    out_channels=out_channels,\n                    temb_channels=temb_channels,\n                    eps=resnet_eps,\n                    groups=resnet_groups,\n                    dropout=dropout,\n                    time_embedding_norm=resnet_time_scale_shift,\n                    non_linearity=resnet_act_fn,\n                    output_scale_factor=output_scale_factor,\n                    pre_norm=resnet_pre_norm,\n                )\n            )\n            if not dual_cross_attention:\n                attentions.append(\n                    Transformer2DModel(\n                        num_attention_heads,\n                        out_channels // num_attention_heads,\n                        in_channels=out_channels,\n                        num_layers=transformer_layers_per_block[i],\n                        cross_attention_dim=cross_attention_dim,\n                        norm_num_groups=resnet_groups,\n                        use_linear_projection=use_linear_projection,\n                        only_cross_attention=only_cross_attention,\n                        upcast_attention=upcast_attention,\n                        attention_type=attention_type,\n                    )\n                )\n            else:\n                attentions.append(\n                    DualTransformer2DModel(\n                        num_attention_heads,\n                        out_channels // num_attention_heads,\n                        in_channels=out_channels,\n                        num_layers=1,\n                        cross_attention_dim=cross_attention_dim,\n                        norm_num_groups=resnet_groups,\n                    )\n                )\n        self.attentions = nn.ModuleList(attentions)\n        self.resnets = nn.ModuleList(resnets)\n\n        if add_downsample:\n            self.downsamplers = nn.ModuleList(\n                [\n                    Downsample2D(\n                        out_channels,\n                        use_conv=True,\n                        out_channels=out_channels,\n                        padding=downsample_padding,\n                        name=\"op\",\n                    )\n                ]\n            )\n        else:\n            self.downsamplers = None\n\n        self.gradient_checkpointing = False\n\n    def forward(\n        self,\n        hidden_states: torch.FloatTensor,\n        temb: Optional[torch.FloatTensor] = None,\n        encoder_hidden_states: Optional[torch.FloatTensor] = None,\n        attention_mask: Optional[torch.FloatTensor] = None,\n        cross_attention_kwargs: Optional[Dict[str, Any]] = None,\n        encoder_attention_mask: Optional[torch.FloatTensor] = None,\n        additional_residuals: Optional[torch.FloatTensor] = None,\n    ) -> Tuple[torch.FloatTensor, Tuple[torch.FloatTensor, ...]]:\n        output_states = ()\n\n        lora_scale = (\n            cross_attention_kwargs.get(\"scale\", 1.0)\n            if cross_attention_kwargs is not None\n            else 1.0\n        )\n\n        blocks = list(zip(self.resnets, self.attentions))\n\n        for i, (resnet, attn) in enumerate(blocks):\n            if self.training and self.gradient_checkpointing:\n\n                def create_custom_forward(module, return_dict=None):\n                    def custom_forward(*inputs):\n                        if return_dict is not None:\n                            return module(*inputs, return_dict=return_dict)\n                        else:\n                            return module(*inputs)\n\n                    return custom_forward\n\n                ckpt_kwargs: Dict[str, Any] = (\n                    {\"use_reentrant\": False} if is_torch_version(\">=\", \"1.11.0\") else {}\n                )\n                hidden_states = torch.utils.checkpoint.checkpoint(\n                    create_custom_forward(resnet),\n                    hidden_states,\n                    temb,\n                    **ckpt_kwargs,\n                )\n                hidden_states, ref_feature = attn(\n                    hidden_states,\n                    encoder_hidden_states=encoder_hidden_states,\n                    cross_attention_kwargs=cross_attention_kwargs,\n                    attention_mask=attention_mask,\n                    encoder_attention_mask=encoder_attention_mask,\n                    return_dict=False,\n                )\n            else:\n                hidden_states = resnet(hidden_states, temb, scale=lora_scale)\n                hidden_states, ref_feature = attn(\n                    hidden_states,\n                    encoder_hidden_states=encoder_hidden_states,\n                    cross_attention_kwargs=cross_attention_kwargs,\n                    attention_mask=attention_mask,\n                    encoder_attention_mask=encoder_attention_mask,\n                    return_dict=False,\n                )\n\n            # apply additional residuals to the output of the last pair of resnet and attention blocks\n            if i == len(blocks) - 1 and additional_residuals is not None:\n                hidden_states = hidden_states + additional_residuals\n\n            output_states = output_states + (hidden_states,)\n\n        if self.downsamplers is not None:\n            for downsampler in self.downsamplers:\n                hidden_states = downsampler(hidden_states, scale=lora_scale)\n\n            output_states = output_states + (hidden_states,)\n\n        return hidden_states, output_states\n\n\nclass DownBlock2D(nn.Module):\n    def __init__(\n        self,\n        in_channels: int,\n        out_channels: int,\n        temb_channels: int,\n        dropout: float = 0.0,\n        num_layers: int = 1,\n        resnet_eps: float = 1e-6,\n        resnet_time_scale_shift: str = \"default\",\n        resnet_act_fn: str = \"swish\",\n        resnet_groups: int = 32,\n        resnet_pre_norm: bool = True,\n        output_scale_factor: float = 1.0,\n        add_downsample: bool = True,\n        downsample_padding: int = 1,\n    ):\n        super().__init__()\n        resnets = []\n\n        for i in range(num_layers):\n            in_channels = in_channels if i == 0 else out_channels\n            resnets.append(\n                ResnetBlock2D(\n                    in_channels=in_channels,\n                    out_channels=out_channels,\n                    temb_channels=temb_channels,\n                    eps=resnet_eps,\n                    groups=resnet_groups,\n                    dropout=dropout,\n                    time_embedding_norm=resnet_time_scale_shift,\n                    non_linearity=resnet_act_fn,\n                    output_scale_factor=output_scale_factor,\n                    pre_norm=resnet_pre_norm,\n                )\n            )\n\n        self.resnets = nn.ModuleList(resnets)\n\n        if add_downsample:\n            self.downsamplers = nn.ModuleList(\n                [\n                    Downsample2D(\n                        out_channels,\n                        use_conv=True,\n                        out_channels=out_channels,\n                        padding=downsample_padding,\n                        name=\"op\",\n                    )\n                ]\n            )\n        else:\n            self.downsamplers = None\n\n        self.gradient_checkpointing = False\n\n    def forward(\n        self,\n        hidden_states: torch.FloatTensor,\n        temb: Optional[torch.FloatTensor] = None,\n        scale: float = 1.0,\n    ) -> Tuple[torch.FloatTensor, Tuple[torch.FloatTensor, ...]]:\n        output_states = ()\n\n        for resnet in self.resnets:\n            if self.training and self.gradient_checkpointing:\n\n                def create_custom_forward(module):\n                    def custom_forward(*inputs):\n                        return module(*inputs)\n\n                    return custom_forward\n\n                if is_torch_version(\">=\", \"1.11.0\"):\n                    hidden_states = torch.utils.checkpoint.checkpoint(\n                        create_custom_forward(resnet),\n                        hidden_states,\n                        temb,\n                        use_reentrant=False,\n                    )\n                else:\n                    hidden_states = torch.utils.checkpoint.checkpoint(\n                        create_custom_forward(resnet), hidden_states, temb\n                    )\n            else:\n                hidden_states = resnet(hidden_states, temb, scale=scale)\n\n            output_states = output_states + (hidden_states,)\n\n        if self.downsamplers is not None:\n            for downsampler in self.downsamplers:\n                hidden_states = downsampler(hidden_states, scale=scale)\n\n            output_states = output_states + (hidden_states,)\n\n        return hidden_states, output_states\n\n\nclass CrossAttnUpBlock2D(nn.Module):\n    def __init__(\n        self,\n        in_channels: int,\n        out_channels: int,\n        prev_output_channel: int,\n        temb_channels: int,\n        resolution_idx: Optional[int] = None,\n        dropout: float = 0.0,\n        num_layers: int = 1,\n        transformer_layers_per_block: Union[int, Tuple[int]] = 1,\n        resnet_eps: float = 1e-6,\n        resnet_time_scale_shift: str = \"default\",\n        resnet_act_fn: str = \"swish\",\n        resnet_groups: int = 32,\n        resnet_pre_norm: bool = True,\n        num_attention_heads: int = 1,\n        cross_attention_dim: int = 1280,\n        output_scale_factor: float = 1.0,\n        add_upsample: bool = True,\n        dual_cross_attention: bool = False,\n        use_linear_projection: bool = False,\n        only_cross_attention: bool = False,\n        upcast_attention: bool = False,\n        attention_type: str = \"default\",\n    ):\n        super().__init__()\n        resnets = []\n        attentions = []\n\n        self.has_cross_attention = True\n        self.num_attention_heads = num_attention_heads\n\n        if isinstance(transformer_layers_per_block, int):\n            transformer_layers_per_block = [transformer_layers_per_block] * num_layers\n\n        for i in range(num_layers):\n            res_skip_channels = in_channels if (i == num_layers - 1) else out_channels\n            resnet_in_channels = prev_output_channel if i == 0 else out_channels\n\n            resnets.append(\n                ResnetBlock2D(\n                    in_channels=resnet_in_channels + res_skip_channels,\n                    out_channels=out_channels,\n                    temb_channels=temb_channels,\n                    eps=resnet_eps,\n                    groups=resnet_groups,\n                    dropout=dropout,\n                    time_embedding_norm=resnet_time_scale_shift,\n                    non_linearity=resnet_act_fn,\n                    output_scale_factor=output_scale_factor,\n                    pre_norm=resnet_pre_norm,\n                )\n            )\n            if not dual_cross_attention:\n                attentions.append(\n                    Transformer2DModel(\n                        num_attention_heads,\n                        out_channels // num_attention_heads,\n                        in_channels=out_channels,\n                        num_layers=transformer_layers_per_block[i],\n                        cross_attention_dim=cross_attention_dim,\n                        norm_num_groups=resnet_groups,\n                        use_linear_projection=use_linear_projection,\n                        only_cross_attention=only_cross_attention,\n                        upcast_attention=upcast_attention,\n                        attention_type=attention_type,\n                    )\n                )\n            else:\n                attentions.append(\n                    DualTransformer2DModel(\n                        num_attention_heads,\n                        out_channels // num_attention_heads,\n                        in_channels=out_channels,\n                        num_layers=1,\n                        cross_attention_dim=cross_attention_dim,\n                        norm_num_groups=resnet_groups,\n                    )\n                )\n        self.attentions = nn.ModuleList(attentions)\n        self.resnets = nn.ModuleList(resnets)\n\n        if add_upsample:\n            self.upsamplers = nn.ModuleList(\n                [Upsample2D(out_channels, use_conv=True, out_channels=out_channels)]\n            )\n        else:\n            self.upsamplers = None\n\n        self.gradient_checkpointing = False\n        self.resolution_idx = resolution_idx\n\n    def forward(\n        self,\n        hidden_states: torch.FloatTensor,\n        res_hidden_states_tuple: Tuple[torch.FloatTensor, ...],\n        temb: Optional[torch.FloatTensor] = None,\n        encoder_hidden_states: Optional[torch.FloatTensor] = None,\n        cross_attention_kwargs: Optional[Dict[str, Any]] = None,\n        upsample_size: Optional[int] = None,\n        attention_mask: Optional[torch.FloatTensor] = None,\n        encoder_attention_mask: Optional[torch.FloatTensor] = None,\n    ) -> torch.FloatTensor:\n        lora_scale = (\n            cross_attention_kwargs.get(\"scale\", 1.0)\n            if cross_attention_kwargs is not None\n            else 1.0\n        )\n        is_freeu_enabled = (\n            getattr(self, \"s1\", None)\n            and getattr(self, \"s2\", None)\n            and getattr(self, \"b1\", None)\n            and getattr(self, \"b2\", None)\n        )\n\n        for resnet, attn in zip(self.resnets, self.attentions):\n            # pop res hidden states\n            res_hidden_states = res_hidden_states_tuple[-1]\n            res_hidden_states_tuple = res_hidden_states_tuple[:-1]\n\n            # FreeU: Only operate on the first two stages\n            if is_freeu_enabled:\n                hidden_states, res_hidden_states = apply_freeu(\n                    self.resolution_idx,\n                    hidden_states,\n                    res_hidden_states,\n                    s1=self.s1,\n                    s2=self.s2,\n                    b1=self.b1,\n                    b2=self.b2,\n                )\n\n            hidden_states = torch.cat([hidden_states, res_hidden_states], dim=1)\n\n            if self.training and self.gradient_checkpointing:\n\n                def create_custom_forward(module, return_dict=None):\n                    def custom_forward(*inputs):\n                        if return_dict is not None:\n                            return module(*inputs, return_dict=return_dict)\n                        else:\n                            return module(*inputs)\n\n                    return custom_forward\n\n                ckpt_kwargs: Dict[str, Any] = (\n                    {\"use_reentrant\": False} if is_torch_version(\">=\", \"1.11.0\") else {}\n                )\n                hidden_states = torch.utils.checkpoint.checkpoint(\n                    create_custom_forward(resnet),\n                    hidden_states,\n                    temb,\n                    **ckpt_kwargs,\n                )\n                hidden_states, ref_feature = attn(\n                    hidden_states,\n                    encoder_hidden_states=encoder_hidden_states,\n                    cross_attention_kwargs=cross_attention_kwargs,\n                    attention_mask=attention_mask,\n                    encoder_attention_mask=encoder_attention_mask,\n                    return_dict=False,\n                )\n            else:\n                hidden_states = resnet(hidden_states, temb, scale=lora_scale)\n                hidden_states, ref_feature = attn(\n                    hidden_states,\n                    encoder_hidden_states=encoder_hidden_states,\n                    cross_attention_kwargs=cross_attention_kwargs,\n                    attention_mask=attention_mask,\n                    encoder_attention_mask=encoder_attention_mask,\n                    return_dict=False,\n                )\n\n        if self.upsamplers is not None:\n            for upsampler in self.upsamplers:\n                hidden_states = upsampler(\n                    hidden_states, upsample_size, scale=lora_scale\n                )\n\n        return hidden_states\n\n\nclass UpBlock2D(nn.Module):\n    def __init__(\n        self,\n        in_channels: int,\n        prev_output_channel: int,\n        out_channels: int,\n        temb_channels: int,\n        resolution_idx: Optional[int] = None,\n        dropout: float = 0.0,\n        num_layers: int = 1,\n        resnet_eps: float = 1e-6,\n        resnet_time_scale_shift: str = \"default\",\n        resnet_act_fn: str = \"swish\",\n        resnet_groups: int = 32,\n        resnet_pre_norm: bool = True,\n        output_scale_factor: float = 1.0,\n        add_upsample: bool = True,\n    ):\n        super().__init__()\n        resnets = []\n\n        for i in range(num_layers):\n            res_skip_channels = in_channels if (i == num_layers - 1) else out_channels\n            resnet_in_channels = prev_output_channel if i == 0 else out_channels\n\n            resnets.append(\n                ResnetBlock2D(\n                    in_channels=resnet_in_channels + res_skip_channels,\n                    out_channels=out_channels,\n                    temb_channels=temb_channels,\n                    eps=resnet_eps,\n                    groups=resnet_groups,\n                    dropout=dropout,\n                    time_embedding_norm=resnet_time_scale_shift,\n                    non_linearity=resnet_act_fn,\n                    output_scale_factor=output_scale_factor,\n                    pre_norm=resnet_pre_norm,\n                )\n            )\n\n        self.resnets = nn.ModuleList(resnets)\n\n        if add_upsample:\n            self.upsamplers = nn.ModuleList(\n                [Upsample2D(out_channels, use_conv=True, out_channels=out_channels)]\n            )\n        else:\n            self.upsamplers = None\n\n        self.gradient_checkpointing = False\n        self.resolution_idx = resolution_idx\n\n    def forward(\n        self,\n        hidden_states: torch.FloatTensor,\n        res_hidden_states_tuple: Tuple[torch.FloatTensor, ...],\n        temb: Optional[torch.FloatTensor] = None,\n        upsample_size: Optional[int] = None,\n        scale: float = 1.0,\n    ) -> torch.FloatTensor:\n        is_freeu_enabled = (\n            getattr(self, \"s1\", None)\n            and getattr(self, \"s2\", None)\n            and getattr(self, \"b1\", None)\n            and getattr(self, \"b2\", None)\n        )\n\n        for resnet in self.resnets:\n            # pop res hidden states\n            res_hidden_states = res_hidden_states_tuple[-1]\n            res_hidden_states_tuple = res_hidden_states_tuple[:-1]\n\n            # FreeU: Only operate on the first two stages\n            if is_freeu_enabled:\n                hidden_states, res_hidden_states = apply_freeu(\n                    self.resolution_idx,\n                    hidden_states,\n                    res_hidden_states,\n                    s1=self.s1,\n                    s2=self.s2,\n                    b1=self.b1,\n                    b2=self.b2,\n                )\n\n            hidden_states = torch.cat([hidden_states, res_hidden_states], dim=1)\n\n            if self.training and self.gradient_checkpointing:\n\n                def create_custom_forward(module):\n                    def custom_forward(*inputs):\n                        return module(*inputs)\n\n                    return custom_forward\n\n                if is_torch_version(\">=\", \"1.11.0\"):\n                    hidden_states = torch.utils.checkpoint.checkpoint(\n                        create_custom_forward(resnet),\n                        hidden_states,\n                        temb,\n                        use_reentrant=False,\n                    )\n                else:\n                    hidden_states = torch.utils.checkpoint.checkpoint(\n                        create_custom_forward(resnet), hidden_states, temb\n                    )\n            else:\n                hidden_states = resnet(hidden_states, temb, scale=scale)\n\n        if self.upsamplers is not None:\n            for upsampler in self.upsamplers:\n                hidden_states = upsampler(hidden_states, upsample_size, scale=scale)\n\n        return hidden_states\n"
  },
  {
    "path": "src/models/unet_2d_condition.py",
    "content": "# Adapted from https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/unet_2d_condition.py\nfrom dataclasses import dataclass\nfrom typing import Any, Dict, List, Optional, Tuple, Union\n\nimport torch\nimport torch.nn as nn\nimport torch.utils.checkpoint\nfrom diffusers.configuration_utils import ConfigMixin, register_to_config\nfrom diffusers.loaders import UNet2DConditionLoadersMixin\nfrom diffusers.models.activations import get_activation\nfrom diffusers.models.attention_processor import (\n    ADDED_KV_ATTENTION_PROCESSORS,\n    CROSS_ATTENTION_PROCESSORS,\n    AttentionProcessor,\n    AttnAddedKVProcessor,\n    AttnProcessor,\n)\nfrom diffusers.models.embeddings import (\n    GaussianFourierProjection,\n    ImageHintTimeEmbedding,\n    ImageProjection,\n    ImageTimeEmbedding,\n    # PositionNet,\n    TextImageProjection,\n    TextImageTimeEmbedding,\n    TextTimeEmbedding,\n    TimestepEmbedding,\n    Timesteps,\n)\nfrom diffusers.models.modeling_utils import ModelMixin\nfrom diffusers.utils import (\n    USE_PEFT_BACKEND,\n    BaseOutput,\n    deprecate,\n    logging,\n    scale_lora_layers,\n    unscale_lora_layers,\n)\n\nfrom .unet_2d_blocks import (\n    UNetMidBlock2D,\n    UNetMidBlock2DCrossAttn,\n    get_down_block,\n    get_up_block,\n)\n\nlogger = logging.get_logger(__name__)  # pylint: disable=invalid-name\n\n\n@dataclass\nclass UNet2DConditionOutput(BaseOutput):\n    \"\"\"\n    The output of [`UNet2DConditionModel`].\n\n    Args:\n        sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n            The hidden states output conditioned on `encoder_hidden_states` input. Output of last layer of model.\n    \"\"\"\n\n    sample: torch.FloatTensor = None\n    ref_features: Tuple[torch.FloatTensor] = None\n\n\nclass UNet2DConditionModel(ModelMixin, ConfigMixin, UNet2DConditionLoadersMixin):\n    r\"\"\"\n    A conditional 2D UNet model that takes a noisy sample, conditional state, and a timestep and returns a sample\n    shaped output.\n\n    This model inherits from [`ModelMixin`]. Check the superclass documentation for it's generic methods implemented\n    for all models (such as downloading or saving).\n\n    Parameters:\n        sample_size (`int` or `Tuple[int, int]`, *optional*, defaults to `None`):\n            Height and width of input/output sample.\n        in_channels (`int`, *optional*, defaults to 4): Number of channels in the input sample.\n        out_channels (`int`, *optional*, defaults to 4): Number of channels in the output.\n        center_input_sample (`bool`, *optional*, defaults to `False`): Whether to center the input sample.\n        flip_sin_to_cos (`bool`, *optional*, defaults to `False`):\n            Whether to flip the sin to cos in the time embedding.\n        freq_shift (`int`, *optional*, defaults to 0): The frequency shift to apply to the time embedding.\n        down_block_types (`Tuple[str]`, *optional*, defaults to `(\"CrossAttnDownBlock2D\", \"CrossAttnDownBlock2D\", \"CrossAttnDownBlock2D\", \"DownBlock2D\")`):\n            The tuple of downsample blocks to use.\n        mid_block_type (`str`, *optional*, defaults to `\"UNetMidBlock2DCrossAttn\"`):\n            Block type for middle of UNet, it can be one of `UNetMidBlock2DCrossAttn`, `UNetMidBlock2D`, or\n            `UNetMidBlock2DSimpleCrossAttn`. If `None`, the mid block layer is skipped.\n        up_block_types (`Tuple[str]`, *optional*, defaults to `(\"UpBlock2D\", \"CrossAttnUpBlock2D\", \"CrossAttnUpBlock2D\", \"CrossAttnUpBlock2D\")`):\n            The tuple of upsample blocks to use.\n        only_cross_attention(`bool` or `Tuple[bool]`, *optional*, default to `False`):\n            Whether to include self-attention in the basic transformer blocks, see\n            [`~models.attention.BasicTransformerBlock`].\n        block_out_channels (`Tuple[int]`, *optional*, defaults to `(320, 640, 1280, 1280)`):\n            The tuple of output channels for each block.\n        layers_per_block (`int`, *optional*, defaults to 2): The number of layers per block.\n        downsample_padding (`int`, *optional*, defaults to 1): The padding to use for the downsampling convolution.\n        mid_block_scale_factor (`float`, *optional*, defaults to 1.0): The scale factor to use for the mid block.\n        dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.\n        act_fn (`str`, *optional*, defaults to `\"silu\"`): The activation function to use.\n        norm_num_groups (`int`, *optional*, defaults to 32): The number of groups to use for the normalization.\n            If `None`, normalization and activation layers is skipped in post-processing.\n        norm_eps (`float`, *optional*, defaults to 1e-5): The epsilon to use for the normalization.\n        cross_attention_dim (`int` or `Tuple[int]`, *optional*, defaults to 1280):\n            The dimension of the cross attention features.\n        transformer_layers_per_block (`int`, `Tuple[int]`, or `Tuple[Tuple]` , *optional*, defaults to 1):\n            The number of transformer blocks of type [`~models.attention.BasicTransformerBlock`]. Only relevant for\n            [`~models.unet_2d_blocks.CrossAttnDownBlock2D`], [`~models.unet_2d_blocks.CrossAttnUpBlock2D`],\n            [`~models.unet_2d_blocks.UNetMidBlock2DCrossAttn`].\n       reverse_transformer_layers_per_block : (`Tuple[Tuple]`, *optional*, defaults to None):\n            The number of transformer blocks of type [`~models.attention.BasicTransformerBlock`], in the upsampling\n            blocks of the U-Net. Only relevant if `transformer_layers_per_block` is of type `Tuple[Tuple]` and for\n            [`~models.unet_2d_blocks.CrossAttnDownBlock2D`], [`~models.unet_2d_blocks.CrossAttnUpBlock2D`],\n            [`~models.unet_2d_blocks.UNetMidBlock2DCrossAttn`].\n        encoder_hid_dim (`int`, *optional*, defaults to None):\n            If `encoder_hid_dim_type` is defined, `encoder_hidden_states` will be projected from `encoder_hid_dim`\n            dimension to `cross_attention_dim`.\n        encoder_hid_dim_type (`str`, *optional*, defaults to `None`):\n            If given, the `encoder_hidden_states` and potentially other embeddings are down-projected to text\n            embeddings of dimension `cross_attention` according to `encoder_hid_dim_type`.\n        attention_head_dim (`int`, *optional*, defaults to 8): The dimension of the attention heads.\n        num_attention_heads (`int`, *optional*):\n            The number of attention heads. If not defined, defaults to `attention_head_dim`\n        resnet_time_scale_shift (`str`, *optional*, defaults to `\"default\"`): Time scale shift config\n            for ResNet blocks (see [`~models.resnet.ResnetBlock2D`]). Choose from `default` or `scale_shift`.\n        class_embed_type (`str`, *optional*, defaults to `None`):\n            The type of class embedding to use which is ultimately summed with the time embeddings. Choose from `None`,\n            `\"timestep\"`, `\"identity\"`, `\"projection\"`, or `\"simple_projection\"`.\n        addition_embed_type (`str`, *optional*, defaults to `None`):\n            Configures an optional embedding which will be summed with the time embeddings. Choose from `None` or\n            \"text\". \"text\" will use the `TextTimeEmbedding` layer.\n        addition_time_embed_dim: (`int`, *optional*, defaults to `None`):\n            Dimension for the timestep embeddings.\n        num_class_embeds (`int`, *optional*, defaults to `None`):\n            Input dimension of the learnable embedding matrix to be projected to `time_embed_dim`, when performing\n            class conditioning with `class_embed_type` equal to `None`.\n        time_embedding_type (`str`, *optional*, defaults to `positional`):\n            The type of position embedding to use for timesteps. Choose from `positional` or `fourier`.\n        time_embedding_dim (`int`, *optional*, defaults to `None`):\n            An optional override for the dimension of the projected time embedding.\n        time_embedding_act_fn (`str`, *optional*, defaults to `None`):\n            Optional activation function to use only once on the time embeddings before they are passed to the rest of\n            the UNet. Choose from `silu`, `mish`, `gelu`, and `swish`.\n        timestep_post_act (`str`, *optional*, defaults to `None`):\n            The second activation function to use in timestep embedding. Choose from `silu`, `mish` and `gelu`.\n        time_cond_proj_dim (`int`, *optional*, defaults to `None`):\n            The dimension of `cond_proj` layer in the timestep embedding.\n        conv_in_kernel (`int`, *optional*, default to `3`): The kernel size of `conv_in` layer. conv_out_kernel (`int`,\n        *optional*, default to `3`): The kernel size of `conv_out` layer. projection_class_embeddings_input_dim (`int`,\n        *optional*): The dimension of the `class_labels` input when\n            `class_embed_type=\"projection\"`. Required when `class_embed_type=\"projection\"`.\n        class_embeddings_concat (`bool`, *optional*, defaults to `False`): Whether to concatenate the time\n            embeddings with the class embeddings.\n        mid_block_only_cross_attention (`bool`, *optional*, defaults to `None`):\n            Whether to use cross attention with the mid block when using the `UNetMidBlock2DSimpleCrossAttn`. If\n            `only_cross_attention` is given as a single boolean and `mid_block_only_cross_attention` is `None`, the\n            `only_cross_attention` value is used as the value for `mid_block_only_cross_attention`. Default to `False`\n            otherwise.\n    \"\"\"\n\n    _supports_gradient_checkpointing = True\n\n    @register_to_config\n    def __init__(\n        self,\n        sample_size: Optional[int] = None,\n        in_channels: int = 4,\n        out_channels: int = 4,\n        center_input_sample: bool = False,\n        flip_sin_to_cos: bool = True,\n        freq_shift: int = 0,\n        down_block_types: Tuple[str] = (\n            \"CrossAttnDownBlock2D\",\n            \"CrossAttnDownBlock2D\",\n            \"CrossAttnDownBlock2D\",\n            \"DownBlock2D\",\n        ),\n        mid_block_type: Optional[str] = \"UNetMidBlock2DCrossAttn\",\n        up_block_types: Tuple[str] = (\n            \"UpBlock2D\",\n            \"CrossAttnUpBlock2D\",\n            \"CrossAttnUpBlock2D\",\n            \"CrossAttnUpBlock2D\",\n        ),\n        only_cross_attention: Union[bool, Tuple[bool]] = False,\n        block_out_channels: Tuple[int] = (320, 640, 1280, 1280),\n        layers_per_block: Union[int, Tuple[int]] = 2,\n        downsample_padding: int = 1,\n        mid_block_scale_factor: float = 1,\n        dropout: float = 0.0,\n        act_fn: str = \"silu\",\n        norm_num_groups: Optional[int] = 32,\n        norm_eps: float = 1e-5,\n        cross_attention_dim: Union[int, Tuple[int]] = 1280,\n        transformer_layers_per_block: Union[int, Tuple[int], Tuple[Tuple]] = 1,\n        reverse_transformer_layers_per_block: Optional[Tuple[Tuple[int]]] = None,\n        encoder_hid_dim: Optional[int] = None,\n        encoder_hid_dim_type: Optional[str] = None,\n        attention_head_dim: Union[int, Tuple[int]] = 8,\n        num_attention_heads: Optional[Union[int, Tuple[int]]] = None,\n        dual_cross_attention: bool = False,\n        use_linear_projection: bool = False,\n        class_embed_type: Optional[str] = None,\n        addition_embed_type: Optional[str] = None,\n        addition_time_embed_dim: Optional[int] = None,\n        num_class_embeds: Optional[int] = None,\n        upcast_attention: bool = False,\n        resnet_time_scale_shift: str = \"default\",\n        resnet_skip_time_act: bool = False,\n        resnet_out_scale_factor: int = 1.0,\n        time_embedding_type: str = \"positional\",\n        time_embedding_dim: Optional[int] = None,\n        time_embedding_act_fn: Optional[str] = None,\n        timestep_post_act: Optional[str] = None,\n        time_cond_proj_dim: Optional[int] = None,\n        conv_in_kernel: int = 3,\n        conv_out_kernel: int = 3,\n        projection_class_embeddings_input_dim: Optional[int] = None,\n        attention_type: str = \"default\",\n        class_embeddings_concat: bool = False,\n        mid_block_only_cross_attention: Optional[bool] = None,\n        cross_attention_norm: Optional[str] = None,\n        addition_embed_type_num_heads=64,\n    ):\n        super().__init__()\n\n        self.sample_size = sample_size\n\n        if num_attention_heads is not None:\n            raise ValueError(\n                \"At the moment it is not possible to define the number of attention heads via `num_attention_heads` because of a naming issue as described in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131. Passing `num_attention_heads` will only be supported in diffusers v0.19.\"\n            )\n\n        # If `num_attention_heads` is not defined (which is the case for most models)\n        # it will default to `attention_head_dim`. This looks weird upon first reading it and it is.\n        # The reason for this behavior is to correct for incorrectly named variables that were introduced\n        # when this library was created. The incorrect naming was only discovered much later in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131\n        # Changing `attention_head_dim` to `num_attention_heads` for 40,000+ configurations is too backwards breaking\n        # which is why we correct for the naming here.\n        num_attention_heads = num_attention_heads or attention_head_dim\n\n        # Check inputs\n        if len(down_block_types) != len(up_block_types):\n            raise ValueError(\n                f\"Must provide the same number of `down_block_types` as `up_block_types`. `down_block_types`: {down_block_types}. `up_block_types`: {up_block_types}.\"\n            )\n\n        if len(block_out_channels) != len(down_block_types):\n            raise ValueError(\n                f\"Must provide the same number of `block_out_channels` as `down_block_types`. `block_out_channels`: {block_out_channels}. `down_block_types`: {down_block_types}.\"\n            )\n\n        if not isinstance(only_cross_attention, bool) and len(\n            only_cross_attention\n        ) != len(down_block_types):\n            raise ValueError(\n                f\"Must provide the same number of `only_cross_attention` as `down_block_types`. `only_cross_attention`: {only_cross_attention}. `down_block_types`: {down_block_types}.\"\n            )\n\n        if not isinstance(num_attention_heads, int) and len(num_attention_heads) != len(\n            down_block_types\n        ):\n            raise ValueError(\n                f\"Must provide the same number of `num_attention_heads` as `down_block_types`. `num_attention_heads`: {num_attention_heads}. `down_block_types`: {down_block_types}.\"\n            )\n\n        if not isinstance(attention_head_dim, int) and len(attention_head_dim) != len(\n            down_block_types\n        ):\n            raise ValueError(\n                f\"Must provide the same number of `attention_head_dim` as `down_block_types`. `attention_head_dim`: {attention_head_dim}. `down_block_types`: {down_block_types}.\"\n            )\n\n        if isinstance(cross_attention_dim, list) and len(cross_attention_dim) != len(\n            down_block_types\n        ):\n            raise ValueError(\n                f\"Must provide the same number of `cross_attention_dim` as `down_block_types`. `cross_attention_dim`: {cross_attention_dim}. `down_block_types`: {down_block_types}.\"\n            )\n\n        if not isinstance(layers_per_block, int) and len(layers_per_block) != len(\n            down_block_types\n        ):\n            raise ValueError(\n                f\"Must provide the same number of `layers_per_block` as `down_block_types`. `layers_per_block`: {layers_per_block}. `down_block_types`: {down_block_types}.\"\n            )\n        if (\n            isinstance(transformer_layers_per_block, list)\n            and reverse_transformer_layers_per_block is None\n        ):\n            for layer_number_per_block in transformer_layers_per_block:\n                if isinstance(layer_number_per_block, list):\n                    raise ValueError(\n                        \"Must provide 'reverse_transformer_layers_per_block` if using asymmetrical UNet.\"\n                    )\n\n        # input\n        conv_in_padding = (conv_in_kernel - 1) // 2\n        self.conv_in = nn.Conv2d(\n            in_channels,\n            block_out_channels[0],\n            kernel_size=conv_in_kernel,\n            padding=conv_in_padding,\n        )\n\n        # time\n        if time_embedding_type == \"fourier\":\n            time_embed_dim = time_embedding_dim or block_out_channels[0] * 2\n            if time_embed_dim % 2 != 0:\n                raise ValueError(\n                    f\"`time_embed_dim` should be divisible by 2, but is {time_embed_dim}.\"\n                )\n            self.time_proj = GaussianFourierProjection(\n                time_embed_dim // 2,\n                set_W_to_weight=False,\n                log=False,\n                flip_sin_to_cos=flip_sin_to_cos,\n            )\n            timestep_input_dim = time_embed_dim\n        elif time_embedding_type == \"positional\":\n            time_embed_dim = time_embedding_dim or block_out_channels[0] * 4\n\n            self.time_proj = Timesteps(\n                block_out_channels[0], flip_sin_to_cos, freq_shift\n            )\n            timestep_input_dim = block_out_channels[0]\n        else:\n            raise ValueError(\n                f\"{time_embedding_type} does not exist. Please make sure to use one of `fourier` or `positional`.\"\n            )\n\n        self.time_embedding = TimestepEmbedding(\n            timestep_input_dim,\n            time_embed_dim,\n            act_fn=act_fn,\n            post_act_fn=timestep_post_act,\n            cond_proj_dim=time_cond_proj_dim,\n        )\n\n        if encoder_hid_dim_type is None and encoder_hid_dim is not None:\n            encoder_hid_dim_type = \"text_proj\"\n            self.register_to_config(encoder_hid_dim_type=encoder_hid_dim_type)\n            logger.info(\n                \"encoder_hid_dim_type defaults to 'text_proj' as `encoder_hid_dim` is defined.\"\n            )\n\n        if encoder_hid_dim is None and encoder_hid_dim_type is not None:\n            raise ValueError(\n                f\"`encoder_hid_dim` has to be defined when `encoder_hid_dim_type` is set to {encoder_hid_dim_type}.\"\n            )\n\n        if encoder_hid_dim_type == \"text_proj\":\n            self.encoder_hid_proj = nn.Linear(encoder_hid_dim, cross_attention_dim)\n        elif encoder_hid_dim_type == \"text_image_proj\":\n            # image_embed_dim DOESN'T have to be `cross_attention_dim`. To not clutter the __init__ too much\n            # they are set to `cross_attention_dim` here as this is exactly the required dimension for the currently only use\n            # case when `addition_embed_type == \"text_image_proj\"` (Kadinsky 2.1)`\n            self.encoder_hid_proj = TextImageProjection(\n                text_embed_dim=encoder_hid_dim,\n                image_embed_dim=cross_attention_dim,\n                cross_attention_dim=cross_attention_dim,\n            )\n        elif encoder_hid_dim_type == \"image_proj\":\n            # Kandinsky 2.2\n            self.encoder_hid_proj = ImageProjection(\n                image_embed_dim=encoder_hid_dim,\n                cross_attention_dim=cross_attention_dim,\n            )\n        elif encoder_hid_dim_type is not None:\n            raise ValueError(\n                f\"encoder_hid_dim_type: {encoder_hid_dim_type} must be None, 'text_proj' or 'text_image_proj'.\"\n            )\n        else:\n            self.encoder_hid_proj = None\n\n        # class embedding\n        if class_embed_type is None and num_class_embeds is not None:\n            self.class_embedding = nn.Embedding(num_class_embeds, time_embed_dim)\n        elif class_embed_type == \"timestep\":\n            self.class_embedding = TimestepEmbedding(\n                timestep_input_dim, time_embed_dim, act_fn=act_fn\n            )\n        elif class_embed_type == \"identity\":\n            self.class_embedding = nn.Identity(time_embed_dim, time_embed_dim)\n        elif class_embed_type == \"projection\":\n            if projection_class_embeddings_input_dim is None:\n                raise ValueError(\n                    \"`class_embed_type`: 'projection' requires `projection_class_embeddings_input_dim` be set\"\n                )\n            # The projection `class_embed_type` is the same as the timestep `class_embed_type` except\n            # 1. the `class_labels` inputs are not first converted to sinusoidal embeddings\n            # 2. it projects from an arbitrary input dimension.\n            #\n            # Note that `TimestepEmbedding` is quite general, being mainly linear layers and activations.\n            # When used for embedding actual timesteps, the timesteps are first converted to sinusoidal embeddings.\n            # As a result, `TimestepEmbedding` can be passed arbitrary vectors.\n            self.class_embedding = TimestepEmbedding(\n                projection_class_embeddings_input_dim, time_embed_dim\n            )\n        elif class_embed_type == \"simple_projection\":\n            if projection_class_embeddings_input_dim is None:\n                raise ValueError(\n                    \"`class_embed_type`: 'simple_projection' requires `projection_class_embeddings_input_dim` be set\"\n                )\n            self.class_embedding = nn.Linear(\n                projection_class_embeddings_input_dim, time_embed_dim\n            )\n        else:\n            self.class_embedding = None\n\n        if addition_embed_type == \"text\":\n            if encoder_hid_dim is not None:\n                text_time_embedding_from_dim = encoder_hid_dim\n            else:\n                text_time_embedding_from_dim = cross_attention_dim\n\n            self.add_embedding = TextTimeEmbedding(\n                text_time_embedding_from_dim,\n                time_embed_dim,\n                num_heads=addition_embed_type_num_heads,\n            )\n        elif addition_embed_type == \"text_image\":\n            # text_embed_dim and image_embed_dim DON'T have to be `cross_attention_dim`. To not clutter the __init__ too much\n            # they are set to `cross_attention_dim` here as this is exactly the required dimension for the currently only use\n            # case when `addition_embed_type == \"text_image\"` (Kadinsky 2.1)`\n            self.add_embedding = TextImageTimeEmbedding(\n                text_embed_dim=cross_attention_dim,\n                image_embed_dim=cross_attention_dim,\n                time_embed_dim=time_embed_dim,\n            )\n        elif addition_embed_type == \"text_time\":\n            self.add_time_proj = Timesteps(\n                addition_time_embed_dim, flip_sin_to_cos, freq_shift\n            )\n            self.add_embedding = TimestepEmbedding(\n                projection_class_embeddings_input_dim, time_embed_dim\n            )\n        elif addition_embed_type == \"image\":\n            # Kandinsky 2.2\n            self.add_embedding = ImageTimeEmbedding(\n                image_embed_dim=encoder_hid_dim, time_embed_dim=time_embed_dim\n            )\n        elif addition_embed_type == \"image_hint\":\n            # Kandinsky 2.2 ControlNet\n            self.add_embedding = ImageHintTimeEmbedding(\n                image_embed_dim=encoder_hid_dim, time_embed_dim=time_embed_dim\n            )\n        elif addition_embed_type is not None:\n            raise ValueError(\n                f\"addition_embed_type: {addition_embed_type} must be None, 'text' or 'text_image'.\"\n            )\n\n        if time_embedding_act_fn is None:\n            self.time_embed_act = None\n        else:\n            self.time_embed_act = get_activation(time_embedding_act_fn)\n\n        self.down_blocks = nn.ModuleList([])\n        self.up_blocks = nn.ModuleList([])\n\n        if isinstance(only_cross_attention, bool):\n            if mid_block_only_cross_attention is None:\n                mid_block_only_cross_attention = only_cross_attention\n\n            only_cross_attention = [only_cross_attention] * len(down_block_types)\n\n        if mid_block_only_cross_attention is None:\n            mid_block_only_cross_attention = False\n\n        if isinstance(num_attention_heads, int):\n            num_attention_heads = (num_attention_heads,) * len(down_block_types)\n\n        if isinstance(attention_head_dim, int):\n            attention_head_dim = (attention_head_dim,) * len(down_block_types)\n\n        if isinstance(cross_attention_dim, int):\n            cross_attention_dim = (cross_attention_dim,) * len(down_block_types)\n\n        if isinstance(layers_per_block, int):\n            layers_per_block = [layers_per_block] * len(down_block_types)\n\n        if isinstance(transformer_layers_per_block, int):\n            transformer_layers_per_block = [transformer_layers_per_block] * len(\n                down_block_types\n            )\n\n        if class_embeddings_concat:\n            # The time embeddings are concatenated with the class embeddings. The dimension of the\n            # time embeddings passed to the down, middle, and up blocks is twice the dimension of the\n            # regular time embeddings\n            blocks_time_embed_dim = time_embed_dim * 2\n        else:\n            blocks_time_embed_dim = time_embed_dim\n\n        # down\n        output_channel = block_out_channels[0]\n        for i, down_block_type in enumerate(down_block_types):\n            input_channel = output_channel\n            output_channel = block_out_channels[i]\n            is_final_block = i == len(block_out_channels) - 1\n\n            down_block = get_down_block(\n                down_block_type,\n                num_layers=layers_per_block[i],\n                transformer_layers_per_block=transformer_layers_per_block[i],\n                in_channels=input_channel,\n                out_channels=output_channel,\n                temb_channels=blocks_time_embed_dim,\n                add_downsample=not is_final_block,\n                resnet_eps=norm_eps,\n                resnet_act_fn=act_fn,\n                resnet_groups=norm_num_groups,\n                cross_attention_dim=cross_attention_dim[i],\n                num_attention_heads=num_attention_heads[i],\n                downsample_padding=downsample_padding,\n                dual_cross_attention=dual_cross_attention,\n                use_linear_projection=use_linear_projection,\n                only_cross_attention=only_cross_attention[i],\n                upcast_attention=upcast_attention,\n                resnet_time_scale_shift=resnet_time_scale_shift,\n                attention_type=attention_type,\n                resnet_skip_time_act=resnet_skip_time_act,\n                resnet_out_scale_factor=resnet_out_scale_factor,\n                cross_attention_norm=cross_attention_norm,\n                attention_head_dim=attention_head_dim[i]\n                if attention_head_dim[i] is not None\n                else output_channel,\n                dropout=dropout,\n            )\n            self.down_blocks.append(down_block)\n\n        # mid\n        if mid_block_type == \"UNetMidBlock2DCrossAttn\":\n            self.mid_block = UNetMidBlock2DCrossAttn(\n                transformer_layers_per_block=transformer_layers_per_block[-1],\n                in_channels=block_out_channels[-1],\n                temb_channels=blocks_time_embed_dim,\n                dropout=dropout,\n                resnet_eps=norm_eps,\n                resnet_act_fn=act_fn,\n                output_scale_factor=mid_block_scale_factor,\n                resnet_time_scale_shift=resnet_time_scale_shift,\n                cross_attention_dim=cross_attention_dim[-1],\n                num_attention_heads=num_attention_heads[-1],\n                resnet_groups=norm_num_groups,\n                dual_cross_attention=dual_cross_attention,\n                use_linear_projection=use_linear_projection,\n                upcast_attention=upcast_attention,\n                attention_type=attention_type,\n            )\n        elif mid_block_type == \"UNetMidBlock2DSimpleCrossAttn\":\n            raise NotImplementedError(f\"Unsupport mid_block_type: {mid_block_type}\")\n        elif mid_block_type == \"UNetMidBlock2D\":\n            self.mid_block = UNetMidBlock2D(\n                in_channels=block_out_channels[-1],\n                temb_channels=blocks_time_embed_dim,\n                dropout=dropout,\n                num_layers=0,\n                resnet_eps=norm_eps,\n                resnet_act_fn=act_fn,\n                output_scale_factor=mid_block_scale_factor,\n                resnet_groups=norm_num_groups,\n                resnet_time_scale_shift=resnet_time_scale_shift,\n                add_attention=False,\n            )\n        elif mid_block_type is None:\n            self.mid_block = None\n        else:\n            raise ValueError(f\"unknown mid_block_type : {mid_block_type}\")\n\n        # count how many layers upsample the images\n        self.num_upsamplers = 0\n\n        # up\n        reversed_block_out_channels = list(reversed(block_out_channels))\n        reversed_num_attention_heads = list(reversed(num_attention_heads))\n        reversed_layers_per_block = list(reversed(layers_per_block))\n        reversed_cross_attention_dim = list(reversed(cross_attention_dim))\n        reversed_transformer_layers_per_block = (\n            list(reversed(transformer_layers_per_block))\n            if reverse_transformer_layers_per_block is None\n            else reverse_transformer_layers_per_block\n        )\n        only_cross_attention = list(reversed(only_cross_attention))\n\n        output_channel = reversed_block_out_channels[0]\n        for i, up_block_type in enumerate(up_block_types):\n            is_final_block = i == len(block_out_channels) - 1\n\n            prev_output_channel = output_channel\n            output_channel = reversed_block_out_channels[i]\n            input_channel = reversed_block_out_channels[\n                min(i + 1, len(block_out_channels) - 1)\n            ]\n\n            # add upsample block for all BUT final layer\n            if not is_final_block:\n                add_upsample = True\n                self.num_upsamplers += 1\n            else:\n                add_upsample = False\n\n            up_block = get_up_block(\n                up_block_type,\n                num_layers=reversed_layers_per_block[i] + 1,\n                transformer_layers_per_block=reversed_transformer_layers_per_block[i],\n                in_channels=input_channel,\n                out_channels=output_channel,\n                prev_output_channel=prev_output_channel,\n                temb_channels=blocks_time_embed_dim,\n                add_upsample=add_upsample,\n                resnet_eps=norm_eps,\n                resnet_act_fn=act_fn,\n                resolution_idx=i,\n                resnet_groups=norm_num_groups,\n                cross_attention_dim=reversed_cross_attention_dim[i],\n                num_attention_heads=reversed_num_attention_heads[i],\n                dual_cross_attention=dual_cross_attention,\n                use_linear_projection=use_linear_projection,\n                only_cross_attention=only_cross_attention[i],\n                upcast_attention=upcast_attention,\n                resnet_time_scale_shift=resnet_time_scale_shift,\n                attention_type=attention_type,\n                resnet_skip_time_act=resnet_skip_time_act,\n                resnet_out_scale_factor=resnet_out_scale_factor,\n                cross_attention_norm=cross_attention_norm,\n                attention_head_dim=attention_head_dim[i]\n                if attention_head_dim[i] is not None\n                else output_channel,\n                dropout=dropout,\n            )\n            self.up_blocks.append(up_block)\n            prev_output_channel = output_channel\n\n        # out\n        if norm_num_groups is not None:\n            self.conv_norm_out = nn.GroupNorm(\n                num_channels=block_out_channels[0],\n                num_groups=norm_num_groups,\n                eps=norm_eps,\n            )\n\n            self.conv_act = get_activation(act_fn)\n\n        else:\n            self.conv_norm_out = None\n            self.conv_act = None\n        self.conv_norm_out = None\n\n        conv_out_padding = (conv_out_kernel - 1) // 2\n        # self.conv_out = nn.Conv2d(\n        #     block_out_channels[0],\n        #     out_channels,\n        #     kernel_size=conv_out_kernel,\n        #     padding=conv_out_padding,\n        # )\n\n        if attention_type in [\"gated\", \"gated-text-image\"]:\n            positive_len = 768\n            if isinstance(cross_attention_dim, int):\n                positive_len = cross_attention_dim\n            elif isinstance(cross_attention_dim, tuple) or isinstance(\n                cross_attention_dim, list\n            ):\n                positive_len = cross_attention_dim[0]\n\n            feature_type = \"text-only\" if attention_type == \"gated\" else \"text-image\"\n            # self.position_net = PositionNet(\n            #     positive_len=positive_len,\n            #     out_dim=cross_attention_dim,\n            #     feature_type=feature_type,\n            # )\n\n    @property\n    def attn_processors(self) -> Dict[str, AttentionProcessor]:\n        r\"\"\"\n        Returns:\n            `dict` of attention processors: A dictionary containing all attention processors used in the model with\n            indexed by its weight name.\n        \"\"\"\n        # set recursively\n        processors = {}\n\n        def fn_recursive_add_processors(\n            name: str,\n            module: torch.nn.Module,\n            processors: Dict[str, AttentionProcessor],\n        ):\n            if hasattr(module, \"get_processor\"):\n                processors[f\"{name}.processor\"] = module.get_processor(\n                    return_deprecated_lora=True\n                )\n\n            for sub_name, child in module.named_children():\n                fn_recursive_add_processors(f\"{name}.{sub_name}\", child, processors)\n\n            return processors\n\n        for name, module in self.named_children():\n            fn_recursive_add_processors(name, module, processors)\n\n        return processors\n\n    def set_attn_processor(\n        self,\n        processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]],\n        _remove_lora=False,\n    ):\n        r\"\"\"\n        Sets the attention processor to use to compute attention.\n\n        Parameters:\n            processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):\n                The instantiated processor class or a dictionary of processor classes that will be set as the processor\n                for **all** `Attention` layers.\n\n                If `processor` is a dict, the key needs to define the path to the corresponding cross attention\n                processor. This is strongly recommended when setting trainable attention processors.\n\n        \"\"\"\n        count = len(self.attn_processors.keys())\n\n        if isinstance(processor, dict) and len(processor) != count:\n            raise ValueError(\n                f\"A dict of processors was passed, but the number of processors {len(processor)} does not match the\"\n                f\" number of attention layers: {count}. Please make sure to pass {count} processor classes.\"\n            )\n\n        def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):\n            if hasattr(module, \"set_processor\"):\n                if not isinstance(processor, dict):\n                    module.set_processor(processor, _remove_lora=_remove_lora)\n                else:\n                    module.set_processor(\n                        processor.pop(f\"{name}.processor\"), _remove_lora=_remove_lora\n                    )\n\n            for sub_name, child in module.named_children():\n                fn_recursive_attn_processor(f\"{name}.{sub_name}\", child, processor)\n\n        for name, module in self.named_children():\n            fn_recursive_attn_processor(name, module, processor)\n\n    def set_default_attn_processor(self):\n        \"\"\"\n        Disables custom attention processors and sets the default attention implementation.\n        \"\"\"\n        if all(\n            proc.__class__ in ADDED_KV_ATTENTION_PROCESSORS\n            for proc in self.attn_processors.values()\n        ):\n            processor = AttnAddedKVProcessor()\n        elif all(\n            proc.__class__ in CROSS_ATTENTION_PROCESSORS\n            for proc in self.attn_processors.values()\n        ):\n            processor = AttnProcessor()\n        else:\n            raise ValueError(\n                f\"Cannot call `set_default_attn_processor` when attention processors are of type {next(iter(self.attn_processors.values()))}\"\n            )\n\n        self.set_attn_processor(processor, _remove_lora=True)\n\n    def set_attention_slice(self, slice_size):\n        r\"\"\"\n        Enable sliced attention computation.\n\n        When this option is enabled, the attention module splits the input tensor in slices to compute attention in\n        several steps. This is useful for saving some memory in exchange for a small decrease in speed.\n\n        Args:\n            slice_size (`str` or `int` or `list(int)`, *optional*, defaults to `\"auto\"`):\n                When `\"auto\"`, input to the attention heads is halved, so attention is computed in two steps. If\n                `\"max\"`, maximum amount of memory is saved by running only one slice at a time. If a number is\n                provided, uses as many slices as `attention_head_dim // slice_size`. In this case, `attention_head_dim`\n                must be a multiple of `slice_size`.\n        \"\"\"\n        sliceable_head_dims = []\n\n        def fn_recursive_retrieve_sliceable_dims(module: torch.nn.Module):\n            if hasattr(module, \"set_attention_slice\"):\n                sliceable_head_dims.append(module.sliceable_head_dim)\n\n            for child in module.children():\n                fn_recursive_retrieve_sliceable_dims(child)\n\n        # retrieve number of attention layers\n        for module in self.children():\n            fn_recursive_retrieve_sliceable_dims(module)\n\n        num_sliceable_layers = len(sliceable_head_dims)\n\n        if slice_size == \"auto\":\n            # half the attention head size is usually a good trade-off between\n            # speed and memory\n            slice_size = [dim // 2 for dim in sliceable_head_dims]\n        elif slice_size == \"max\":\n            # make smallest slice possible\n            slice_size = num_sliceable_layers * [1]\n\n        slice_size = (\n            num_sliceable_layers * [slice_size]\n            if not isinstance(slice_size, list)\n            else slice_size\n        )\n\n        if len(slice_size) != len(sliceable_head_dims):\n            raise ValueError(\n                f\"You have provided {len(slice_size)}, but {self.config} has {len(sliceable_head_dims)} different\"\n                f\" attention layers. Make sure to match `len(slice_size)` to be {len(sliceable_head_dims)}.\"\n            )\n\n        for i in range(len(slice_size)):\n            size = slice_size[i]\n            dim = sliceable_head_dims[i]\n            if size is not None and size > dim:\n                raise ValueError(f\"size {size} has to be smaller or equal to {dim}.\")\n\n        # Recursively walk through all the children.\n        # Any children which exposes the set_attention_slice method\n        # gets the message\n        def fn_recursive_set_attention_slice(\n            module: torch.nn.Module, slice_size: List[int]\n        ):\n            if hasattr(module, \"set_attention_slice\"):\n                module.set_attention_slice(slice_size.pop())\n\n            for child in module.children():\n                fn_recursive_set_attention_slice(child, slice_size)\n\n        reversed_slice_size = list(reversed(slice_size))\n        for module in self.children():\n            fn_recursive_set_attention_slice(module, reversed_slice_size)\n\n    def _set_gradient_checkpointing(self, module, value=False):\n        if hasattr(module, \"gradient_checkpointing\"):\n            module.gradient_checkpointing = value\n\n    def enable_freeu(self, s1, s2, b1, b2):\n        r\"\"\"Enables the FreeU mechanism from https://arxiv.org/abs/2309.11497.\n\n        The suffixes after the scaling factors represent the stage blocks where they are being applied.\n\n        Please refer to the [official repository](https://github.com/ChenyangSi/FreeU) for combinations of values that\n        are known to work well for different pipelines such as Stable Diffusion v1, v2, and Stable Diffusion XL.\n\n        Args:\n            s1 (`float`):\n                Scaling factor for stage 1 to attenuate the contributions of the skip features. This is done to\n                mitigate the \"oversmoothing effect\" in the enhanced denoising process.\n            s2 (`float`):\n                Scaling factor for stage 2 to attenuate the contributions of the skip features. This is done to\n                mitigate the \"oversmoothing effect\" in the enhanced denoising process.\n            b1 (`float`): Scaling factor for stage 1 to amplify the contributions of backbone features.\n            b2 (`float`): Scaling factor for stage 2 to amplify the contributions of backbone features.\n        \"\"\"\n        for i, upsample_block in enumerate(self.up_blocks):\n            setattr(upsample_block, \"s1\", s1)\n            setattr(upsample_block, \"s2\", s2)\n            setattr(upsample_block, \"b1\", b1)\n            setattr(upsample_block, \"b2\", b2)\n\n    def disable_freeu(self):\n        \"\"\"Disables the FreeU mechanism.\"\"\"\n        freeu_keys = {\"s1\", \"s2\", \"b1\", \"b2\"}\n        for i, upsample_block in enumerate(self.up_blocks):\n            for k in freeu_keys:\n                if (\n                    hasattr(upsample_block, k)\n                    or getattr(upsample_block, k, None) is not None\n                ):\n                    setattr(upsample_block, k, None)\n\n    def forward(\n        self,\n        sample: torch.FloatTensor,\n        timestep: Union[torch.Tensor, float, int],\n        encoder_hidden_states: torch.Tensor,\n        class_labels: Optional[torch.Tensor] = None,\n        timestep_cond: Optional[torch.Tensor] = None,\n        attention_mask: Optional[torch.Tensor] = None,\n        cross_attention_kwargs: Optional[Dict[str, Any]] = None,\n        added_cond_kwargs: Optional[Dict[str, torch.Tensor]] = None,\n        down_block_additional_residuals: Optional[Tuple[torch.Tensor]] = None,\n        mid_block_additional_residual: Optional[torch.Tensor] = None,\n        down_intrablock_additional_residuals: Optional[Tuple[torch.Tensor]] = None,\n        encoder_attention_mask: Optional[torch.Tensor] = None,\n        return_dict: bool = True,\n    ) -> Union[UNet2DConditionOutput, Tuple]:\n        r\"\"\"\n        The [`UNet2DConditionModel`] forward method.\n\n        Args:\n            sample (`torch.FloatTensor`):\n                The noisy input tensor with the following shape `(batch, channel, height, width)`.\n            timestep (`torch.FloatTensor` or `float` or `int`): The number of timesteps to denoise an input.\n            encoder_hidden_states (`torch.FloatTensor`):\n                The encoder hidden states with shape `(batch, sequence_length, feature_dim)`.\n            class_labels (`torch.Tensor`, *optional*, defaults to `None`):\n                Optional class labels for conditioning. Their embeddings will be summed with the timestep embeddings.\n            timestep_cond: (`torch.Tensor`, *optional*, defaults to `None`):\n                Conditional embeddings for timestep. If provided, the embeddings will be summed with the samples passed\n                through the `self.time_embedding` layer to obtain the timestep embeddings.\n            attention_mask (`torch.Tensor`, *optional*, defaults to `None`):\n                An attention mask of shape `(batch, key_tokens)` is applied to `encoder_hidden_states`. If `1` the mask\n                is kept, otherwise if `0` it is discarded. Mask will be converted into a bias, which adds large\n                negative values to the attention scores corresponding to \"discard\" tokens.\n            cross_attention_kwargs (`dict`, *optional*):\n                A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under\n                `self.processor` in\n                [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).\n            added_cond_kwargs: (`dict`, *optional*):\n                A kwargs dictionary containing additional embeddings that if specified are added to the embeddings that\n                are passed along to the UNet blocks.\n            down_block_additional_residuals: (`tuple` of `torch.Tensor`, *optional*):\n                A tuple of tensors that if specified are added to the residuals of down unet blocks.\n            mid_block_additional_residual: (`torch.Tensor`, *optional*):\n                A tensor that if specified is added to the residual of the middle unet block.\n            encoder_attention_mask (`torch.Tensor`):\n                A cross-attention mask of shape `(batch, sequence_length)` is applied to `encoder_hidden_states`. If\n                `True` the mask is kept, otherwise if `False` it is discarded. Mask will be converted into a bias,\n                which adds large negative values to the attention scores corresponding to \"discard\" tokens.\n            return_dict (`bool`, *optional*, defaults to `True`):\n                Whether or not to return a [`~models.unet_2d_condition.UNet2DConditionOutput`] instead of a plain\n                tuple.\n            cross_attention_kwargs (`dict`, *optional*):\n                A kwargs dictionary that if specified is passed along to the [`AttnProcessor`].\n            added_cond_kwargs: (`dict`, *optional*):\n                A kwargs dictionary containin additional embeddings that if specified are added to the embeddings that\n                are passed along to the UNet blocks.\n            down_block_additional_residuals (`tuple` of `torch.Tensor`, *optional*):\n                additional residuals to be added to UNet long skip connections from down blocks to up blocks for\n                example from ControlNet side model(s)\n            mid_block_additional_residual (`torch.Tensor`, *optional*):\n                additional residual to be added to UNet mid block output, for example from ControlNet side model\n            down_intrablock_additional_residuals (`tuple` of `torch.Tensor`, *optional*):\n                additional residuals to be added within UNet down blocks, for example from T2I-Adapter side model(s)\n\n        Returns:\n            [`~models.unet_2d_condition.UNet2DConditionOutput`] or `tuple`:\n                If `return_dict` is True, an [`~models.unet_2d_condition.UNet2DConditionOutput`] is returned, otherwise\n                a `tuple` is returned where the first element is the sample tensor.\n        \"\"\"\n        # By default samples have to be AT least a multiple of the overall upsampling factor.\n        # The overall upsampling factor is equal to 2 ** (# num of upsampling layers).\n        # However, the upsampling interpolation output size can be forced to fit any upsampling size\n        # on the fly if necessary.\n        default_overall_up_factor = 2**self.num_upsamplers\n\n        # upsample size should be forwarded when sample is not a multiple of `default_overall_up_factor`\n        forward_upsample_size = False\n        upsample_size = None\n\n        for dim in sample.shape[-2:]:\n            if dim % default_overall_up_factor != 0:\n                # Forward upsample size to force interpolation output size.\n                forward_upsample_size = True\n                break\n\n        # ensure attention_mask is a bias, and give it a singleton query_tokens dimension\n        # expects mask of shape:\n        #   [batch, key_tokens]\n        # adds singleton query_tokens dimension:\n        #   [batch,                    1, key_tokens]\n        # this helps to broadcast it as a bias over attention scores, which will be in one of the following shapes:\n        #   [batch,  heads, query_tokens, key_tokens] (e.g. torch sdp attn)\n        #   [batch * heads, query_tokens, key_tokens] (e.g. xformers or classic attn)\n        if attention_mask is not None:\n            # assume that mask is expressed as:\n            #   (1 = keep,      0 = discard)\n            # convert mask into a bias that can be added to attention scores:\n            #       (keep = +0,     discard = -10000.0)\n            attention_mask = (1 - attention_mask.to(sample.dtype)) * -10000.0\n            attention_mask = attention_mask.unsqueeze(1)\n\n        # convert encoder_attention_mask to a bias the same way we do for attention_mask\n        if encoder_attention_mask is not None:\n            encoder_attention_mask = (\n                1 - encoder_attention_mask.to(sample.dtype)\n            ) * -10000.0\n            encoder_attention_mask = encoder_attention_mask.unsqueeze(1)\n\n        # 0. center input if necessary\n        if self.config.center_input_sample:\n            sample = 2 * sample - 1.0\n\n        # 1. time\n        timesteps = timestep\n        if not torch.is_tensor(timesteps):\n            # TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can\n            # This would be a good case for the `match` statement (Python 3.10+)\n            is_mps = sample.device.type == \"mps\"\n            if isinstance(timestep, float):\n                dtype = torch.float32 if is_mps else torch.float64\n            else:\n                dtype = torch.int32 if is_mps else torch.int64\n            timesteps = torch.tensor([timesteps], dtype=dtype, device=sample.device)\n        elif len(timesteps.shape) == 0:\n            timesteps = timesteps[None].to(sample.device)\n\n        # broadcast to batch dimension in a way that's compatible with ONNX/Core ML\n        timesteps = timesteps.expand(sample.shape[0])\n\n        t_emb = self.time_proj(timesteps)\n\n        # `Timesteps` does not contain any weights and will always return f32 tensors\n        # but time_embedding might actually be running in fp16. so we need to cast here.\n        # there might be better ways to encapsulate this.\n        t_emb = t_emb.to(dtype=sample.dtype)\n\n        emb = self.time_embedding(t_emb, timestep_cond)\n        aug_emb = None\n\n        if self.class_embedding is not None:\n            if class_labels is None:\n                raise ValueError(\n                    \"class_labels should be provided when num_class_embeds > 0\"\n                )\n\n            if self.config.class_embed_type == \"timestep\":\n                class_labels = self.time_proj(class_labels)\n\n                # `Timesteps` does not contain any weights and will always return f32 tensors\n                # there might be better ways to encapsulate this.\n                class_labels = class_labels.to(dtype=sample.dtype)\n\n            class_emb = self.class_embedding(class_labels).to(dtype=sample.dtype)\n\n            if self.config.class_embeddings_concat:\n                emb = torch.cat([emb, class_emb], dim=-1)\n            else:\n                emb = emb + class_emb\n\n        if self.config.addition_embed_type == \"text\":\n            aug_emb = self.add_embedding(encoder_hidden_states)\n        elif self.config.addition_embed_type == \"text_image\":\n            # Kandinsky 2.1 - style\n            if \"image_embeds\" not in added_cond_kwargs:\n                raise ValueError(\n                    f\"{self.__class__} has the config param `addition_embed_type` set to 'text_image' which requires the keyword argument `image_embeds` to be passed in `added_cond_kwargs`\"\n                )\n\n            image_embs = added_cond_kwargs.get(\"image_embeds\")\n            text_embs = added_cond_kwargs.get(\"text_embeds\", encoder_hidden_states)\n            aug_emb = self.add_embedding(text_embs, image_embs)\n        elif self.config.addition_embed_type == \"text_time\":\n            # SDXL - style\n            if \"text_embeds\" not in added_cond_kwargs:\n                raise ValueError(\n                    f\"{self.__class__} has the config param `addition_embed_type` set to 'text_time' which requires the keyword argument `text_embeds` to be passed in `added_cond_kwargs`\"\n                )\n            text_embeds = added_cond_kwargs.get(\"text_embeds\")\n            if \"time_ids\" not in added_cond_kwargs:\n                raise ValueError(\n                    f\"{self.__class__} has the config param `addition_embed_type` set to 'text_time' which requires the keyword argument `time_ids` to be passed in `added_cond_kwargs`\"\n                )\n            time_ids = added_cond_kwargs.get(\"time_ids\")\n            time_embeds = self.add_time_proj(time_ids.flatten())\n            time_embeds = time_embeds.reshape((text_embeds.shape[0], -1))\n            add_embeds = torch.concat([text_embeds, time_embeds], dim=-1)\n            add_embeds = add_embeds.to(emb.dtype)\n            aug_emb = self.add_embedding(add_embeds)\n        elif self.config.addition_embed_type == \"image\":\n            # Kandinsky 2.2 - style\n            if \"image_embeds\" not in added_cond_kwargs:\n                raise ValueError(\n                    f\"{self.__class__} has the config param `addition_embed_type` set to 'image' which requires the keyword argument `image_embeds` to be passed in `added_cond_kwargs`\"\n                )\n            image_embs = added_cond_kwargs.get(\"image_embeds\")\n            aug_emb = self.add_embedding(image_embs)\n        elif self.config.addition_embed_type == \"image_hint\":\n            # Kandinsky 2.2 - style\n            if (\n                \"image_embeds\" not in added_cond_kwargs\n                or \"hint\" not in added_cond_kwargs\n            ):\n                raise ValueError(\n                    f\"{self.__class__} has the config param `addition_embed_type` set to 'image_hint' which requires the keyword arguments `image_embeds` and `hint` to be passed in `added_cond_kwargs`\"\n                )\n            image_embs = added_cond_kwargs.get(\"image_embeds\")\n            hint = added_cond_kwargs.get(\"hint\")\n            aug_emb, hint = self.add_embedding(image_embs, hint)\n            sample = torch.cat([sample, hint], dim=1)\n\n        emb = emb + aug_emb if aug_emb is not None else emb\n\n        if self.time_embed_act is not None:\n            emb = self.time_embed_act(emb)\n\n        if (\n            self.encoder_hid_proj is not None\n            and self.config.encoder_hid_dim_type == \"text_proj\"\n        ):\n            encoder_hidden_states = self.encoder_hid_proj(encoder_hidden_states)\n        elif (\n            self.encoder_hid_proj is not None\n            and self.config.encoder_hid_dim_type == \"text_image_proj\"\n        ):\n            # Kadinsky 2.1 - style\n            if \"image_embeds\" not in added_cond_kwargs:\n                raise ValueError(\n                    f\"{self.__class__} has the config param `encoder_hid_dim_type` set to 'text_image_proj' which requires the keyword argument `image_embeds` to be passed in  `added_conditions`\"\n                )\n\n            image_embeds = added_cond_kwargs.get(\"image_embeds\")\n            encoder_hidden_states = self.encoder_hid_proj(\n                encoder_hidden_states, image_embeds\n            )\n        elif (\n            self.encoder_hid_proj is not None\n            and self.config.encoder_hid_dim_type == \"image_proj\"\n        ):\n            # Kandinsky 2.2 - style\n            if \"image_embeds\" not in added_cond_kwargs:\n                raise ValueError(\n                    f\"{self.__class__} has the config param `encoder_hid_dim_type` set to 'image_proj' which requires the keyword argument `image_embeds` to be passed in  `added_conditions`\"\n                )\n            image_embeds = added_cond_kwargs.get(\"image_embeds\")\n            encoder_hidden_states = self.encoder_hid_proj(image_embeds)\n        elif (\n            self.encoder_hid_proj is not None\n            and self.config.encoder_hid_dim_type == \"ip_image_proj\"\n        ):\n            if \"image_embeds\" not in added_cond_kwargs:\n                raise ValueError(\n                    f\"{self.__class__} has the config param `encoder_hid_dim_type` set to 'ip_image_proj' which requires the keyword argument `image_embeds` to be passed in  `added_conditions`\"\n                )\n            image_embeds = added_cond_kwargs.get(\"image_embeds\")\n            image_embeds = self.encoder_hid_proj(image_embeds).to(\n                encoder_hidden_states.dtype\n            )\n            encoder_hidden_states = torch.cat(\n                [encoder_hidden_states, image_embeds], dim=1\n            )\n\n        # 2. pre-process\n        sample = self.conv_in(sample)\n\n        # # 2.5 GLIGEN position net\n        # if (\n        #     cross_attention_kwargs is not None\n        #     and cross_attention_kwargs.get(\"gligen\", None) is not None\n        # ):\n        #     cross_attention_kwargs = cross_attention_kwargs.copy()\n        #     gligen_args = cross_attention_kwargs.pop(\"gligen\")\n        #     cross_attention_kwargs[\"gligen\"] = {\n        #         \"objs\": self.position_net(**gligen_args)\n        #     }\n\n        # 3. down\n        lora_scale = (\n            cross_attention_kwargs.get(\"scale\", 1.0)\n            if cross_attention_kwargs is not None\n            else 1.0\n        )\n        if USE_PEFT_BACKEND:\n            # weight the lora layers by setting `lora_scale` for each PEFT layer\n            scale_lora_layers(self, lora_scale)\n\n        is_controlnet = (\n            mid_block_additional_residual is not None\n            and down_block_additional_residuals is not None\n        )\n        # using new arg down_intrablock_additional_residuals for T2I-Adapters, to distinguish from controlnets\n        is_adapter = down_intrablock_additional_residuals is not None\n        # maintain backward compatibility for legacy usage, where\n        #       T2I-Adapter and ControlNet both use down_block_additional_residuals arg\n        #       but can only use one or the other\n        if (\n            not is_adapter\n            and mid_block_additional_residual is None\n            and down_block_additional_residuals is not None\n        ):\n            deprecate(\n                \"T2I should not use down_block_additional_residuals\",\n                \"1.3.0\",\n                \"Passing intrablock residual connections with `down_block_additional_residuals` is deprecated \\\n                       and will be removed in diffusers 1.3.0.  `down_block_additional_residuals` should only be used \\\n                       for ControlNet. Please make sure use `down_intrablock_additional_residuals` instead. \",\n                standard_warn=False,\n            )\n            down_intrablock_additional_residuals = down_block_additional_residuals\n            is_adapter = True\n\n        down_block_res_samples = (sample,)\n        tot_referece_features = ()\n        for downsample_block in self.down_blocks:\n            if (\n                hasattr(downsample_block, \"has_cross_attention\")\n                and downsample_block.has_cross_attention\n            ):\n                # For t2i-adapter CrossAttnDownBlock2D\n                additional_residuals = {}\n                if is_adapter and len(down_intrablock_additional_residuals) > 0:\n                    additional_residuals[\n                        \"additional_residuals\"\n                    ] = down_intrablock_additional_residuals.pop(0)\n\n                sample, res_samples = downsample_block(\n                    hidden_states=sample,\n                    temb=emb,\n                    encoder_hidden_states=encoder_hidden_states,\n                    attention_mask=attention_mask,\n                    cross_attention_kwargs=cross_attention_kwargs,\n                    encoder_attention_mask=encoder_attention_mask,\n                    **additional_residuals,\n                )\n            else:\n                sample, res_samples = downsample_block(\n                    hidden_states=sample, temb=emb, scale=lora_scale\n                )\n                if is_adapter and len(down_intrablock_additional_residuals) > 0:\n                    sample += down_intrablock_additional_residuals.pop(0)\n\n            down_block_res_samples += res_samples\n\n        if is_controlnet:\n            new_down_block_res_samples = ()\n\n            for down_block_res_sample, down_block_additional_residual in zip(\n                down_block_res_samples, down_block_additional_residuals\n            ):\n                down_block_res_sample = (\n                    down_block_res_sample + down_block_additional_residual\n                )\n                new_down_block_res_samples = new_down_block_res_samples + (\n                    down_block_res_sample,\n                )\n\n            down_block_res_samples = new_down_block_res_samples\n\n        # 4. mid\n        if self.mid_block is not None:\n            if (\n                hasattr(self.mid_block, \"has_cross_attention\")\n                and self.mid_block.has_cross_attention\n            ):\n                sample = self.mid_block(\n                    sample,\n                    emb,\n                    encoder_hidden_states=encoder_hidden_states,\n                    attention_mask=attention_mask,\n                    cross_attention_kwargs=cross_attention_kwargs,\n                    encoder_attention_mask=encoder_attention_mask,\n                )\n            else:\n                sample = self.mid_block(sample, emb)\n\n            # To support T2I-Adapter-XL\n            if (\n                is_adapter\n                and len(down_intrablock_additional_residuals) > 0\n                and sample.shape == down_intrablock_additional_residuals[0].shape\n            ):\n                sample += down_intrablock_additional_residuals.pop(0)\n\n        if is_controlnet:\n            sample = sample + mid_block_additional_residual\n\n        # 5. up\n        for i, upsample_block in enumerate(self.up_blocks):\n            is_final_block = i == len(self.up_blocks) - 1\n\n            res_samples = down_block_res_samples[-len(upsample_block.resnets) :]\n            down_block_res_samples = down_block_res_samples[\n                : -len(upsample_block.resnets)\n            ]\n\n            # if we have not reached the final block and need to forward the\n            # upsample size, we do it here\n            if not is_final_block and forward_upsample_size:\n                upsample_size = down_block_res_samples[-1].shape[2:]\n\n            if (\n                hasattr(upsample_block, \"has_cross_attention\")\n                and upsample_block.has_cross_attention\n            ):\n                sample = upsample_block(\n                    hidden_states=sample,\n                    temb=emb,\n                    res_hidden_states_tuple=res_samples,\n                    encoder_hidden_states=encoder_hidden_states,\n                    cross_attention_kwargs=cross_attention_kwargs,\n                    upsample_size=upsample_size,\n                    attention_mask=attention_mask,\n                    encoder_attention_mask=encoder_attention_mask,\n                )\n            else:\n                sample = upsample_block(\n                    hidden_states=sample,\n                    temb=emb,\n                    res_hidden_states_tuple=res_samples,\n                    upsample_size=upsample_size,\n                    scale=lora_scale,\n                )\n\n        # 6. post-process\n        # if self.conv_norm_out:\n        #     sample = self.conv_norm_out(sample)\n        #     sample = self.conv_act(sample)\n        # sample = self.conv_out(sample)\n\n        if USE_PEFT_BACKEND:\n            # remove `lora_scale` from each PEFT layer\n            unscale_lora_layers(self, lora_scale)\n\n        if not return_dict:\n            return (sample,)\n\n        return UNet2DConditionOutput(sample=sample)\n"
  },
  {
    "path": "src/models/unet_2d_condition_main.py",
    "content": "# Adapted from https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/unet_2d_condition.py\nfrom dataclasses import dataclass\nfrom typing import Any, Dict, List, Optional, Tuple, Union\n\nimport torch\nimport torch.nn as nn\nimport torch.utils.checkpoint\nfrom diffusers.configuration_utils import ConfigMixin, register_to_config\nfrom diffusers.loaders import UNet2DConditionLoadersMixin\nfrom diffusers.models.activations import get_activation\nfrom diffusers.models.attention_processor import (\n    ADDED_KV_ATTENTION_PROCESSORS,\n    CROSS_ATTENTION_PROCESSORS,\n    AttentionProcessor,\n    AttnAddedKVProcessor,\n    AttnProcessor,\n)\nfrom diffusers.models.embeddings import (\n    GaussianFourierProjection,\n    ImageHintTimeEmbedding,\n    ImageProjection,\n    ImageTimeEmbedding,\n    # PositionNet,\n    TextImageProjection,\n    TextImageTimeEmbedding,\n    TextTimeEmbedding,\n    TimestepEmbedding,\n    Timesteps,\n)\nfrom diffusers.models.modeling_utils import ModelMixin\nfrom diffusers.utils import (\n    USE_PEFT_BACKEND,\n    BaseOutput,\n    deprecate,\n    logging,\n    scale_lora_layers,\n    unscale_lora_layers,\n)\n\nfrom .unet_2d_blocks import (\n    UNetMidBlock2D,\n    UNetMidBlock2DCrossAttn,\n    get_down_block,\n    get_up_block,\n    get_mid_block\n)\n\nlogger = logging.get_logger(__name__)  # pylint: disable=invalid-name\n\n@dataclass\nclass UNet2DConditionOutput(BaseOutput):\n    \"\"\"\n    The output of [`UNet2DConditionModel`].\n\n    Args:\n        sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n            The hidden states output conditioned on `encoder_hidden_states` input. Output of last layer of model.\n    \"\"\"\n\n    sample: torch.FloatTensor = None\n\n\nclass UNet2DConditionModel_main(ModelMixin, ConfigMixin, UNet2DConditionLoadersMixin):\n    r\"\"\"\n    A conditional 2D UNet model that takes a noisy sample, conditional state, and a timestep and returns a sample\n    shaped output.\n\n    This model inherits from [`ModelMixin`]. Check the superclass documentation for it's generic methods implemented\n    for all models (such as downloading or saving).\n\n    Parameters:\n        sample_size (`int` or `Tuple[int, int]`, *optional*, defaults to `None`):\n            Height and width of input/output sample.\n        in_channels (`int`, *optional*, defaults to 4): Number of channels in the input sample.\n        out_channels (`int`, *optional*, defaults to 4): Number of channels in the output.\n        center_input_sample (`bool`, *optional*, defaults to `False`): Whether to center the input sample.\n        flip_sin_to_cos (`bool`, *optional*, defaults to `True`):\n            Whether to flip the sin to cos in the time embedding.\n        freq_shift (`int`, *optional*, defaults to 0): The frequency shift to apply to the time embedding.\n        down_block_types (`Tuple[str]`, *optional*, defaults to `(\"CrossAttnDownBlock2D\", \"CrossAttnDownBlock2D\", \"CrossAttnDownBlock2D\", \"DownBlock2D\")`):\n            The tuple of downsample blocks to use.\n        mid_block_type (`str`, *optional*, defaults to `\"UNetMidBlock2DCrossAttn\"`):\n            Block type for middle of UNet, it can be one of `UNetMidBlock2DCrossAttn`, `UNetMidBlock2D`, or\n            `UNetMidBlock2DSimpleCrossAttn`. If `None`, the mid block layer is skipped.\n        up_block_types (`Tuple[str]`, *optional*, defaults to `(\"UpBlock2D\", \"CrossAttnUpBlock2D\", \"CrossAttnUpBlock2D\", \"CrossAttnUpBlock2D\")`):\n            The tuple of upsample blocks to use.\n        only_cross_attention(`bool` or `Tuple[bool]`, *optional*, default to `False`):\n            Whether to include self-attention in the basic transformer blocks, see\n            [`~models.attention.BasicTransformerBlock`].\n        block_out_channels (`Tuple[int]`, *optional*, defaults to `(320, 640, 1280, 1280)`):\n            The tuple of output channels for each block.\n        layers_per_block (`int`, *optional*, defaults to 2): The number of layers per block.\n        downsample_padding (`int`, *optional*, defaults to 1): The padding to use for the downsampling convolution.\n        mid_block_scale_factor (`float`, *optional*, defaults to 1.0): The scale factor to use for the mid block.\n        dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.\n        act_fn (`str`, *optional*, defaults to `\"silu\"`): The activation function to use.\n        norm_num_groups (`int`, *optional*, defaults to 32): The number of groups to use for the normalization.\n            If `None`, normalization and activation layers is skipped in post-processing.\n        norm_eps (`float`, *optional*, defaults to 1e-5): The epsilon to use for the normalization.\n        cross_attention_dim (`int` or `Tuple[int]`, *optional*, defaults to 1280):\n            The dimension of the cross attention features.\n        transformer_layers_per_block (`int`, `Tuple[int]`, or `Tuple[Tuple]` , *optional*, defaults to 1):\n            The number of transformer blocks of type [`~models.attention.BasicTransformerBlock`]. Only relevant for\n            [`~models.unet_2d_blocks.CrossAttnDownBlock2D`], [`~models.unet_2d_blocks.CrossAttnUpBlock2D`],\n            [`~models.unet_2d_blocks.UNetMidBlock2DCrossAttn`].\n        reverse_transformer_layers_per_block : (`Tuple[Tuple]`, *optional*, defaults to None):\n            The number of transformer blocks of type [`~models.attention.BasicTransformerBlock`], in the upsampling\n            blocks of the U-Net. Only relevant if `transformer_layers_per_block` is of type `Tuple[Tuple]` and for\n            [`~models.unet_2d_blocks.CrossAttnDownBlock2D`], [`~models.unet_2d_blocks.CrossAttnUpBlock2D`],\n            [`~models.unet_2d_blocks.UNetMidBlock2DCrossAttn`].\n        encoder_hid_dim (`int`, *optional*, defaults to None):\n            If `encoder_hid_dim_type` is defined, `encoder_hidden_states` will be projected from `encoder_hid_dim`\n            dimension to `cross_attention_dim`.\n        encoder_hid_dim_type (`str`, *optional*, defaults to `None`):\n            If given, the `encoder_hidden_states` and potentially other embeddings are down-projected to text\n            embeddings of dimension `cross_attention` according to `encoder_hid_dim_type`.\n        attention_head_dim (`int`, *optional*, defaults to 8): The dimension of the attention heads.\n        num_attention_heads (`int`, *optional*):\n            The number of attention heads. If not defined, defaults to `attention_head_dim`\n        resnet_time_scale_shift (`str`, *optional*, defaults to `\"default\"`): Time scale shift config\n            for ResNet blocks (see [`~models.resnet.ResnetBlock2D`]). Choose from `default` or `scale_shift`.\n        class_embed_type (`str`, *optional*, defaults to `None`):\n            The type of class embedding to use which is ultimately summed with the time embeddings. Choose from `None`,\n            `\"timestep\"`, `\"identity\"`, `\"projection\"`, or `\"simple_projection\"`.\n        addition_embed_type (`str`, *optional*, defaults to `None`):\n            Configures an optional embedding which will be summed with the time embeddings. Choose from `None` or\n            \"text\". \"text\" will use the `TextTimeEmbedding` layer.\n        addition_time_embed_dim: (`int`, *optional*, defaults to `None`):\n            Dimension for the timestep embeddings.\n        num_class_embeds (`int`, *optional*, defaults to `None`):\n            Input dimension of the learnable embedding matrix to be projected to `time_embed_dim`, when performing\n            class conditioning with `class_embed_type` equal to `None`.\n        time_embedding_type (`str`, *optional*, defaults to `positional`):\n            The type of position embedding to use for timesteps. Choose from `positional` or `fourier`.\n        time_embedding_dim (`int`, *optional*, defaults to `None`):\n            An optional override for the dimension of the projected time embedding.\n        time_embedding_act_fn (`str`, *optional*, defaults to `None`):\n            Optional activation function to use only once on the time embeddings before they are passed to the rest of\n            the UNet. Choose from `silu`, `mish`, `gelu`, and `swish`.\n        timestep_post_act (`str`, *optional*, defaults to `None`):\n            The second activation function to use in timestep embedding. Choose from `silu`, `mish` and `gelu`.\n        time_cond_proj_dim (`int`, *optional*, defaults to `None`):\n            The dimension of `cond_proj` layer in the timestep embedding.\n        conv_in_kernel (`int`, *optional*, default to `3`): The kernel size of `conv_in` layer.\n        conv_out_kernel (`int`, *optional*, default to `3`): The kernel size of `conv_out` layer.\n        projection_class_embeddings_input_dim (`int`, *optional*): The dimension of the `class_labels` input when\n            `class_embed_type=\"projection\"`. Required when `class_embed_type=\"projection\"`.\n        class_embeddings_concat (`bool`, *optional*, defaults to `False`): Whether to concatenate the time\n            embeddings with the class embeddings.\n        mid_block_only_cross_attention (`bool`, *optional*, defaults to `None`):\n            Whether to use cross attention with the mid block when using the `UNetMidBlock2DSimpleCrossAttn`. If\n            `only_cross_attention` is given as a single boolean and `mid_block_only_cross_attention` is `None`, the\n            `only_cross_attention` value is used as the value for `mid_block_only_cross_attention`. Default to `False`\n            otherwise.\n    \"\"\"\n\n    _supports_gradient_checkpointing = True\n\n    @register_to_config\n    def __init__(\n        self,\n        sample_size: Optional[int] = None,\n        in_channels: int = 4,\n        out_channels: int = 4,\n        center_input_sample: bool = False,\n        flip_sin_to_cos: bool = True,\n        freq_shift: int = 0,\n        down_block_types: Tuple[str] = (\n            \"CrossAttnDownBlock2D\",\n            \"CrossAttnDownBlock2D\",\n            \"CrossAttnDownBlock2D\",\n            \"DownBlock2D\",\n        ),\n        mid_block_type: Optional[str] = \"UNetMidBlock2DCrossAttn\",\n        up_block_types: Tuple[str] = (\"UpBlock2D\", \"CrossAttnUpBlock2D\", \"CrossAttnUpBlock2D\", \"CrossAttnUpBlock2D\"),\n        only_cross_attention: Union[bool, Tuple[bool]] = False,\n        block_out_channels: Tuple[int] = (320, 640, 1280, 1280),\n        layers_per_block: Union[int, Tuple[int]] = 2,\n        downsample_padding: int = 1,\n        mid_block_scale_factor: float = 1,\n        dropout: float = 0.0,\n        act_fn: str = \"silu\",\n        norm_num_groups: Optional[int] = 32,\n        norm_eps: float = 1e-5,\n        cross_attention_dim: Union[int, Tuple[int]] = 1280,\n        transformer_layers_per_block: Union[int, Tuple[int], Tuple[Tuple]] = 1,\n        reverse_transformer_layers_per_block: Optional[Tuple[Tuple[int]]] = None,\n        encoder_hid_dim: Optional[int] = None,\n        encoder_hid_dim_type: Optional[str] = None,\n        attention_head_dim: Union[int, Tuple[int]] = 8,\n        num_attention_heads: Optional[Union[int, Tuple[int]]] = None,\n        dual_cross_attention: bool = False,\n        use_linear_projection: bool = False,\n        class_embed_type: Optional[str] = None,\n        addition_embed_type: Optional[str] = None,\n        addition_time_embed_dim: Optional[int] = None,\n        num_class_embeds: Optional[int] = None,\n        upcast_attention: bool = False,\n        resnet_time_scale_shift: str = \"default\",\n        resnet_skip_time_act: bool = False,\n        resnet_out_scale_factor: float = 1.0,\n        time_embedding_type: str = \"positional\",\n        time_embedding_dim: Optional[int] = None,\n        time_embedding_act_fn: Optional[str] = None,\n        timestep_post_act: Optional[str] = None,\n        time_cond_proj_dim: Optional[int] = None,\n        conv_in_kernel: int = 3,\n        conv_out_kernel: int = 3,\n        projection_class_embeddings_input_dim: Optional[int] = None,\n        attention_type: str = \"default\",\n        class_embeddings_concat: bool = False,\n        mid_block_only_cross_attention: Optional[bool] = None,\n        cross_attention_norm: Optional[str] = None,\n        addition_embed_type_num_heads: int = 64,\n    ):\n        super().__init__()\n\n        self.sample_size = sample_size\n\n        if num_attention_heads is not None:\n            raise ValueError(\n                \"At the moment it is not possible to define the number of attention heads via `num_attention_heads` because of a naming issue as described in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131. Passing `num_attention_heads` will only be supported in diffusers v0.19.\"\n            )\n\n        # If `num_attention_heads` is not defined (which is the case for most models)\n        # it will default to `attention_head_dim`. This looks weird upon first reading it and it is.\n        # The reason for this behavior is to correct for incorrectly named variables that were introduced\n        # when this library was created. The incorrect naming was only discovered much later in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131\n        # Changing `attention_head_dim` to `num_attention_heads` for 40,000+ configurations is too backwards breaking\n        # which is why we correct for the naming here.\n        num_attention_heads = num_attention_heads or attention_head_dim\n\n        # Check inputs\n        self._check_config(\n            down_block_types=down_block_types,\n            up_block_types=up_block_types,\n            only_cross_attention=only_cross_attention,\n            block_out_channels=block_out_channels,\n            layers_per_block=layers_per_block,\n            cross_attention_dim=cross_attention_dim,\n            transformer_layers_per_block=transformer_layers_per_block,\n            reverse_transformer_layers_per_block=reverse_transformer_layers_per_block,\n            attention_head_dim=attention_head_dim,\n            num_attention_heads=num_attention_heads,\n        )\n\n        # input\n        conv_in_padding = (conv_in_kernel - 1) // 2\n        self.conv_in = nn.Conv2d(\n            in_channels, block_out_channels[0], kernel_size=conv_in_kernel, padding=conv_in_padding\n        )\n\n        # time\n        time_embed_dim, timestep_input_dim = self._set_time_proj(\n            time_embedding_type,\n            block_out_channels=block_out_channels,\n            flip_sin_to_cos=flip_sin_to_cos,\n            freq_shift=freq_shift,\n            time_embedding_dim=time_embedding_dim,\n        )\n\n        self.time_embedding = TimestepEmbedding(\n            timestep_input_dim,\n            time_embed_dim,\n            act_fn=act_fn,\n            post_act_fn=timestep_post_act,\n            cond_proj_dim=time_cond_proj_dim,\n        )\n\n        self._set_encoder_hid_proj(\n            encoder_hid_dim_type,\n            cross_attention_dim=cross_attention_dim,\n            encoder_hid_dim=encoder_hid_dim,\n        )\n\n        # class embedding\n        self._set_class_embedding(\n            class_embed_type,\n            act_fn=act_fn,\n            num_class_embeds=num_class_embeds,\n            projection_class_embeddings_input_dim=projection_class_embeddings_input_dim,\n            time_embed_dim=time_embed_dim,\n            timestep_input_dim=timestep_input_dim,\n        )\n\n        self._set_add_embedding(\n            addition_embed_type,\n            addition_embed_type_num_heads=addition_embed_type_num_heads,\n            addition_time_embed_dim=addition_time_embed_dim,\n            cross_attention_dim=cross_attention_dim,\n            encoder_hid_dim=encoder_hid_dim,\n            flip_sin_to_cos=flip_sin_to_cos,\n            freq_shift=freq_shift,\n            projection_class_embeddings_input_dim=projection_class_embeddings_input_dim,\n            time_embed_dim=time_embed_dim,\n        )\n\n        if time_embedding_act_fn is None:\n            self.time_embed_act = None\n        else:\n            self.time_embed_act = get_activation(time_embedding_act_fn)\n\n        self.down_blocks = nn.ModuleList([])\n        self.up_blocks = nn.ModuleList([])\n\n        if isinstance(only_cross_attention, bool):\n            if mid_block_only_cross_attention is None:\n                mid_block_only_cross_attention = only_cross_attention\n\n            only_cross_attention = [only_cross_attention] * len(down_block_types)\n\n        if mid_block_only_cross_attention is None:\n            mid_block_only_cross_attention = False\n\n        if isinstance(num_attention_heads, int):\n            num_attention_heads = (num_attention_heads,) * len(down_block_types)\n\n        if isinstance(attention_head_dim, int):\n            attention_head_dim = (attention_head_dim,) * len(down_block_types)\n\n        if isinstance(cross_attention_dim, int):\n            cross_attention_dim = (cross_attention_dim,) * len(down_block_types)\n\n        if isinstance(layers_per_block, int):\n            layers_per_block = [layers_per_block] * len(down_block_types)\n\n        if isinstance(transformer_layers_per_block, int):\n            transformer_layers_per_block = [transformer_layers_per_block] * len(down_block_types)\n\n        if class_embeddings_concat:\n            # The time embeddings are concatenated with the class embeddings. The dimension of the\n            # time embeddings passed to the down, middle, and up blocks is twice the dimension of the\n            # regular time embeddings\n            blocks_time_embed_dim = time_embed_dim * 2\n        else:\n            blocks_time_embed_dim = time_embed_dim\n\n        # down\n        output_channel = block_out_channels[0]\n        for i, down_block_type in enumerate(down_block_types):\n            input_channel = output_channel\n            output_channel = block_out_channels[i]\n            is_final_block = i == len(block_out_channels) - 1\n\n            down_block = get_down_block(\n                down_block_type,\n                num_layers=layers_per_block[i],\n                transformer_layers_per_block=transformer_layers_per_block[i],\n                in_channels=input_channel,\n                out_channels=output_channel,\n                temb_channels=blocks_time_embed_dim,\n                add_downsample=not is_final_block,\n                resnet_eps=norm_eps,\n                resnet_act_fn=act_fn,\n                resnet_groups=norm_num_groups,\n                cross_attention_dim=cross_attention_dim[i],\n                num_attention_heads=num_attention_heads[i],\n                downsample_padding=downsample_padding,\n                dual_cross_attention=dual_cross_attention,\n                use_linear_projection=use_linear_projection,\n                only_cross_attention=only_cross_attention[i],\n                upcast_attention=upcast_attention,\n                resnet_time_scale_shift=resnet_time_scale_shift,\n                attention_type=attention_type,\n                resnet_skip_time_act=resnet_skip_time_act,\n                resnet_out_scale_factor=resnet_out_scale_factor,\n                cross_attention_norm=cross_attention_norm,\n                attention_head_dim=attention_head_dim[i] if attention_head_dim[i] is not None else output_channel,\n                dropout=dropout,\n            )\n            self.down_blocks.append(down_block)\n\n        # mid\n        self.mid_block = get_mid_block(\n            mid_block_type,\n            temb_channels=blocks_time_embed_dim,\n            in_channels=block_out_channels[-1],\n            resnet_eps=norm_eps,\n            resnet_act_fn=act_fn,\n            resnet_groups=norm_num_groups,\n            output_scale_factor=mid_block_scale_factor,\n            transformer_layers_per_block=transformer_layers_per_block[-1],\n            num_attention_heads=num_attention_heads[-1],\n            cross_attention_dim=cross_attention_dim[-1],\n            dual_cross_attention=dual_cross_attention,\n            use_linear_projection=use_linear_projection,\n            mid_block_only_cross_attention=mid_block_only_cross_attention,\n            upcast_attention=upcast_attention,\n            resnet_time_scale_shift=resnet_time_scale_shift,\n            attention_type=attention_type,\n            resnet_skip_time_act=resnet_skip_time_act,\n            cross_attention_norm=cross_attention_norm,\n            attention_head_dim=attention_head_dim[-1],\n            dropout=dropout,\n        )\n\n        # count how many layers upsample the images\n        self.num_upsamplers = 0\n\n        # up\n        reversed_block_out_channels = list(reversed(block_out_channels))\n        reversed_num_attention_heads = list(reversed(num_attention_heads))\n        reversed_layers_per_block = list(reversed(layers_per_block))\n        reversed_cross_attention_dim = list(reversed(cross_attention_dim))\n        reversed_transformer_layers_per_block = (\n            list(reversed(transformer_layers_per_block))\n            if reverse_transformer_layers_per_block is None\n            else reverse_transformer_layers_per_block\n        )\n        only_cross_attention = list(reversed(only_cross_attention))\n\n        output_channel = reversed_block_out_channels[0]\n        for i, up_block_type in enumerate(up_block_types):\n            is_final_block = i == len(block_out_channels) - 1\n\n            prev_output_channel = output_channel\n            output_channel = reversed_block_out_channels[i]\n            input_channel = reversed_block_out_channels[min(i + 1, len(block_out_channels) - 1)]\n\n            # add upsample block for all BUT final layer\n            if not is_final_block:\n                add_upsample = True\n                self.num_upsamplers += 1\n            else:\n                add_upsample = False\n\n            up_block = get_up_block(\n                up_block_type,\n                num_layers=reversed_layers_per_block[i] + 1,\n                transformer_layers_per_block=reversed_transformer_layers_per_block[i],\n                in_channels=input_channel,\n                out_channels=output_channel,\n                prev_output_channel=prev_output_channel,\n                temb_channels=blocks_time_embed_dim,\n                add_upsample=add_upsample,\n                resnet_eps=norm_eps,\n                resnet_act_fn=act_fn,\n                resolution_idx=i,\n                resnet_groups=norm_num_groups,\n                cross_attention_dim=reversed_cross_attention_dim[i],\n                num_attention_heads=reversed_num_attention_heads[i],\n                dual_cross_attention=dual_cross_attention,\n                use_linear_projection=use_linear_projection,\n                only_cross_attention=only_cross_attention[i],\n                upcast_attention=upcast_attention,\n                resnet_time_scale_shift=resnet_time_scale_shift,\n                attention_type=attention_type,\n                resnet_skip_time_act=resnet_skip_time_act,\n                resnet_out_scale_factor=resnet_out_scale_factor,\n                cross_attention_norm=cross_attention_norm,\n                attention_head_dim=attention_head_dim[i] if attention_head_dim[i] is not None else output_channel,\n                dropout=dropout,\n            )\n            self.up_blocks.append(up_block)\n            prev_output_channel = output_channel\n\n        # out\n        if norm_num_groups is not None:\n            self.conv_norm_out = nn.GroupNorm(\n                num_channels=block_out_channels[0], num_groups=norm_num_groups, eps=norm_eps\n            )\n\n            self.conv_act = get_activation(act_fn)\n\n        else:\n            self.conv_norm_out = None\n            self.conv_act = None\n\n        conv_out_padding = (conv_out_kernel - 1) // 2\n        self.conv_out = nn.Conv2d(\n            block_out_channels[0], out_channels, kernel_size=conv_out_kernel, padding=conv_out_padding\n        )\n\n        self._set_pos_net_if_use_gligen(attention_type=attention_type, cross_attention_dim=cross_attention_dim)\n\n    def _check_config(\n        self,\n        down_block_types: Tuple[str],\n        up_block_types: Tuple[str],\n        only_cross_attention: Union[bool, Tuple[bool]],\n        block_out_channels: Tuple[int],\n        layers_per_block: Union[int, Tuple[int]],\n        cross_attention_dim: Union[int, Tuple[int]],\n        transformer_layers_per_block: Union[int, Tuple[int], Tuple[Tuple[int]]],\n        reverse_transformer_layers_per_block: bool,\n        attention_head_dim: int,\n        num_attention_heads: Optional[Union[int, Tuple[int]]],\n    ):\n        if len(down_block_types) != len(up_block_types):\n            raise ValueError(\n                f\"Must provide the same number of `down_block_types` as `up_block_types`. `down_block_types`: {down_block_types}. `up_block_types`: {up_block_types}.\"\n            )\n\n        if len(block_out_channels) != len(down_block_types):\n            raise ValueError(\n                f\"Must provide the same number of `block_out_channels` as `down_block_types`. `block_out_channels`: {block_out_channels}. `down_block_types`: {down_block_types}.\"\n            )\n\n        if not isinstance(only_cross_attention, bool) and len(only_cross_attention) != len(down_block_types):\n            raise ValueError(\n                f\"Must provide the same number of `only_cross_attention` as `down_block_types`. `only_cross_attention`: {only_cross_attention}. `down_block_types`: {down_block_types}.\"\n            )\n\n        if not isinstance(num_attention_heads, int) and len(num_attention_heads) != len(down_block_types):\n            raise ValueError(\n                f\"Must provide the same number of `num_attention_heads` as `down_block_types`. `num_attention_heads`: {num_attention_heads}. `down_block_types`: {down_block_types}.\"\n            )\n\n        if not isinstance(attention_head_dim, int) and len(attention_head_dim) != len(down_block_types):\n            raise ValueError(\n                f\"Must provide the same number of `attention_head_dim` as `down_block_types`. `attention_head_dim`: {attention_head_dim}. `down_block_types`: {down_block_types}.\"\n            )\n\n        if isinstance(cross_attention_dim, list) and len(cross_attention_dim) != len(down_block_types):\n            raise ValueError(\n                f\"Must provide the same number of `cross_attention_dim` as `down_block_types`. `cross_attention_dim`: {cross_attention_dim}. `down_block_types`: {down_block_types}.\"\n            )\n\n        if not isinstance(layers_per_block, int) and len(layers_per_block) != len(down_block_types):\n            raise ValueError(\n                f\"Must provide the same number of `layers_per_block` as `down_block_types`. `layers_per_block`: {layers_per_block}. `down_block_types`: {down_block_types}.\"\n            )\n        if isinstance(transformer_layers_per_block, list) and reverse_transformer_layers_per_block is None:\n            for layer_number_per_block in transformer_layers_per_block:\n                if isinstance(layer_number_per_block, list):\n                    raise ValueError(\"Must provide 'reverse_transformer_layers_per_block` if using asymmetrical UNet.\")\n\n    def _set_time_proj(\n        self,\n        time_embedding_type: str,\n        block_out_channels: int,\n        flip_sin_to_cos: bool,\n        freq_shift: float,\n        time_embedding_dim: int,\n    ) -> Tuple[int, int]:\n        if time_embedding_type == \"fourier\":\n            time_embed_dim = time_embedding_dim or block_out_channels[0] * 2\n            if time_embed_dim % 2 != 0:\n                raise ValueError(f\"`time_embed_dim` should be divisible by 2, but is {time_embed_dim}.\")\n            self.time_proj = GaussianFourierProjection(\n                time_embed_dim // 2, set_W_to_weight=False, log=False, flip_sin_to_cos=flip_sin_to_cos\n            )\n            timestep_input_dim = time_embed_dim\n        elif time_embedding_type == \"positional\":\n            time_embed_dim = time_embedding_dim or block_out_channels[0] * 4\n\n            self.time_proj = Timesteps(block_out_channels[0], flip_sin_to_cos, freq_shift)\n            timestep_input_dim = block_out_channels[0]\n        else:\n            raise ValueError(\n                f\"{time_embedding_type} does not exist. Please make sure to use one of `fourier` or `positional`.\"\n            )\n\n        return time_embed_dim, timestep_input_dim\n\n    def _set_encoder_hid_proj(\n        self,\n        encoder_hid_dim_type: Optional[str],\n        cross_attention_dim: Union[int, Tuple[int]],\n        encoder_hid_dim: Optional[int],\n    ):\n        if encoder_hid_dim_type is None and encoder_hid_dim is not None:\n            encoder_hid_dim_type = \"text_proj\"\n            self.register_to_config(encoder_hid_dim_type=encoder_hid_dim_type)\n            logger.info(\"encoder_hid_dim_type defaults to 'text_proj' as `encoder_hid_dim` is defined.\")\n\n        if encoder_hid_dim is None and encoder_hid_dim_type is not None:\n            raise ValueError(\n                f\"`encoder_hid_dim` has to be defined when `encoder_hid_dim_type` is set to {encoder_hid_dim_type}.\"\n            )\n\n        if encoder_hid_dim_type == \"text_proj\":\n            self.encoder_hid_proj = nn.Linear(encoder_hid_dim, cross_attention_dim)\n        elif encoder_hid_dim_type == \"text_image_proj\":\n            # image_embed_dim DOESN'T have to be `cross_attention_dim`. To not clutter the __init__ too much\n            # they are set to `cross_attention_dim` here as this is exactly the required dimension for the currently only use\n            # case when `addition_embed_type == \"text_image_proj\"` (Kandinsky 2.1)`\n            self.encoder_hid_proj = TextImageProjection(\n                text_embed_dim=encoder_hid_dim,\n                image_embed_dim=cross_attention_dim,\n                cross_attention_dim=cross_attention_dim,\n            )\n        elif encoder_hid_dim_type == \"image_proj\":\n            # Kandinsky 2.2\n            self.encoder_hid_proj = ImageProjection(\n                image_embed_dim=encoder_hid_dim,\n                cross_attention_dim=cross_attention_dim,\n            )\n        elif encoder_hid_dim_type is not None:\n            raise ValueError(\n                f\"encoder_hid_dim_type: {encoder_hid_dim_type} must be None, 'text_proj' or 'text_image_proj'.\"\n            )\n        else:\n            self.encoder_hid_proj = None\n\n    def _set_class_embedding(\n        self,\n        class_embed_type: Optional[str],\n        act_fn: str,\n        num_class_embeds: Optional[int],\n        projection_class_embeddings_input_dim: Optional[int],\n        time_embed_dim: int,\n        timestep_input_dim: int,\n    ):\n        if class_embed_type is None and num_class_embeds is not None:\n            self.class_embedding = nn.Embedding(num_class_embeds, time_embed_dim)\n        elif class_embed_type == \"timestep\":\n            self.class_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim, act_fn=act_fn)\n        elif class_embed_type == \"identity\":\n            self.class_embedding = nn.Identity(time_embed_dim, time_embed_dim)\n        elif class_embed_type == \"projection\":\n            if projection_class_embeddings_input_dim is None:\n                raise ValueError(\n                    \"`class_embed_type`: 'projection' requires `projection_class_embeddings_input_dim` be set\"\n                )\n            # The projection `class_embed_type` is the same as the timestep `class_embed_type` except\n            # 1. the `class_labels` inputs are not first converted to sinusoidal embeddings\n            # 2. it projects from an arbitrary input dimension.\n            #\n            # Note that `TimestepEmbedding` is quite general, being mainly linear layers and activations.\n            # When used for embedding actual timesteps, the timesteps are first converted to sinusoidal embeddings.\n            # As a result, `TimestepEmbedding` can be passed arbitrary vectors.\n            self.class_embedding = TimestepEmbedding(projection_class_embeddings_input_dim, time_embed_dim)\n        elif class_embed_type == \"simple_projection\":\n            if projection_class_embeddings_input_dim is None:\n                raise ValueError(\n                    \"`class_embed_type`: 'simple_projection' requires `projection_class_embeddings_input_dim` be set\"\n                )\n            self.class_embedding = nn.Linear(projection_class_embeddings_input_dim, time_embed_dim)\n        else:\n            self.class_embedding = None\n\n    def _set_add_embedding(\n        self,\n        addition_embed_type: str,\n        addition_embed_type_num_heads: int,\n        addition_time_embed_dim: Optional[int],\n        flip_sin_to_cos: bool,\n        freq_shift: float,\n        cross_attention_dim: Optional[int],\n        encoder_hid_dim: Optional[int],\n        projection_class_embeddings_input_dim: Optional[int],\n        time_embed_dim: int,\n    ):\n        if addition_embed_type == \"text\":\n            if encoder_hid_dim is not None:\n                text_time_embedding_from_dim = encoder_hid_dim\n            else:\n                text_time_embedding_from_dim = cross_attention_dim\n\n            self.add_embedding = TextTimeEmbedding(\n                text_time_embedding_from_dim, time_embed_dim, num_heads=addition_embed_type_num_heads\n            )\n        elif addition_embed_type == \"text_image\":\n            # text_embed_dim and image_embed_dim DON'T have to be `cross_attention_dim`. To not clutter the __init__ too much\n            # they are set to `cross_attention_dim` here as this is exactly the required dimension for the currently only use\n            # case when `addition_embed_type == \"text_image\"` (Kandinsky 2.1)`\n            self.add_embedding = TextImageTimeEmbedding(\n                text_embed_dim=cross_attention_dim, image_embed_dim=cross_attention_dim, time_embed_dim=time_embed_dim\n            )\n        elif addition_embed_type == \"text_time\":\n            self.add_time_proj = Timesteps(addition_time_embed_dim, flip_sin_to_cos, freq_shift)\n            self.add_embedding = TimestepEmbedding(projection_class_embeddings_input_dim, time_embed_dim)\n        elif addition_embed_type == \"image\":\n            # Kandinsky 2.2\n            self.add_embedding = ImageTimeEmbedding(image_embed_dim=encoder_hid_dim, time_embed_dim=time_embed_dim)\n        elif addition_embed_type == \"image_hint\":\n            # Kandinsky 2.2 ControlNet\n            self.add_embedding = ImageHintTimeEmbedding(image_embed_dim=encoder_hid_dim, time_embed_dim=time_embed_dim)\n        elif addition_embed_type is not None:\n            raise ValueError(f\"addition_embed_type: {addition_embed_type} must be None, 'text' or 'text_image'.\")\n\n    def _set_pos_net_if_use_gligen(self, attention_type: str, cross_attention_dim: int):\n        if attention_type in [\"gated\", \"gated-text-image\"]:\n            positive_len = 768\n            if isinstance(cross_attention_dim, int):\n                positive_len = cross_attention_dim\n            elif isinstance(cross_attention_dim, tuple) or isinstance(cross_attention_dim, list):\n                positive_len = cross_attention_dim[0]\n\n            feature_type = \"text-only\" if attention_type == \"gated\" else \"text-image\"\n            self.position_net = GLIGENTextBoundingboxProjection(\n                positive_len=positive_len, out_dim=cross_attention_dim, feature_type=feature_type\n            )\n\n    @property\n    def attn_processors(self) -> Dict[str, AttentionProcessor]:\n        r\"\"\"\n        Returns:\n            `dict` of attention processors: A dictionary containing all attention processors used in the model with\n            indexed by its weight name.\n        \"\"\"\n        # set recursively\n        processors = {}\n\n        def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]):\n            if hasattr(module, \"get_processor\"):\n                processors[f\"{name}.processor\"] = module.get_processor(return_deprecated_lora=True)\n\n            for sub_name, child in module.named_children():\n                fn_recursive_add_processors(f\"{name}.{sub_name}\", child, processors)\n\n            return processors\n\n        for name, module in self.named_children():\n            fn_recursive_add_processors(name, module, processors)\n\n        return processors\n\n    def set_attn_processor(self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]]):\n        r\"\"\"\n        Sets the attention processor to use to compute attention.\n\n        Parameters:\n            processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):\n                The instantiated processor class or a dictionary of processor classes that will be set as the processor\n                for **all** `Attention` layers.\n\n                If `processor` is a dict, the key needs to define the path to the corresponding cross attention\n                processor. This is strongly recommended when setting trainable attention processors.\n\n        \"\"\"\n        count = len(self.attn_processors.keys())\n\n        if isinstance(processor, dict) and len(processor) != count:\n            raise ValueError(\n                f\"A dict of processors was passed, but the number of processors {len(processor)} does not match the\"\n                f\" number of attention layers: {count}. Please make sure to pass {count} processor classes.\"\n            )\n\n        def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):\n            if hasattr(module, \"set_processor\"):\n                if not isinstance(processor, dict):\n                    module.set_processor(processor)\n                else:\n                    module.set_processor(processor.pop(f\"{name}.processor\"))\n\n            for sub_name, child in module.named_children():\n                fn_recursive_attn_processor(f\"{name}.{sub_name}\", child, processor)\n\n        for name, module in self.named_children():\n            fn_recursive_attn_processor(name, module, processor)\n\n    def set_default_attn_processor(self):\n        \"\"\"\n        Disables custom attention processors and sets the default attention implementation.\n        \"\"\"\n        if all(proc.__class__ in ADDED_KV_ATTENTION_PROCESSORS for proc in self.attn_processors.values()):\n            processor = AttnAddedKVProcessor()\n        elif all(proc.__class__ in CROSS_ATTENTION_PROCESSORS for proc in self.attn_processors.values()):\n            processor = AttnProcessor()\n        else:\n            raise ValueError(\n                f\"Cannot call `set_default_attn_processor` when attention processors are of type {next(iter(self.attn_processors.values()))}\"\n            )\n\n        self.set_attn_processor(processor)\n\n    def set_attention_slice(self, slice_size: Union[str, int, List[int]] = \"auto\"):\n        r\"\"\"\n        Enable sliced attention computation.\n\n        When this option is enabled, the attention module splits the input tensor in slices to compute attention in\n        several steps. This is useful for saving some memory in exchange for a small decrease in speed.\n\n        Args:\n            slice_size (`str` or `int` or `list(int)`, *optional*, defaults to `\"auto\"`):\n                When `\"auto\"`, input to the attention heads is halved, so attention is computed in two steps. If\n                `\"max\"`, maximum amount of memory is saved by running only one slice at a time. If a number is\n                provided, uses as many slices as `attention_head_dim // slice_size`. In this case, `attention_head_dim`\n                must be a multiple of `slice_size`.\n        \"\"\"\n        sliceable_head_dims = []\n\n        def fn_recursive_retrieve_sliceable_dims(module: torch.nn.Module):\n            if hasattr(module, \"set_attention_slice\"):\n                sliceable_head_dims.append(module.sliceable_head_dim)\n\n            for child in module.children():\n                fn_recursive_retrieve_sliceable_dims(child)\n\n        # retrieve number of attention layers\n        for module in self.children():\n            fn_recursive_retrieve_sliceable_dims(module)\n\n        num_sliceable_layers = len(sliceable_head_dims)\n\n        if slice_size == \"auto\":\n            # half the attention head size is usually a good trade-off between\n            # speed and memory\n            slice_size = [dim // 2 for dim in sliceable_head_dims]\n        elif slice_size == \"max\":\n            # make smallest slice possible\n            slice_size = num_sliceable_layers * [1]\n\n        slice_size = num_sliceable_layers * [slice_size] if not isinstance(slice_size, list) else slice_size\n\n        if len(slice_size) != len(sliceable_head_dims):\n            raise ValueError(\n                f\"You have provided {len(slice_size)}, but {self.config} has {len(sliceable_head_dims)} different\"\n                f\" attention layers. Make sure to match `len(slice_size)` to be {len(sliceable_head_dims)}.\"\n            )\n\n        for i in range(len(slice_size)):\n            size = slice_size[i]\n            dim = sliceable_head_dims[i]\n            if size is not None and size > dim:\n                raise ValueError(f\"size {size} has to be smaller or equal to {dim}.\")\n\n        # Recursively walk through all the children.\n        # Any children which exposes the set_attention_slice method\n        # gets the message\n        def fn_recursive_set_attention_slice(module: torch.nn.Module, slice_size: List[int]):\n            if hasattr(module, \"set_attention_slice\"):\n                module.set_attention_slice(slice_size.pop())\n\n            for child in module.children():\n                fn_recursive_set_attention_slice(child, slice_size)\n\n        reversed_slice_size = list(reversed(slice_size))\n        for module in self.children():\n            fn_recursive_set_attention_slice(module, reversed_slice_size)\n\n    def _set_gradient_checkpointing(self, module, value=False):\n        if hasattr(module, \"gradient_checkpointing\"):\n            module.gradient_checkpointing = value\n\n    def enable_freeu(self, s1: float, s2: float, b1: float, b2: float):\n        r\"\"\"Enables the FreeU mechanism from https://arxiv.org/abs/2309.11497.\n\n        The suffixes after the scaling factors represent the stage blocks where they are being applied.\n\n        Please refer to the [official repository](https://github.com/ChenyangSi/FreeU) for combinations of values that\n        are known to work well for different pipelines such as Stable Diffusion v1, v2, and Stable Diffusion XL.\n\n        Args:\n            s1 (`float`):\n                Scaling factor for stage 1 to attenuate the contributions of the skip features. This is done to\n                mitigate the \"oversmoothing effect\" in the enhanced denoising process.\n            s2 (`float`):\n                Scaling factor for stage 2 to attenuate the contributions of the skip features. This is done to\n                mitigate the \"oversmoothing effect\" in the enhanced denoising process.\n            b1 (`float`): Scaling factor for stage 1 to amplify the contributions of backbone features.\n            b2 (`float`): Scaling factor for stage 2 to amplify the contributions of backbone features.\n        \"\"\"\n        for i, upsample_block in enumerate(self.up_blocks):\n            setattr(upsample_block, \"s1\", s1)\n            setattr(upsample_block, \"s2\", s2)\n            setattr(upsample_block, \"b1\", b1)\n            setattr(upsample_block, \"b2\", b2)\n\n    def disable_freeu(self):\n        \"\"\"Disables the FreeU mechanism.\"\"\"\n        freeu_keys = {\"s1\", \"s2\", \"b1\", \"b2\"}\n        for i, upsample_block in enumerate(self.up_blocks):\n            for k in freeu_keys:\n                if hasattr(upsample_block, k) or getattr(upsample_block, k, None) is not None:\n                    setattr(upsample_block, k, None)\n\n    def fuse_qkv_projections(self):\n        \"\"\"\n        Enables fused QKV projections. For self-attention modules, all projection matrices (i.e., query, key, value)\n        are fused. For cross-attention modules, key and value projection matrices are fused.\n\n        <Tip warning={true}>\n\n        This API is 🧪 experimental.\n\n        </Tip>\n        \"\"\"\n        self.original_attn_processors = None\n\n        for _, attn_processor in self.attn_processors.items():\n            if \"Added\" in str(attn_processor.__class__.__name__):\n                raise ValueError(\"`fuse_qkv_projections()` is not supported for models having added KV projections.\")\n\n        self.original_attn_processors = self.attn_processors\n\n        for module in self.modules():\n            if isinstance(module, Attention):\n                module.fuse_projections(fuse=True)\n\n    def unfuse_qkv_projections(self):\n        \"\"\"Disables the fused QKV projection if enabled.\n\n        <Tip warning={true}>\n\n        This API is 🧪 experimental.\n\n        </Tip>\n\n        \"\"\"\n        if self.original_attn_processors is not None:\n            self.set_attn_processor(self.original_attn_processors)\n\n    def unload_lora(self):\n        \"\"\"Unloads LoRA weights.\"\"\"\n        deprecate(\n            \"unload_lora\",\n            \"0.28.0\",\n            \"Calling `unload_lora()` is deprecated and will be removed in a future version. Please install `peft` and then call `disable_adapters().\",\n        )\n        for module in self.modules():\n            if hasattr(module, \"set_lora_layer\"):\n                module.set_lora_layer(None)\n\n    def get_time_embed(\n        self, sample: torch.Tensor, timestep: Union[torch.Tensor, float, int]\n    ) -> Optional[torch.Tensor]:\n        timesteps = timestep\n        if not torch.is_tensor(timesteps):\n            # TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can\n            # This would be a good case for the `match` statement (Python 3.10+)\n            is_mps = sample.device.type == \"mps\"\n            if isinstance(timestep, float):\n                dtype = torch.float32 if is_mps else torch.float64\n            else:\n                dtype = torch.int32 if is_mps else torch.int64\n            timesteps = torch.tensor([timesteps], dtype=dtype, device=sample.device)\n        elif len(timesteps.shape) == 0:\n            timesteps = timesteps[None].to(sample.device)\n\n        # broadcast to batch dimension in a way that's compatible with ONNX/Core ML\n        timesteps = timesteps.expand(sample.shape[0])\n\n        t_emb = self.time_proj(timesteps)\n        # `Timesteps` does not contain any weights and will always return f32 tensors\n        # but time_embedding might actually be running in fp16. so we need to cast here.\n        # there might be better ways to encapsulate this.\n        t_emb = t_emb.to(dtype=sample.dtype)\n        return t_emb\n\n    def get_class_embed(self, sample: torch.Tensor, class_labels: Optional[torch.Tensor]) -> Optional[torch.Tensor]:\n        class_emb = None\n        if self.class_embedding is not None:\n            if class_labels is None:\n                raise ValueError(\"class_labels should be provided when num_class_embeds > 0\")\n\n            if self.config.class_embed_type == \"timestep\":\n                class_labels = self.time_proj(class_labels)\n\n                # `Timesteps` does not contain any weights and will always return f32 tensors\n                # there might be better ways to encapsulate this.\n                class_labels = class_labels.to(dtype=sample.dtype)\n\n            class_emb = self.class_embedding(class_labels).to(dtype=sample.dtype)\n        return class_emb\n\n    def get_aug_embed(\n        self, emb: torch.Tensor, encoder_hidden_states: torch.Tensor, added_cond_kwargs: Dict[str, Any]\n    ) -> Optional[torch.Tensor]:\n        aug_emb = None\n        if self.config.addition_embed_type == \"text\":\n            aug_emb = self.add_embedding(encoder_hidden_states)\n        elif self.config.addition_embed_type == \"text_image\":\n            # Kandinsky 2.1 - style\n            if \"image_embeds\" not in added_cond_kwargs:\n                raise ValueError(\n                    f\"{self.__class__} has the config param `addition_embed_type` set to 'text_image' which requires the keyword argument `image_embeds` to be passed in `added_cond_kwargs`\"\n                )\n\n            image_embs = added_cond_kwargs.get(\"image_embeds\")\n            text_embs = added_cond_kwargs.get(\"text_embeds\", encoder_hidden_states)\n            aug_emb = self.add_embedding(text_embs, image_embs)\n        elif self.config.addition_embed_type == \"text_time\":\n            # SDXL - style\n            if \"text_embeds\" not in added_cond_kwargs:\n                raise ValueError(\n                    f\"{self.__class__} has the config param `addition_embed_type` set to 'text_time' which requires the keyword argument `text_embeds` to be passed in `added_cond_kwargs`\"\n                )\n            text_embeds = added_cond_kwargs.get(\"text_embeds\")\n            if \"time_ids\" not in added_cond_kwargs:\n                raise ValueError(\n                    f\"{self.__class__} has the config param `addition_embed_type` set to 'text_time' which requires the keyword argument `time_ids` to be passed in `added_cond_kwargs`\"\n                )\n            time_ids = added_cond_kwargs.get(\"time_ids\")\n            time_embeds = self.add_time_proj(time_ids.flatten())\n            time_embeds = time_embeds.reshape((text_embeds.shape[0], -1))\n            add_embeds = torch.concat([text_embeds, time_embeds], dim=-1)\n            add_embeds = add_embeds.to(emb.dtype)\n            aug_emb = self.add_embedding(add_embeds)\n        elif self.config.addition_embed_type == \"image\":\n            # Kandinsky 2.2 - style\n            if \"image_embeds\" not in added_cond_kwargs:\n                raise ValueError(\n                    f\"{self.__class__} has the config param `addition_embed_type` set to 'image' which requires the keyword argument `image_embeds` to be passed in `added_cond_kwargs`\"\n                )\n            image_embs = added_cond_kwargs.get(\"image_embeds\")\n            aug_emb = self.add_embedding(image_embs)\n        elif self.config.addition_embed_type == \"image_hint\":\n            # Kandinsky 2.2 - style\n            if \"image_embeds\" not in added_cond_kwargs or \"hint\" not in added_cond_kwargs:\n                raise ValueError(\n                    f\"{self.__class__} has the config param `addition_embed_type` set to 'image_hint' which requires the keyword arguments `image_embeds` and `hint` to be passed in `added_cond_kwargs`\"\n                )\n            image_embs = added_cond_kwargs.get(\"image_embeds\")\n            hint = added_cond_kwargs.get(\"hint\")\n            aug_emb = self.add_embedding(image_embs, hint)\n        return aug_emb\n\n    def process_encoder_hidden_states(\n        self, encoder_hidden_states: torch.Tensor, added_cond_kwargs: Dict[str, Any]\n    ) -> torch.Tensor:\n        if self.encoder_hid_proj is not None and self.config.encoder_hid_dim_type == \"text_proj\":\n            encoder_hidden_states = self.encoder_hid_proj(encoder_hidden_states)\n        elif self.encoder_hid_proj is not None and self.config.encoder_hid_dim_type == \"text_image_proj\":\n            # Kandinsky 2.1 - style\n            if \"image_embeds\" not in added_cond_kwargs:\n                raise ValueError(\n                    f\"{self.__class__} has the config param `encoder_hid_dim_type` set to 'text_image_proj' which requires the keyword argument `image_embeds` to be passed in  `added_conditions`\"\n                )\n\n            image_embeds = added_cond_kwargs.get(\"image_embeds\")\n            encoder_hidden_states = self.encoder_hid_proj(encoder_hidden_states, image_embeds)\n        elif self.encoder_hid_proj is not None and self.config.encoder_hid_dim_type == \"image_proj\":\n            # Kandinsky 2.2 - style\n            if \"image_embeds\" not in added_cond_kwargs:\n                raise ValueError(\n                    f\"{self.__class__} has the config param `encoder_hid_dim_type` set to 'image_proj' which requires the keyword argument `image_embeds` to be passed in  `added_conditions`\"\n                )\n            image_embeds = added_cond_kwargs.get(\"image_embeds\")\n            encoder_hidden_states = self.encoder_hid_proj(image_embeds)\n        elif self.encoder_hid_proj is not None and self.config.encoder_hid_dim_type == \"ip_image_proj\":\n            if \"image_embeds\" not in added_cond_kwargs:\n                raise ValueError(\n                    f\"{self.__class__} has the config param `encoder_hid_dim_type` set to 'ip_image_proj' which requires the keyword argument `image_embeds` to be passed in  `added_conditions`\"\n                )\n            image_embeds = added_cond_kwargs.get(\"image_embeds\")\n            image_embeds = self.encoder_hid_proj(image_embeds)\n            encoder_hidden_states = (encoder_hidden_states, image_embeds)\n        return encoder_hidden_states\n\n    def forward(\n        self,\n        sample: torch.FloatTensor,\n        timestep: Union[torch.Tensor, float, int],\n        encoder_hidden_states: torch.Tensor,\n        class_labels: Optional[torch.Tensor] = None,\n        timestep_cond: Optional[torch.Tensor] = None,\n        attention_mask: Optional[torch.Tensor] = None,\n        cross_attention_kwargs: Optional[Dict[str, Any]] = None,\n        added_cond_kwargs: Optional[Dict[str, torch.Tensor]] = None,\n        down_block_additional_residuals: Optional[Tuple[torch.Tensor]] = None,\n        mid_block_additional_residual: Optional[torch.Tensor] = None,\n        down_intrablock_additional_residuals: Optional[Tuple[torch.Tensor]] = None,\n        encoder_attention_mask: Optional[torch.Tensor] = None,\n        return_dict: bool = True,\n    ) -> Union[UNet2DConditionOutput, Tuple]:\n        r\"\"\"\n        The [`UNet2DConditionModel`] forward method.\n\n        Args:\n            sample (`torch.FloatTensor`):\n                The noisy input tensor with the following shape `(batch, channel, height, width)`.\n            timestep (`torch.FloatTensor` or `float` or `int`): The number of timesteps to denoise an input.\n            encoder_hidden_states (`torch.FloatTensor`):\n                The encoder hidden states with shape `(batch, sequence_length, feature_dim)`.\n            class_labels (`torch.Tensor`, *optional*, defaults to `None`):\n                Optional class labels for conditioning. Their embeddings will be summed with the timestep embeddings.\n            timestep_cond: (`torch.Tensor`, *optional*, defaults to `None`):\n                Conditional embeddings for timestep. If provided, the embeddings will be summed with the samples passed\n                through the `self.time_embedding` layer to obtain the timestep embeddings.\n            attention_mask (`torch.Tensor`, *optional*, defaults to `None`):\n                An attention mask of shape `(batch, key_tokens)` is applied to `encoder_hidden_states`. If `1` the mask\n                is kept, otherwise if `0` it is discarded. Mask will be converted into a bias, which adds large\n                negative values to the attention scores corresponding to \"discard\" tokens.\n            cross_attention_kwargs (`dict`, *optional*):\n                A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under\n                `self.processor` in\n                [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).\n            added_cond_kwargs: (`dict`, *optional*):\n                A kwargs dictionary containing additional embeddings that if specified are added to the embeddings that\n                are passed along to the UNet blocks.\n            down_block_additional_residuals: (`tuple` of `torch.Tensor`, *optional*):\n                A tuple of tensors that if specified are added to the residuals of down unet blocks.\n            mid_block_additional_residual: (`torch.Tensor`, *optional*):\n                A tensor that if specified is added to the residual of the middle unet block.\n            down_intrablock_additional_residuals (`tuple` of `torch.Tensor`, *optional*):\n                additional residuals to be added within UNet down blocks, for example from T2I-Adapter side model(s)\n            encoder_attention_mask (`torch.Tensor`):\n                A cross-attention mask of shape `(batch, sequence_length)` is applied to `encoder_hidden_states`. If\n                `True` the mask is kept, otherwise if `False` it is discarded. Mask will be converted into a bias,\n                which adds large negative values to the attention scores corresponding to \"discard\" tokens.\n            return_dict (`bool`, *optional*, defaults to `True`):\n                Whether or not to return a [`~models.unets.unet_2d_condition.UNet2DConditionOutput`] instead of a plain\n                tuple.\n\n        Returns:\n            [`~models.unets.unet_2d_condition.UNet2DConditionOutput`] or `tuple`:\n                If `return_dict` is True, an [`~models.unets.unet_2d_condition.UNet2DConditionOutput`] is returned,\n                otherwise a `tuple` is returned where the first element is the sample tensor.\n        \"\"\"\n        # By default samples have to be AT least a multiple of the overall upsampling factor.\n        # The overall upsampling factor is equal to 2 ** (# num of upsampling layers).\n        # However, the upsampling interpolation output size can be forced to fit any upsampling size\n        # on the fly if necessary.\n        default_overall_up_factor = 2**self.num_upsamplers\n\n        # upsample size should be forwarded when sample is not a multiple of `default_overall_up_factor`\n        forward_upsample_size = False\n        upsample_size = None\n\n        for dim in sample.shape[-2:]:\n            if dim % default_overall_up_factor != 0:\n                # Forward upsample size to force interpolation output size.\n                forward_upsample_size = True\n                break\n\n        # ensure attention_mask is a bias, and give it a singleton query_tokens dimension\n        # expects mask of shape:\n        #   [batch, key_tokens]\n        # adds singleton query_tokens dimension:\n        #   [batch,                    1, key_tokens]\n        # this helps to broadcast it as a bias over attention scores, which will be in one of the following shapes:\n        #   [batch,  heads, query_tokens, key_tokens] (e.g. torch sdp attn)\n        #   [batch * heads, query_tokens, key_tokens] (e.g. xformers or classic attn)\n        if attention_mask is not None:\n            # assume that mask is expressed as:\n            #   (1 = keep,      0 = discard)\n            # convert mask into a bias that can be added to attention scores:\n            #       (keep = +0,     discard = -10000.0)\n            attention_mask = (1 - attention_mask.to(sample.dtype)) * -10000.0\n            attention_mask = attention_mask.unsqueeze(1)\n\n        # convert encoder_attention_mask to a bias the same way we do for attention_mask\n        if encoder_attention_mask is not None:\n            encoder_attention_mask = (1 - encoder_attention_mask.to(sample.dtype)) * -10000.0\n            encoder_attention_mask = encoder_attention_mask.unsqueeze(1)\n\n        # 0. center input if necessary\n        if self.config.center_input_sample:\n            sample = 2 * sample - 1.0\n\n        # 1. time\n        t_emb = self.get_time_embed(sample=sample, timestep=timestep)\n        emb = self.time_embedding(t_emb, timestep_cond)\n        aug_emb = None\n\n        class_emb = self.get_class_embed(sample=sample, class_labels=class_labels)\n        if class_emb is not None:\n            if self.config.class_embeddings_concat:\n                emb = torch.cat([emb, class_emb], dim=-1)\n            else:\n                emb = emb + class_emb\n\n        aug_emb = self.get_aug_embed(\n            emb=emb, encoder_hidden_states=encoder_hidden_states, added_cond_kwargs=added_cond_kwargs\n        )\n        if self.config.addition_embed_type == \"image_hint\":\n            aug_emb, hint = aug_emb\n            sample = torch.cat([sample, hint], dim=1)\n\n        emb = emb + aug_emb if aug_emb is not None else emb\n\n        if self.time_embed_act is not None:\n            emb = self.time_embed_act(emb)\n\n        encoder_hidden_states = self.process_encoder_hidden_states(\n            encoder_hidden_states=encoder_hidden_states, added_cond_kwargs=added_cond_kwargs\n        )\n\n        # 2. pre-process\n        sample = self.conv_in(sample)\n\n        # 2.5 GLIGEN position net\n        if cross_attention_kwargs is not None and cross_attention_kwargs.get(\"gligen\", None) is not None:\n            cross_attention_kwargs = cross_attention_kwargs.copy()\n            gligen_args = cross_attention_kwargs.pop(\"gligen\")\n            cross_attention_kwargs[\"gligen\"] = {\"objs\": self.position_net(**gligen_args)}\n\n        # 3. down\n        # we're popping the `scale` instead of getting it because otherwise `scale` will be propagated\n        # to the internal blocks and will raise deprecation warnings. this will be confusing for our users.\n        if cross_attention_kwargs is not None:\n            cross_attention_kwargs = cross_attention_kwargs.copy()\n            lora_scale = cross_attention_kwargs.pop(\"scale\", 1.0)\n        else:\n            lora_scale = 1.0\n\n        if USE_PEFT_BACKEND:\n            # weight the lora layers by setting `lora_scale` for each PEFT layer\n            scale_lora_layers(self, lora_scale)\n\n        is_controlnet = mid_block_additional_residual is not None and down_block_additional_residuals is not None\n        # using new arg down_intrablock_additional_residuals for T2I-Adapters, to distinguish from controlnets\n        is_adapter = down_intrablock_additional_residuals is not None\n        # maintain backward compatibility for legacy usage, where\n        #       T2I-Adapter and ControlNet both use down_block_additional_residuals arg\n        #       but can only use one or the other\n        if not is_adapter and mid_block_additional_residual is None and down_block_additional_residuals is not None:\n            deprecate(\n                \"T2I should not use down_block_additional_residuals\",\n                \"1.3.0\",\n                \"Passing intrablock residual connections with `down_block_additional_residuals` is deprecated \\\n                       and will be removed in diffusers 1.3.0.  `down_block_additional_residuals` should only be used \\\n                       for ControlNet. Please make sure use `down_intrablock_additional_residuals` instead. \",\n                standard_warn=False,\n            )\n            down_intrablock_additional_residuals = down_block_additional_residuals\n            is_adapter = True\n\n        down_block_res_samples = (sample,)\n        for downsample_block in self.down_blocks:\n            if hasattr(downsample_block, \"has_cross_attention\") and downsample_block.has_cross_attention:\n                # For t2i-adapter CrossAttnDownBlock2D\n                additional_residuals = {}\n                if is_adapter and len(down_intrablock_additional_residuals) > 0:\n                    additional_residuals[\"additional_residuals\"] = down_intrablock_additional_residuals.pop(0)\n\n                sample, res_samples = downsample_block(\n                    hidden_states=sample,\n                    temb=emb,\n                    encoder_hidden_states=encoder_hidden_states,\n                    attention_mask=attention_mask,\n                    cross_attention_kwargs=cross_attention_kwargs,\n                    encoder_attention_mask=encoder_attention_mask,\n                    **additional_residuals,\n                )\n            else:\n                sample, res_samples = downsample_block(hidden_states=sample, temb=emb)\n                if is_adapter and len(down_intrablock_additional_residuals) > 0:\n                    sample += down_intrablock_additional_residuals.pop(0)\n\n            down_block_res_samples += res_samples\n\n        if is_controlnet:\n            new_down_block_res_samples = ()\n\n            for down_block_res_sample, down_block_additional_residual in zip(\n                down_block_res_samples, down_block_additional_residuals\n            ):\n                down_block_res_sample = down_block_res_sample + down_block_additional_residual\n                new_down_block_res_samples = new_down_block_res_samples + (down_block_res_sample,)\n\n            down_block_res_samples = new_down_block_res_samples\n\n        # 4. mid\n        if self.mid_block is not None:\n            if hasattr(self.mid_block, \"has_cross_attention\") and self.mid_block.has_cross_attention:\n                sample = self.mid_block(\n                    sample,\n                    emb,\n                    encoder_hidden_states=encoder_hidden_states,\n                    attention_mask=attention_mask,\n                    cross_attention_kwargs=cross_attention_kwargs,\n                    encoder_attention_mask=encoder_attention_mask,\n                )\n            else:\n                sample = self.mid_block(sample, emb)\n\n            # To support T2I-Adapter-XL\n            if (\n                is_adapter\n                and len(down_intrablock_additional_residuals) > 0\n                and sample.shape == down_intrablock_additional_residuals[0].shape\n            ):\n                sample += down_intrablock_additional_residuals.pop(0)\n\n        if is_controlnet:\n            sample = sample + mid_block_additional_residual\n\n        # 5. up\n        for i, upsample_block in enumerate(self.up_blocks):\n            is_final_block = i == len(self.up_blocks) - 1\n\n            res_samples = down_block_res_samples[-len(upsample_block.resnets) :]\n            down_block_res_samples = down_block_res_samples[: -len(upsample_block.resnets)]\n\n            # if we have not reached the final block and need to forward the\n            # upsample size, we do it here\n            if not is_final_block and forward_upsample_size:\n                upsample_size = down_block_res_samples[-1].shape[2:]\n\n            if hasattr(upsample_block, \"has_cross_attention\") and upsample_block.has_cross_attention:\n                sample = upsample_block(\n                    hidden_states=sample,\n                    temb=emb,\n                    res_hidden_states_tuple=res_samples,\n                    encoder_hidden_states=encoder_hidden_states,\n                    cross_attention_kwargs=cross_attention_kwargs,\n                    upsample_size=upsample_size,\n                    attention_mask=attention_mask,\n                    encoder_attention_mask=encoder_attention_mask,\n                )\n            else:\n                sample = upsample_block(\n                    hidden_states=sample,\n                    temb=emb,\n                    res_hidden_states_tuple=res_samples,\n                    upsample_size=upsample_size,\n                )\n\n        # 6. post-process\n        if self.conv_norm_out:\n            sample = self.conv_norm_out(sample)\n            sample = self.conv_act(sample)\n        sample = self.conv_out(sample)\n\n        if USE_PEFT_BACKEND:\n            # remove `lora_scale` from each PEFT layer\n            unscale_lora_layers(self, lora_scale)\n\n        if not return_dict:\n            return (sample,)\n\n        return UNet2DConditionOutput(sample=sample)"
  },
  {
    "path": "utils/image_util.py",
    "content": "import matplotlib\nimport numpy as np\nimport torch\nfrom PIL import Image\nimport cv2\nfrom torchvision.transforms.functional import resize\nfrom torchvision.transforms import InterpolationMode\nfrom scipy.interpolate import griddata\nfrom enum import Enum\nimport os\nfrom scipy.interpolate import griddata as interp_grid\n\nclass DepthFileNameMode(Enum):\n    \"\"\"Prediction file naming modes\"\"\"\n\n    id = 1  # id.png\n    rgb_id = 2  # rgb_id.png\n    i_d_rgb = 3  # i_d_1_rgb.png\n    rgb_i_d = 4\n\ndef get_filled_depth(depth, mask, method):\n    x, y = np.indices(depth.shape)\n    known_points = mask == 0\n    points = np.array((x[known_points], y[known_points])).T\n    values = depth[known_points]\n    # print(values.min(), values.max())\n    all_points = np.array((x.flatten(), y.flatten())).T\n    filled_depth = griddata(points, values, all_points, method=method, fill_value=0)\n    return filled_depth.reshape(depth.shape).astype(np.float32)\ndef resize_max_res(img: Image.Image, max_edge_resolution: int, resample=Image.BICUBIC) -> Image.Image:\n    \"\"\"\n    Resize image to limit maximum edge length while keeping aspect ratio.\n    Args:\n        img (`Image.Image`):\n            Image to be resized.\n        max_edge_resolution (`int`):\n            Maximum edge length (pixel).\n    Returns:\n        `Image.Image`: Resized image.\n    \"\"\"\n    \n    original_width, original_height = img.size\n    \n    downscale_factor = min(\n        max_edge_resolution / original_width, max_edge_resolution / original_height\n    )\n\n    new_width = int(original_width * downscale_factor)\n    new_height = int(original_height * downscale_factor)\n\n    resized_img = img.resize((new_width, new_height), resample=resample)\n    return resized_img\n\ndef resize_max_res_cv2(img: np.ndarray, max_edge_resolution: int, interpolation=cv2.INTER_CUBIC) -> np.ndarray:\n    \"\"\"\n    Resize image to limit maximum edge length while keeping aspect ratio.\n    Args:\n        img (`np.ndarray`):\n            Image to be resized.\n        max_edge_resolution (`int`):\n            Maximum edge length (pixel).\n    Returns:\n        `np.ndarray`: Resized image.\n    \"\"\"\n    \n    original_height, original_width = img.shape[:2]\n    \n    downscale_factor = min(\n        max_edge_resolution / original_width, max_edge_resolution / original_height\n    )\n\n    new_width = int(original_width * downscale_factor)\n    new_height = int(original_height * downscale_factor)\n\n    resized_img = cv2.resize(img, (new_width, new_height), interpolation=interpolation)\n    return resized_img\n\ndef resize_max_res_tensor(input_tensor,recom_resolution=768):\n    \"\"\"\n    Resize image to limit maximum edge length while keeping aspect ratio.\n\n    Args:\n        img (`torch.Tensor`):\n            Image tensor to be resized. Expected shape: [B, C, H, W]\n        max_edge_resolution (`int`):\n            Maximum edge length (pixel).\n        resample_method (`PIL.Image.Resampling`):\n            Resampling method used to resize images.\n\n    Returns:\n        `torch.Tensor`: Resized image.\n    \"\"\"\n    assert 4 == input_tensor.dim(), f\"Invalid input shape {input_tensor.shape}\"\n\n    original_height, original_width =input_tensor.shape[-2:]\n    downscale_factor = min(\n        recom_resolution / original_width, recom_resolution / original_height\n    )\n\n    new_width = int(original_width * downscale_factor)\n    new_height = int(original_height * downscale_factor)\n\n    resized_img = resize(input_tensor, (new_height, new_width), InterpolationMode.BILINEAR, antialias=True)\n    return resized_img\n\ndef colorize_depth_maps(\n    depth_map, min_depth, max_depth, cmap=\"Spectral\", valid_mask=None\n):\n    \"\"\"\n    Colorize depth maps.\n    \"\"\"\n    assert len(depth_map.shape) >= 2, \"Invalid dimension\"\n\n    if isinstance(depth_map, torch.Tensor):\n        depth = depth_map.detach().clone().squeeze().numpy()\n    elif isinstance(depth_map, np.ndarray):\n        depth = depth_map.copy().squeeze()\n    # reshape to [ (B,) H, W ]\n    if depth.ndim < 3:\n        depth = depth[np.newaxis, :, :]\n\n    # colorize\n    cm = matplotlib.colormaps[cmap]\n    depth = ((depth - min_depth) / (max_depth - min_depth)).clip(0, 1)\n    img_colored_np = cm(depth, bytes=False)[:, :, :, 0:3]  # value from 0 to 1\n    img_colored_np = np.rollaxis(img_colored_np, 3, 1)\n\n    if valid_mask is not None:\n        if isinstance(depth_map, torch.Tensor):\n            valid_mask = valid_mask.detach().numpy()\n        valid_mask = valid_mask.squeeze()  # [H, W] or [B, H, W]\n        if valid_mask.ndim < 3:\n            valid_mask = valid_mask[np.newaxis, np.newaxis, :, :]\n        else:\n            valid_mask = valid_mask[:, np.newaxis, :, :]\n        valid_mask = np.repeat(valid_mask, 3, axis=1)\n        img_colored_np[~valid_mask] = 0\n\n    if isinstance(depth_map, torch.Tensor):\n        img_colored = torch.from_numpy(img_colored_np).float()\n    elif isinstance(depth_map, np.ndarray):\n        img_colored = img_colored_np\n\n    return img_colored\n\ndef chw2hwc(chw):\n    assert 3 == len(chw.shape)\n    if isinstance(chw, torch.Tensor):\n        hwc = torch.permute(chw, (1, 2, 0))\n    elif isinstance(chw, np.ndarray):\n        hwc = np.moveaxis(chw, 0, -1)\n    return hwc\n\ndef Disparity_Normalization_mask_scale(disparity, min_value, max_value, scale=0.6):\n    min_value = min_value.view(-1, 1, 1, 1)\n    max_value = max_value.view(-1, 1, 1, 1)\n    normalized_disparity = ((disparity - min_value) / (max_value - min_value + 1e-6) - 0.5) * scale*2\n    return normalized_disparity\n\ndef get_pred_name(rgb_basename, name_mode, suffix=\".png\"):\n    if DepthFileNameMode.rgb_id == name_mode:\n        pred_basename = \"pred_\" + rgb_basename.split(\"_\")[1]\n    elif DepthFileNameMode.i_d_rgb == name_mode:\n        pred_basename = rgb_basename.replace(\"_rgb.\", \"_pred.\")\n    elif DepthFileNameMode.id == name_mode:\n        pred_basename = \"pred_\" + rgb_basename\n    elif DepthFileNameMode.rgb_i_d == name_mode:\n        pred_basename = \"pred_\" + \"_\".join(rgb_basename.split(\"_\")[1:])\n    else:\n        raise NotImplementedError\n    # change suffix\n    pred_basename = os.path.splitext(pred_basename)[0] + suffix\n\n    return pred_basename\n\ndef get_filled_for_latents(mask, sparse_depth):\n    H, W = mask.shape\n    known_depth_y_coords, known_depth_x_coords = np.where(np.array(mask)== 0)\n    known_depth_coords = np.stack([known_depth_x_coords, known_depth_y_coords], axis=-1)\n    known_depth = sparse_depth[known_depth_y_coords, known_depth_x_coords]\n    x, y = np.meshgrid(np.arange(W, dtype=np.float32), np.arange(H, dtype=np.float32), indexing='xy')\n    grid = np.stack((x,y), axis=-1).reshape(-1,2)\n\n    dense_depth = interp_grid(known_depth_coords, known_depth, grid, method='nearest')\n    dense_depth = dense_depth.reshape(H, W)\n    dense_depth = dense_depth.astype(np.float32)\n    return dense_depth\n\n"
  },
  {
    "path": "utils/seed_all.py",
    "content": "# Copyright 2023 Bingxin Ke, ETH Zurich. All rights reserved.\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# --------------------------------------------------------------------------\n# If you find this code useful, we kindly ask you to cite our paper in your work.\n# Please find bibtex at: https://github.com/prs-eth/Marigold#-citation\n# More information about the method can be found at https://marigoldmonodepth.github.io\n# --------------------------------------------------------------------------\n\n\nimport numpy as np\nimport random\nimport torch\n\n\ndef seed_all(seed: int = 0):\n    \"\"\"\n    Set random seeds of all components.\n    \"\"\"\n    random.seed(seed)\n    np.random.seed(seed)\n    torch.manual_seed(seed)\n    torch.cuda.manual_seed_all(seed)\n"
  }
]