[
  {
    "path": "CODE_OF_CONDUCT.md",
    "content": "# Code of Conduct\n\n## Our Pledge\n\nIn the interest of fostering an open and welcoming environment, we as\ncontributors and maintainers pledge to make participation in our project and\nour community a harassment-free experience for everyone, regardless of age, body\nsize, disability, ethnicity, sex characteristics, gender identity and expression,\nlevel of experience, education, socio-economic status, nationality, personal\nappearance, race, religion, or sexual identity and orientation.\n\n## Our Standards\n\nExamples of behavior that contributes to creating a positive environment\ninclude:\n\n* Using welcoming and inclusive language\n* Being respectful of differing viewpoints and experiences\n* Gracefully accepting constructive criticism\n* Focusing on what is best for the community\n* Showing empathy towards other community members\n\nExamples of unacceptable behavior by participants include:\n\n* The use of sexualized language or imagery and unwelcome sexual attention or\nadvances\n* Trolling, insulting/derogatory comments, and personal or political attacks\n* Public or private harassment\n* Publishing others' private information, such as a physical or electronic\naddress, without explicit permission\n* Other conduct which could reasonably be considered inappropriate in a\nprofessional setting\n\n## Our Responsibilities\n\nProject maintainers are responsible for clarifying the standards of acceptable\nbehavior and are expected to take appropriate and fair corrective action in\nresponse to any instances of unacceptable behavior.\n\nProject maintainers have the right and responsibility to remove, edit, or\nreject comments, commits, code, wiki edits, issues, and other contributions\nthat are not aligned to this Code of Conduct, or to ban temporarily or\npermanently any contributor for other behaviors that they deem inappropriate,\nthreatening, offensive, or harmful.\n\n## Scope\n\nThis Code of Conduct applies within all project spaces, and it also applies when\nan individual is representing the project or its community in public spaces.\nExamples of representing a project or community include using an official\nproject e-mail address, posting via an official social media account, or acting\nas an appointed representative at an online or offline event. Representation of\na project may be further defined and clarified by project maintainers.\n\nThis Code of Conduct also applies outside the project spaces when there is a\nreasonable belief that an individual's behavior may have a negative impact on\nthe project or its community.\n\n## Enforcement\n\nInstances of abusive, harassing, or otherwise unacceptable behavior may be\nreported by contacting the project team at <opensource-conduct@meta.com>. All\ncomplaints will be reviewed and investigated and will result in a response that\nis deemed necessary and appropriate to the circumstances. The project team is\nobligated to maintain confidentiality with regard to the reporter of an incident.\nFurther details of specific enforcement policies may be posted separately.\n\nProject maintainers who do not follow or enforce the Code of Conduct in good\nfaith may face temporary or permanent repercussions as determined by other\nmembers of the project's leadership.\n\n## Attribution\n\nThis Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,\navailable at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html\n\n[homepage]: https://www.contributor-covenant.org\n\nFor answers to common questions about this code of conduct, see\nhttps://www.contributor-covenant.org/faq\n"
  },
  {
    "path": "CONTRIBUTING.md",
    "content": "# Contributing to DiT\nWe want to make contributing to this project as easy and transparent as\npossible.\n\n## Our Development Process\nWork on the `DiT` repo has mostly concluded.\n\n## Pull Requests\nWe actively welcome your pull requests.\n\n1. Fork the repo and create your branch from `main`.\n2. If you've added code that should be tested, add tests.\n3. If you've changed APIs, update the documentation.\n4. Ensure the test suite passes.\n5. Make sure your code lints.\n6. If you haven't already, complete the Contributor License Agreement (\"CLA\").\n\n## Contributor License Agreement (\"CLA\")\nIn order to accept your pull request, we need you to submit a CLA. You only need\nto do this once to work on any of Meta's open source projects.\n\nComplete your CLA here: <https://code.facebook.com/cla>\n\n## Issues\nWe use GitHub issues to track public bugs. Please ensure your description is\nclear and has sufficient instructions to be able to reproduce the issue.\n\nMeta has a [bounty program](https://www.facebook.com/whitehat/) for the safe\ndisclosure of security bugs. In those cases, please go through the process\noutlined on that page and do not file a public issue.\n\n## License\nBy contributing to `DiT`, you agree that your contributions will be licensed\nunder the LICENSE file in the root directory of this source tree."
  },
  {
    "path": "LICENSE.txt",
    "content": "\nAttribution-NonCommercial 4.0 International\n\n=======================================================================\n\nCreative Commons Corporation (\"Creative Commons\") is not a law firm and\ndoes not provide legal services or legal advice. Distribution of\nCreative Commons public licenses does not create a lawyer-client or\nother relationship. Creative Commons makes its licenses and related\ninformation available on an \"as-is\" basis. Creative Commons gives no\nwarranties regarding its licenses, any material licensed under their\nterms and conditions, or any related information. Creative Commons\ndisclaims all liability for damages resulting from their use to the\nfullest extent possible.\n\nUsing Creative Commons Public Licenses\n\nCreative Commons public licenses provide a standard set of terms and\nconditions that creators and other rights holders may use to share\noriginal works of authorship and other material subject to copyright\nand certain other rights specified in the public license below. The\nfollowing considerations are for informational purposes only, are not\nexhaustive, and do not form part of our licenses.\n\n     Considerations for licensors: Our public licenses are\n     intended for use by those authorized to give the public\n     permission to use material in ways otherwise restricted by\n     copyright and certain other rights. Our licenses are\n     irrevocable. Licensors should read and understand the terms\n     and conditions of the license they choose before applying it.\n     Licensors should also secure all rights necessary before\n     applying our licenses so that the public can reuse the\n     material as expected. Licensors should clearly mark any\n     material not subject to the license. This includes other CC-\n     licensed material, or material used under an exception or\n     limitation to copyright. More considerations for licensors:\n\twiki.creativecommons.org/Considerations_for_licensors\n\n     Considerations for the public: By using one of our public\n     licenses, a licensor grants the public permission to use the\n     licensed material under specified terms and conditions. If\n     the licensor's permission is not necessary for any reason--for\n     example, because of any applicable exception or limitation to\n     copyright--then that use is not regulated by the license. Our\n     licenses grant only permissions under copyright and certain\n     other rights that a licensor has authority to grant. Use of\n     the licensed material may still be restricted for other\n     reasons, including because others have copyright or other\n     rights in the material. A licensor may make special requests,\n     such as asking that all changes be marked or described.\n     Although not required by our licenses, you are encouraged to\n     respect those requests where reasonable. More_considerations\n     for the public: \n\twiki.creativecommons.org/Considerations_for_licensees\n\n=======================================================================\n\nCreative Commons Attribution-NonCommercial 4.0 International Public\nLicense\n\nBy exercising the Licensed Rights (defined below), You accept and agree\nto be bound by the terms and conditions of this Creative Commons\nAttribution-NonCommercial 4.0 International Public License (\"Public\nLicense\"). To the extent this Public License may be interpreted as a\ncontract, You are granted the Licensed Rights in consideration of Your\nacceptance of these terms and conditions, and the Licensor grants You\nsuch rights in consideration of benefits the Licensor receives from\nmaking the Licensed Material available under these terms and\nconditions.\n\nSection 1 -- Definitions.\n\n  a. Adapted Material means material subject to Copyright and Similar\n     Rights that is derived from or based upon the Licensed Material\n     and in which the Licensed Material is translated, altered,\n     arranged, transformed, or otherwise modified in a manner requiring\n     permission under the Copyright and Similar Rights held by the\n     Licensor. For purposes of this Public License, where the Licensed\n     Material is a musical work, performance, or sound recording,\n     Adapted Material is always produced where the Licensed Material is\n     synched in timed relation with a moving image.\n\n  b. Adapter's License means the license You apply to Your Copyright\n     and Similar Rights in Your contributions to Adapted Material in\n     accordance with the terms and conditions of this Public License.\n\n  c. Copyright and Similar Rights means copyright and/or similar rights\n     closely related to copyright including, without limitation,\n     performance, broadcast, sound recording, and Sui Generis Database\n     Rights, without regard to how the rights are labeled or\n     categorized. For purposes of this Public License, the rights\n     specified in Section 2(b)(1)-(2) are not Copyright and Similar\n     Rights.\n  d. Effective Technological Measures means those measures that, in the\n     absence of proper authority, may not be circumvented under laws\n     fulfilling obligations under Article 11 of the WIPO Copyright\n     Treaty adopted on December 20, 1996, and/or similar international\n     agreements.\n\n  e. Exceptions and Limitations means fair use, fair dealing, and/or\n     any other exception or limitation to Copyright and Similar Rights\n     that applies to Your use of the Licensed Material.\n\n  f. Licensed Material means the artistic or literary work, database,\n     or other material to which the Licensor applied this Public\n     License.\n\n  g. Licensed Rights means the rights granted to You subject to the\n     terms and conditions of this Public License, which are limited to\n     all Copyright and Similar Rights that apply to Your use of the\n     Licensed Material and that the Licensor has authority to license.\n\n  h. Licensor means the individual(s) or entity(ies) granting rights\n     under this Public License.\n\n  i. NonCommercial means not primarily intended for or directed towards\n     commercial advantage or monetary compensation. For purposes of\n     this Public License, the exchange of the Licensed Material for\n     other material subject to Copyright and Similar Rights by digital\n     file-sharing or similar means is NonCommercial provided there is\n     no payment of monetary compensation in connection with the\n     exchange.\n\n  j. Share means to provide material to the public by any means or\n     process that requires permission under the Licensed Rights, such\n     as reproduction, public display, public performance, distribution,\n     dissemination, communication, or importation, and to make material\n     available to the public including in ways that members of the\n     public may access the material from a place and at a time\n     individually chosen by them.\n\n  k. Sui Generis Database Rights means rights other than copyright\n     resulting from Directive 96/9/EC of the European Parliament and of\n     the Council of 11 March 1996 on the legal protection of databases,\n     as amended and/or succeeded, as well as other essentially\n     equivalent rights anywhere in the world.\n\n  l. You means the individual or entity exercising the Licensed Rights\n     under this Public License. Your has a corresponding meaning.\n\nSection 2 -- Scope.\n\n  a. License grant.\n\n       1. Subject to the terms and conditions of this Public License,\n          the Licensor hereby grants You a worldwide, royalty-free,\n          non-sublicensable, non-exclusive, irrevocable license to\n          exercise the Licensed Rights in the Licensed Material to:\n\n            a. reproduce and Share the Licensed Material, in whole or\n               in part, for NonCommercial purposes only; and\n\n            b. produce, reproduce, and Share Adapted Material for\n               NonCommercial purposes only.\n\n       2. Exceptions and Limitations. For the avoidance of doubt, where\n          Exceptions and Limitations apply to Your use, this Public\n          License does not apply, and You do not need to comply with\n          its terms and conditions.\n\n       3. Term. The term of this Public License is specified in Section\n          6(a).\n\n       4. Media and formats; technical modifications allowed. The\n          Licensor authorizes You to exercise the Licensed Rights in\n          all media and formats whether now known or hereafter created,\n          and to make technical modifications necessary to do so. The\n          Licensor waives and/or agrees not to assert any right or\n          authority to forbid You from making technical modifications\n          necessary to exercise the Licensed Rights, including\n          technical modifications necessary to circumvent Effective\n          Technological Measures. For purposes of this Public License,\n          simply making modifications authorized by this Section 2(a)\n          (4) never produces Adapted Material.\n\n       5. Downstream recipients.\n\n            a. Offer from the Licensor -- Licensed Material. Every\n               recipient of the Licensed Material automatically\n               receives an offer from the Licensor to exercise the\n               Licensed Rights under the terms and conditions of this\n               Public License.\n\n            b. No downstream restrictions. You may not offer or impose\n               any additional or different terms or conditions on, or\n               apply any Effective Technological Measures to, the\n               Licensed Material if doing so restricts exercise of the\n               Licensed Rights by any recipient of the Licensed\n               Material.\n\n       6. No endorsement. Nothing in this Public License constitutes or\n          may be construed as permission to assert or imply that You\n          are, or that Your use of the Licensed Material is, connected\n          with, or sponsored, endorsed, or granted official status by,\n          the Licensor or others designated to receive attribution as\n          provided in Section 3(a)(1)(A)(i).\n\n  b. Other rights.\n\n       1. Moral rights, such as the right of integrity, are not\n          licensed under this Public License, nor are publicity,\n          privacy, and/or other similar personality rights; however, to\n          the extent possible, the Licensor waives and/or agrees not to\n          assert any such rights held by the Licensor to the limited\n          extent necessary to allow You to exercise the Licensed\n          Rights, but not otherwise.\n\n       2. Patent and trademark rights are not licensed under this\n          Public License.\n\n       3. To the extent possible, the Licensor waives any right to\n          collect royalties from You for the exercise of the Licensed\n          Rights, whether directly or through a collecting society\n          under any voluntary or waivable statutory or compulsory\n          licensing scheme. In all other cases the Licensor expressly\n          reserves any right to collect such royalties, including when\n          the Licensed Material is used other than for NonCommercial\n          purposes.\n\nSection 3 -- License Conditions.\n\nYour exercise of the Licensed Rights is expressly made subject to the\nfollowing conditions.\n\n  a. Attribution.\n\n       1. If You Share the Licensed Material (including in modified\n          form), You must:\n\n            a. retain the following if it is supplied by the Licensor\n               with the Licensed Material:\n\n                 i. identification of the creator(s) of the Licensed\n                    Material and any others designated to receive\n                    attribution, in any reasonable manner requested by\n                    the Licensor (including by pseudonym if\n                    designated);\n\n                ii. a copyright notice;\n\n               iii. a notice that refers to this Public License;\n\n                iv. a notice that refers to the disclaimer of\n                    warranties;\n\n                 v. a URI or hyperlink to the Licensed Material to the\n                    extent reasonably practicable;\n\n            b. indicate if You modified the Licensed Material and\n               retain an indication of any previous modifications; and\n\n            c. indicate the Licensed Material is licensed under this\n               Public License, and include the text of, or the URI or\n               hyperlink to, this Public License.\n\n       2. You may satisfy the conditions in Section 3(a)(1) in any\n          reasonable manner based on the medium, means, and context in\n          which You Share the Licensed Material. For example, it may be\n          reasonable to satisfy the conditions by providing a URI or\n          hyperlink to a resource that includes the required\n          information.\n\n       3. If requested by the Licensor, You must remove any of the\n          information required by Section 3(a)(1)(A) to the extent\n          reasonably practicable.\n\n       4. If You Share Adapted Material You produce, the Adapter's\n          License You apply must not prevent recipients of the Adapted\n          Material from complying with this Public License.\n\nSection 4 -- Sui Generis Database Rights.\n\nWhere the Licensed Rights include Sui Generis Database Rights that\napply to Your use of the Licensed Material:\n\n  a. for the avoidance of doubt, Section 2(a)(1) grants You the right\n     to extract, reuse, reproduce, and Share all or a substantial\n     portion of the contents of the database for NonCommercial purposes\n     only;\n\n  b. if You include all or a substantial portion of the database\n     contents in a database in which You have Sui Generis Database\n     Rights, then the database in which You have Sui Generis Database\n     Rights (but not its individual contents) is Adapted Material; and\n\n  c. You must comply with the conditions in Section 3(a) if You Share\n     all or a substantial portion of the contents of the database.\n\nFor the avoidance of doubt, this Section 4 supplements and does not\nreplace Your obligations under this Public License where the Licensed\nRights include other Copyright and Similar Rights.\n\nSection 5 -- Disclaimer of Warranties and Limitation of Liability.\n\n  a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE\n     EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS\n     AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF\n     ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,\n     IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,\n     WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR\n     PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,\n     ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT\n     KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT\n     ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.\n\n  b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE\n     TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,\n     NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,\n     INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,\n     COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR\n     USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN\n     ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR\n     DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR\n     IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.\n\n  c. The disclaimer of warranties and limitation of liability provided\n     above shall be interpreted in a manner that, to the extent\n     possible, most closely approximates an absolute disclaimer and\n     waiver of all liability.\n\nSection 6 -- Term and Termination.\n\n  a. This Public License applies for the term of the Copyright and\n     Similar Rights licensed here. However, if You fail to comply with\n     this Public License, then Your rights under this Public License\n     terminate automatically.\n\n  b. Where Your right to use the Licensed Material has terminated under\n     Section 6(a), it reinstates:\n\n       1. automatically as of the date the violation is cured, provided\n          it is cured within 30 days of Your discovery of the\n          violation; or\n\n       2. upon express reinstatement by the Licensor.\n\n     For the avoidance of doubt, this Section 6(b) does not affect any\n     right the Licensor may have to seek remedies for Your violations\n     of this Public License.\n\n  c. For the avoidance of doubt, the Licensor may also offer the\n     Licensed Material under separate terms or conditions or stop\n     distributing the Licensed Material at any time; however, doing so\n     will not terminate this Public License.\n\n  d. Sections 1, 5, 6, 7, and 8 survive termination of this Public\n     License.\n\nSection 7 -- Other Terms and Conditions.\n\n  a. The Licensor shall not be bound by any additional or different\n     terms or conditions communicated by You unless expressly agreed.\n\n  b. Any arrangements, understandings, or agreements regarding the\n     Licensed Material not stated herein are separate from and\n     independent of the terms and conditions of this Public License.\n\nSection 8 -- Interpretation.\n\n  a. For the avoidance of doubt, this Public License does not, and\n     shall not be interpreted to, reduce, limit, restrict, or impose\n     conditions on any use of the Licensed Material that could lawfully\n     be made without permission under this Public License.\n\n  b. To the extent possible, if any provision of this Public License is\n     deemed unenforceable, it shall be automatically reformed to the\n     minimum extent necessary to make it enforceable. If the provision\n     cannot be reformed, it shall be severed from this Public License\n     without affecting the enforceability of the remaining terms and\n     conditions.\n\n  c. No term or condition of this Public License will be waived and no\n     failure to comply consented to unless expressly agreed to by the\n     Licensor.\n\n  d. Nothing in this Public License constitutes or may be interpreted\n     as a limitation upon, or waiver of, any privileges and immunities\n     that apply to the Licensor or You, including from the legal\n     processes of any jurisdiction or authority.\n\n=======================================================================\n\nCreative Commons is not a party to its public\nlicenses. Notwithstanding, Creative Commons may elect to apply one of\nits public licenses to material it publishes and in those instances\nwill be considered the “Licensor.” The text of the Creative Commons\npublic licenses is dedicated to the public domain under the CC0 Public\nDomain Dedication. Except for the limited purpose of indicating that\nmaterial is shared under a Creative Commons public license or as\notherwise permitted by the Creative Commons policies published at\ncreativecommons.org/policies, Creative Commons does not authorize the\nuse of the trademark \"Creative Commons\" or any other trademark or logo\nof Creative Commons without its prior written consent including,\nwithout limitation, in connection with any unauthorized modifications\nto any of its public licenses or any other arrangements,\nunderstandings, or agreements concerning use of licensed material. For\nthe avoidance of doubt, this paragraph does not form part of the\npublic licenses.\n\nCreative Commons may be contacted at creativecommons.org.\n"
  },
  {
    "path": "README.md",
    "content": "## Scalable Diffusion Models with Transformers (DiT)<br><sub>Official PyTorch Implementation</sub>\n\n### [Paper](http://arxiv.org/abs/2212.09748) | [Project Page](https://www.wpeebles.com/DiT) | Run DiT-XL/2 [![Hugging Face Spaces](https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Spaces-blue)](https://huggingface.co/spaces/wpeebles/DiT) [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](http://colab.research.google.com/github/facebookresearch/DiT/blob/main/run_DiT.ipynb) <a href=\"https://replicate.com/arielreplicate/scalable_diffusion_with_transformers\"><img src=\"https://replicate.com/arielreplicate/scalable_diffusion_with_transformers/badge\"></a>\n\n![DiT samples](visuals/sample_grid_0.png)\n\nThis repo contains PyTorch model definitions, pre-trained weights and training/sampling code for our paper exploring \ndiffusion models with transformers (DiTs). You can find more visualizations on our [project page](https://www.wpeebles.com/DiT).\n\n> [**Scalable Diffusion Models with Transformers**](https://www.wpeebles.com/DiT)<br>\n> [William Peebles](https://www.wpeebles.com), [Saining Xie](https://www.sainingxie.com)\n> <br>UC Berkeley, New York University<br>\n\nWe train latent diffusion models, replacing the commonly-used U-Net backbone with a transformer that operates on \nlatent patches. We analyze the scalability of our Diffusion Transformers (DiTs) through the lens of forward pass \ncomplexity as measured by Gflops. We find that DiTs with higher Gflops---through increased transformer depth/width or\nincreased number of input tokens---consistently have lower FID. In addition to good scalability properties, our \nDiT-XL/2 models outperform all prior diffusion models on the class-conditional ImageNet 512×512 and 256×256 benchmarks, \nachieving a state-of-the-art FID of 2.27 on the latter.\n\nThis repository contains:\n\n* 🪐 A simple PyTorch [implementation](models.py) of DiT\n* ⚡️ Pre-trained class-conditional DiT models trained on ImageNet (512x512 and 256x256)\n* 💥 A self-contained [Hugging Face Space](https://huggingface.co/spaces/wpeebles/DiT) and [Colab notebook](http://colab.research.google.com/github/facebookresearch/DiT/blob/main/run_DiT.ipynb) for running pre-trained DiT-XL/2 models\n* 🛸 A DiT [training script](train.py) using PyTorch DDP\n\nAn implementation of DiT directly in Hugging Face `diffusers` can also be found [here](https://github.com/huggingface/diffusers/blob/main/docs/source/en/api/pipelines/dit.mdx).\n\n\n## Setup\n\nFirst, download and set up the repo:\n\n```bash\ngit clone https://github.com/facebookresearch/DiT.git\ncd DiT\n```\n\nWe provide an [`environment.yml`](environment.yml) file that can be used to create a Conda environment. If you only want \nto run pre-trained models locally on CPU, you can remove the `cudatoolkit` and `pytorch-cuda` requirements from the file.\n\n```bash\nconda env create -f environment.yml\nconda activate DiT\n```\n\n\n## Sampling [![Hugging Face Spaces](https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Spaces-blue)](https://huggingface.co/spaces/wpeebles/DiT) [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](http://colab.research.google.com/github/facebookresearch/DiT/blob/main/run_DiT.ipynb)\n![More DiT samples](visuals/sample_grid_1.png)\n\n**Pre-trained DiT checkpoints.** You can sample from our pre-trained DiT models with [`sample.py`](sample.py). Weights for our pre-trained DiT model will be \nautomatically downloaded depending on the model you use. The script has various arguments to switch between the 256x256\nand 512x512 models, adjust sampling steps, change the classifier-free guidance scale, etc. For example, to sample from\nour 512x512 DiT-XL/2 model, you can use:\n\n```bash\npython sample.py --image-size 512 --seed 1\n```\n\nFor convenience, our pre-trained DiT models can be downloaded directly here as well:\n\n| DiT Model     | Image Resolution | FID-50K | Inception Score | Gflops | \n|---------------|------------------|---------|-----------------|--------|\n| [XL/2](https://dl.fbaipublicfiles.com/DiT/models/DiT-XL-2-256x256.pt) | 256x256          | 2.27    | 278.24          | 119    |\n| [XL/2](https://dl.fbaipublicfiles.com/DiT/models/DiT-XL-2-512x512.pt) | 512x512          | 3.04    | 240.82          | 525    |\n\n\n**Custom DiT checkpoints.** If you've trained a new DiT model with [`train.py`](train.py) (see [below](#training-dit)), you can add the `--ckpt`\nargument to use your own checkpoint instead. For example, to sample from the EMA weights of a custom \n256x256 DiT-L/4 model, run:\n\n```bash\npython sample.py --model DiT-L/4 --image-size 256 --ckpt /path/to/model.pt\n```\n\n\n## Training DiT\n\nWe provide a training script for DiT in [`train.py`](train.py). This script can be used to train class-conditional \nDiT models, but it can be easily modified to support other types of conditioning. To launch DiT-XL/2 (256x256) training with `N` GPUs on \none node:\n\n```bash\ntorchrun --nnodes=1 --nproc_per_node=N train.py --model DiT-XL/2 --data-path /path/to/imagenet/train\n```\n\n### PyTorch Training Results\n\nWe've trained DiT-XL/2 and DiT-B/4 models from scratch with the PyTorch training script\nto verify that it reproduces the original JAX results up to several hundred thousand training iterations. Across our experiments, the PyTorch-trained models give \nsimilar (and sometimes slightly better) results compared to the JAX-trained models up to reasonable random variation. Some data points:\n\n| DiT Model  | Train Steps | FID-50K<br> (JAX Training) | FID-50K<br> (PyTorch Training) | PyTorch Global Training Seed |\n|------------|-------------|----------------------------|--------------------------------|------------------------------|\n| XL/2       | 400K        | 19.5                       | **18.1**                       | 42                           |\n| B/4        | 400K        | **68.4**                   | 68.9                           | 42                           |\n| B/4        | 400K        | 68.4                       | **68.3**                       | 100                          |\n\nThese models were trained at 256x256 resolution; we used 8x A100s to train XL/2 and 4x A100s to train B/4. Note that FID \nhere is computed with 250 DDPM sampling steps, with the `mse` VAE decoder and without guidance (`cfg-scale=1`). \n\n**TF32 Note (important for A100 users).** When we ran the above tests, TF32 matmuls were disabled per PyTorch's defaults. \nWe've enabled them at the top of `train.py` and `sample.py` because it makes training and sampling way way way faster on \nA100s (and should for other Ampere GPUs too), but note that the use of TF32 may lead to some differences compared to \nthe above results.\n\n### Enhancements\nTraining (and sampling) could likely be sped-up significantly by:\n- [ ] using [Flash Attention](https://github.com/HazyResearch/flash-attention) in the DiT model\n- [ ] using `torch.compile` in PyTorch 2.0\n\nBasic features that would be nice to add:\n- [ ] Monitor FID and other metrics\n- [ ] Generate and save samples from the EMA model periodically\n- [ ] Resume training from a checkpoint\n- [ ] AMP/bfloat16 support\n\n**🔥 Feature Update** Check out this repository at https://github.com/chuanyangjin/fast-DiT to preview a selection of training speed acceleration and memory saving features including gradient checkpointing, mixed precision training and pre-extrated VAE features. With these advancements, we have achieved a training speed of 0.84 steps/sec for DiT-XL/2 using just a single A100 GPU.\n\n## Evaluation (FID, Inception Score, etc.)\n\nWe include a [`sample_ddp.py`](sample_ddp.py) script which samples a large number of images from a DiT model in parallel. This script \ngenerates a folder of samples as well as a `.npz` file which can be directly used with [ADM's TensorFlow\nevaluation suite](https://github.com/openai/guided-diffusion/tree/main/evaluations) to compute FID, Inception Score and\nother metrics. For example, to sample 50K images from our pre-trained DiT-XL/2 model over `N` GPUs, run:\n\n```bash\ntorchrun --nnodes=1 --nproc_per_node=N sample_ddp.py --model DiT-XL/2 --num-fid-samples 50000\n```\n\nThere are several additional options; see [`sample_ddp.py`](sample_ddp.py) for details. \n\n\n## Differences from JAX\n\nOur models were originally trained in JAX on TPUs. The weights in this repo are ported directly from the JAX models. \nThere may be minor differences in results stemming from sampling with different floating point precisions. We re-evaluated \nour ported PyTorch weights at FP32, and they actually perform marginally better than sampling in JAX (2.21 FID \nversus 2.27 in the paper).\n\n\n## BibTeX\n\n```bibtex\n@article{Peebles2022DiT,\n  title={Scalable Diffusion Models with Transformers},\n  author={William Peebles and Saining Xie},\n  year={2022},\n  journal={arXiv preprint arXiv:2212.09748},\n}\n```\n\n\n## Acknowledgments\nWe thank Kaiming He, Ronghang Hu, Alexander Berg, Shoubhik Debnath, Tim Brooks, Ilija Radosavovic and Tete Xiao for helpful discussions. \nWilliam Peebles is supported by the NSF Graduate Research Fellowship.\n\nThis codebase borrows from OpenAI's diffusion repos, most notably [ADM](https://github.com/openai/guided-diffusion).\n\n\n## License\nThe code and model weights are licensed under CC-BY-NC. See [`LICENSE.txt`](LICENSE.txt) for details.\n"
  },
  {
    "path": "diffusion/__init__.py",
    "content": "# Modified from OpenAI's diffusion repos\n#     GLIDE: https://github.com/openai/glide-text2im/blob/main/glide_text2im/gaussian_diffusion.py\n#     ADM:   https://github.com/openai/guided-diffusion/blob/main/guided_diffusion\n#     IDDPM: https://github.com/openai/improved-diffusion/blob/main/improved_diffusion/gaussian_diffusion.py\n\nfrom . import gaussian_diffusion as gd\nfrom .respace import SpacedDiffusion, space_timesteps\n\n\ndef create_diffusion(\n    timestep_respacing,\n    noise_schedule=\"linear\", \n    use_kl=False,\n    sigma_small=False,\n    predict_xstart=False,\n    learn_sigma=True,\n    rescale_learned_sigmas=False,\n    diffusion_steps=1000\n):\n    betas = gd.get_named_beta_schedule(noise_schedule, diffusion_steps)\n    if use_kl:\n        loss_type = gd.LossType.RESCALED_KL\n    elif rescale_learned_sigmas:\n        loss_type = gd.LossType.RESCALED_MSE\n    else:\n        loss_type = gd.LossType.MSE\n    if timestep_respacing is None or timestep_respacing == \"\":\n        timestep_respacing = [diffusion_steps]\n    return SpacedDiffusion(\n        use_timesteps=space_timesteps(diffusion_steps, timestep_respacing),\n        betas=betas,\n        model_mean_type=(\n            gd.ModelMeanType.EPSILON if not predict_xstart else gd.ModelMeanType.START_X\n        ),\n        model_var_type=(\n            (\n                gd.ModelVarType.FIXED_LARGE\n                if not sigma_small\n                else gd.ModelVarType.FIXED_SMALL\n            )\n            if not learn_sigma\n            else gd.ModelVarType.LEARNED_RANGE\n        ),\n        loss_type=loss_type\n        # rescale_timesteps=rescale_timesteps,\n    )\n"
  },
  {
    "path": "diffusion/diffusion_utils.py",
    "content": "# Modified from OpenAI's diffusion repos\n#     GLIDE: https://github.com/openai/glide-text2im/blob/main/glide_text2im/gaussian_diffusion.py\n#     ADM:   https://github.com/openai/guided-diffusion/blob/main/guided_diffusion\n#     IDDPM: https://github.com/openai/improved-diffusion/blob/main/improved_diffusion/gaussian_diffusion.py\n\nimport torch as th\nimport numpy as np\n\n\ndef normal_kl(mean1, logvar1, mean2, logvar2):\n    \"\"\"\n    Compute the KL divergence between two gaussians.\n    Shapes are automatically broadcasted, so batches can be compared to\n    scalars, among other use cases.\n    \"\"\"\n    tensor = None\n    for obj in (mean1, logvar1, mean2, logvar2):\n        if isinstance(obj, th.Tensor):\n            tensor = obj\n            break\n    assert tensor is not None, \"at least one argument must be a Tensor\"\n\n    # Force variances to be Tensors. Broadcasting helps convert scalars to\n    # Tensors, but it does not work for th.exp().\n    logvar1, logvar2 = [\n        x if isinstance(x, th.Tensor) else th.tensor(x).to(tensor)\n        for x in (logvar1, logvar2)\n    ]\n\n    return 0.5 * (\n        -1.0\n        + logvar2\n        - logvar1\n        + th.exp(logvar1 - logvar2)\n        + ((mean1 - mean2) ** 2) * th.exp(-logvar2)\n    )\n\n\ndef approx_standard_normal_cdf(x):\n    \"\"\"\n    A fast approximation of the cumulative distribution function of the\n    standard normal.\n    \"\"\"\n    return 0.5 * (1.0 + th.tanh(np.sqrt(2.0 / np.pi) * (x + 0.044715 * th.pow(x, 3))))\n\n\ndef continuous_gaussian_log_likelihood(x, *, means, log_scales):\n    \"\"\"\n    Compute the log-likelihood of a continuous Gaussian distribution.\n    :param x: the targets\n    :param means: the Gaussian mean Tensor.\n    :param log_scales: the Gaussian log stddev Tensor.\n    :return: a tensor like x of log probabilities (in nats).\n    \"\"\"\n    centered_x = x - means\n    inv_stdv = th.exp(-log_scales)\n    normalized_x = centered_x * inv_stdv\n    log_probs = th.distributions.Normal(th.zeros_like(x), th.ones_like(x)).log_prob(normalized_x)\n    return log_probs\n\n\ndef discretized_gaussian_log_likelihood(x, *, means, log_scales):\n    \"\"\"\n    Compute the log-likelihood of a Gaussian distribution discretizing to a\n    given image.\n    :param x: the target images. It is assumed that this was uint8 values,\n              rescaled to the range [-1, 1].\n    :param means: the Gaussian mean Tensor.\n    :param log_scales: the Gaussian log stddev Tensor.\n    :return: a tensor like x of log probabilities (in nats).\n    \"\"\"\n    assert x.shape == means.shape == log_scales.shape\n    centered_x = x - means\n    inv_stdv = th.exp(-log_scales)\n    plus_in = inv_stdv * (centered_x + 1.0 / 255.0)\n    cdf_plus = approx_standard_normal_cdf(plus_in)\n    min_in = inv_stdv * (centered_x - 1.0 / 255.0)\n    cdf_min = approx_standard_normal_cdf(min_in)\n    log_cdf_plus = th.log(cdf_plus.clamp(min=1e-12))\n    log_one_minus_cdf_min = th.log((1.0 - cdf_min).clamp(min=1e-12))\n    cdf_delta = cdf_plus - cdf_min\n    log_probs = th.where(\n        x < -0.999,\n        log_cdf_plus,\n        th.where(x > 0.999, log_one_minus_cdf_min, th.log(cdf_delta.clamp(min=1e-12))),\n    )\n    assert log_probs.shape == x.shape\n    return log_probs\n"
  },
  {
    "path": "diffusion/gaussian_diffusion.py",
    "content": "# Modified from OpenAI's diffusion repos\n#     GLIDE: https://github.com/openai/glide-text2im/blob/main/glide_text2im/gaussian_diffusion.py\n#     ADM:   https://github.com/openai/guided-diffusion/blob/main/guided_diffusion\n#     IDDPM: https://github.com/openai/improved-diffusion/blob/main/improved_diffusion/gaussian_diffusion.py\n\n\nimport math\n\nimport numpy as np\nimport torch as th\nimport enum\n\nfrom .diffusion_utils import discretized_gaussian_log_likelihood, normal_kl\n\n\ndef mean_flat(tensor):\n    \"\"\"\n    Take the mean over all non-batch dimensions.\n    \"\"\"\n    return tensor.mean(dim=list(range(1, len(tensor.shape))))\n\n\nclass ModelMeanType(enum.Enum):\n    \"\"\"\n    Which type of output the model predicts.\n    \"\"\"\n\n    PREVIOUS_X = enum.auto()  # the model predicts x_{t-1}\n    START_X = enum.auto()  # the model predicts x_0\n    EPSILON = enum.auto()  # the model predicts epsilon\n\n\nclass ModelVarType(enum.Enum):\n    \"\"\"\n    What is used as the model's output variance.\n    The LEARNED_RANGE option has been added to allow the model to predict\n    values between FIXED_SMALL and FIXED_LARGE, making its job easier.\n    \"\"\"\n\n    LEARNED = enum.auto()\n    FIXED_SMALL = enum.auto()\n    FIXED_LARGE = enum.auto()\n    LEARNED_RANGE = enum.auto()\n\n\nclass LossType(enum.Enum):\n    MSE = enum.auto()  # use raw MSE loss (and KL when learning variances)\n    RESCALED_MSE = (\n        enum.auto()\n    )  # use raw MSE loss (with RESCALED_KL when learning variances)\n    KL = enum.auto()  # use the variational lower-bound\n    RESCALED_KL = enum.auto()  # like KL, but rescale to estimate the full VLB\n\n    def is_vb(self):\n        return self == LossType.KL or self == LossType.RESCALED_KL\n\n\ndef _warmup_beta(beta_start, beta_end, num_diffusion_timesteps, warmup_frac):\n    betas = beta_end * np.ones(num_diffusion_timesteps, dtype=np.float64)\n    warmup_time = int(num_diffusion_timesteps * warmup_frac)\n    betas[:warmup_time] = np.linspace(beta_start, beta_end, warmup_time, dtype=np.float64)\n    return betas\n\n\ndef get_beta_schedule(beta_schedule, *, beta_start, beta_end, num_diffusion_timesteps):\n    \"\"\"\n    This is the deprecated API for creating beta schedules.\n    See get_named_beta_schedule() for the new library of schedules.\n    \"\"\"\n    if beta_schedule == \"quad\":\n        betas = (\n            np.linspace(\n                beta_start ** 0.5,\n                beta_end ** 0.5,\n                num_diffusion_timesteps,\n                dtype=np.float64,\n            )\n            ** 2\n        )\n    elif beta_schedule == \"linear\":\n        betas = np.linspace(beta_start, beta_end, num_diffusion_timesteps, dtype=np.float64)\n    elif beta_schedule == \"warmup10\":\n        betas = _warmup_beta(beta_start, beta_end, num_diffusion_timesteps, 0.1)\n    elif beta_schedule == \"warmup50\":\n        betas = _warmup_beta(beta_start, beta_end, num_diffusion_timesteps, 0.5)\n    elif beta_schedule == \"const\":\n        betas = beta_end * np.ones(num_diffusion_timesteps, dtype=np.float64)\n    elif beta_schedule == \"jsd\":  # 1/T, 1/(T-1), 1/(T-2), ..., 1\n        betas = 1.0 / np.linspace(\n            num_diffusion_timesteps, 1, num_diffusion_timesteps, dtype=np.float64\n        )\n    else:\n        raise NotImplementedError(beta_schedule)\n    assert betas.shape == (num_diffusion_timesteps,)\n    return betas\n\n\ndef get_named_beta_schedule(schedule_name, num_diffusion_timesteps):\n    \"\"\"\n    Get a pre-defined beta schedule for the given name.\n    The beta schedule library consists of beta schedules which remain similar\n    in the limit of num_diffusion_timesteps.\n    Beta schedules may be added, but should not be removed or changed once\n    they are committed to maintain backwards compatibility.\n    \"\"\"\n    if schedule_name == \"linear\":\n        # Linear schedule from Ho et al, extended to work for any number of\n        # diffusion steps.\n        scale = 1000 / num_diffusion_timesteps\n        return get_beta_schedule(\n            \"linear\",\n            beta_start=scale * 0.0001,\n            beta_end=scale * 0.02,\n            num_diffusion_timesteps=num_diffusion_timesteps,\n        )\n    elif schedule_name == \"squaredcos_cap_v2\":\n        return betas_for_alpha_bar(\n            num_diffusion_timesteps,\n            lambda t: math.cos((t + 0.008) / 1.008 * math.pi / 2) ** 2,\n        )\n    else:\n        raise NotImplementedError(f\"unknown beta schedule: {schedule_name}\")\n\n\ndef betas_for_alpha_bar(num_diffusion_timesteps, alpha_bar, max_beta=0.999):\n    \"\"\"\n    Create a beta schedule that discretizes the given alpha_t_bar function,\n    which defines the cumulative product of (1-beta) over time from t = [0,1].\n    :param num_diffusion_timesteps: the number of betas to produce.\n    :param alpha_bar: a lambda that takes an argument t from 0 to 1 and\n                      produces the cumulative product of (1-beta) up to that\n                      part of the diffusion process.\n    :param max_beta: the maximum beta to use; use values lower than 1 to\n                     prevent singularities.\n    \"\"\"\n    betas = []\n    for i in range(num_diffusion_timesteps):\n        t1 = i / num_diffusion_timesteps\n        t2 = (i + 1) / num_diffusion_timesteps\n        betas.append(min(1 - alpha_bar(t2) / alpha_bar(t1), max_beta))\n    return np.array(betas)\n\n\nclass GaussianDiffusion:\n    \"\"\"\n    Utilities for training and sampling diffusion models.\n    Original ported from this codebase:\n    https://github.com/hojonathanho/diffusion/blob/1e0dceb3b3495bbe19116a5e1b3596cd0706c543/diffusion_tf/diffusion_utils_2.py#L42\n    :param betas: a 1-D numpy array of betas for each diffusion timestep,\n                  starting at T and going to 1.\n    \"\"\"\n\n    def __init__(\n        self,\n        *,\n        betas,\n        model_mean_type,\n        model_var_type,\n        loss_type\n    ):\n\n        self.model_mean_type = model_mean_type\n        self.model_var_type = model_var_type\n        self.loss_type = loss_type\n\n        # Use float64 for accuracy.\n        betas = np.array(betas, dtype=np.float64)\n        self.betas = betas\n        assert len(betas.shape) == 1, \"betas must be 1-D\"\n        assert (betas > 0).all() and (betas <= 1).all()\n\n        self.num_timesteps = int(betas.shape[0])\n\n        alphas = 1.0 - betas\n        self.alphas_cumprod = np.cumprod(alphas, axis=0)\n        self.alphas_cumprod_prev = np.append(1.0, self.alphas_cumprod[:-1])\n        self.alphas_cumprod_next = np.append(self.alphas_cumprod[1:], 0.0)\n        assert self.alphas_cumprod_prev.shape == (self.num_timesteps,)\n\n        # calculations for diffusion q(x_t | x_{t-1}) and others\n        self.sqrt_alphas_cumprod = np.sqrt(self.alphas_cumprod)\n        self.sqrt_one_minus_alphas_cumprod = np.sqrt(1.0 - self.alphas_cumprod)\n        self.log_one_minus_alphas_cumprod = np.log(1.0 - self.alphas_cumprod)\n        self.sqrt_recip_alphas_cumprod = np.sqrt(1.0 / self.alphas_cumprod)\n        self.sqrt_recipm1_alphas_cumprod = np.sqrt(1.0 / self.alphas_cumprod - 1)\n\n        # calculations for posterior q(x_{t-1} | x_t, x_0)\n        self.posterior_variance = (\n            betas * (1.0 - self.alphas_cumprod_prev) / (1.0 - self.alphas_cumprod)\n        )\n        # below: log calculation clipped because the posterior variance is 0 at the beginning of the diffusion chain\n        self.posterior_log_variance_clipped = np.log(\n            np.append(self.posterior_variance[1], self.posterior_variance[1:])\n        ) if len(self.posterior_variance) > 1 else np.array([])\n\n        self.posterior_mean_coef1 = (\n            betas * np.sqrt(self.alphas_cumprod_prev) / (1.0 - self.alphas_cumprod)\n        )\n        self.posterior_mean_coef2 = (\n            (1.0 - self.alphas_cumprod_prev) * np.sqrt(alphas) / (1.0 - self.alphas_cumprod)\n        )\n\n    def q_mean_variance(self, x_start, t):\n        \"\"\"\n        Get the distribution q(x_t | x_0).\n        :param x_start: the [N x C x ...] tensor of noiseless inputs.\n        :param t: the number of diffusion steps (minus 1). Here, 0 means one step.\n        :return: A tuple (mean, variance, log_variance), all of x_start's shape.\n        \"\"\"\n        mean = _extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start\n        variance = _extract_into_tensor(1.0 - self.alphas_cumprod, t, x_start.shape)\n        log_variance = _extract_into_tensor(self.log_one_minus_alphas_cumprod, t, x_start.shape)\n        return mean, variance, log_variance\n\n    def q_sample(self, x_start, t, noise=None):\n        \"\"\"\n        Diffuse the data for a given number of diffusion steps.\n        In other words, sample from q(x_t | x_0).\n        :param x_start: the initial data batch.\n        :param t: the number of diffusion steps (minus 1). Here, 0 means one step.\n        :param noise: if specified, the split-out normal noise.\n        :return: A noisy version of x_start.\n        \"\"\"\n        if noise is None:\n            noise = th.randn_like(x_start)\n        assert noise.shape == x_start.shape\n        return (\n            _extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start\n            + _extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_start.shape) * noise\n        )\n\n    def q_posterior_mean_variance(self, x_start, x_t, t):\n        \"\"\"\n        Compute the mean and variance of the diffusion posterior:\n            q(x_{t-1} | x_t, x_0)\n        \"\"\"\n        assert x_start.shape == x_t.shape\n        posterior_mean = (\n            _extract_into_tensor(self.posterior_mean_coef1, t, x_t.shape) * x_start\n            + _extract_into_tensor(self.posterior_mean_coef2, t, x_t.shape) * x_t\n        )\n        posterior_variance = _extract_into_tensor(self.posterior_variance, t, x_t.shape)\n        posterior_log_variance_clipped = _extract_into_tensor(\n            self.posterior_log_variance_clipped, t, x_t.shape\n        )\n        assert (\n            posterior_mean.shape[0]\n            == posterior_variance.shape[0]\n            == posterior_log_variance_clipped.shape[0]\n            == x_start.shape[0]\n        )\n        return posterior_mean, posterior_variance, posterior_log_variance_clipped\n\n    def p_mean_variance(self, model, x, t, clip_denoised=True, denoised_fn=None, model_kwargs=None):\n        \"\"\"\n        Apply the model to get p(x_{t-1} | x_t), as well as a prediction of\n        the initial x, x_0.\n        :param model: the model, which takes a signal and a batch of timesteps\n                      as input.\n        :param x: the [N x C x ...] tensor at time t.\n        :param t: a 1-D Tensor of timesteps.\n        :param clip_denoised: if True, clip the denoised signal into [-1, 1].\n        :param denoised_fn: if not None, a function which applies to the\n            x_start prediction before it is used to sample. Applies before\n            clip_denoised.\n        :param model_kwargs: if not None, a dict of extra keyword arguments to\n            pass to the model. This can be used for conditioning.\n        :return: a dict with the following keys:\n                 - 'mean': the model mean output.\n                 - 'variance': the model variance output.\n                 - 'log_variance': the log of 'variance'.\n                 - 'pred_xstart': the prediction for x_0.\n        \"\"\"\n        if model_kwargs is None:\n            model_kwargs = {}\n\n        B, C = x.shape[:2]\n        assert t.shape == (B,)\n        model_output = model(x, t, **model_kwargs)\n        if isinstance(model_output, tuple):\n            model_output, extra = model_output\n        else:\n            extra = None\n\n        if self.model_var_type in [ModelVarType.LEARNED, ModelVarType.LEARNED_RANGE]:\n            assert model_output.shape == (B, C * 2, *x.shape[2:])\n            model_output, model_var_values = th.split(model_output, C, dim=1)\n            min_log = _extract_into_tensor(self.posterior_log_variance_clipped, t, x.shape)\n            max_log = _extract_into_tensor(np.log(self.betas), t, x.shape)\n            # The model_var_values is [-1, 1] for [min_var, max_var].\n            frac = (model_var_values + 1) / 2\n            model_log_variance = frac * max_log + (1 - frac) * min_log\n            model_variance = th.exp(model_log_variance)\n        else:\n            model_variance, model_log_variance = {\n                # for fixedlarge, we set the initial (log-)variance like so\n                # to get a better decoder log likelihood.\n                ModelVarType.FIXED_LARGE: (\n                    np.append(self.posterior_variance[1], self.betas[1:]),\n                    np.log(np.append(self.posterior_variance[1], self.betas[1:])),\n                ),\n                ModelVarType.FIXED_SMALL: (\n                    self.posterior_variance,\n                    self.posterior_log_variance_clipped,\n                ),\n            }[self.model_var_type]\n            model_variance = _extract_into_tensor(model_variance, t, x.shape)\n            model_log_variance = _extract_into_tensor(model_log_variance, t, x.shape)\n\n        def process_xstart(x):\n            if denoised_fn is not None:\n                x = denoised_fn(x)\n            if clip_denoised:\n                return x.clamp(-1, 1)\n            return x\n\n        if self.model_mean_type == ModelMeanType.START_X:\n            pred_xstart = process_xstart(model_output)\n        else:\n            pred_xstart = process_xstart(\n                self._predict_xstart_from_eps(x_t=x, t=t, eps=model_output)\n            )\n        model_mean, _, _ = self.q_posterior_mean_variance(x_start=pred_xstart, x_t=x, t=t)\n\n        assert model_mean.shape == model_log_variance.shape == pred_xstart.shape == x.shape\n        return {\n            \"mean\": model_mean,\n            \"variance\": model_variance,\n            \"log_variance\": model_log_variance,\n            \"pred_xstart\": pred_xstart,\n            \"extra\": extra,\n        }\n\n    def _predict_xstart_from_eps(self, x_t, t, eps):\n        assert x_t.shape == eps.shape\n        return (\n            _extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t\n            - _extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape) * eps\n        )\n\n    def _predict_eps_from_xstart(self, x_t, t, pred_xstart):\n        return (\n            _extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t - pred_xstart\n        ) / _extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape)\n\n    def condition_mean(self, cond_fn, p_mean_var, x, t, model_kwargs=None):\n        \"\"\"\n        Compute the mean for the previous step, given a function cond_fn that\n        computes the gradient of a conditional log probability with respect to\n        x. In particular, cond_fn computes grad(log(p(y|x))), and we want to\n        condition on y.\n        This uses the conditioning strategy from Sohl-Dickstein et al. (2015).\n        \"\"\"\n        gradient = cond_fn(x, t, **model_kwargs)\n        new_mean = p_mean_var[\"mean\"].float() + p_mean_var[\"variance\"] * gradient.float()\n        return new_mean\n\n    def condition_score(self, cond_fn, p_mean_var, x, t, model_kwargs=None):\n        \"\"\"\n        Compute what the p_mean_variance output would have been, should the\n        model's score function be conditioned by cond_fn.\n        See condition_mean() for details on cond_fn.\n        Unlike condition_mean(), this instead uses the conditioning strategy\n        from Song et al (2020).\n        \"\"\"\n        alpha_bar = _extract_into_tensor(self.alphas_cumprod, t, x.shape)\n\n        eps = self._predict_eps_from_xstart(x, t, p_mean_var[\"pred_xstart\"])\n        eps = eps - (1 - alpha_bar).sqrt() * cond_fn(x, t, **model_kwargs)\n\n        out = p_mean_var.copy()\n        out[\"pred_xstart\"] = self._predict_xstart_from_eps(x, t, eps)\n        out[\"mean\"], _, _ = self.q_posterior_mean_variance(x_start=out[\"pred_xstart\"], x_t=x, t=t)\n        return out\n\n    def p_sample(\n        self,\n        model,\n        x,\n        t,\n        clip_denoised=True,\n        denoised_fn=None,\n        cond_fn=None,\n        model_kwargs=None,\n    ):\n        \"\"\"\n        Sample x_{t-1} from the model at the given timestep.\n        :param model: the model to sample from.\n        :param x: the current tensor at x_{t-1}.\n        :param t: the value of t, starting at 0 for the first diffusion step.\n        :param clip_denoised: if True, clip the x_start prediction to [-1, 1].\n        :param denoised_fn: if not None, a function which applies to the\n            x_start prediction before it is used to sample.\n        :param cond_fn: if not None, this is a gradient function that acts\n                        similarly to the model.\n        :param model_kwargs: if not None, a dict of extra keyword arguments to\n            pass to the model. This can be used for conditioning.\n        :return: a dict containing the following keys:\n                 - 'sample': a random sample from the model.\n                 - 'pred_xstart': a prediction of x_0.\n        \"\"\"\n        out = self.p_mean_variance(\n            model,\n            x,\n            t,\n            clip_denoised=clip_denoised,\n            denoised_fn=denoised_fn,\n            model_kwargs=model_kwargs,\n        )\n        noise = th.randn_like(x)\n        nonzero_mask = (\n            (t != 0).float().view(-1, *([1] * (len(x.shape) - 1)))\n        )  # no noise when t == 0\n        if cond_fn is not None:\n            out[\"mean\"] = self.condition_mean(cond_fn, out, x, t, model_kwargs=model_kwargs)\n        sample = out[\"mean\"] + nonzero_mask * th.exp(0.5 * out[\"log_variance\"]) * noise\n        return {\"sample\": sample, \"pred_xstart\": out[\"pred_xstart\"]}\n\n    def p_sample_loop(\n        self,\n        model,\n        shape,\n        noise=None,\n        clip_denoised=True,\n        denoised_fn=None,\n        cond_fn=None,\n        model_kwargs=None,\n        device=None,\n        progress=False,\n    ):\n        \"\"\"\n        Generate samples from the model.\n        :param model: the model module.\n        :param shape: the shape of the samples, (N, C, H, W).\n        :param noise: if specified, the noise from the encoder to sample.\n                      Should be of the same shape as `shape`.\n        :param clip_denoised: if True, clip x_start predictions to [-1, 1].\n        :param denoised_fn: if not None, a function which applies to the\n            x_start prediction before it is used to sample.\n        :param cond_fn: if not None, this is a gradient function that acts\n                        similarly to the model.\n        :param model_kwargs: if not None, a dict of extra keyword arguments to\n            pass to the model. This can be used for conditioning.\n        :param device: if specified, the device to create the samples on.\n                       If not specified, use a model parameter's device.\n        :param progress: if True, show a tqdm progress bar.\n        :return: a non-differentiable batch of samples.\n        \"\"\"\n        final = None\n        for sample in self.p_sample_loop_progressive(\n            model,\n            shape,\n            noise=noise,\n            clip_denoised=clip_denoised,\n            denoised_fn=denoised_fn,\n            cond_fn=cond_fn,\n            model_kwargs=model_kwargs,\n            device=device,\n            progress=progress,\n        ):\n            final = sample\n        return final[\"sample\"]\n\n    def p_sample_loop_progressive(\n        self,\n        model,\n        shape,\n        noise=None,\n        clip_denoised=True,\n        denoised_fn=None,\n        cond_fn=None,\n        model_kwargs=None,\n        device=None,\n        progress=False,\n    ):\n        \"\"\"\n        Generate samples from the model and yield intermediate samples from\n        each timestep of diffusion.\n        Arguments are the same as p_sample_loop().\n        Returns a generator over dicts, where each dict is the return value of\n        p_sample().\n        \"\"\"\n        if device is None:\n            device = next(model.parameters()).device\n        assert isinstance(shape, (tuple, list))\n        if noise is not None:\n            img = noise\n        else:\n            img = th.randn(*shape, device=device)\n        indices = list(range(self.num_timesteps))[::-1]\n\n        if progress:\n            # Lazy import so that we don't depend on tqdm.\n            from tqdm.auto import tqdm\n\n            indices = tqdm(indices)\n\n        for i in indices:\n            t = th.tensor([i] * shape[0], device=device)\n            with th.no_grad():\n                out = self.p_sample(\n                    model,\n                    img,\n                    t,\n                    clip_denoised=clip_denoised,\n                    denoised_fn=denoised_fn,\n                    cond_fn=cond_fn,\n                    model_kwargs=model_kwargs,\n                )\n                yield out\n                img = out[\"sample\"]\n\n    def ddim_sample(\n        self,\n        model,\n        x,\n        t,\n        clip_denoised=True,\n        denoised_fn=None,\n        cond_fn=None,\n        model_kwargs=None,\n        eta=0.0,\n    ):\n        \"\"\"\n        Sample x_{t-1} from the model using DDIM.\n        Same usage as p_sample().\n        \"\"\"\n        out = self.p_mean_variance(\n            model,\n            x,\n            t,\n            clip_denoised=clip_denoised,\n            denoised_fn=denoised_fn,\n            model_kwargs=model_kwargs,\n        )\n        if cond_fn is not None:\n            out = self.condition_score(cond_fn, out, x, t, model_kwargs=model_kwargs)\n\n        # Usually our model outputs epsilon, but we re-derive it\n        # in case we used x_start or x_prev prediction.\n        eps = self._predict_eps_from_xstart(x, t, out[\"pred_xstart\"])\n\n        alpha_bar = _extract_into_tensor(self.alphas_cumprod, t, x.shape)\n        alpha_bar_prev = _extract_into_tensor(self.alphas_cumprod_prev, t, x.shape)\n        sigma = (\n            eta\n            * th.sqrt((1 - alpha_bar_prev) / (1 - alpha_bar))\n            * th.sqrt(1 - alpha_bar / alpha_bar_prev)\n        )\n        # Equation 12.\n        noise = th.randn_like(x)\n        mean_pred = (\n            out[\"pred_xstart\"] * th.sqrt(alpha_bar_prev)\n            + th.sqrt(1 - alpha_bar_prev - sigma ** 2) * eps\n        )\n        nonzero_mask = (\n            (t != 0).float().view(-1, *([1] * (len(x.shape) - 1)))\n        )  # no noise when t == 0\n        sample = mean_pred + nonzero_mask * sigma * noise\n        return {\"sample\": sample, \"pred_xstart\": out[\"pred_xstart\"]}\n\n    def ddim_reverse_sample(\n        self,\n        model,\n        x,\n        t,\n        clip_denoised=True,\n        denoised_fn=None,\n        cond_fn=None,\n        model_kwargs=None,\n        eta=0.0,\n    ):\n        \"\"\"\n        Sample x_{t+1} from the model using DDIM reverse ODE.\n        \"\"\"\n        assert eta == 0.0, \"Reverse ODE only for deterministic path\"\n        out = self.p_mean_variance(\n            model,\n            x,\n            t,\n            clip_denoised=clip_denoised,\n            denoised_fn=denoised_fn,\n            model_kwargs=model_kwargs,\n        )\n        if cond_fn is not None:\n            out = self.condition_score(cond_fn, out, x, t, model_kwargs=model_kwargs)\n        # Usually our model outputs epsilon, but we re-derive it\n        # in case we used x_start or x_prev prediction.\n        eps = (\n            _extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x.shape) * x\n            - out[\"pred_xstart\"]\n        ) / _extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x.shape)\n        alpha_bar_next = _extract_into_tensor(self.alphas_cumprod_next, t, x.shape)\n\n        # Equation 12. reversed\n        mean_pred = out[\"pred_xstart\"] * th.sqrt(alpha_bar_next) + th.sqrt(1 - alpha_bar_next) * eps\n\n        return {\"sample\": mean_pred, \"pred_xstart\": out[\"pred_xstart\"]}\n\n    def ddim_sample_loop(\n        self,\n        model,\n        shape,\n        noise=None,\n        clip_denoised=True,\n        denoised_fn=None,\n        cond_fn=None,\n        model_kwargs=None,\n        device=None,\n        progress=False,\n        eta=0.0,\n    ):\n        \"\"\"\n        Generate samples from the model using DDIM.\n        Same usage as p_sample_loop().\n        \"\"\"\n        final = None\n        for sample in self.ddim_sample_loop_progressive(\n            model,\n            shape,\n            noise=noise,\n            clip_denoised=clip_denoised,\n            denoised_fn=denoised_fn,\n            cond_fn=cond_fn,\n            model_kwargs=model_kwargs,\n            device=device,\n            progress=progress,\n            eta=eta,\n        ):\n            final = sample\n        return final[\"sample\"]\n\n    def ddim_sample_loop_progressive(\n        self,\n        model,\n        shape,\n        noise=None,\n        clip_denoised=True,\n        denoised_fn=None,\n        cond_fn=None,\n        model_kwargs=None,\n        device=None,\n        progress=False,\n        eta=0.0,\n    ):\n        \"\"\"\n        Use DDIM to sample from the model and yield intermediate samples from\n        each timestep of DDIM.\n        Same usage as p_sample_loop_progressive().\n        \"\"\"\n        if device is None:\n            device = next(model.parameters()).device\n        assert isinstance(shape, (tuple, list))\n        if noise is not None:\n            img = noise\n        else:\n            img = th.randn(*shape, device=device)\n        indices = list(range(self.num_timesteps))[::-1]\n\n        if progress:\n            # Lazy import so that we don't depend on tqdm.\n            from tqdm.auto import tqdm\n\n            indices = tqdm(indices)\n\n        for i in indices:\n            t = th.tensor([i] * shape[0], device=device)\n            with th.no_grad():\n                out = self.ddim_sample(\n                    model,\n                    img,\n                    t,\n                    clip_denoised=clip_denoised,\n                    denoised_fn=denoised_fn,\n                    cond_fn=cond_fn,\n                    model_kwargs=model_kwargs,\n                    eta=eta,\n                )\n                yield out\n                img = out[\"sample\"]\n\n    def _vb_terms_bpd(\n            self, model, x_start, x_t, t, clip_denoised=True, model_kwargs=None\n    ):\n        \"\"\"\n        Get a term for the variational lower-bound.\n        The resulting units are bits (rather than nats, as one might expect).\n        This allows for comparison to other papers.\n        :return: a dict with the following keys:\n                 - 'output': a shape [N] tensor of NLLs or KLs.\n                 - 'pred_xstart': the x_0 predictions.\n        \"\"\"\n        true_mean, _, true_log_variance_clipped = self.q_posterior_mean_variance(\n            x_start=x_start, x_t=x_t, t=t\n        )\n        out = self.p_mean_variance(\n            model, x_t, t, clip_denoised=clip_denoised, model_kwargs=model_kwargs\n        )\n        kl = normal_kl(\n            true_mean, true_log_variance_clipped, out[\"mean\"], out[\"log_variance\"]\n        )\n        kl = mean_flat(kl) / np.log(2.0)\n\n        decoder_nll = -discretized_gaussian_log_likelihood(\n            x_start, means=out[\"mean\"], log_scales=0.5 * out[\"log_variance\"]\n        )\n        assert decoder_nll.shape == x_start.shape\n        decoder_nll = mean_flat(decoder_nll) / np.log(2.0)\n\n        # At the first timestep return the decoder NLL,\n        # otherwise return KL(q(x_{t-1}|x_t,x_0) || p(x_{t-1}|x_t))\n        output = th.where((t == 0), decoder_nll, kl)\n        return {\"output\": output, \"pred_xstart\": out[\"pred_xstart\"]}\n\n    def training_losses(self, model, x_start, t, model_kwargs=None, noise=None):\n        \"\"\"\n        Compute training losses for a single timestep.\n        :param model: the model to evaluate loss on.\n        :param x_start: the [N x C x ...] tensor of inputs.\n        :param t: a batch of timestep indices.\n        :param model_kwargs: if not None, a dict of extra keyword arguments to\n            pass to the model. This can be used for conditioning.\n        :param noise: if specified, the specific Gaussian noise to try to remove.\n        :return: a dict with the key \"loss\" containing a tensor of shape [N].\n                 Some mean or variance settings may also have other keys.\n        \"\"\"\n        if model_kwargs is None:\n            model_kwargs = {}\n        if noise is None:\n            noise = th.randn_like(x_start)\n        x_t = self.q_sample(x_start, t, noise=noise)\n\n        terms = {}\n\n        if self.loss_type == LossType.KL or self.loss_type == LossType.RESCALED_KL:\n            terms[\"loss\"] = self._vb_terms_bpd(\n                model=model,\n                x_start=x_start,\n                x_t=x_t,\n                t=t,\n                clip_denoised=False,\n                model_kwargs=model_kwargs,\n            )[\"output\"]\n            if self.loss_type == LossType.RESCALED_KL:\n                terms[\"loss\"] *= self.num_timesteps\n        elif self.loss_type == LossType.MSE or self.loss_type == LossType.RESCALED_MSE:\n            model_output = model(x_t, t, **model_kwargs)\n\n            if self.model_var_type in [\n                ModelVarType.LEARNED,\n                ModelVarType.LEARNED_RANGE,\n            ]:\n                B, C = x_t.shape[:2]\n                assert model_output.shape == (B, C * 2, *x_t.shape[2:])\n                model_output, model_var_values = th.split(model_output, C, dim=1)\n                # Learn the variance using the variational bound, but don't let\n                # it affect our mean prediction.\n                frozen_out = th.cat([model_output.detach(), model_var_values], dim=1)\n                terms[\"vb\"] = self._vb_terms_bpd(\n                    model=lambda *args, r=frozen_out: r,\n                    x_start=x_start,\n                    x_t=x_t,\n                    t=t,\n                    clip_denoised=False,\n                )[\"output\"]\n                if self.loss_type == LossType.RESCALED_MSE:\n                    # Divide by 1000 for equivalence with initial implementation.\n                    # Without a factor of 1/1000, the VB term hurts the MSE term.\n                    terms[\"vb\"] *= self.num_timesteps / 1000.0\n\n            target = {\n                ModelMeanType.PREVIOUS_X: self.q_posterior_mean_variance(\n                    x_start=x_start, x_t=x_t, t=t\n                )[0],\n                ModelMeanType.START_X: x_start,\n                ModelMeanType.EPSILON: noise,\n            }[self.model_mean_type]\n            assert model_output.shape == target.shape == x_start.shape\n            terms[\"mse\"] = mean_flat((target - model_output) ** 2)\n            if \"vb\" in terms:\n                terms[\"loss\"] = terms[\"mse\"] + terms[\"vb\"]\n            else:\n                terms[\"loss\"] = terms[\"mse\"]\n        else:\n            raise NotImplementedError(self.loss_type)\n\n        return terms\n\n    def _prior_bpd(self, x_start):\n        \"\"\"\n        Get the prior KL term for the variational lower-bound, measured in\n        bits-per-dim.\n        This term can't be optimized, as it only depends on the encoder.\n        :param x_start: the [N x C x ...] tensor of inputs.\n        :return: a batch of [N] KL values (in bits), one per batch element.\n        \"\"\"\n        batch_size = x_start.shape[0]\n        t = th.tensor([self.num_timesteps - 1] * batch_size, device=x_start.device)\n        qt_mean, _, qt_log_variance = self.q_mean_variance(x_start, t)\n        kl_prior = normal_kl(\n            mean1=qt_mean, logvar1=qt_log_variance, mean2=0.0, logvar2=0.0\n        )\n        return mean_flat(kl_prior) / np.log(2.0)\n\n    def calc_bpd_loop(self, model, x_start, clip_denoised=True, model_kwargs=None):\n        \"\"\"\n        Compute the entire variational lower-bound, measured in bits-per-dim,\n        as well as other related quantities.\n        :param model: the model to evaluate loss on.\n        :param x_start: the [N x C x ...] tensor of inputs.\n        :param clip_denoised: if True, clip denoised samples.\n        :param model_kwargs: if not None, a dict of extra keyword arguments to\n            pass to the model. This can be used for conditioning.\n        :return: a dict containing the following keys:\n                 - total_bpd: the total variational lower-bound, per batch element.\n                 - prior_bpd: the prior term in the lower-bound.\n                 - vb: an [N x T] tensor of terms in the lower-bound.\n                 - xstart_mse: an [N x T] tensor of x_0 MSEs for each timestep.\n                 - mse: an [N x T] tensor of epsilon MSEs for each timestep.\n        \"\"\"\n        device = x_start.device\n        batch_size = x_start.shape[0]\n\n        vb = []\n        xstart_mse = []\n        mse = []\n        for t in list(range(self.num_timesteps))[::-1]:\n            t_batch = th.tensor([t] * batch_size, device=device)\n            noise = th.randn_like(x_start)\n            x_t = self.q_sample(x_start=x_start, t=t_batch, noise=noise)\n            # Calculate VLB term at the current timestep\n            with th.no_grad():\n                out = self._vb_terms_bpd(\n                    model,\n                    x_start=x_start,\n                    x_t=x_t,\n                    t=t_batch,\n                    clip_denoised=clip_denoised,\n                    model_kwargs=model_kwargs,\n                )\n            vb.append(out[\"output\"])\n            xstart_mse.append(mean_flat((out[\"pred_xstart\"] - x_start) ** 2))\n            eps = self._predict_eps_from_xstart(x_t, t_batch, out[\"pred_xstart\"])\n            mse.append(mean_flat((eps - noise) ** 2))\n\n        vb = th.stack(vb, dim=1)\n        xstart_mse = th.stack(xstart_mse, dim=1)\n        mse = th.stack(mse, dim=1)\n\n        prior_bpd = self._prior_bpd(x_start)\n        total_bpd = vb.sum(dim=1) + prior_bpd\n        return {\n            \"total_bpd\": total_bpd,\n            \"prior_bpd\": prior_bpd,\n            \"vb\": vb,\n            \"xstart_mse\": xstart_mse,\n            \"mse\": mse,\n        }\n\n\ndef _extract_into_tensor(arr, timesteps, broadcast_shape):\n    \"\"\"\n    Extract values from a 1-D numpy array for a batch of indices.\n    :param arr: the 1-D numpy array.\n    :param timesteps: a tensor of indices into the array to extract.\n    :param broadcast_shape: a larger shape of K dimensions with the batch\n                            dimension equal to the length of timesteps.\n    :return: a tensor of shape [batch_size, 1, ...] where the shape has K dims.\n    \"\"\"\n    res = th.from_numpy(arr).to(device=timesteps.device)[timesteps].float()\n    while len(res.shape) < len(broadcast_shape):\n        res = res[..., None]\n    return res + th.zeros(broadcast_shape, device=timesteps.device)\n"
  },
  {
    "path": "diffusion/respace.py",
    "content": "# Modified from OpenAI's diffusion repos\n#     GLIDE: https://github.com/openai/glide-text2im/blob/main/glide_text2im/gaussian_diffusion.py\n#     ADM:   https://github.com/openai/guided-diffusion/blob/main/guided_diffusion\n#     IDDPM: https://github.com/openai/improved-diffusion/blob/main/improved_diffusion/gaussian_diffusion.py\n\nimport numpy as np\nimport torch as th\n\nfrom .gaussian_diffusion import GaussianDiffusion\n\n\ndef space_timesteps(num_timesteps, section_counts):\n    \"\"\"\n    Create a list of timesteps to use from an original diffusion process,\n    given the number of timesteps we want to take from equally-sized portions\n    of the original process.\n    For example, if there's 300 timesteps and the section counts are [10,15,20]\n    then the first 100 timesteps are strided to be 10 timesteps, the second 100\n    are strided to be 15 timesteps, and the final 100 are strided to be 20.\n    If the stride is a string starting with \"ddim\", then the fixed striding\n    from the DDIM paper is used, and only one section is allowed.\n    :param num_timesteps: the number of diffusion steps in the original\n                          process to divide up.\n    :param section_counts: either a list of numbers, or a string containing\n                           comma-separated numbers, indicating the step count\n                           per section. As a special case, use \"ddimN\" where N\n                           is a number of steps to use the striding from the\n                           DDIM paper.\n    :return: a set of diffusion steps from the original process to use.\n    \"\"\"\n    if isinstance(section_counts, str):\n        if section_counts.startswith(\"ddim\"):\n            desired_count = int(section_counts[len(\"ddim\") :])\n            for i in range(1, num_timesteps):\n                if len(range(0, num_timesteps, i)) == desired_count:\n                    return set(range(0, num_timesteps, i))\n            raise ValueError(\n                f\"cannot create exactly {num_timesteps} steps with an integer stride\"\n            )\n        section_counts = [int(x) for x in section_counts.split(\",\")]\n    size_per = num_timesteps // len(section_counts)\n    extra = num_timesteps % len(section_counts)\n    start_idx = 0\n    all_steps = []\n    for i, section_count in enumerate(section_counts):\n        size = size_per + (1 if i < extra else 0)\n        if size < section_count:\n            raise ValueError(\n                f\"cannot divide section of {size} steps into {section_count}\"\n            )\n        if section_count <= 1:\n            frac_stride = 1\n        else:\n            frac_stride = (size - 1) / (section_count - 1)\n        cur_idx = 0.0\n        taken_steps = []\n        for _ in range(section_count):\n            taken_steps.append(start_idx + round(cur_idx))\n            cur_idx += frac_stride\n        all_steps += taken_steps\n        start_idx += size\n    return set(all_steps)\n\n\nclass SpacedDiffusion(GaussianDiffusion):\n    \"\"\"\n    A diffusion process which can skip steps in a base diffusion process.\n    :param use_timesteps: a collection (sequence or set) of timesteps from the\n                          original diffusion process to retain.\n    :param kwargs: the kwargs to create the base diffusion process.\n    \"\"\"\n\n    def __init__(self, use_timesteps, **kwargs):\n        self.use_timesteps = set(use_timesteps)\n        self.timestep_map = []\n        self.original_num_steps = len(kwargs[\"betas\"])\n\n        base_diffusion = GaussianDiffusion(**kwargs)  # pylint: disable=missing-kwoa\n        last_alpha_cumprod = 1.0\n        new_betas = []\n        for i, alpha_cumprod in enumerate(base_diffusion.alphas_cumprod):\n            if i in self.use_timesteps:\n                new_betas.append(1 - alpha_cumprod / last_alpha_cumprod)\n                last_alpha_cumprod = alpha_cumprod\n                self.timestep_map.append(i)\n        kwargs[\"betas\"] = np.array(new_betas)\n        super().__init__(**kwargs)\n\n    def p_mean_variance(\n        self, model, *args, **kwargs\n    ):  # pylint: disable=signature-differs\n        return super().p_mean_variance(self._wrap_model(model), *args, **kwargs)\n\n    def training_losses(\n        self, model, *args, **kwargs\n    ):  # pylint: disable=signature-differs\n        return super().training_losses(self._wrap_model(model), *args, **kwargs)\n\n    def condition_mean(self, cond_fn, *args, **kwargs):\n        return super().condition_mean(self._wrap_model(cond_fn), *args, **kwargs)\n\n    def condition_score(self, cond_fn, *args, **kwargs):\n        return super().condition_score(self._wrap_model(cond_fn), *args, **kwargs)\n\n    def _wrap_model(self, model):\n        if isinstance(model, _WrappedModel):\n            return model\n        return _WrappedModel(\n            model, self.timestep_map, self.original_num_steps\n        )\n\n    def _scale_timesteps(self, t):\n        # Scaling is done by the wrapped model.\n        return t\n\n\nclass _WrappedModel:\n    def __init__(self, model, timestep_map, original_num_steps):\n        self.model = model\n        self.timestep_map = timestep_map\n        # self.rescale_timesteps = rescale_timesteps\n        self.original_num_steps = original_num_steps\n\n    def __call__(self, x, ts, **kwargs):\n        map_tensor = th.tensor(self.timestep_map, device=ts.device, dtype=ts.dtype)\n        new_ts = map_tensor[ts]\n        # if self.rescale_timesteps:\n        #     new_ts = new_ts.float() * (1000.0 / self.original_num_steps)\n        return self.model(x, new_ts, **kwargs)\n"
  },
  {
    "path": "diffusion/timestep_sampler.py",
    "content": "# Modified from OpenAI's diffusion repos\n#     GLIDE: https://github.com/openai/glide-text2im/blob/main/glide_text2im/gaussian_diffusion.py\n#     ADM:   https://github.com/openai/guided-diffusion/blob/main/guided_diffusion\n#     IDDPM: https://github.com/openai/improved-diffusion/blob/main/improved_diffusion/gaussian_diffusion.py\n\nfrom abc import ABC, abstractmethod\n\nimport numpy as np\nimport torch as th\nimport torch.distributed as dist\n\n\ndef create_named_schedule_sampler(name, diffusion):\n    \"\"\"\n    Create a ScheduleSampler from a library of pre-defined samplers.\n    :param name: the name of the sampler.\n    :param diffusion: the diffusion object to sample for.\n    \"\"\"\n    if name == \"uniform\":\n        return UniformSampler(diffusion)\n    elif name == \"loss-second-moment\":\n        return LossSecondMomentResampler(diffusion)\n    else:\n        raise NotImplementedError(f\"unknown schedule sampler: {name}\")\n\n\nclass ScheduleSampler(ABC):\n    \"\"\"\n    A distribution over timesteps in the diffusion process, intended to reduce\n    variance of the objective.\n    By default, samplers perform unbiased importance sampling, in which the\n    objective's mean is unchanged.\n    However, subclasses may override sample() to change how the resampled\n    terms are reweighted, allowing for actual changes in the objective.\n    \"\"\"\n\n    @abstractmethod\n    def weights(self):\n        \"\"\"\n        Get a numpy array of weights, one per diffusion step.\n        The weights needn't be normalized, but must be positive.\n        \"\"\"\n\n    def sample(self, batch_size, device):\n        \"\"\"\n        Importance-sample timesteps for a batch.\n        :param batch_size: the number of timesteps.\n        :param device: the torch device to save to.\n        :return: a tuple (timesteps, weights):\n                 - timesteps: a tensor of timestep indices.\n                 - weights: a tensor of weights to scale the resulting losses.\n        \"\"\"\n        w = self.weights()\n        p = w / np.sum(w)\n        indices_np = np.random.choice(len(p), size=(batch_size,), p=p)\n        indices = th.from_numpy(indices_np).long().to(device)\n        weights_np = 1 / (len(p) * p[indices_np])\n        weights = th.from_numpy(weights_np).float().to(device)\n        return indices, weights\n\n\nclass UniformSampler(ScheduleSampler):\n    def __init__(self, diffusion):\n        self.diffusion = diffusion\n        self._weights = np.ones([diffusion.num_timesteps])\n\n    def weights(self):\n        return self._weights\n\n\nclass LossAwareSampler(ScheduleSampler):\n    def update_with_local_losses(self, local_ts, local_losses):\n        \"\"\"\n        Update the reweighting using losses from a model.\n        Call this method from each rank with a batch of timesteps and the\n        corresponding losses for each of those timesteps.\n        This method will perform synchronization to make sure all of the ranks\n        maintain the exact same reweighting.\n        :param local_ts: an integer Tensor of timesteps.\n        :param local_losses: a 1D Tensor of losses.\n        \"\"\"\n        batch_sizes = [\n            th.tensor([0], dtype=th.int32, device=local_ts.device)\n            for _ in range(dist.get_world_size())\n        ]\n        dist.all_gather(\n            batch_sizes,\n            th.tensor([len(local_ts)], dtype=th.int32, device=local_ts.device),\n        )\n\n        # Pad all_gather batches to be the maximum batch size.\n        batch_sizes = [x.item() for x in batch_sizes]\n        max_bs = max(batch_sizes)\n\n        timestep_batches = [th.zeros(max_bs).to(local_ts) for bs in batch_sizes]\n        loss_batches = [th.zeros(max_bs).to(local_losses) for bs in batch_sizes]\n        dist.all_gather(timestep_batches, local_ts)\n        dist.all_gather(loss_batches, local_losses)\n        timesteps = [\n            x.item() for y, bs in zip(timestep_batches, batch_sizes) for x in y[:bs]\n        ]\n        losses = [x.item() for y, bs in zip(loss_batches, batch_sizes) for x in y[:bs]]\n        self.update_with_all_losses(timesteps, losses)\n\n    @abstractmethod\n    def update_with_all_losses(self, ts, losses):\n        \"\"\"\n        Update the reweighting using losses from a model.\n        Sub-classes should override this method to update the reweighting\n        using losses from the model.\n        This method directly updates the reweighting without synchronizing\n        between workers. It is called by update_with_local_losses from all\n        ranks with identical arguments. Thus, it should have deterministic\n        behavior to maintain state across workers.\n        :param ts: a list of int timesteps.\n        :param losses: a list of float losses, one per timestep.\n        \"\"\"\n\n\nclass LossSecondMomentResampler(LossAwareSampler):\n    def __init__(self, diffusion, history_per_term=10, uniform_prob=0.001):\n        self.diffusion = diffusion\n        self.history_per_term = history_per_term\n        self.uniform_prob = uniform_prob\n        self._loss_history = np.zeros(\n            [diffusion.num_timesteps, history_per_term], dtype=np.float64\n        )\n        self._loss_counts = np.zeros([diffusion.num_timesteps], dtype=np.int)\n\n    def weights(self):\n        if not self._warmed_up():\n            return np.ones([self.diffusion.num_timesteps], dtype=np.float64)\n        weights = np.sqrt(np.mean(self._loss_history ** 2, axis=-1))\n        weights /= np.sum(weights)\n        weights *= 1 - self.uniform_prob\n        weights += self.uniform_prob / len(weights)\n        return weights\n\n    def update_with_all_losses(self, ts, losses):\n        for t, loss in zip(ts, losses):\n            if self._loss_counts[t] == self.history_per_term:\n                # Shift out the oldest loss term.\n                self._loss_history[t, :-1] = self._loss_history[t, 1:]\n                self._loss_history[t, -1] = loss\n            else:\n                self._loss_history[t, self._loss_counts[t]] = loss\n                self._loss_counts[t] += 1\n\n    def _warmed_up(self):\n        return (self._loss_counts == self.history_per_term).all()\n"
  },
  {
    "path": "download.py",
    "content": "# Copyright (c) Meta Platforms, Inc. and affiliates.\n# All rights reserved.\n\n# This source code is licensed under the license found in the\n# LICENSE file in the root directory of this source tree.\n\n\"\"\"\nFunctions for downloading pre-trained DiT models\n\"\"\"\nfrom torchvision.datasets.utils import download_url\nimport torch\nimport os\n\n\npretrained_models = {'DiT-XL-2-512x512.pt', 'DiT-XL-2-256x256.pt'}\n\n\ndef find_model(model_name):\n    \"\"\"\n    Finds a pre-trained DiT model, downloading it if necessary. Alternatively, loads a model from a local path.\n    \"\"\"\n    if model_name in pretrained_models:  # Find/download our pre-trained DiT checkpoints\n        return download_model(model_name)\n    else:  # Load a custom DiT checkpoint:\n        assert os.path.isfile(model_name), f'Could not find DiT checkpoint at {model_name}'\n        checkpoint = torch.load(model_name, map_location=lambda storage, loc: storage)\n        if \"ema\" in checkpoint:  # supports checkpoints from train.py\n            checkpoint = checkpoint[\"ema\"]\n        return checkpoint\n\n\ndef download_model(model_name):\n    \"\"\"\n    Downloads a pre-trained DiT model from the web.\n    \"\"\"\n    assert model_name in pretrained_models\n    local_path = f'pretrained_models/{model_name}'\n    if not os.path.isfile(local_path):\n        os.makedirs('pretrained_models', exist_ok=True)\n        web_path = f'https://dl.fbaipublicfiles.com/DiT/models/{model_name}'\n        download_url(web_path, 'pretrained_models')\n    model = torch.load(local_path, map_location=lambda storage, loc: storage)\n    return model\n\n\nif __name__ == \"__main__\":\n    # Download all DiT checkpoints\n    for model in pretrained_models:\n        download_model(model)\n    print('Done.')\n"
  },
  {
    "path": "environment.yml",
    "content": "name: DiT\nchannels:\n  - pytorch\n  - nvidia\ndependencies:\n  - python >= 3.8\n  - pytorch >= 1.13\n  - torchvision\n  - pytorch-cuda=11.7\n  - pip:\n    - timm\n    - diffusers\n    - accelerate\n"
  },
  {
    "path": "models.py",
    "content": "# Copyright (c) Meta Platforms, Inc. and affiliates.\n# All rights reserved.\n\n# This source code is licensed under the license found in the\n# LICENSE file in the root directory of this source tree.\n# --------------------------------------------------------\n# References:\n# GLIDE: https://github.com/openai/glide-text2im\n# MAE: https://github.com/facebookresearch/mae/blob/main/models_mae.py\n# --------------------------------------------------------\n\nimport torch\nimport torch.nn as nn\nimport numpy as np\nimport math\nfrom timm.models.vision_transformer import PatchEmbed, Attention, Mlp\n\n\ndef modulate(x, shift, scale):\n    return x * (1 + scale.unsqueeze(1)) + shift.unsqueeze(1)\n\n\n#################################################################################\n#               Embedding Layers for Timesteps and Class Labels                 #\n#################################################################################\n\nclass TimestepEmbedder(nn.Module):\n    \"\"\"\n    Embeds scalar timesteps into vector representations.\n    \"\"\"\n    def __init__(self, hidden_size, frequency_embedding_size=256):\n        super().__init__()\n        self.mlp = nn.Sequential(\n            nn.Linear(frequency_embedding_size, hidden_size, bias=True),\n            nn.SiLU(),\n            nn.Linear(hidden_size, hidden_size, bias=True),\n        )\n        self.frequency_embedding_size = frequency_embedding_size\n\n    @staticmethod\n    def timestep_embedding(t, dim, max_period=10000):\n        \"\"\"\n        Create sinusoidal timestep embeddings.\n        :param t: a 1-D Tensor of N indices, one per batch element.\n                          These may be fractional.\n        :param dim: the dimension of the output.\n        :param max_period: controls the minimum frequency of the embeddings.\n        :return: an (N, D) Tensor of positional embeddings.\n        \"\"\"\n        # https://github.com/openai/glide-text2im/blob/main/glide_text2im/nn.py\n        half = dim // 2\n        freqs = torch.exp(\n            -math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half\n        ).to(device=t.device)\n        args = t[:, None].float() * freqs[None]\n        embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)\n        if dim % 2:\n            embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)\n        return embedding\n\n    def forward(self, t):\n        t_freq = self.timestep_embedding(t, self.frequency_embedding_size)\n        t_emb = self.mlp(t_freq)\n        return t_emb\n\n\nclass LabelEmbedder(nn.Module):\n    \"\"\"\n    Embeds class labels into vector representations. Also handles label dropout for classifier-free guidance.\n    \"\"\"\n    def __init__(self, num_classes, hidden_size, dropout_prob):\n        super().__init__()\n        use_cfg_embedding = dropout_prob > 0\n        self.embedding_table = nn.Embedding(num_classes + use_cfg_embedding, hidden_size)\n        self.num_classes = num_classes\n        self.dropout_prob = dropout_prob\n\n    def token_drop(self, labels, force_drop_ids=None):\n        \"\"\"\n        Drops labels to enable classifier-free guidance.\n        \"\"\"\n        if force_drop_ids is None:\n            drop_ids = torch.rand(labels.shape[0], device=labels.device) < self.dropout_prob\n        else:\n            drop_ids = force_drop_ids == 1\n        labels = torch.where(drop_ids, self.num_classes, labels)\n        return labels\n\n    def forward(self, labels, train, force_drop_ids=None):\n        use_dropout = self.dropout_prob > 0\n        if (train and use_dropout) or (force_drop_ids is not None):\n            labels = self.token_drop(labels, force_drop_ids)\n        embeddings = self.embedding_table(labels)\n        return embeddings\n\n\n#################################################################################\n#                                 Core DiT Model                                #\n#################################################################################\n\nclass DiTBlock(nn.Module):\n    \"\"\"\n    A DiT block with adaptive layer norm zero (adaLN-Zero) conditioning.\n    \"\"\"\n    def __init__(self, hidden_size, num_heads, mlp_ratio=4.0, **block_kwargs):\n        super().__init__()\n        self.norm1 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)\n        self.attn = Attention(hidden_size, num_heads=num_heads, qkv_bias=True, **block_kwargs)\n        self.norm2 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)\n        mlp_hidden_dim = int(hidden_size * mlp_ratio)\n        approx_gelu = lambda: nn.GELU(approximate=\"tanh\")\n        self.mlp = Mlp(in_features=hidden_size, hidden_features=mlp_hidden_dim, act_layer=approx_gelu, drop=0)\n        self.adaLN_modulation = nn.Sequential(\n            nn.SiLU(),\n            nn.Linear(hidden_size, 6 * hidden_size, bias=True)\n        )\n\n    def forward(self, x, c):\n        shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.adaLN_modulation(c).chunk(6, dim=1)\n        x = x + gate_msa.unsqueeze(1) * self.attn(modulate(self.norm1(x), shift_msa, scale_msa))\n        x = x + gate_mlp.unsqueeze(1) * self.mlp(modulate(self.norm2(x), shift_mlp, scale_mlp))\n        return x\n\n\nclass FinalLayer(nn.Module):\n    \"\"\"\n    The final layer of DiT.\n    \"\"\"\n    def __init__(self, hidden_size, patch_size, out_channels):\n        super().__init__()\n        self.norm_final = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)\n        self.linear = nn.Linear(hidden_size, patch_size * patch_size * out_channels, bias=True)\n        self.adaLN_modulation = nn.Sequential(\n            nn.SiLU(),\n            nn.Linear(hidden_size, 2 * hidden_size, bias=True)\n        )\n\n    def forward(self, x, c):\n        shift, scale = self.adaLN_modulation(c).chunk(2, dim=1)\n        x = modulate(self.norm_final(x), shift, scale)\n        x = self.linear(x)\n        return x\n\n\nclass DiT(nn.Module):\n    \"\"\"\n    Diffusion model with a Transformer backbone.\n    \"\"\"\n    def __init__(\n        self,\n        input_size=32,\n        patch_size=2,\n        in_channels=4,\n        hidden_size=1152,\n        depth=28,\n        num_heads=16,\n        mlp_ratio=4.0,\n        class_dropout_prob=0.1,\n        num_classes=1000,\n        learn_sigma=True,\n    ):\n        super().__init__()\n        self.learn_sigma = learn_sigma\n        self.in_channels = in_channels\n        self.out_channels = in_channels * 2 if learn_sigma else in_channels\n        self.patch_size = patch_size\n        self.num_heads = num_heads\n\n        self.x_embedder = PatchEmbed(input_size, patch_size, in_channels, hidden_size, bias=True)\n        self.t_embedder = TimestepEmbedder(hidden_size)\n        self.y_embedder = LabelEmbedder(num_classes, hidden_size, class_dropout_prob)\n        num_patches = self.x_embedder.num_patches\n        # Will use fixed sin-cos embedding:\n        self.pos_embed = nn.Parameter(torch.zeros(1, num_patches, hidden_size), requires_grad=False)\n\n        self.blocks = nn.ModuleList([\n            DiTBlock(hidden_size, num_heads, mlp_ratio=mlp_ratio) for _ in range(depth)\n        ])\n        self.final_layer = FinalLayer(hidden_size, patch_size, self.out_channels)\n        self.initialize_weights()\n\n    def initialize_weights(self):\n        # Initialize transformer layers:\n        def _basic_init(module):\n            if isinstance(module, nn.Linear):\n                torch.nn.init.xavier_uniform_(module.weight)\n                if module.bias is not None:\n                    nn.init.constant_(module.bias, 0)\n        self.apply(_basic_init)\n\n        # Initialize (and freeze) pos_embed by sin-cos embedding:\n        pos_embed = get_2d_sincos_pos_embed(self.pos_embed.shape[-1], int(self.x_embedder.num_patches ** 0.5))\n        self.pos_embed.data.copy_(torch.from_numpy(pos_embed).float().unsqueeze(0))\n\n        # Initialize patch_embed like nn.Linear (instead of nn.Conv2d):\n        w = self.x_embedder.proj.weight.data\n        nn.init.xavier_uniform_(w.view([w.shape[0], -1]))\n        nn.init.constant_(self.x_embedder.proj.bias, 0)\n\n        # Initialize label embedding table:\n        nn.init.normal_(self.y_embedder.embedding_table.weight, std=0.02)\n\n        # Initialize timestep embedding MLP:\n        nn.init.normal_(self.t_embedder.mlp[0].weight, std=0.02)\n        nn.init.normal_(self.t_embedder.mlp[2].weight, std=0.02)\n\n        # Zero-out adaLN modulation layers in DiT blocks:\n        for block in self.blocks:\n            nn.init.constant_(block.adaLN_modulation[-1].weight, 0)\n            nn.init.constant_(block.adaLN_modulation[-1].bias, 0)\n\n        # Zero-out output layers:\n        nn.init.constant_(self.final_layer.adaLN_modulation[-1].weight, 0)\n        nn.init.constant_(self.final_layer.adaLN_modulation[-1].bias, 0)\n        nn.init.constant_(self.final_layer.linear.weight, 0)\n        nn.init.constant_(self.final_layer.linear.bias, 0)\n\n    def unpatchify(self, x):\n        \"\"\"\n        x: (N, T, patch_size**2 * C)\n        imgs: (N, H, W, C)\n        \"\"\"\n        c = self.out_channels\n        p = self.x_embedder.patch_size[0]\n        h = w = int(x.shape[1] ** 0.5)\n        assert h * w == x.shape[1]\n\n        x = x.reshape(shape=(x.shape[0], h, w, p, p, c))\n        x = torch.einsum('nhwpqc->nchpwq', x)\n        imgs = x.reshape(shape=(x.shape[0], c, h * p, h * p))\n        return imgs\n\n    def forward(self, x, t, y):\n        \"\"\"\n        Forward pass of DiT.\n        x: (N, C, H, W) tensor of spatial inputs (images or latent representations of images)\n        t: (N,) tensor of diffusion timesteps\n        y: (N,) tensor of class labels\n        \"\"\"\n        x = self.x_embedder(x) + self.pos_embed  # (N, T, D), where T = H * W / patch_size ** 2\n        t = self.t_embedder(t)                   # (N, D)\n        y = self.y_embedder(y, self.training)    # (N, D)\n        c = t + y                                # (N, D)\n        for block in self.blocks:\n            x = block(x, c)                      # (N, T, D)\n        x = self.final_layer(x, c)                # (N, T, patch_size ** 2 * out_channels)\n        x = self.unpatchify(x)                   # (N, out_channels, H, W)\n        return x\n\n    def forward_with_cfg(self, x, t, y, cfg_scale):\n        \"\"\"\n        Forward pass of DiT, but also batches the unconditional forward pass for classifier-free guidance.\n        \"\"\"\n        # https://github.com/openai/glide-text2im/blob/main/notebooks/text2im.ipynb\n        half = x[: len(x) // 2]\n        combined = torch.cat([half, half], dim=0)\n        model_out = self.forward(combined, t, y)\n        # For exact reproducibility reasons, we apply classifier-free guidance on only\n        # three channels by default. The standard approach to cfg applies it to all channels.\n        # This can be done by uncommenting the following line and commenting-out the line following that.\n        # eps, rest = model_out[:, :self.in_channels], model_out[:, self.in_channels:]\n        eps, rest = model_out[:, :3], model_out[:, 3:]\n        cond_eps, uncond_eps = torch.split(eps, len(eps) // 2, dim=0)\n        half_eps = uncond_eps + cfg_scale * (cond_eps - uncond_eps)\n        eps = torch.cat([half_eps, half_eps], dim=0)\n        return torch.cat([eps, rest], dim=1)\n\n\n#################################################################################\n#                   Sine/Cosine Positional Embedding Functions                  #\n#################################################################################\n# https://github.com/facebookresearch/mae/blob/main/util/pos_embed.py\n\ndef get_2d_sincos_pos_embed(embed_dim, grid_size, cls_token=False, extra_tokens=0):\n    \"\"\"\n    grid_size: int of the grid height and width\n    return:\n    pos_embed: [grid_size*grid_size, embed_dim] or [1+grid_size*grid_size, embed_dim] (w/ or w/o cls_token)\n    \"\"\"\n    grid_h = np.arange(grid_size, dtype=np.float32)\n    grid_w = np.arange(grid_size, dtype=np.float32)\n    grid = np.meshgrid(grid_w, grid_h)  # here w goes first\n    grid = np.stack(grid, axis=0)\n\n    grid = grid.reshape([2, 1, grid_size, grid_size])\n    pos_embed = get_2d_sincos_pos_embed_from_grid(embed_dim, grid)\n    if cls_token and extra_tokens > 0:\n        pos_embed = np.concatenate([np.zeros([extra_tokens, embed_dim]), pos_embed], axis=0)\n    return pos_embed\n\n\ndef get_2d_sincos_pos_embed_from_grid(embed_dim, grid):\n    assert embed_dim % 2 == 0\n\n    # use half of dimensions to encode grid_h\n    emb_h = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[0])  # (H*W, D/2)\n    emb_w = get_1d_sincos_pos_embed_from_grid(embed_dim // 2, grid[1])  # (H*W, D/2)\n\n    emb = np.concatenate([emb_h, emb_w], axis=1) # (H*W, D)\n    return emb\n\n\ndef get_1d_sincos_pos_embed_from_grid(embed_dim, pos):\n    \"\"\"\n    embed_dim: output dimension for each position\n    pos: a list of positions to be encoded: size (M,)\n    out: (M, D)\n    \"\"\"\n    assert embed_dim % 2 == 0\n    omega = np.arange(embed_dim // 2, dtype=np.float64)\n    omega /= embed_dim / 2.\n    omega = 1. / 10000**omega  # (D/2,)\n\n    pos = pos.reshape(-1)  # (M,)\n    out = np.einsum('m,d->md', pos, omega)  # (M, D/2), outer product\n\n    emb_sin = np.sin(out) # (M, D/2)\n    emb_cos = np.cos(out) # (M, D/2)\n\n    emb = np.concatenate([emb_sin, emb_cos], axis=1)  # (M, D)\n    return emb\n\n\n#################################################################################\n#                                   DiT Configs                                  #\n#################################################################################\n\ndef DiT_XL_2(**kwargs):\n    return DiT(depth=28, hidden_size=1152, patch_size=2, num_heads=16, **kwargs)\n\ndef DiT_XL_4(**kwargs):\n    return DiT(depth=28, hidden_size=1152, patch_size=4, num_heads=16, **kwargs)\n\ndef DiT_XL_8(**kwargs):\n    return DiT(depth=28, hidden_size=1152, patch_size=8, num_heads=16, **kwargs)\n\ndef DiT_L_2(**kwargs):\n    return DiT(depth=24, hidden_size=1024, patch_size=2, num_heads=16, **kwargs)\n\ndef DiT_L_4(**kwargs):\n    return DiT(depth=24, hidden_size=1024, patch_size=4, num_heads=16, **kwargs)\n\ndef DiT_L_8(**kwargs):\n    return DiT(depth=24, hidden_size=1024, patch_size=8, num_heads=16, **kwargs)\n\ndef DiT_B_2(**kwargs):\n    return DiT(depth=12, hidden_size=768, patch_size=2, num_heads=12, **kwargs)\n\ndef DiT_B_4(**kwargs):\n    return DiT(depth=12, hidden_size=768, patch_size=4, num_heads=12, **kwargs)\n\ndef DiT_B_8(**kwargs):\n    return DiT(depth=12, hidden_size=768, patch_size=8, num_heads=12, **kwargs)\n\ndef DiT_S_2(**kwargs):\n    return DiT(depth=12, hidden_size=384, patch_size=2, num_heads=6, **kwargs)\n\ndef DiT_S_4(**kwargs):\n    return DiT(depth=12, hidden_size=384, patch_size=4, num_heads=6, **kwargs)\n\ndef DiT_S_8(**kwargs):\n    return DiT(depth=12, hidden_size=384, patch_size=8, num_heads=6, **kwargs)\n\n\nDiT_models = {\n    'DiT-XL/2': DiT_XL_2,  'DiT-XL/4': DiT_XL_4,  'DiT-XL/8': DiT_XL_8,\n    'DiT-L/2':  DiT_L_2,   'DiT-L/4':  DiT_L_4,   'DiT-L/8':  DiT_L_8,\n    'DiT-B/2':  DiT_B_2,   'DiT-B/4':  DiT_B_4,   'DiT-B/8':  DiT_B_8,\n    'DiT-S/2':  DiT_S_2,   'DiT-S/4':  DiT_S_4,   'DiT-S/8':  DiT_S_8,\n}\n"
  },
  {
    "path": "run_DiT.ipynb",
    "content": "{\n \"cells\": [\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {\n    \"id\": \"355UKMUQJxFd\"\n   },\n   \"source\": [\n    \"# Scalable Diffusion Models with Transformer (DiT)\\n\",\n    \"\\n\",\n    \"This notebook samples from pre-trained DiT models. DiTs are class-conditional latent diffusion models trained on ImageNet that use transformers in place of U-Nets as the DDPM backbone. DiT outperforms all prior diffusion models on the ImageNet benchmarks.\\n\",\n    \"\\n\",\n    \"[Project Page](https://www.wpeebles.com/DiT) | [HuggingFace Space](https://huggingface.co/spaces/wpeebles/DiT) | [Paper](http://arxiv.org/abs/2212.09748) | [GitHub](github.com/facebookresearch/DiT)\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {\n    \"id\": \"zJlgLkSaKn7u\"\n   },\n   \"source\": [\n    \"# 1. Setup\\n\",\n    \"\\n\",\n    \"We recommend using GPUs (Runtime > Change runtime type > Hardware accelerator > GPU). Run this cell to clone the DiT GitHub repo and setup PyTorch. You only have to run this once.\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"!git clone https://github.com/facebookresearch/DiT.git\\n\",\n    \"import DiT, os\\n\",\n    \"os.chdir('DiT')\\n\",\n    \"os.environ['PYTHONPATH'] = '/env/python:/content/DiT'\\n\",\n    \"!pip install diffusers timm --upgrade\\n\",\n    \"# DiT imports:\\n\",\n    \"import torch\\n\",\n    \"from torchvision.utils import save_image\\n\",\n    \"from diffusion import create_diffusion\\n\",\n    \"from diffusers.models import AutoencoderKL\\n\",\n    \"from download import find_model\\n\",\n    \"from models import DiT_XL_2\\n\",\n    \"from PIL import Image\\n\",\n    \"from IPython.display import display\\n\",\n    \"torch.set_grad_enabled(False)\\n\",\n    \"device = \\\"cuda\\\" if torch.cuda.is_available() else \\\"cpu\\\"\\n\",\n    \"if device == \\\"cpu\\\":\\n\",\n    \"    print(\\\"GPU not found. Using CPU instead.\\\")\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {\n    \"id\": \"AXpziRkoOvV9\"\n   },\n   \"source\": [\n    \"# Download DiT-XL/2 Models\\n\",\n    \"\\n\",\n    \"You can choose between a 512x512 model and a 256x256 model. You can swap-out the LDM VAE, too.\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {\n    \"id\": \"EWG-WNimO59K\"\n   },\n   \"outputs\": [],\n   \"source\": [\n    \"image_size = 256 #@param [256, 512]\\n\",\n    \"vae_model = \\\"stabilityai/sd-vae-ft-ema\\\" #@param [\\\"stabilityai/sd-vae-ft-mse\\\", \\\"stabilityai/sd-vae-ft-ema\\\"]\\n\",\n    \"latent_size = int(image_size) // 8\\n\",\n    \"# Load model:\\n\",\n    \"model = DiT_XL_2(input_size=latent_size).to(device)\\n\",\n    \"state_dict = find_model(f\\\"DiT-XL-2-{image_size}x{image_size}.pt\\\")\\n\",\n    \"model.load_state_dict(state_dict)\\n\",\n    \"model.eval() # important!\\n\",\n    \"vae = AutoencoderKL.from_pretrained(vae_model).to(device)\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {\n    \"id\": \"5JTNyzNZKb9E\"\n   },\n   \"source\": [\n    \"# 2. Sample from Pre-trained DiT Models\\n\",\n    \"\\n\",\n    \"You can customize several sampling options. For the full list of ImageNet classes, [check out this](https://gist.github.com/yrevar/942d3a0ac09ec9e5eb3a).\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {\n    \"id\": \"-Hw7B5h4Kk4p\"\n   },\n   \"outputs\": [],\n   \"source\": [\n    \"# Set user inputs:\\n\",\n    \"seed = 0 #@param {type:\\\"number\\\"}\\n\",\n    \"torch.manual_seed(seed)\\n\",\n    \"num_sampling_steps = 250 #@param {type:\\\"slider\\\", min:0, max:1000, step:1}\\n\",\n    \"cfg_scale = 4 #@param {type:\\\"slider\\\", min:1, max:10, step:0.1}\\n\",\n    \"class_labels = 207, 360, 387, 974, 88, 979, 417, 279 #@param {type:\\\"raw\\\"}\\n\",\n    \"samples_per_row = 4 #@param {type:\\\"number\\\"}\\n\",\n    \"\\n\",\n    \"# Create diffusion object:\\n\",\n    \"diffusion = create_diffusion(str(num_sampling_steps))\\n\",\n    \"\\n\",\n    \"# Create sampling noise:\\n\",\n    \"n = len(class_labels)\\n\",\n    \"z = torch.randn(n, 4, latent_size, latent_size, device=device)\\n\",\n    \"y = torch.tensor(class_labels, device=device)\\n\",\n    \"\\n\",\n    \"# Setup classifier-free guidance:\\n\",\n    \"z = torch.cat([z, z], 0)\\n\",\n    \"y_null = torch.tensor([1000] * n, device=device)\\n\",\n    \"y = torch.cat([y, y_null], 0)\\n\",\n    \"model_kwargs = dict(y=y, cfg_scale=cfg_scale)\\n\",\n    \"\\n\",\n    \"# Sample images:\\n\",\n    \"samples = diffusion.p_sample_loop(\\n\",\n    \"    model.forward_with_cfg, z.shape, z, clip_denoised=False, \\n\",\n    \"    model_kwargs=model_kwargs, progress=True, device=device\\n\",\n    \")\\n\",\n    \"samples, _ = samples.chunk(2, dim=0)  # Remove null class samples\\n\",\n    \"samples = vae.decode(samples / 0.18215).sample\\n\",\n    \"\\n\",\n    \"# Save and display images:\\n\",\n    \"save_image(samples, \\\"sample.png\\\", nrow=int(samples_per_row), \\n\",\n    \"           normalize=True, value_range=(-1, 1))\\n\",\n    \"samples = Image.open(\\\"sample.png\\\")\\n\",\n    \"display(samples)\"\n   ]\n  }\n ],\n \"metadata\": {\n  \"colab\": {\n   \"provenance\": []\n  },\n  \"kernelspec\": {\n   \"display_name\": \"Python 3.8.10 64-bit\",\n   \"language\": \"python\",\n   \"name\": \"python3\"\n  },\n  \"language_info\": {\n   \"name\": \"python\",\n   \"version\": \"3.8.10\"\n  },\n  \"vscode\": {\n   \"interpreter\": {\n    \"hash\": \"31f2aee4e71d21fbe5cf8b01ff0e069b9275f58929596ceb00d14d90e3e16cd6\"\n   }\n  }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 0\n}\n"
  },
  {
    "path": "sample.py",
    "content": "# Copyright (c) Meta Platforms, Inc. and affiliates.\n# All rights reserved.\n\n# This source code is licensed under the license found in the\n# LICENSE file in the root directory of this source tree.\n\n\"\"\"\nSample new images from a pre-trained DiT.\n\"\"\"\nimport torch\ntorch.backends.cuda.matmul.allow_tf32 = True\ntorch.backends.cudnn.allow_tf32 = True\nfrom torchvision.utils import save_image\nfrom diffusion import create_diffusion\nfrom diffusers.models import AutoencoderKL\nfrom download import find_model\nfrom models import DiT_models\nimport argparse\n\n\ndef main(args):\n    # Setup PyTorch:\n    torch.manual_seed(args.seed)\n    torch.set_grad_enabled(False)\n    device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n\n    if args.ckpt is None:\n        assert args.model == \"DiT-XL/2\", \"Only DiT-XL/2 models are available for auto-download.\"\n        assert args.image_size in [256, 512]\n        assert args.num_classes == 1000\n\n    # Load model:\n    latent_size = args.image_size // 8\n    model = DiT_models[args.model](\n        input_size=latent_size,\n        num_classes=args.num_classes\n    ).to(device)\n    # Auto-download a pre-trained model or load a custom DiT checkpoint from train.py:\n    ckpt_path = args.ckpt or f\"DiT-XL-2-{args.image_size}x{args.image_size}.pt\"\n    state_dict = find_model(ckpt_path)\n    model.load_state_dict(state_dict)\n    model.eval()  # important!\n    diffusion = create_diffusion(str(args.num_sampling_steps))\n    vae = AutoencoderKL.from_pretrained(f\"stabilityai/sd-vae-ft-{args.vae}\").to(device)\n\n    # Labels to condition the model with (feel free to change):\n    class_labels = [207, 360, 387, 974, 88, 979, 417, 279]\n\n    # Create sampling noise:\n    n = len(class_labels)\n    z = torch.randn(n, 4, latent_size, latent_size, device=device)\n    y = torch.tensor(class_labels, device=device)\n\n    # Setup classifier-free guidance:\n    z = torch.cat([z, z], 0)\n    y_null = torch.tensor([1000] * n, device=device)\n    y = torch.cat([y, y_null], 0)\n    model_kwargs = dict(y=y, cfg_scale=args.cfg_scale)\n\n    # Sample images:\n    samples = diffusion.p_sample_loop(\n        model.forward_with_cfg, z.shape, z, clip_denoised=False, model_kwargs=model_kwargs, progress=True, device=device\n    )\n    samples, _ = samples.chunk(2, dim=0)  # Remove null class samples\n    samples = vae.decode(samples / 0.18215).sample\n\n    # Save and display images:\n    save_image(samples, \"sample.png\", nrow=4, normalize=True, value_range=(-1, 1))\n\n\nif __name__ == \"__main__\":\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\"--model\", type=str, choices=list(DiT_models.keys()), default=\"DiT-XL/2\")\n    parser.add_argument(\"--vae\", type=str, choices=[\"ema\", \"mse\"], default=\"mse\")\n    parser.add_argument(\"--image-size\", type=int, choices=[256, 512], default=256)\n    parser.add_argument(\"--num-classes\", type=int, default=1000)\n    parser.add_argument(\"--cfg-scale\", type=float, default=4.0)\n    parser.add_argument(\"--num-sampling-steps\", type=int, default=250)\n    parser.add_argument(\"--seed\", type=int, default=0)\n    parser.add_argument(\"--ckpt\", type=str, default=None,\n                        help=\"Optional path to a DiT checkpoint (default: auto-download a pre-trained DiT-XL/2 model).\")\n    args = parser.parse_args()\n    main(args)\n"
  },
  {
    "path": "sample_ddp.py",
    "content": "# Copyright (c) Meta Platforms, Inc. and affiliates.\n# All rights reserved.\n\n# This source code is licensed under the license found in the\n# LICENSE file in the root directory of this source tree.\n\n\"\"\"\nSamples a large number of images from a pre-trained DiT model using DDP.\nSubsequently saves a .npz file that can be used to compute FID and other\nevaluation metrics via the ADM repo: https://github.com/openai/guided-diffusion/tree/main/evaluations\n\nFor a simple single-GPU/CPU sampling script, see sample.py.\n\"\"\"\nimport torch\nimport torch.distributed as dist\nfrom models import DiT_models\nfrom download import find_model\nfrom diffusion import create_diffusion\nfrom diffusers.models import AutoencoderKL\nfrom tqdm import tqdm\nimport os\nfrom PIL import Image\nimport numpy as np\nimport math\nimport argparse\n\n\ndef create_npz_from_sample_folder(sample_dir, num=50_000):\n    \"\"\"\n    Builds a single .npz file from a folder of .png samples.\n    \"\"\"\n    samples = []\n    for i in tqdm(range(num), desc=\"Building .npz file from samples\"):\n        sample_pil = Image.open(f\"{sample_dir}/{i:06d}.png\")\n        sample_np = np.asarray(sample_pil).astype(np.uint8)\n        samples.append(sample_np)\n    samples = np.stack(samples)\n    assert samples.shape == (num, samples.shape[1], samples.shape[2], 3)\n    npz_path = f\"{sample_dir}.npz\"\n    np.savez(npz_path, arr_0=samples)\n    print(f\"Saved .npz file to {npz_path} [shape={samples.shape}].\")\n    return npz_path\n\n\ndef main(args):\n    \"\"\"\n    Run sampling.\n    \"\"\"\n    torch.backends.cuda.matmul.allow_tf32 = args.tf32  # True: fast but may lead to some small numerical differences\n    assert torch.cuda.is_available(), \"Sampling with DDP requires at least one GPU. sample.py supports CPU-only usage\"\n    torch.set_grad_enabled(False)\n\n    # Setup DDP:\n    dist.init_process_group(\"nccl\")\n    rank = dist.get_rank()\n    device = rank % torch.cuda.device_count()\n    seed = args.global_seed * dist.get_world_size() + rank\n    torch.manual_seed(seed)\n    torch.cuda.set_device(device)\n    print(f\"Starting rank={rank}, seed={seed}, world_size={dist.get_world_size()}.\")\n\n    if args.ckpt is None:\n        assert args.model == \"DiT-XL/2\", \"Only DiT-XL/2 models are available for auto-download.\"\n        assert args.image_size in [256, 512]\n        assert args.num_classes == 1000\n\n    # Load model:\n    latent_size = args.image_size // 8\n    model = DiT_models[args.model](\n        input_size=latent_size,\n        num_classes=args.num_classes\n    ).to(device)\n    # Auto-download a pre-trained model or load a custom DiT checkpoint from train.py:\n    ckpt_path = args.ckpt or f\"DiT-XL-2-{args.image_size}x{args.image_size}.pt\"\n    state_dict = find_model(ckpt_path)\n    model.load_state_dict(state_dict)\n    model.eval()  # important!\n    diffusion = create_diffusion(str(args.num_sampling_steps))\n    vae = AutoencoderKL.from_pretrained(f\"stabilityai/sd-vae-ft-{args.vae}\").to(device)\n    assert args.cfg_scale >= 1.0, \"In almost all cases, cfg_scale be >= 1.0\"\n    using_cfg = args.cfg_scale > 1.0\n\n    # Create folder to save samples:\n    model_string_name = args.model.replace(\"/\", \"-\")\n    ckpt_string_name = os.path.basename(args.ckpt).replace(\".pt\", \"\") if args.ckpt else \"pretrained\"\n    folder_name = f\"{model_string_name}-{ckpt_string_name}-size-{args.image_size}-vae-{args.vae}-\" \\\n                  f\"cfg-{args.cfg_scale}-seed-{args.global_seed}\"\n    sample_folder_dir = f\"{args.sample_dir}/{folder_name}\"\n    if rank == 0:\n        os.makedirs(sample_folder_dir, exist_ok=True)\n        print(f\"Saving .png samples at {sample_folder_dir}\")\n    dist.barrier()\n\n    # Figure out how many samples we need to generate on each GPU and how many iterations we need to run:\n    n = args.per_proc_batch_size\n    global_batch_size = n * dist.get_world_size()\n    # To make things evenly-divisible, we'll sample a bit more than we need and then discard the extra samples:\n    total_samples = int(math.ceil(args.num_fid_samples / global_batch_size) * global_batch_size)\n    if rank == 0:\n        print(f\"Total number of images that will be sampled: {total_samples}\")\n    assert total_samples % dist.get_world_size() == 0, \"total_samples must be divisible by world_size\"\n    samples_needed_this_gpu = int(total_samples // dist.get_world_size())\n    assert samples_needed_this_gpu % n == 0, \"samples_needed_this_gpu must be divisible by the per-GPU batch size\"\n    iterations = int(samples_needed_this_gpu // n)\n    pbar = range(iterations)\n    pbar = tqdm(pbar) if rank == 0 else pbar\n    total = 0\n    for _ in pbar:\n        # Sample inputs:\n        z = torch.randn(n, model.in_channels, latent_size, latent_size, device=device)\n        y = torch.randint(0, args.num_classes, (n,), device=device)\n\n        # Setup classifier-free guidance:\n        if using_cfg:\n            z = torch.cat([z, z], 0)\n            y_null = torch.tensor([1000] * n, device=device)\n            y = torch.cat([y, y_null], 0)\n            model_kwargs = dict(y=y, cfg_scale=args.cfg_scale)\n            sample_fn = model.forward_with_cfg\n        else:\n            model_kwargs = dict(y=y)\n            sample_fn = model.forward\n\n        # Sample images:\n        samples = diffusion.p_sample_loop(\n            sample_fn, z.shape, z, clip_denoised=False, model_kwargs=model_kwargs, progress=False, device=device\n        )\n        if using_cfg:\n            samples, _ = samples.chunk(2, dim=0)  # Remove null class samples\n\n        samples = vae.decode(samples / 0.18215).sample\n        samples = torch.clamp(127.5 * samples + 128.0, 0, 255).permute(0, 2, 3, 1).to(\"cpu\", dtype=torch.uint8).numpy()\n\n        # Save samples to disk as individual .png files\n        for i, sample in enumerate(samples):\n            index = i * dist.get_world_size() + rank + total\n            Image.fromarray(sample).save(f\"{sample_folder_dir}/{index:06d}.png\")\n        total += global_batch_size\n\n    # Make sure all processes have finished saving their samples before attempting to convert to .npz\n    dist.barrier()\n    if rank == 0:\n        create_npz_from_sample_folder(sample_folder_dir, args.num_fid_samples)\n        print(\"Done.\")\n    dist.barrier()\n    dist.destroy_process_group()\n\n\nif __name__ == \"__main__\":\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\"--model\", type=str, choices=list(DiT_models.keys()), default=\"DiT-XL/2\")\n    parser.add_argument(\"--vae\",  type=str, choices=[\"ema\", \"mse\"], default=\"ema\")\n    parser.add_argument(\"--sample-dir\", type=str, default=\"samples\")\n    parser.add_argument(\"--per-proc-batch-size\", type=int, default=32)\n    parser.add_argument(\"--num-fid-samples\", type=int, default=50_000)\n    parser.add_argument(\"--image-size\", type=int, choices=[256, 512], default=256)\n    parser.add_argument(\"--num-classes\", type=int, default=1000)\n    parser.add_argument(\"--cfg-scale\",  type=float, default=1.5)\n    parser.add_argument(\"--num-sampling-steps\", type=int, default=250)\n    parser.add_argument(\"--global-seed\", type=int, default=0)\n    parser.add_argument(\"--tf32\", action=argparse.BooleanOptionalAction, default=True,\n                        help=\"By default, use TF32 matmuls. This massively accelerates sampling on Ampere GPUs.\")\n    parser.add_argument(\"--ckpt\", type=str, default=None,\n                        help=\"Optional path to a DiT checkpoint (default: auto-download a pre-trained DiT-XL/2 model).\")\n    args = parser.parse_args()\n    main(args)\n"
  },
  {
    "path": "train.py",
    "content": "# Copyright (c) Meta Platforms, Inc. and affiliates.\n# All rights reserved.\n\n# This source code is licensed under the license found in the\n# LICENSE file in the root directory of this source tree.\n\n\"\"\"\nA minimal training script for DiT using PyTorch DDP.\n\"\"\"\nimport torch\n# the first flag below was False when we tested this script but True makes A100 training a lot faster:\ntorch.backends.cuda.matmul.allow_tf32 = True\ntorch.backends.cudnn.allow_tf32 = True\nimport torch.distributed as dist\nfrom torch.nn.parallel import DistributedDataParallel as DDP\nfrom torch.utils.data import DataLoader\nfrom torch.utils.data.distributed import DistributedSampler\nfrom torchvision.datasets import ImageFolder\nfrom torchvision import transforms\nimport numpy as np\nfrom collections import OrderedDict\nfrom PIL import Image\nfrom copy import deepcopy\nfrom glob import glob\nfrom time import time\nimport argparse\nimport logging\nimport os\n\nfrom models import DiT_models\nfrom diffusion import create_diffusion\nfrom diffusers.models import AutoencoderKL\n\n\n#################################################################################\n#                             Training Helper Functions                         #\n#################################################################################\n\n@torch.no_grad()\ndef update_ema(ema_model, model, decay=0.9999):\n    \"\"\"\n    Step the EMA model towards the current model.\n    \"\"\"\n    ema_params = OrderedDict(ema_model.named_parameters())\n    model_params = OrderedDict(model.named_parameters())\n\n    for name, param in model_params.items():\n        # TODO: Consider applying only to params that require_grad to avoid small numerical changes of pos_embed\n        ema_params[name].mul_(decay).add_(param.data, alpha=1 - decay)\n\n\ndef requires_grad(model, flag=True):\n    \"\"\"\n    Set requires_grad flag for all parameters in a model.\n    \"\"\"\n    for p in model.parameters():\n        p.requires_grad = flag\n\n\ndef cleanup():\n    \"\"\"\n    End DDP training.\n    \"\"\"\n    dist.destroy_process_group()\n\n\ndef create_logger(logging_dir):\n    \"\"\"\n    Create a logger that writes to a log file and stdout.\n    \"\"\"\n    if dist.get_rank() == 0:  # real logger\n        logging.basicConfig(\n            level=logging.INFO,\n            format='[\\033[34m%(asctime)s\\033[0m] %(message)s',\n            datefmt='%Y-%m-%d %H:%M:%S',\n            handlers=[logging.StreamHandler(), logging.FileHandler(f\"{logging_dir}/log.txt\")]\n        )\n        logger = logging.getLogger(__name__)\n    else:  # dummy logger (does nothing)\n        logger = logging.getLogger(__name__)\n        logger.addHandler(logging.NullHandler())\n    return logger\n\n\ndef center_crop_arr(pil_image, image_size):\n    \"\"\"\n    Center cropping implementation from ADM.\n    https://github.com/openai/guided-diffusion/blob/8fb3ad9197f16bbc40620447b2742e13458d2831/guided_diffusion/image_datasets.py#L126\n    \"\"\"\n    while min(*pil_image.size) >= 2 * image_size:\n        pil_image = pil_image.resize(\n            tuple(x // 2 for x in pil_image.size), resample=Image.BOX\n        )\n\n    scale = image_size / min(*pil_image.size)\n    pil_image = pil_image.resize(\n        tuple(round(x * scale) for x in pil_image.size), resample=Image.BICUBIC\n    )\n\n    arr = np.array(pil_image)\n    crop_y = (arr.shape[0] - image_size) // 2\n    crop_x = (arr.shape[1] - image_size) // 2\n    return Image.fromarray(arr[crop_y: crop_y + image_size, crop_x: crop_x + image_size])\n\n\n#################################################################################\n#                                  Training Loop                                #\n#################################################################################\n\ndef main(args):\n    \"\"\"\n    Trains a new DiT model.\n    \"\"\"\n    assert torch.cuda.is_available(), \"Training currently requires at least one GPU.\"\n\n    # Setup DDP:\n    dist.init_process_group(\"nccl\")\n    assert args.global_batch_size % dist.get_world_size() == 0, f\"Batch size must be divisible by world size.\"\n    rank = dist.get_rank()\n    device = rank % torch.cuda.device_count()\n    seed = args.global_seed * dist.get_world_size() + rank\n    torch.manual_seed(seed)\n    torch.cuda.set_device(device)\n    print(f\"Starting rank={rank}, seed={seed}, world_size={dist.get_world_size()}.\")\n\n    # Setup an experiment folder:\n    if rank == 0:\n        os.makedirs(args.results_dir, exist_ok=True)  # Make results folder (holds all experiment subfolders)\n        experiment_index = len(glob(f\"{args.results_dir}/*\"))\n        model_string_name = args.model.replace(\"/\", \"-\")  # e.g., DiT-XL/2 --> DiT-XL-2 (for naming folders)\n        experiment_dir = f\"{args.results_dir}/{experiment_index:03d}-{model_string_name}\"  # Create an experiment folder\n        checkpoint_dir = f\"{experiment_dir}/checkpoints\"  # Stores saved model checkpoints\n        os.makedirs(checkpoint_dir, exist_ok=True)\n        logger = create_logger(experiment_dir)\n        logger.info(f\"Experiment directory created at {experiment_dir}\")\n    else:\n        logger = create_logger(None)\n\n    # Create model:\n    assert args.image_size % 8 == 0, \"Image size must be divisible by 8 (for the VAE encoder).\"\n    latent_size = args.image_size // 8\n    model = DiT_models[args.model](\n        input_size=latent_size,\n        num_classes=args.num_classes\n    )\n    # Note that parameter initialization is done within the DiT constructor\n    ema = deepcopy(model).to(device)  # Create an EMA of the model for use after training\n    requires_grad(ema, False)\n    model = DDP(model.to(device), device_ids=[rank])\n    diffusion = create_diffusion(timestep_respacing=\"\")  # default: 1000 steps, linear noise schedule\n    vae = AutoencoderKL.from_pretrained(f\"stabilityai/sd-vae-ft-{args.vae}\").to(device)\n    logger.info(f\"DiT Parameters: {sum(p.numel() for p in model.parameters()):,}\")\n\n    # Setup optimizer (we used default Adam betas=(0.9, 0.999) and a constant learning rate of 1e-4 in our paper):\n    opt = torch.optim.AdamW(model.parameters(), lr=1e-4, weight_decay=0)\n\n    # Setup data:\n    transform = transforms.Compose([\n        transforms.Lambda(lambda pil_image: center_crop_arr(pil_image, args.image_size)),\n        transforms.RandomHorizontalFlip(),\n        transforms.ToTensor(),\n        transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5], inplace=True)\n    ])\n    dataset = ImageFolder(args.data_path, transform=transform)\n    sampler = DistributedSampler(\n        dataset,\n        num_replicas=dist.get_world_size(),\n        rank=rank,\n        shuffle=True,\n        seed=args.global_seed\n    )\n    loader = DataLoader(\n        dataset,\n        batch_size=int(args.global_batch_size // dist.get_world_size()),\n        shuffle=False,\n        sampler=sampler,\n        num_workers=args.num_workers,\n        pin_memory=True,\n        drop_last=True\n    )\n    logger.info(f\"Dataset contains {len(dataset):,} images ({args.data_path})\")\n\n    # Prepare models for training:\n    update_ema(ema, model.module, decay=0)  # Ensure EMA is initialized with synced weights\n    model.train()  # important! This enables embedding dropout for classifier-free guidance\n    ema.eval()  # EMA model should always be in eval mode\n\n    # Variables for monitoring/logging purposes:\n    train_steps = 0\n    log_steps = 0\n    running_loss = 0\n    start_time = time()\n\n    logger.info(f\"Training for {args.epochs} epochs...\")\n    for epoch in range(args.epochs):\n        sampler.set_epoch(epoch)\n        logger.info(f\"Beginning epoch {epoch}...\")\n        for x, y in loader:\n            x = x.to(device)\n            y = y.to(device)\n            with torch.no_grad():\n                # Map input images to latent space + normalize latents:\n                x = vae.encode(x).latent_dist.sample().mul_(0.18215)\n            t = torch.randint(0, diffusion.num_timesteps, (x.shape[0],), device=device)\n            model_kwargs = dict(y=y)\n            loss_dict = diffusion.training_losses(model, x, t, model_kwargs)\n            loss = loss_dict[\"loss\"].mean()\n            opt.zero_grad()\n            loss.backward()\n            opt.step()\n            update_ema(ema, model.module)\n\n            # Log loss values:\n            running_loss += loss.item()\n            log_steps += 1\n            train_steps += 1\n            if train_steps % args.log_every == 0:\n                # Measure training speed:\n                torch.cuda.synchronize()\n                end_time = time()\n                steps_per_sec = log_steps / (end_time - start_time)\n                # Reduce loss history over all processes:\n                avg_loss = torch.tensor(running_loss / log_steps, device=device)\n                dist.all_reduce(avg_loss, op=dist.ReduceOp.SUM)\n                avg_loss = avg_loss.item() / dist.get_world_size()\n                logger.info(f\"(step={train_steps:07d}) Train Loss: {avg_loss:.4f}, Train Steps/Sec: {steps_per_sec:.2f}\")\n                # Reset monitoring variables:\n                running_loss = 0\n                log_steps = 0\n                start_time = time()\n\n            # Save DiT checkpoint:\n            if train_steps % args.ckpt_every == 0 and train_steps > 0:\n                if rank == 0:\n                    checkpoint = {\n                        \"model\": model.module.state_dict(),\n                        \"ema\": ema.state_dict(),\n                        \"opt\": opt.state_dict(),\n                        \"args\": args\n                    }\n                    checkpoint_path = f\"{checkpoint_dir}/{train_steps:07d}.pt\"\n                    torch.save(checkpoint, checkpoint_path)\n                    logger.info(f\"Saved checkpoint to {checkpoint_path}\")\n                dist.barrier()\n\n    model.eval()  # important! This disables randomized embedding dropout\n    # do any sampling/FID calculation/etc. with ema (or model) in eval mode ...\n\n    logger.info(\"Done!\")\n    cleanup()\n\n\nif __name__ == \"__main__\":\n    # Default args here will train DiT-XL/2 with the hyperparameters we used in our paper (except training iters).\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\"--data-path\", type=str, required=True)\n    parser.add_argument(\"--results-dir\", type=str, default=\"results\")\n    parser.add_argument(\"--model\", type=str, choices=list(DiT_models.keys()), default=\"DiT-XL/2\")\n    parser.add_argument(\"--image-size\", type=int, choices=[256, 512], default=256)\n    parser.add_argument(\"--num-classes\", type=int, default=1000)\n    parser.add_argument(\"--epochs\", type=int, default=1400)\n    parser.add_argument(\"--global-batch-size\", type=int, default=256)\n    parser.add_argument(\"--global-seed\", type=int, default=0)\n    parser.add_argument(\"--vae\", type=str, choices=[\"ema\", \"mse\"], default=\"ema\")  # Choice doesn't affect training\n    parser.add_argument(\"--num-workers\", type=int, default=4)\n    parser.add_argument(\"--log-every\", type=int, default=100)\n    parser.add_argument(\"--ckpt-every\", type=int, default=50_000)\n    args = parser.parse_args()\n    main(args)\n"
  }
]