[
  {
    "path": ".github/workflows/close_issue.yaml",
    "content": "name: Close inactive issues\non:\n  schedule:\n    - cron: \"30 1 * * *\"\n\njobs:\n  close-issues:\n    runs-on: ubuntu-latest\n    permissions:\n      issues: write\n      pull-requests: write\n    steps:\n      - uses: actions/stale@v9\n        with:\n          days-before-issue-stale: 7\n          days-before-issue-close: 7\n          stale-issue-label: \"stale\"\n          stale-issue-message: \"This issue is stale because it has been open for 7 days with no activity.\"\n          close-issue-message: \"This issue was closed because it has been inactive for 7 days since being marked as stale.\"\n          days-before-pr-stale: -1\n          days-before-pr-close: -1\n          repo-token: ${{ secrets.GITHUB_TOKEN }}\n"
  },
  {
    "path": ".github/workflows/github_page.yaml",
    "content": "name: GitHub Pages\n\non:\n  workflow_dispatch:\n\njobs:\n  deploy:\n    runs-on: ubuntu-22.04\n    permissions:\n      contents: write\n    concurrency:\n      group: ${{ github.workflow }}-${{ github.ref }}\n    steps:\n      - uses: actions/checkout@v3\n        with:\n          ref: gallery\n\n      - name: Setup Node\n        uses: actions/setup-node@v4\n        with:\n          node-version: 20\n\n      - run: npm install\n      - run: npm run build\n\n      - name: Deploy\n        uses: peaceiris/actions-gh-pages@v3\n        with:\n          github_token: ${{ secrets.GITHUB_TOKEN }}\n          publish_dir: ./build\n"
  },
  {
    "path": ".gitignore",
    "content": "__pycache__/\n*.py[cod]\n*$py.class\n\n# C extensions\n*.so\n\n# Distribution / packaging\n.Python\nbuild/\ndevelop-eggs/\ndist/\ndownloads/\neggs/\n.eggs/\nlib/\nlib64/\nparts/\nsdist/\nvar/\nwheels/\nshare/python-wheels/\n*.egg-info/\n.installed.cfg\n*.egg\nMANIFEST\n\n# PyInstaller\n#  Usually these files are written by a python script from a template\n#  before PyInstaller builds the exe, so as to inject date/other infos into it.\n*.manifest\n*.spec\n\n# Installer logs\npip-log.txt\npip-delete-this-directory.txt\n\n# Unit test / coverage reports\nhtmlcov/\n.tox/\n.nox/\n.coverage\n.coverage.*\n.cache\nnosetests.xml\ncoverage.xml\n*.cover\n*.py,cover\n.hypothesis/\n.pytest_cache/\ncover/\n\n# Translations\n*.mo\n*.pot\n\n# Django stuff:\n*.log\nlocal_settings.py\ndb.sqlite3\ndb.sqlite3-journal\n\n# Flask stuff:\ninstance/\n.webassets-cache\n\n# Scrapy stuff:\n.scrapy\n\n# Sphinx documentation\ndocs/_build/\n\n# PyBuilder\n.pybuilder/\ntarget/\n\n# Jupyter Notebook\n.ipynb_checkpoints\n\n# IPython\nprofile_default/\nipython_config.py\n\n# pyenv\n#   For a library or package, you might want to ignore these files since the code is\n#   intended to run in multiple environments; otherwise, check them in:\n# .python-version\n\n# pipenv\n#   According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.\n#   However, in case of collaboration, if having platform-specific dependencies or dependencies\n#   having no cross-platform support, pipenv may install dependencies that don't work, or not\n#   install all needed dependencies.\n#Pipfile.lock\n\n# poetry\n#   Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.\n#   This is especially recommended for binary packages to ensure reproducibility, and is more\n#   commonly ignored for libraries.\n#   https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control\n#poetry.lock\n\n# pdm\n#   Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.\n#pdm.lock\n#   pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it\n#   in version control.\n#   https://pdm.fming.dev/#use-with-ide\n.pdm.toml\n\n# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm\n__pypackages__/\n\n# Celery stuff\ncelerybeat-schedule\ncelerybeat.pid\n\n# SageMath parsed files\n*.sage.py\n\n# Environments\n.env\n.venv\nenv/\nvenv/\nENV/\nenv.bak/\nvenv.bak/\n\n\n# Spyder project settings\n.spyderproject\n.spyproject\n\n# Rope project settings\n.ropeproject\n\n# mkdocs documentation\n/site\n\n# mypy\n.mypy_cache/\n.dmypy.json\ndmypy.json\n\n# Pyre type checker\n.pyre/\n\n# pytype static type analyzer\n.pytype/\n\n# Cython debug symbols\ncython_debug/\n\n# PyCharm\n#  JetBrains specific template is maintained in a separate JetBrains.gitignore that can\n#  be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore\n#  and can be added to the global gitignore or merged into this file.  For a more nuclear\n#  option (not recommended) you can uncomment the following to ignore the entire idea folder.\n.idea/\n.vscode/\n\n# macos\n*.DS_Store\n\n# misc files\ndata/\ndataset/\nruns/\ncheckpoints/\noutputs/\noutputs\nsamples/\nsamples\nlogs/\npretrained_models/\npretrained_models\nevaluation_results/\ncache/\n*.swp\ndebug/\n\n# Secret files\nhostfiles/\nhostfile*\nrun.sh\ngradio_cached_examples/\nwandb/\n\n# npm\nnode_modules/\npackage-lock.json\npackage.json\n\nexps\nckpts\nflash-attention\ndatasets\n"
  },
  {
    "path": ".pre-commit-config.yaml",
    "content": "repos:\n\n  - repo: https://github.com/PyCQA/autoflake\n    rev: v2.2.1\n    hooks:\n      - id: autoflake\n        name: autoflake (python)\n        args: ['--in-place']\n\n  - repo: https://github.com/pycqa/isort\n    rev: 5.12.0\n    hooks:\n      - id: isort\n        name: sort all imports (python)\n\n  - repo: https://github.com/psf/black-pre-commit-mirror\n    rev: 23.9.1\n    hooks:\n    - id: black\n      name: black formatter\n\n  - repo: https://github.com/pre-commit/pre-commit-hooks\n    rev: v4.3.0\n    hooks:\n      - id: check-yaml\n      - id: check-merge-conflict\n      - id: check-case-conflict\n      - id: trailing-whitespace\n      - id: end-of-file-fixer\n      - id: mixed-line-ending\n        args: ['--fix=lf']\n"
  },
  {
    "path": "CONTRIBUTING.md",
    "content": "# Contributing\n\nThe Open-Sora project welcomes any constructive contribution from the community and the team is more than willing to work on problems you have encountered to make it a better project.\n\n## Development Environment Setup\n\nTo contribute to Open-Sora, we would like to first guide you to set up a proper development environment so that you can better implement your code. You can install this library from source with the `editable` flag (`-e`, for development mode) so that your change to the source code will be reflected in runtime without re-installation.\n\nYou can refer to the [Installation Section](./README.md#installation) and replace `pip install -v .` with `pip install -v -e .`.\n\n### Code Style\n\nWe have some static checks when you commit your code change, please make sure you can pass all the tests and make sure the coding style meets our requirements. We use pre-commit hook to make sure the code is aligned with the writing standard. To set up the code style checking, you need to follow the steps below.\n\n```shell\n# these commands are executed under the Open-Sora directory\npip install pre-commit\npre-commit install\n```\n\nCode format checking will be automatically executed when you commit your changes.\n\n## Contribution Guide\n\nYou need to follow these steps below to make contribution to the main repository via pull request. You can learn about the details of pull request [here](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/about-pull-requests).\n\n### 1. Fork the Official Repository\n\nFirstly, you need to visit the [Open-Sora repository](https://github.com/hpcaitech/Open-Sora) and fork into your own account. The `fork` button is at the right top corner of the web page alongside with buttons such as `watch` and `star`.\n\nNow, you can clone your own forked repository into your local environment.\n\n```shell\ngit clone https://github.com/<YOUR-USERNAME>/Open-Sora.git\n```\n\n### 2. Configure Git\n\nYou need to set the official repository as your upstream so that you can synchronize with the latest update in the official repository. You can learn about upstream [here](https://www.atlassian.com/git/tutorials/git-forks-and-upstreams).\n\nThen add the original repository as upstream\n\n```shell\ncd Open-Sora\ngit remote add upstream https://github.com/hpcaitech/Open-Sora.git\n```\n\nyou can use the following command to verify that the remote is set. You should see both `origin` and `upstream` in the output.\n\n```shell\ngit remote -v\n```\n\n### 3. Synchronize with Official Repository\n\nBefore you make changes to the codebase, it is always good to fetch the latest updates in the official repository. In order to do so, you can use the commands below.\n\n```shell\ngit fetch upstream\ngit checkout main\ngit merge upstream/main\ngit push origin main\n```\n\n### 5. Create a New Branch\n\nYou should not make changes to the `main` branch of your forked repository as this might make upstream synchronization difficult. You can create a new branch with the appropriate name. General branch name format should start with `hotfix/` and `feature/`. `hotfix` is for bug fix and `feature` is for addition of a new feature.\n\n```shell\ngit checkout -b <NEW-BRANCH-NAME>\n```\n\n### 6. Implementation and Code Commit\n\nNow you can implement your code change in the source code. Remember that you installed the system in development, thus you do not need to uninstall and install to make the code take effect. The code change will be reflected in every new PyThon execution.\nYou can commit and push the changes to your local repository. The changes should be kept logical, modular and atomic.\n\n```shell\ngit add -A\ngit commit -m \"<COMMIT-MESSAGE>\"\ngit push -u origin <NEW-BRANCH-NAME>\n```\n\n### 7. Open a Pull Request\n\nYou can now create a pull request on the GitHub webpage of your repository. The source branch is `<NEW-BRANCH-NAME>` of your repository and the target branch should be `main` of `hpcaitech/Open-Sora`. After creating this pull request, you should be able to see it [here](https://github.com/hpcaitech/Open-Sora/pulls).\n\nThe Open-Sora team will review your code change and merge your code if applicable.\n\n## FQA\n\n1. `pylint` cannot recognize some members:\n\nAdd this into your `settings.json` in VSCode:\n\n```json\n\"pylint.args\": [\n \"--generated-members=numpy.* ,torch.*,cv2.*\",\n],\n```\n"
  },
  {
    "path": "LICENSE",
    "content": "                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"[]\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright 2024 HPC-AI Technology Inc.\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n\n   =========================================================================\n   This project is inspired by the listed projects and is subject to the following licenses:\n\n   10. [T5: Text-To-Text Transfer Transformer](https://github.com/google-research/text-to-text-transfer-transformer)\n\n   Copyright 2019 Google\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n\n   11. [CLIP](https://github.com/openai/CLIP/tree/main)\n\n   MIT License\n\n   Copyright (c) 2021 OpenAI\n\n   Permission is hereby granted, free of charge, to any person obtaining a copy\n   of this software and associated documentation files (the \"Software\"), to deal\n   in the Software without restriction, including without limitation the rights\n   to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n   copies of the Software, and to permit persons to whom the Software is\n   furnished to do so, subject to the following conditions:\n\n   The above copyright notice and this permission notice shall be included in all\n   copies or substantial portions of the Software.\n\n   12. [FLUX](https://github.com/black-forest-labs/flux)\n\n   Copyright 2024 Black Forest Labs\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n\n   13. [EfficientViT](https://github.com/mit-han-lab/efficientvit)\n\n   Copyright [2023] [Han Cai]\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n\n   14. [HunyuanVideo](https://github.com/Tencent/HunyuanVideo/tree/main)\n\n   TENCENT HUNYUAN COMMUNITY LICENSE AGREEMENT\n   Tencent HunyuanVideo Release Date: December 3, 2024\n   THIS LICENSE AGREEMENT DOES NOT APPLY IN THE EUROPEAN UNION, UNITED KINGDOM AND SOUTH KOREA AND IS EXPRESSLY LIMITED TO THE TERRITORY, AS DEFINED BELOW.\n   By clicking to agree or by using, reproducing, modifying, distributing, performing or displaying any portion or element of the Tencent Hunyuan Works, including via any Hosted Service, You will be deemed to have recognized and accepted the content of this Agreement, which is effective immediately.\n\n   1. DEFINITIONS.\n   a. “Acceptable Use Policy” shall mean the policy made available by Tencent as set forth in the Exhibit A.\n   b. “Agreement” shall mean the terms and conditions for use, reproduction, distribution, modification, performance and displaying of Tencent Hunyuan Works or any portion or element thereof set forth herein.\n   c. “Documentation” shall mean the specifications, manuals and documentation for Tencent Hunyuan made publicly available by Tencent.\n   d. “Hosted Service” shall mean a hosted service offered via an application programming interface (API), web access, or any other electronic or remote means.\n   e. “Licensee,” “You” or “Your” shall mean a natural person or legal entity exercising the rights granted by this Agreement and/or using the Tencent Hunyuan Works for any purpose and in any field of use.\n   f. “Materials” shall mean, collectively, Tencent’s proprietary Tencent Hunyuan and Documentation (and any portion thereof) as made available by Tencent under this Agreement.\n   g. “Model Derivatives” shall mean all: (i) modifications to Tencent Hunyuan or any Model Derivative of Tencent Hunyuan; (ii) works based on Tencent Hunyuan or any Model Derivative of Tencent Hunyuan; or (iii) any other machine learning model which is created by transfer of patterns of the weights, parameters, operations, or Output of Tencent Hunyuan or any Model Derivative of Tencent Hunyuan, to that model in order to cause that model to perform similarly to Tencent Hunyuan or a Model Derivative of Tencent Hunyuan, including distillation methods, methods that use intermediate data representations, or methods based on the generation of synthetic data Outputs by Tencent Hunyuan or a Model Derivative of Tencent Hunyuan for training that model. For clarity, Outputs by themselves are not deemed Model Derivatives.\n   h. “Output” shall mean the information and/or content output of Tencent Hunyuan or a Model Derivative that results from operating or otherwise using Tencent Hunyuan or a Model Derivative, including via a Hosted Service.\n   i. “Tencent,” “We” or “Us” shall mean THL A29 Limited.\n   j. “Tencent Hunyuan” shall mean the large language models, text/image/video/audio/3D generation models, and multimodal large language models and their software and algorithms, including trained model weights, parameters (including optimizer states), machine-learning model code, inference-enabling code, training-enabling code, fine-tuning enabling code and other elements of the foregoing made publicly available by Us, including, without limitation to, Tencent HunyuanVideo released at [https://github.com/Tencent/HunyuanVideo].\n   k. “Tencent Hunyuan Works” shall mean: (i) the Materials; (ii) Model Derivatives; and (iii) all derivative works thereof.\n   l. “Territory” shall mean the worldwide territory, excluding the territory of the European Union, United Kingdom and South Korea.\n   m. “Third Party” or “Third Parties” shall mean individuals or legal entities that are not under common control with Us or You.\n   n. “including” shall mean including but not limited to.\n   2. GRANT OF RIGHTS.\n   We grant You, for the Territory only, a non-exclusive, non-transferable and royalty-free limited license under Tencent’s intellectual property or other rights owned by Us embodied in or utilized by the Materials to use, reproduce, distribute, create derivative works of (including Model Derivatives), and make modifications to the Materials, only in accordance with the terms of this Agreement and the Acceptable Use Policy, and You must not violate (or encourage or permit anyone else to violate) any term of this Agreement or the Acceptable Use Policy.\n   3. DISTRIBUTION.\n   You may, subject to Your compliance with this Agreement, distribute or make available to Third Parties the Tencent Hunyuan Works, exclusively in the Territory, provided that You meet all of the following conditions:\n   a. You must provide all such Third Party recipients of the Tencent Hunyuan Works or products or services using them a copy of this Agreement;\n   b. You must cause any modified files to carry prominent notices stating that You changed the files;\n   c. You are encouraged to: (i) publish at least one technology introduction blogpost or one public statement expressing Your experience of using the Tencent Hunyuan Works; and (ii) mark the products or services developed by using the Tencent Hunyuan Works to indicate that the product/service is “Powered by Tencent Hunyuan”; and\n   d. All distributions to Third Parties (other than through a Hosted Service) must be accompanied by a “Notice” text file that contains the following notice: “Tencent Hunyuan is licensed under the Tencent Hunyuan Community License Agreement, Copyright © 2024 Tencent. All Rights Reserved. The trademark rights of “Tencent Hunyuan” are owned by Tencent or its affiliate.”\n   You may add Your own copyright statement to Your modifications and, except as set forth in this Section and in Section 5, may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Model Derivatives as a whole, provided Your use, reproduction, modification, distribution, performance and display of the work otherwise complies with the terms and conditions of this Agreement (including as regards the Territory). If You receive Tencent Hunyuan Works from a Licensee as part of an integrated end user product, then this Section 3 of this Agreement will not apply to You.\n   4. ADDITIONAL COMMERCIAL TERMS.\n   If, on the Tencent Hunyuan version release date, the monthly active users of all products or services made available by or for Licensee is greater than 100 million monthly active users in the preceding calendar month, You must request a license from Tencent, which Tencent may grant to You in its sole discretion, and You are not authorized to exercise any of the rights under this Agreement unless or until Tencent otherwise expressly grants You such rights.\n   5. RULES OF USE.\n   a. Your use of the Tencent Hunyuan Works must comply with applicable laws and regulations (including trade compliance laws and regulations) and adhere to the Acceptable Use Policy for the Tencent Hunyuan Works, which is hereby incorporated by reference into this Agreement. You must include the use restrictions referenced in these Sections 5(a) and 5(b) as an enforceable provision in any agreement (e.g., license agreement, terms of use, etc.) governing the use and/or distribution of Tencent Hunyuan Works and You must provide notice to subsequent users to whom You distribute that Tencent Hunyuan Works are subject to the use restrictions in these Sections 5(a) and 5(b).\n   b. You must not use the Tencent Hunyuan Works or any Output or results of the Tencent Hunyuan Works to improve any other AI model (other than Tencent Hunyuan or Model Derivatives thereof).\n   c. You must not use, reproduce, modify, distribute, or display the Tencent Hunyuan Works, Output or results of the Tencent Hunyuan Works outside the Territory. Any such use outside the Territory is unlicensed and unauthorized under this Agreement.\n   6. INTELLECTUAL PROPERTY.\n   a. Subject to Tencent’s ownership of Tencent Hunyuan Works made by or for Tencent and intellectual property rights therein, conditioned upon Your compliance with the terms and conditions of this Agreement, as between You and Tencent, You will be the owner of any derivative works and modifications of the Materials and any Model Derivatives that are made by or for You.\n   b. No trademark licenses are granted under this Agreement, and in connection with the Tencent Hunyuan Works, Licensee may not use any name or mark owned by or associated with Tencent or any of its affiliates, except as required for reasonable and customary use in describing and distributing the Tencent Hunyuan Works. Tencent hereby grants You a license to use “Tencent Hunyuan” (the “Mark”) in the Territory solely as required to comply with the provisions of Section 3(c), provided that You comply with any applicable laws related to trademark protection. All goodwill arising out of Your use of the Mark will inure to the benefit of Tencent.\n   c. If You commence a lawsuit or other proceedings (including a cross-claim or counterclaim in a lawsuit) against Us or any person or entity alleging that the Materials or any Output, or any portion of any of the foregoing, infringe any intellectual property or other right owned or licensable by You, then all licenses granted to You under this Agreement shall terminate as of the date such lawsuit or other proceeding is filed. You will defend, indemnify and hold harmless Us from and against any claim by any Third Party arising out of or related to Your or the Third Party’s use or distribution of the Tencent Hunyuan Works.\n   d. Tencent claims no rights in Outputs You generate. You and Your users are solely responsible for Outputs and their subsequent uses.\n   7. DISCLAIMERS OF WARRANTY AND LIMITATIONS OF LIABILITY.\n   a. We are not obligated to support, update, provide training for, or develop any further version of the Tencent Hunyuan Works or to grant any license thereto.\n   b. UNLESS AND ONLY TO THE EXTENT REQUIRED BY APPLICABLE LAW, THE TENCENT HUNYUAN WORKS AND ANY OUTPUT AND RESULTS THEREFROM ARE PROVIDED “AS IS” WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES OF ANY KIND INCLUDING ANY WARRANTIES OF TITLE, MERCHANTABILITY, NONINFRINGEMENT, COURSE OF DEALING, USAGE OF TRADE, OR FITNESS FOR A PARTICULAR PURPOSE. YOU ARE SOLELY RESPONSIBLE FOR DETERMINING THE APPROPRIATENESS OF USING, REPRODUCING, MODIFYING, PERFORMING, DISPLAYING OR DISTRIBUTING ANY OF THE TENCENT HUNYUAN WORKS OR OUTPUTS AND ASSUME ANY AND ALL RISKS ASSOCIATED WITH YOUR OR A THIRD PARTY’S USE OR DISTRIBUTION OF ANY OF THE TENCENT HUNYUAN WORKS OR OUTPUTS AND YOUR EXERCISE OF RIGHTS AND PERMISSIONS UNDER THIS AGREEMENT.\n   c. TO THE FULLEST EXTENT PERMITTED BY APPLICABLE LAW, IN NO EVENT SHALL TENCENT OR ITS AFFILIATES BE LIABLE UNDER ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, TORT, NEGLIGENCE, PRODUCTS LIABILITY, OR OTHERWISE, FOR ANY DAMAGES, INCLUDING ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL, EXEMPLARY, CONSEQUENTIAL OR PUNITIVE DAMAGES, OR LOST PROFITS OF ANY KIND ARISING FROM THIS AGREEMENT OR RELATED TO ANY OF THE TENCENT HUNYUAN WORKS OR OUTPUTS, EVEN IF TENCENT OR ITS AFFILIATES HAVE BEEN ADVISED OF THE POSSIBILITY OF ANY OF THE FOREGOING.\n   8. SURVIVAL AND TERMINATION.\n   a. The term of this Agreement shall commence upon Your acceptance of this Agreement or access to the Materials and will continue in full force and effect until terminated in accordance with the terms and conditions herein.\n   b. We may terminate this Agreement if You breach any of the terms or conditions of this Agreement. Upon termination of this Agreement, You must promptly delete and cease use of the Tencent Hunyuan Works. Sections 6(a), 6(c), 7 and 9 shall survive the termination of this Agreement.\n   9. GOVERNING LAW AND JURISDICTION.\n   a. This Agreement and any dispute arising out of or relating to it will be governed by the laws of the Hong Kong Special Administrative Region of the People’s Republic of China, without regard to conflict of law principles, and the UN Convention on Contracts for the International Sale of Goods does not apply to this Agreement.\n   b. Exclusive jurisdiction and venue for any dispute arising out of or relating to this Agreement will be a court of competent jurisdiction in the Hong Kong Special Administrative Region of the People’s Republic of China, and Tencent and Licensee consent to the exclusive jurisdiction of such court with respect to any such dispute.\n\n   EXHIBIT A\n   ACCEPTABLE USE POLICY\n\n   Tencent reserves the right to update this Acceptable Use Policy from time to time.\n   Last modified: November 5, 2024\n\n   Tencent endeavors to promote safe and fair use of its tools and features, including Tencent Hunyuan. You agree not to use Tencent Hunyuan or Model Derivatives:\n\n   1. Outside the Territory;\n   2. In any way that violates any applicable national, federal, state, local, international or any other law or regulation;\n   3. To harm Yourself or others;\n   4. To repurpose or distribute output from Tencent Hunyuan or any Model Derivatives to harm Yourself or others;\n   5. To override or circumvent the safety guardrails and safeguards We have put in place;\n   6. For the purpose of exploiting, harming or attempting to exploit or harm minors in any way;\n   7. To generate or disseminate verifiably false information and/or content with the purpose of harming others or influencing elections;\n   8. To generate or facilitate false online engagement, including fake reviews and other means of fake online engagement;\n   9. To intentionally defame, disparage or otherwise harass others;\n   10. To generate and/or disseminate malware (including ransomware) or any other content to be used for the purpose of harming electronic systems;\n   11. To generate or disseminate personal identifiable information with the purpose of harming others;\n   12. To generate or disseminate information (including images, code, posts, articles), and place the information in any public context (including –through the use of bot generated tweets), without expressly and conspicuously identifying that the information and/or content is machine generated;\n   13. To impersonate another individual without consent, authorization, or legal right;\n   14. To make high-stakes automated decisions in domains that affect an individual’s safety, rights or wellbeing (e.g., law enforcement, migration, medicine/health, management of critical infrastructure, safety components of products, essential services, credit, employment, housing, education, social scoring, or insurance);\n   15. In a manner that violates or disrespects the social ethics and moral standards of other countries or regions;\n   16. To perform, facilitate, threaten, incite, plan, promote or encourage violent extremism or terrorism;\n   17. For any use intended to discriminate against or harm individuals or groups based on protected characteristics or categories, online or offline social behavior or known or predicted personal or personality characteristics;\n   18. To intentionally exploit any of the vulnerabilities of a specific group of persons based on their age, social, physical or mental characteristics, in order to materially distort the behavior of a person pertaining to that group in a manner that causes or is likely to cause that person or another person physical or psychological harm;\n   19. For military purposes;\n   20. To engage in the unauthorized or unlicensed practice of any profession including, but not limited to, financial, legal, medical/health, or other professional practices.\n"
  },
  {
    "path": "README.md",
    "content": "<p align=\"center\">\n    <img src=\"https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/icon.png\" width=\"250\"/>\n</p>\n<div align=\"center\">\n    <a href=\"https://github.com/hpcaitech/Open-Sora/stargazers\"><img src=\"https://img.shields.io/github/stars/hpcaitech/Open-Sora?style=social\"></a>\n    <a href=\"https://arxiv.org/abs/2503.09642v1\"><img src=\"https://img.shields.io/static/v1?label=Tech Report 2.0&message=Arxiv&color=red\"></a>\n    <a href=\"https://arxiv.org/abs/2412.20404\"><img src=\"https://img.shields.io/static/v1?label=Tech Report 1.2&message=Arxiv&color=red\"></a>\n    <a href=\"https://hpcaitech.github.io/Open-Sora/\"><img src=\"https://img.shields.io/badge/Gallery-View-orange?logo=&amp\"></a>\n</div>\n\n<div align=\"center\">\n    <a href=\"https://discord.gg/kZakZzrSUT\"><img src=\"https://img.shields.io/badge/Discord-join-blueviolet?logo=discord&amp\"></a>\n    <a href=\"https://join.slack.com/t/colossalaiworkspace/shared_invite/zt-247ipg9fk-KRRYmUl~u2ll2637WRURVA\"><img src=\"https://img.shields.io/badge/Slack-ColossalAI-blueviolet?logo=slack&amp\"></a>\n    <a href=\"https://x.com/YangYou1991/status/1899973689460044010\"><img src=\"https://img.shields.io/badge/Twitter-Discuss-blue?logo=twitter&amp\"></a>\n    <a href=\"https://raw.githubusercontent.com/hpcaitech/public_assets/main/colossalai/img/WeChat.png\"><img src=\"https://img.shields.io/badge/微信-小助手加群-green?logo=wechat&amp\"></a>\n</div>\n\n## Open-Sora: Democratizing Efficient Video Production for All\n\nWe design and implement **Open-Sora**, an initiative dedicated to **efficiently** producing high-quality video. We hope to make the model,\ntools and all details accessible to all. By embracing **open-source** principles,\nOpen-Sora not only democratizes access to advanced video generation techniques, but also offers a\nstreamlined and user-friendly platform that simplifies the complexities of video generation.\nWith Open-Sora, our goal is to foster innovation, creativity, and inclusivity within the field of content creation.\n\n🎬 For a professional AI video-generation product, try [Video Ocean](https://video-ocean.com/) — powered by a superior model.\n<div align=\"center\">\n   <a href=\"https://video-ocean.com/\">\n   <img src=\"https://github.com/hpcaitech/public_assets/blob/main/colossalai/img/3.gif\" width=\"850\" />\n   </a>\n</div>\n\n<div align=\"center\">\n   <a href=\"https://hpc-ai.com/?utm_source=github&utm_medium=social&utm_campaign=promotion-opensora\">\n   <img src=\"https://github.com/hpcaitech/public_assets/blob/main/colossalai/img/1.gif\" width=\"850\" />\n   </a>\n</div>\n\n<!-- [[中文文档](/docs/zh_CN/README.md)] [[潞晨云](https://cloud.luchentech.com/)|[OpenSora镜像](https://cloud.luchentech.com/doc/docs/image/open-sora/)|[视频教程](https://www.bilibili.com/video/BV1ow4m1e7PX/?vd_source=c6b752764cd36ff0e535a768e35d98d2)] -->\n\n## 📰 News\n\n- **[2025.03.12]** 🔥 We released **Open-Sora 2.0** (11B). 🎬 11B model achieves [on-par performance](#evaluation) with 11B HunyuanVideo & 30B Step-Video on 📐VBench & 📊Human Preference. 🛠️ Fully open-source: checkpoints and training codes for training with only **$200K**. [[report]](https://arxiv.org/abs/2503.09642v1)\n- **[2025.02.20]** 🔥 We released **Open-Sora 1.3** (1B). With the upgraded VAE and Transformer architecture, the quality of our generated videos has been greatly improved 🚀. [[checkpoints]](#open-sora-13-model-weights) [[report]](/docs/report_04.md) [[demo]](https://huggingface.co/spaces/hpcai-tech/open-sora)\n- **[2024.12.23]** The development cost of video generation models has saved by 50%! Open-source solutions are now available with H200 GPU vouchers. [[blog]](https://company.hpc-ai.com/blog/the-development-cost-of-video-generation-models-has-saved-by-50-open-source-solutions-are-now-available-with-h200-gpu-vouchers) [[code]](https://github.com/hpcaitech/Open-Sora/blob/main/scripts/train.py) [[vouchers]](https://colossalai.org/zh-Hans/docs/get_started/bonus/)\n- **[2024.06.17]** We released **Open-Sora 1.2**, which includes **3D-VAE**, **rectified flow**, and **score condition**. The video quality is greatly improved. [[checkpoints]](#open-sora-12-model-weights) [[report]](/docs/report_03.md) [[arxiv]](https://arxiv.org/abs/2412.20404)\n- **[2024.04.25]** 🤗 We released the [Gradio demo for Open-Sora](https://huggingface.co/spaces/hpcai-tech/open-sora) on Hugging Face Spaces.\n- **[2024.04.25]** We released **Open-Sora 1.1**, which supports **2s~15s, 144p to 720p, any aspect ratio** text-to-image, **text-to-video, image-to-video, video-to-video, infinite time** generation. In addition, a full video processing pipeline is released. [[checkpoints]](#open-sora-11-model-weights) [[report]](/docs/report_02.md)\n- **[2024.03.18]** We released **Open-Sora 1.0**, a fully open-source project for video generation.\n  Open-Sora 1.0 supports a full pipeline of video data preprocessing, training with\n  <a href=\"https://github.com/hpcaitech/ColossalAI\"><img src=\"https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/colossal_ai.png\" width=\"8%\" ></a>\n  acceleration,\n  inference, and more. Our model can produce 2s 512x512 videos with only 3 days training. [[checkpoints]](#open-sora-10-model-weights)\n  [[blog]](https://hpc-ai.com/blog/open-sora-v1.0) [[report]](/docs/report_01.md)\n- **[2024.03.04]** Open-Sora provides training with 46% cost reduction.\n  [[blog]](https://hpc-ai.com/blog/open-sora)\n\n📍 Since Open-Sora is under active development, we remain different branches for different versions. The latest version is [main](https://github.com/hpcaitech/Open-Sora). Old versions include: [v1.0](https://github.com/hpcaitech/Open-Sora/tree/opensora/v1.0), [v1.1](https://github.com/hpcaitech/Open-Sora/tree/opensora/v1.1), [v1.2](https://github.com/hpcaitech/Open-Sora/tree/opensora/v1.2), [v1.3](https://github.com/hpcaitech/Open-Sora/tree/opensora/v1.3).\n\n## 🎥 Latest Demo\n\nDemos are presented in compressed GIF format for convenience. For original quality samples and their corresponding prompts, please visit our [Gallery](https://hpcaitech.github.io/Open-Sora/).\n\n| **5s 1024×576**                                                                                                                                    | **5s 576×1024**                                                                                                                                    | **5s 576×1024**                                                                                                                                   |\n| -------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |\n| [<img src=\"https://github.com/hpcaitech/Open-Sora-Demo/blob/main/demo/v2.0/ft_0001_1_1.gif\" width=\"\">](https://streamable.com/e/8g9y9h?autoplay=1) | [<img src=\"https://github.com/hpcaitech/Open-Sora-Demo/blob/main/demo/v2.0/movie_0160.gif\" width=\"\">](https://streamable.com/e/k50mnv?autoplay=1)  | [<img src=\"https://github.com/hpcaitech/Open-Sora-Demo/blob/main/demo/v2.0/movie_0017.gif\" width=\"\">](https://streamable.com/e/bzrn9n?autoplay=1) |\n| [<img src=\"https://github.com/hpcaitech/Open-Sora-Demo/blob/main/demo/v2.0/ft_0012_1_1.gif\" width=\"\">](https://streamable.com/e/dsv8da?autoplay=1) | [<img src=\"https://github.com/hpcaitech/Open-Sora-Demo/blob/main/demo/v2.0/douyin_0005.gif\" width=\"\">](https://streamable.com/e/3wif07?autoplay=1) | [<img src=\"https://github.com/hpcaitech/Open-Sora-Demo/blob/main/demo/v2.0/movie_0037.gif\" width=\"\">](https://streamable.com/e/us2w7h?autoplay=1) |\n| [<img src=\"https://github.com/hpcaitech/Open-Sora-Demo/blob/main/demo/v2.0/ft_0055_1_1.gif\" width=\"\">](https://streamable.com/e/yfwk8i?autoplay=1) | [<img src=\"https://github.com/hpcaitech/Open-Sora-Demo/blob/main/demo/v2.0/sora_0019.gif\" width=\"\">](https://streamable.com/e/jgjil0?autoplay=1)   | [<img src=\"https://github.com/hpcaitech/Open-Sora-Demo/blob/main/demo/v2.0/movie_0463.gif\" width=\"\">](https://streamable.com/e/lsoai1?autoplay=1) |\n\n<details>\n<summary>OpenSora 1.3 Demo</summary>\n\n| **5s 720×1280**                                                                                                                                                        | **5s 720×1280**                                                                                                                                                           | **5s 720×1280**                                                                                                                                                              |\n| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| [<img src=\"https://github.com/hpcaitech/Open-Sora-Demo/blob/main/demo/v1.3/demo_tomato.gif\" width=\"\">](https://streamable.com/e/r0imrp?quality=highest&amp;autoplay=1) | [<img src=\"https://github.com/hpcaitech/Open-Sora-Demo/blob/main/demo/v1.3/demo_fisherman.gif\" width=\"\">](https://streamable.com/e/hfvjkh?quality=highest&amp;autoplay=1) | [<img src=\"https://github.com/hpcaitech/Open-Sora-Demo/blob/main/demo/v1.3/demo_girl2.gif\" width=\"\">](https://streamable.com/e/kutmma?quality=highest&amp;autoplay=1)        |\n| [<img src=\"https://github.com/hpcaitech/Open-Sora-Demo/blob/main/demo/v1.3/demo_grape.gif\" width=\"\">](https://streamable.com/e/osn1la?quality=highest&amp;autoplay=1)  | [<img src=\"https://github.com/hpcaitech/Open-Sora-Demo/blob/main/demo/v1.3/demo_mushroom.gif\" width=\"\">](https://streamable.com/e/l1pzws?quality=highest&amp;autoplay=1)  | [<img src=\"https://github.com/hpcaitech/Open-Sora-Demo/blob/main/demo/v1.3/demo_parrot.gif\" width=\"\">](https://streamable.com/e/2vqari?quality=highest&amp;autoplay=1)       |\n| [<img src=\"https://github.com/hpcaitech/Open-Sora-Demo/blob/main/demo/v1.3/demo_trans.gif\" width=\"\">](https://streamable.com/e/1in7d6?quality=highest&amp;autoplay=1)  | [<img src=\"https://github.com/hpcaitech/Open-Sora-Demo/blob/main/demo/v1.3/demo_bear.gif\" width=\"\">](https://streamable.com/e/e9bi4o?quality=highest&amp;autoplay=1)      | [<img src=\"https://github.com/hpcaitech/Open-Sora-Demo/blob/main/demo/v1.3/demo_futureflower.gif\" width=\"\">](https://streamable.com/e/09z7xi?quality=highest&amp;autoplay=1) |\n| [<img src=\"https://github.com/hpcaitech/Open-Sora-Demo/blob/main/demo/v1.3/demo_fire.gif\" width=\"\">](https://streamable.com/e/16c3hk?quality=highest&amp;autoplay=1)   | [<img src=\"https://github.com/hpcaitech/Open-Sora-Demo/blob/main/demo/v1.3/demo_man.gif\" width=\"\">](https://streamable.com/e/wi250w?quality=highest&amp;autoplay=1)       | [<img src=\"https://github.com/hpcaitech/Open-Sora-Demo/blob/main/demo/v1.3/demo_black.gif\" width=\"\">](https://streamable.com/e/vw5b64?quality=highest&amp;autoplay=1)        |\n\n</details>\n\n<details>\n<summary>OpenSora 1.2 Demo</summary>\n\n| **4s 720×1280**                                                                                                                                                                                     | **4s 720×1280**                                                                                                                                                                                     | **4s 720×1280**                                                                                                                                                                                     |\n| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| [<img src=\"https://github.com/hpcaitech/Open-Sora-Demo/blob/main/demo/v1.2/sample_0013.gif\" width=\"\">](https://github.com/hpcaitech/Open-Sora/assets/99191637/7895aab6-ed23-488c-8486-091480c26327) | [<img src=\"https://github.com/hpcaitech/Open-Sora-Demo/blob/main/demo/v1.2/sample_1718.gif\" width=\"\">](https://github.com/hpcaitech/Open-Sora/assets/99191637/20f07c7b-182b-4562-bbee-f1df74c86c9a) | [<img src=\"https://github.com/hpcaitech/Open-Sora-Demo/blob/main/demo/v1.2/sample_0087.gif\" width=\"\">](https://github.com/hpcaitech/Open-Sora/assets/99191637/3d897e0d-dc21-453a-b911-b3bda838acc2) |\n| [<img src=\"https://github.com/hpcaitech/Open-Sora-Demo/blob/main/demo/v1.2/sample_0052.gif\" width=\"\">](https://github.com/hpcaitech/Open-Sora/assets/99191637/644bf938-96ce-44aa-b797-b3c0b513d64c) | [<img src=\"https://github.com/hpcaitech/Open-Sora-Demo/blob/main/demo/v1.2/sample_1719.gif\" width=\"\">](https://github.com/hpcaitech/Open-Sora/assets/99191637/272d88ac-4b4a-484d-a665-8d07431671d0) | [<img src=\"https://github.com/hpcaitech/Open-Sora-Demo/blob/main/demo/v1.2/sample_0002.gif\" width=\"\">](https://github.com/hpcaitech/Open-Sora/assets/99191637/ebbac621-c34e-4bb4-9543-1c34f8989764) |\n| [<img src=\"https://github.com/hpcaitech/Open-Sora-Demo/blob/main/demo/v1.2/sample_0011.gif\" width=\"\">](https://github.com/hpcaitech/Open-Sora/assets/99191637/a1e3a1a3-4abd-45f5-8df2-6cced69da4ca) | [<img src=\"https://github.com/hpcaitech/Open-Sora-Demo/blob/main/demo/v1.2/sample_0004.gif\" width=\"\">](https://github.com/hpcaitech/Open-Sora/assets/99191637/d6ce9c13-28e1-4dff-9644-cc01f5f11926) | [<img src=\"https://github.com/hpcaitech/Open-Sora-Demo/blob/main/demo/v1.2/sample_0061.gif\" width=\"\">](https://github.com/hpcaitech/Open-Sora/assets/99191637/561978f8-f1b0-4f4d-ae7b-45bec9001b4a) |\n\n</details>\n\n<details>\n<summary>OpenSora 1.1 Demo</summary>\n\n| **2s 240×426**                                                                                                                                                                                                  | **2s 240×426**                                                                                                                                                                                                 |\n| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| [<img src=\"https://github.com/hpcaitech/Open-Sora-Demo/blob/main/demo/v1.1/sample_16x240x426_9.gif\" width=\"\">](https://github.com/hpcaitech/Open-Sora-dev/assets/99191637/c31ebc52-de39-4a4e-9b1e-9211d45e05b2) | [<img src=\"https://github.com/hpcaitech/Open-Sora-Demo/blob/main/demo/v1.1/sora_16x240x426_26.gif\" width=\"\">](https://github.com/hpcaitech/Open-Sora-dev/assets/99191637/c31ebc52-de39-4a4e-9b1e-9211d45e05b2) |\n| [<img src=\"https://github.com/hpcaitech/Open-Sora-Demo/blob/main/demo/v1.1/sora_16x240x426_27.gif\" width=\"\">](https://github.com/hpcaitech/Open-Sora-dev/assets/99191637/f7ce4aaa-528f-40a8-be7a-72e61eaacbbd)  | [<img src=\"https://github.com/hpcaitech/Open-Sora-Demo/blob/main/demo/v1.1/sora_16x240x426_40.gif\" width=\"\">](https://github.com/hpcaitech/Open-Sora-dev/assets/99191637/5d58d71e-1fda-4d90-9ad3-5f2f7b75c6a9) |\n\n| **2s 426×240**                                                                                                                                                                                                 | **4s 480×854**                                                                                                                                                                                                  |\n| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| [<img src=\"https://github.com/hpcaitech/Open-Sora-Demo/blob/main/demo/v1.1/sora_16x426x240_24.gif\" width=\"\">](https://github.com/hpcaitech/Open-Sora-dev/assets/99191637/34ecb4a0-4eef-4286-ad4c-8e3a87e5a9fd) | [<img src=\"https://github.com/hpcaitech/Open-Sora-Demo/blob/main/demo/v1.1/sample_32x480x854_9.gif\" width=\"\">](https://github.com/hpcaitech/Open-Sora-dev/assets/99191637/c1619333-25d7-42ba-a91c-18dbc1870b18) |\n\n| **16s 320×320**                                                                                                                                                                                            | **16s 224×448**                                                                                                                                                                                            | **2s 426×240**                                                                                                                                                                                                |\n| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| [<img src=\"https://github.com/hpcaitech/Open-Sora-Demo/blob/main/demo/v1.1/sample_16s_320x320.gif\" width=\"\">](https://github.com/hpcaitech/Open-Sora/assets/99191637/3cab536e-9b43-4b33-8da8-a0f9cf842ff2) | [<img src=\"https://github.com/hpcaitech/Open-Sora-Demo/blob/main/demo/v1.1/sample_16s_224x448.gif\" width=\"\">](https://github.com/hpcaitech/Open-Sora/assets/99191637/9fb0b9e0-c6f4-4935-b29e-4cac10b373c4) | [<img src=\"https://github.com/hpcaitech/Open-Sora-Demo/blob/main/demo/v1.1/sora_16x426x240_3.gif\" width=\"\">](https://github.com/hpcaitech/Open-Sora-dev/assets/99191637/3e892ad2-9543-4049-b005-643a4c1bf3bf) |\n\n</details>\n\n<details>\n<summary>OpenSora 1.0 Demo</summary>\n\n| **2s 512×512**                                                                                                                                                                                   | **2s 512×512**                                                                                                                                                                                   | **2s 512×512**                                                                                                                                                                                   |\n| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |\n| [<img src=\"https://github.com/hpcaitech/Open-Sora-Demo/blob/main/demo/v1.0/sample_0.gif\" width=\"\">](https://github.com/hpcaitech/Open-Sora/assets/99191637/de1963d3-b43b-4e68-a670-bb821ebb6f80) | [<img src=\"https://github.com/hpcaitech/Open-Sora-Demo/blob/main/demo/v1.0/sample_1.gif\" width=\"\">](https://github.com/hpcaitech/Open-Sora/assets/99191637/13f8338f-3d42-4b71-8142-d234fbd746cc) | [<img src=\"https://github.com/hpcaitech/Open-Sora-Demo/blob/main/demo/v1.0/sample_2.gif\" width=\"\">](https://github.com/hpcaitech/Open-Sora/assets/99191637/fa6a65a6-e32a-4d64-9a9e-eabb0ebb8c16) |\n| A serene night scene in a forested area. [...] The video is a time-lapse, capturing the transition from day to night, with the lake and forest serving as a constant backdrop.                   | A soaring drone footage captures the majestic beauty of a coastal cliff, [...] The water gently laps at the rock base and the greenery that clings to the top of the cliff.                      | The majestic beauty of a waterfall cascading down a cliff into a serene lake. [...] The camera angle provides a bird's eye view of the waterfall.                                                |\n| [<img src=\"https://github.com/hpcaitech/Open-Sora-Demo/blob/main/demo/v1.0/sample_3.gif\" width=\"\">](https://github.com/hpcaitech/Open-Sora/assets/99191637/64232f84-1b36-4750-a6c0-3e610fa9aa94) | [<img src=\"https://github.com/hpcaitech/Open-Sora-Demo/blob/main/demo/v1.0/sample_4.gif\" width=\"\">](https://github.com/hpcaitech/Open-Sora/assets/99191637/983a1965-a374-41a7-a76b-c07941a6c1e9) | [<img src=\"https://github.com/hpcaitech/Open-Sora-Demo/blob/main/demo/v1.0/sample_5.gif\" width=\"\">](https://github.com/hpcaitech/Open-Sora/assets/99191637/ec10c879-9767-4c31-865f-2e8d6cf11e65) |\n| A bustling city street at night, filled with the glow of car headlights and the ambient light of streetlights. [...]                                                                             | The vibrant beauty of a sunflower field. The sunflowers are arranged in neat rows, creating a sense of order and symmetry. [...]                                                                 | A serene underwater scene featuring a sea turtle swimming through a coral reef. The turtle, with its greenish-brown shell [...]                                                                  |\n\nVideos are downsampled to `.gif` for display. Click for original videos. Prompts are trimmed for display,\nsee [here](/assets/texts/t2v_samples.txt) for full prompts.\n\n</details>\n\n## 🔆 Reports\n\n- **[Tech Report of Open-Sora 2.0](https://arxiv.org/abs/2503.09642v1)**\n- **[Step by step to train or finetune your own model](docs/train.md)**\n- **[Step by step to train and evaluate an video autoencoder](docs/ae.md)**\n- **[Visit the high compression video autoencoder](docs/hcae.md)**\n- Reports of previous version (better see in according branch):\n  - [Open-Sora 1.3](docs/report_04.md): shift-window attention, unified spatial-temporal VAE, etc.\n  - [Open-Sora 1.2](docs/report_03.md), [Tech Report](https://arxiv.org/abs/2412.20404): rectified flow, 3d-VAE, score condition, evaluation, etc.\n  - [Open-Sora 1.1](docs/report_02.md): multi-resolution/length/aspect-ratio, image/video conditioning/editing, data preprocessing, etc.\n  - [Open-Sora 1.0](docs/report_01.md): architecture, captioning, etc.\n\n📍 Since Open-Sora is under active development, we remain different branches for different versions. The latest version is [main](https://github.com/hpcaitech/Open-Sora). Old versions include: [v1.0](https://github.com/hpcaitech/Open-Sora/tree/opensora/v1.0), [v1.1](https://github.com/hpcaitech/Open-Sora/tree/opensora/v1.1), [v1.2](https://github.com/hpcaitech/Open-Sora/tree/opensora/v1.2), [v1.3](https://github.com/hpcaitech/Open-Sora/tree/opensora/v1.3).\n\n## Quickstart\n\n### Installation\n\n```bash\n# create a virtual env and activate (conda as an example)\nconda create -n opensora python=3.10\nconda activate opensora\n\n# download the repo\ngit clone https://github.com/hpcaitech/Open-Sora\ncd Open-Sora\n\n# Ensure torch >= 2.4.0\npip install -v . # for development mode, `pip install -v -e .`\npip install xformers==0.0.27.post2 --index-url https://download.pytorch.org/whl/cu121 # install xformers according to your cuda version\npip install flash-attn --no-build-isolation\n```\n\nOptionally, you can install flash attention 3 for faster speed.\n\n```bash\ngit clone https://github.com/Dao-AILab/flash-attention # 4f0640d5\ncd flash-attention/hopper\npython setup.py install\n```\n\n### Model Download\n\nOur 11B model supports 256px and 768px resolution. Both T2V and I2V are supported by one model. 🤗 [Huggingface](https://huggingface.co/hpcai-tech/Open-Sora-v2) 🤖 [ModelScope](https://modelscope.cn/models/luchentech/Open-Sora-v2).\n\nDownload from huggingface:\n\n```bash\npip install \"huggingface_hub[cli]\"\nhuggingface-cli download hpcai-tech/Open-Sora-v2 --local-dir ./ckpts\n```\n\nDownload from ModelScope:\n\n```bash\npip install modelscope\nmodelscope download hpcai-tech/Open-Sora-v2 --local_dir ./ckpts\n```\n\n### Text-to-Video Generation\n\nOur model is optimized for image-to-video generation, but it can also be used for text-to-video generation. To generate high quality videos, with the help of flux text-to-image model, we build a text-to-image-to-video pipeline. For 256x256 resolution:\n\n```bash\n# Generate one given prompt\ntorchrun --nproc_per_node 1 --standalone scripts/diffusion/inference.py configs/diffusion/inference/t2i2v_256px.py --save-dir samples --prompt \"raining, sea\"\n\n# Save memory with offloading\ntorchrun --nproc_per_node 1 --standalone scripts/diffusion/inference.py configs/diffusion/inference/t2i2v_256px.py --save-dir samples --prompt \"raining, sea\" --offload True\n\n# Generation with csv\ntorchrun --nproc_per_node 1 --standalone scripts/diffusion/inference.py configs/diffusion/inference/t2i2v_256px.py --save-dir samples --dataset.data-path assets/texts/example.csv\n```\n\nFor 768x768 resolution:\n\n```bash\n# One GPU\ntorchrun --nproc_per_node 1 --standalone scripts/diffusion/inference.py configs/diffusion/inference/t2i2v_768px.py --save-dir samples --prompt \"raining, sea\"\n\n# Multi-GPU with colossalai sp\ntorchrun --nproc_per_node 8 --standalone scripts/diffusion/inference.py configs/diffusion/inference/t2i2v_768px.py --save-dir samples --prompt \"raining, sea\"\n```\n\nYou can adjust the generation aspect ratio by `--aspect_ratio` and the generation length by `--num_frames`. Candidate values for aspect_ratio includes `16:9`, `9:16`, `1:1`, `2.39:1`. Candidate values for num_frames should be `4k+1` and less than 129.\n\nYou can also run direct text-to-video by:\n\n```bash\n# One GPU for 256px\ntorchrun --nproc_per_node 1 --standalone scripts/diffusion/inference.py configs/diffusion/inference/256px.py --prompt \"raining, sea\"\n# Multi-GPU for 768px\ntorchrun --nproc_per_node 8 --standalone scripts/diffusion/inference.py configs/diffusion/inference/768px.py --prompt \"raining, sea\"\n```\n\n### Image-to-Video Generation\n\nGiven a prompt and a reference image, you can generate a video with the following command:\n\n```bash\n# 256px\ntorchrun --nproc_per_node 1 --standalone scripts/diffusion/inference.py configs/diffusion/inference/256px.py --cond_type i2v_head --prompt \"A plump pig wallows in a muddy pond on a rustic farm, its pink snout poking out as it snorts contentedly. The camera captures the pig's playful splashes, sending ripples through the water under the midday sun. Wooden fences and a red barn stand in the background, framed by rolling green hills. The pig's muddy coat glistens in the sunlight, showcasing the simple pleasures of its carefree life.\" --ref assets/texts/i2v.png\n\n# 256px with csv\ntorchrun --nproc_per_node 1 --standalone scripts/diffusion/inference.py configs/diffusion/inference/256px.py --cond_type i2v_head --dataset.data-path assets/texts/i2v.csv\n\n# Multi-GPU 768px\ntorchrun --nproc_per_node 8 --standalone scripts/diffusion/inference.py configs/diffusion/inference/768px.py --cond_type i2v_head --dataset.data-path assets/texts/i2v.csv\n```\n\n## Advanced Usage\n\n### Motion Score\n\nDuring training, we provide motion score into the text prompt. During inference, you can use the following command to generate videos with motion score (the default score is 4):\n\n```bash\ntorchrun --nproc_per_node 1 --standalone scripts/diffusion/inference.py configs/diffusion/inference/t2i2v_256px.py --save-dir samples --prompt \"raining, sea\" --motion-score 4\n```\n\nWe also provide a dynamic motion score evaluator. After setting your OpenAI API key, you can use the following command to evaluate the motion score of a video:\n\n```bash\ntorchrun --nproc_per_node 1 --standalone scripts/diffusion/inference.py configs/diffusion/inference/t2i2v_256px.py --save-dir samples --prompt \"raining, sea\" --motion-score dynamic\n```\n\n| Score | 1                                                                                                       | 4                                                                                                       | 7                                                                                                       |\n| ----- | ------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- |\n|       | <img src=\"https://github.com/hpcaitech/Open-Sora-Demo/blob/main/demo/v2.0/motion_score_1.gif\" width=\"\"> | <img src=\"https://github.com/hpcaitech/Open-Sora-Demo/blob/main/demo/v2.0/motion_score_4.gif\" width=\"\"> | <img src=\"https://github.com/hpcaitech/Open-Sora-Demo/blob/main/demo/v2.0/motion_score_7.gif\" width=\"\"> |\n\n### Prompt Refine\n\nWe take advantage of ChatGPT to refine the prompt. You can use the following command to refine the prompt. The function is available for both text-to-video and image-to-video generation.\n\n```bash\nexport OPENAI_API_KEY=sk-xxxx\ntorchrun --nproc_per_node 1 --standalone scripts/diffusion/inference.py configs/diffusion/inference/t2i2v_256px.py --save-dir samples --prompt \"raining, sea\" --refine-prompt True\n```\n\n### Reproductivity\n\nTo make the results reproducible, you can set the random seed by:\n\n```bash\ntorchrun --nproc_per_node 1 --standalone scripts/diffusion/inference.py configs/diffusion/inference/t2i2v_256px.py --save-dir samples --prompt \"raining, sea\" --sampling_option.seed 42 --seed 42\n```\n\nUse `--num-sample k` to generate `k` samples for each prompt.\n\n## Computational Efficiency\n\nWe test the computational efficiency of text-to-video on H100/H800 GPU. For 256x256, we use colossalai's tensor parallelism, and `--offload True` is used. For 768x768, we use colossalai's sequence parallelism. All use number of steps 50. The results are presented in the format: $\\color{blue}{\\text{Total time (s)}}/\\color{red}{\\text{peak GPU memory (GB)}}$\n\n| Resolution | 1x GPU                                 | 2x GPUs                               | 4x GPUs                               | 8x GPUs                               |\n| ---------- | -------------------------------------- | ------------------------------------- | ------------------------------------- | ------------------------------------- |\n| 256x256    | $\\color{blue}{60}/\\color{red}{52.5}$   | $\\color{blue}{40}/\\color{red}{44.3}$  | $\\color{blue}{34}/\\color{red}{44.3}$  |                                       |\n| 768x768    | $\\color{blue}{1656}/\\color{red}{60.3}$ | $\\color{blue}{863}/\\color{red}{48.3}$ | $\\color{blue}{466}/\\color{red}{44.3}$ | $\\color{blue}{276}/\\color{red}{44.3}$ |\n\n## Evaluation\n\nOn [VBench](https://huggingface.co/spaces/Vchitect/VBench_Leaderboard), Open-Sora 2.0 significantly narrows the gap with OpenAI’s Sora, reducing it from 4.52% → 0.69% compared to Open-Sora 1.2.\n\n![VBench](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/v2_vbench.png)\n\nHuman preference results show our model is on par with HunyuanVideo 11B and Step-Video 30B.\n\n![Win Rate](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/v2_winrate.png)\n\nWith strong performance, Open-Sora 2.0 is cost-effective.\n\n![Cost](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/v2_cost.png)\n\n## Contribution\n\nThanks goes to these wonderful contributors:\n\n<a href=\"https://github.com/hpcaitech/Open-Sora/graphs/contributors\">\n  <img src=\"https://contrib.rocks/image?repo=hpcaitech/Open-Sora\" />\n</a>\n\nIf you wish to contribute to this project, please refer to the [Contribution Guideline](./CONTRIBUTING.md).\n\n## Acknowledgement\n\nHere we only list a few of the projects. For other works and datasets, please refer to our report.\n\n- [ColossalAI](https://github.com/hpcaitech/ColossalAI): A powerful large model parallel acceleration and optimization\n  system.\n- [DiT](https://github.com/facebookresearch/DiT): Scalable Diffusion Models with Transformers.\n- [OpenDiT](https://github.com/NUS-HPC-AI-Lab/OpenDiT): An acceleration for DiT training. We adopt valuable acceleration\n  strategies for training progress from OpenDiT.\n- [PixArt](https://github.com/PixArt-alpha/PixArt-alpha): An open-source DiT-based text-to-image model.\n- [Flux](https://github.com/black-forest-labs/flux): A powerful text-to-image generation model.\n- [Latte](https://github.com/Vchitect/Latte): An attempt to efficiently train DiT for video.\n- [HunyuanVideo](https://github.com/Tencent/HunyuanVideo/tree/main?tab=readme-ov-file): Open-Source text-to-video model.\n- [StabilityAI VAE](https://huggingface.co/stabilityai/sd-vae-ft-mse-original): A powerful image VAE model.\n- [DC-AE](https://github.com/mit-han-lab/efficientvit): Deep Compression AutoEncoder for image compression.\n- [CLIP](https://github.com/openai/CLIP): A powerful text-image embedding model.\n- [T5](https://github.com/google-research/text-to-text-transfer-transformer): A powerful text encoder.\n- [LLaVA](https://github.com/haotian-liu/LLaVA): A powerful image captioning model based on [Mistral-7B](https://huggingface.co/mistralai/Mistral-7B-v0.1) and [Yi-34B](https://huggingface.co/01-ai/Yi-34B).\n- [PLLaVA](https://github.com/magic-research/PLLaVA): A powerful video captioning model.\n- [MiraData](https://github.com/mira-space/MiraData): A large-scale video dataset with long durations and structured caption.\n\n## Citation\n\n```bibtex\n@article{opensora,\n  title={Open-sora: Democratizing efficient video production for all},\n  author={Zheng, Zangwei and Peng, Xiangyu and Yang, Tianji and Shen, Chenhui and Li, Shenggui and Liu, Hongxin and Zhou, Yukun and Li, Tianyi and You, Yang},\n  journal={arXiv preprint arXiv:2412.20404},\n  year={2024}\n}\n\n@article{opensora2,\n    title={Open-Sora 2.0: Training a Commercial-Level Video Generation Model in $200k}, \n    author={Xiangyu Peng and Zangwei Zheng and Chenhui Shen and Tom Young and Xinying Guo and Binluo Wang and Hang Xu and Hongxin Liu and Mingyan Jiang and Wenjun Li and Yuhui Wang and Anbang Ye and Gang Ren and Qianran Ma and Wanying Liang and Xiang Lian and Xiwen Wu and Yuting Zhong and Zhuangyan Li and Chaoyu Gong and Guojun Lei and Leijun Cheng and Limin Zhang and Minghao Li and Ruijie Zhang and Silan Hu and Shijie Huang and Xiaokang Wang and Yuanheng Zhao and Yuqi Wang and Ziang Wei and Yang You},\n    year={2025},\n    journal={arXiv preprint arXiv:2503.09642},\n}\n```\n\n## Star History\n\n[![Star History Chart](https://api.star-history.com/svg?repos=hpcaitech/Open-Sora&type=Date)](https://star-history.com/#hpcaitech/Open-Sora&Date)\n"
  },
  {
    "path": "assets/texts/example.csv",
    "content": "text\n\"Imagine a cyberpunk close-up shot capturing the upper body of a character with an melancholic demeanor. The subject is gesturing with one hand while shaking the head, showcasing natural body language. The background features a vibrant carnival, complementing the character's pose. The lighting is dim and moody, emphasizing the contours of their face and upper body. The camera subtly pans or zooms, drawing attention to the harmony between expression, posture, and setting.\"\n\"A sleek red sports car speeds through a winding mountain road, its engine roaring against the backdrop of towering snow-capped peaks. The sunlight glints off the polished surface, creating dazzling reflections. The camera pans to capture the lush greenery surrounding the road. The atmosphere is exhilarating, with a cinematic style emphasizing speed and adventure. The lighting is golden, suggesting early morning or late afternoon.\"\n\"A group of fluffy baby chicks huddle together under a heat lamp in a rustic barn. Their soft peeping fills the air as they nudge each other for warmth. The wooden floor beneath them is strewn with straw, and the gentle light creates a cozy, heartwarming atmosphere. The video captures their tiny, detailed movements in a close-up, realistic style.\"\n\"A black-and-white film of a pianist playing in an empty theater. His fingers move deftly across the keys, the music echoing in the large, empty hall. Dust motes float in the air, caught in the faint light streaming through the high windows. The grand piano gleams under the spotlight, contrasting with the decaying seats and peeling walls. The atmosphere is haunting and nostalgic.\"\n\"A wave of glowing steam crashes into a stone wall, the vapor hissing and swirling as it dissipates.\"\n\"A tomato surfing on a piece of lettuce down a waterfall of ranch dressing, with exaggerated surfing moves and creamy wave effects to highlight the 3D animated fun.\"\n\"A cheerful panda on a bustling city street, casually playing a violin while sitting on a bench. People passing by stop to enjoy the impromptu performance, and a group of children dance around, clapping their hands to the upbeat tempo. The panda’s paws move swiftly, creating a lively tune that brings a sense of joy and energy to the urban scene.\"\n\"A shimmering, crystalline city built into the side of a massive mountain on a distant planet. Waterfalls of liquid light cascade down the cliffs, with hovering bridges connecting the structures. The entire city glows as it absorbs energy from the planet’s core.\"\n"
  },
  {
    "path": "assets/texts/i2v.csv",
    "content": "text,ref\n\"A plump pig wallows in a muddy pond on a rustic farm, its pink snout poking out as it snorts contentedly. The camera captures the pig's playful splashes, sending ripples through the water under the midday sun. Wooden fences and a red barn stand in the background, framed by rolling green hills. The pig's muddy coat glistens in the sunlight, showcasing the simple pleasures of its carefree life.\",assets/texts/i2v.png\n"
  },
  {
    "path": "assets/texts/sora.csv",
    "content": "text\n\"A stylish woman walks down a Tokyo street filled with warm glowing neon and animated city signage. She wears a black leather jacket, a long red dress, and black boots, and carries a black purse. She wears sunglasses and red lipstick. She walks confidently and casually. The street is damp and reflective, creating a mirror effect of the colorful lights. Many pedestrians walk about.\"\n\"Several giant wooly mammoths approach treading through a snowy meadow, their long wooly fur lightly blows in the wind as they walk, snow covered trees and dramatic snow capped mountains in the distance, mid afternoon light with wispy clouds and a sun high in the distance creates a warm glow, the low camera view is stunning capturing the large furry mammal with beautiful photography, depth of field.\"\n\"A movie trailer featuring the adventures of the 30 year old space man wearing a red wool knitted motorcycle helmet, blue sky, salt desert, cinematic style, shot on 35mm film, vivid colors.\"\n\"Drone view of waves crashing against the rugged cliffs along Big Sur's garay point beach. The crashing blue waters create white-tipped waves, while the golden light of the setting sun illuminates the rocky shore. A small island with a lighthouse sits in the distance, and green shrubbery covers the cliff's edge. The steep drop from the road down to the beach is a dramatic feat, with the cliff's edges jutting out over the sea. This is a view that captures the raw beauty of the coast and the rugged landscape of the Pacific Coast Highway.\"\n\"Animated scene features a close-up of a short fluffy monster kneeling beside a melting red candle. The art style is 3D and realistic, with a focus on lighting and texture. The mood of the painting is one of wonder and curiosity, as the monster gazes at the flame with wide eyes and open mouth. Its pose and expression convey a sense of innocence and playfulness, as if it is exploring the world around it for the first time. The use of warm colors and dramatic lighting further enhances the cozy atmosphere of the image.\"\n\"A gorgeously rendered papercraft world of a coral reef, rife with colorful fish and sea creatures.\"\n\"This close-up shot of a Victoria crowned pigeon showcases its striking blue plumage and red chest. Its crest is made of delicate, lacy feathers, while its eye is a striking red color. The bird's head is tilted slightly to the side, giving the impression of it looking regal and majestic. The background is blurred, drawing attention to the bird's striking appearance.\"\nPhotorealistic closeup video of two pirate ships battling each other as they sail inside a cup of coffee.\n\"A young man at his 20s is sitting on a piece of cloud in the sky, reading a book.\"\nHistorical footage of California during the gold rush.\nA close up view of a glass sphere that has a zen garden within it. There is a small dwarf in the sphere who is raking the zen garden and creating patterns in the sand.\n\"Extreme close up of a 24 year old woman's eye blinking, standing in Marrakech during magic hour, cinematic film shot in 70mm, depth of field, vivid colors, cinematic\"\nA cartoon kangaroo disco dances.\n\"A beautiful homemade video showing the people of Lagos, Nigeria in the year 2056. Shot with a mobile phone camera.\"\nA petri dish with a bamboo forest growing within it that has tiny red pandas running around.\n\"The camera rotates around a large stack of vintage televisions all showing different programs — 1950s sci-fi movies, horror movies, news, static, a 1970s sitcom, etc, set inside a large New York museum gallery.\"\n\"3D animation of a small, round, fluffy creature with big, expressive eyes explores a vibrant, enchanted forest. The creature, a whimsical blend of a rabbit and a squirrel, has soft blue fur and a bushy, striped tail. It hops along a sparkling stream, its eyes wide with wonder. The forest is alive with magical elements: flowers that glow and change colors, trees with leaves in shades of purple and silver, and small floating lights that resemble fireflies. The creature stops to interact playfully with a group of tiny, fairy-like beings dancing around a mushroom ring. The creature looks up in awe at a large, glowing tree that seems to be the heart of the forest.\"\n\"The camera follows behind a white vintage SUV with a black roof rack as it speeds up a steep dirt road surrounded by pine trees on a steep mountain slope, dust kicks up from it's tires, the sunlight shines on the SUV as it speeds along the dirt road, casting a warm glow over the scene. The dirt road curves gently into the distance, with no other cars or vehicles in sight. The trees on either side of the road are redwoods, with patches of greenery scattered throughout. The car is seen from the rear following the curve with ease, making it seem as if it is on a rugged drive through the rugged terrain. The dirt road itself is surrounded by steep hills and mountains, with a clear blue sky above with wispy clouds.\"\nReflections in the window of a train traveling through the Tokyo suburbs.\n\"A drone camera circles around a beautiful historic church built on a rocky outcropping along the Amalfi Coast, the view showcases historic and magnificent architectural details and tiered pathways and patios, waves are seen crashing against the rocks below as the view overlooks the horizon of the coastal waters and hilly landscapes of the Amalfi Coast Italy, several distant people are seen walking and enjoying vistas on patios of the dramatic ocean views, the warm glow of the afternoon sun creates a magical and romantic feeling to the scene, the view is stunning captured with beautiful photography.\"\n\"A large orange octopus is seen resting on the bottom of the ocean floor, blending in with the sandy and rocky terrain. Its tentacles are spread out around its body, and its eyes are closed. The octopus is unaware of a king crab that is crawling towards it from behind a rock, its claws raised and ready to attack. The crab is brown and spiny, with long legs and antennae. The scene is captured from a wide angle, showing the vastness and depth of the ocean. The water is clear and blue, with rays of sunlight filtering through. The shot is sharp and crisp, with a high dynamic range. The octopus and the crab are in focus, while the background is slightly blurred, creating a depth of field effect.\"\n\"A flock of paper airplanes flutters through a dense jungle, weaving around trees as if they were migrating birds.\"\n\"A cat waking up its sleeping owner demanding breakfast. The owner tries to ignore the cat, but the cat tries new tactics and finally the owner pulls out a secret stash of treats from under the pillow to hold the cat off a little longer.\"\nBorneo wildlife on the Kinabatangan River\nA Chinese Lunar New Year celebration video with Chinese Dragon.\nTour of an art gallery with many beautiful works of art in different styles.\n\"Beautiful, snowy Tokyo city is bustling. The camera moves through the bustling city street, following several people enjoying the beautiful snowy weather and shopping at nearby stalls. Gorgeous sakura petals are flying through the wind along with snowflakes.\"\nA stop motion animation of a flower growing out of the windowsill of a suburban house.\nThe story of a robot's life in a cyberpunk setting.\n\"An extreme close-up of an gray-haired man with a beard in his 60s, he is deep in thought pondering the history of the universe as he sits at a cafe in Paris, his eyes focus on people offscreen as they walk as he sits mostly motionless, he is dressed in a wool coat suit coat with a button-down shirt , he wears a brown beret and glasses and has a very professorial appearance, and the end he offers a subtle closed-mouth smile as if he found the answer to the mystery of life, the lighting is very cinematic with the golden light and the Parisian streets and city in the background, depth of field, cinematic 35mm film.\"\n\"A beautiful silhouette animation shows a wolf howling at the moon, feeling lonely, until it finds its pack.\"\n\"New York City submerged like Atlantis. Fish, whales, sea turtles and sharks swim through the streets of New York.\"\n\"A litter of golden retriever puppies playing in the snow. Their heads pop out of the snow, covered in.\"\n\"Step-printing scene of a person running, cinematic film shot in 35mm.\"\n\"Five gray wolf pups frolicking and chasing each other around a remote gravel road, surrounded by grass. The pups run and leap, chasing each other, and nipping at each other, playing.\"\nBasketball through hoop then explodes.\n\"Archeologists discover a generic plastic chair in the desert, excavating and dusting it with great care.\"\n\"A grandmother with neatly combed grey hair stands behind a colorful birthday cake with numerous candles at a wood dining room table, expression is one of pure joy and happiness, with a happy glow in her eye. She leans forward and blows out the candles with a gentle puff, the cake has pink frosting and sprinkles and the candles cease to flicker, the grandmother wears a light blue blouse adorned with floral patterns, several happy friends and family sitting at the table can be seen celebrating, out of focus. The scene is beautifully captured, cinematic, showing a 3/4 view of the grandmother and the dining room. Warm color tones and soft lighting enhance the mood.\"\nThe camera directly faces colorful buildings in Burano Italy. An adorable dalmation looks through a window on a building on the ground floor. Many people are walking and cycling along the canal streets in front of the buildings.\n\"An adorable happy otter confidently stands on a surfboard wearing a yellow lifejacket, riding along turquoise tropical waters near lush tropical islands, 3D digital render art style.\"\n\"This close-up shot of a chameleon showcases its striking color changing capabilities. The background is blurred, drawing attention to the animal's striking appearance.\"\nA corgi vlogging itself in tropical Maui.\n\"A white and orange tabby cat is seen happily darting through a dense garden, as if chasing something. Its eyes are wide and happy as it jogs forward, scanning the branches, flowers, and leaves as it walks. The path is narrow as it makes its way between all the plants. the scene is captured from a ground-level angle, following the cat closely, giving a low and intimate perspective. The image is cinematic with warm tones and a grainy texture. The scattered daylight between the leaves and plants above creates a warm contrast, accentuating the cat's orange fur. The shot is clear and sharp, with a shallow depth of field.\"\n\"Aerial view of Santorini during the blue hour, showcasing the stunning architecture of white Cycladic buildings with blue domes. The caldera views are breathtaking, and the lighting creates a beautiful, serene atmosphere.\"\n\"Tiltshift of a construction site filled with workers, equipment, and heavy machinery.\"\n\"A giant, towering cloud in the shape of a man looms over the earth. The cloud man shoots lighting bolts down to the earth.\"\nA Samoyed and a Golden Retriever dog are playfully romping through a futuristic neon city at night. The neon lights emitted from the nearby buildings glistens off of their fur.\n\"The Glenfinnan Viaduct is a historic railway bridge in Scotland, UK, that crosses over the west highland line between the towns of Mallaig and Fort William. It is a stunning sight as a steam train leaves the bridge, traveling over the arch-covered viaduct. The landscape is dotted with lush greenery and rocky mountains, creating a picturesque backdrop for the train journey. The sky is blue and the sun is shining, making for a beautiful day to explore this majestic spot.\"\n"
  },
  {
    "path": "configs/diffusion/inference/256px.py",
    "content": "save_dir = \"samples\"  # save directory\nseed = 42  # random seed (except seed for z)\nbatch_size = 1\ndtype = \"bf16\"\n\ncond_type = \"t2v\"\n# conditional inference options:\n# t2v: text-to-video\n# i2v_head: image-to-video (head)\n# i2v_tail: image-to-video (tail)\n# i2v_loop: connect images\n# v2v_head_half: video extension with first half\n# v2v_tail_half: video extension with second half\n\ndataset = dict(type=\"text\")\nsampling_option = dict(\n    resolution=\"256px\",  # 256px or 768px\n    aspect_ratio=\"16:9\",  # 9:16 or 16:9 or 1:1\n    num_frames=129,  # number of frames\n    num_steps=50,  # number of steps\n    shift=True,\n    temporal_reduction=4,\n    is_causal_vae=True,\n    guidance=7.5,  # guidance for text-to-video\n    guidance_img=3.0,  # guidance for image-to-video\n    text_osci=True,  # enable text guidance oscillation\n    image_osci=True,  # enable image guidance oscillation\n    scale_temporal_osci=True,\n    method=\"i2v\",  # hard-coded for now\n    seed=None,  # random seed for z\n)\nmotion_score = \"4\"  # motion score for video generation\nfps_save = 24  # fps for video generation and saving\n\n# Define model components\nmodel = dict(\n    type=\"flux\",\n    from_pretrained=\"./ckpts/Open_Sora_v2.safetensors\",\n    guidance_embed=False,\n    fused_qkv=False,\n    use_liger_rope=True,\n    # model architecture\n    in_channels=64,\n    vec_in_dim=768,\n    context_in_dim=4096,\n    hidden_size=3072,\n    mlp_ratio=4.0,\n    num_heads=24,\n    depth=19,\n    depth_single_blocks=38,\n    axes_dim=[16, 56, 56],\n    theta=10_000,\n    qkv_bias=True,\n    cond_embed=True,\n)\nae = dict(\n    type=\"hunyuan_vae\",\n    from_pretrained=\"./ckpts/hunyuan_vae.safetensors\",\n    in_channels=3,\n    out_channels=3,\n    layers_per_block=2,\n    latent_channels=16,\n    use_spatial_tiling=True,\n    use_temporal_tiling=False,\n)\nt5 = dict(\n    type=\"text_embedder\",\n    from_pretrained=\"./ckpts/google/t5-v1_1-xxl\",\n    max_length=512,\n    shardformer=True,\n)\nclip = dict(\n    type=\"text_embedder\",\n    from_pretrained=\"./ckpts/openai/clip-vit-large-patch14\",\n    max_length=77,\n)\n"
  },
  {
    "path": "configs/diffusion/inference/256px_tp.py",
    "content": "_base_ = [  # inherit grammer from mmengine\n    \"256px.py\",\n    \"plugins/tp.py\",  # use tensor parallel\n]\n"
  },
  {
    "path": "configs/diffusion/inference/768px.py",
    "content": "_base_ = [  # inherit grammer from mmengine\n    \"256px.py\",\n    \"plugins/sp.py\",  # use sequence parallel\n]\n\nsampling_option = dict(\n    resolution=\"768px\",\n)\n"
  },
  {
    "path": "configs/diffusion/inference/high_compression.py",
    "content": "_base_ = [\"t2i2v_768px.py\"]\n\n# no need for parallelism\nplugin = None\nplugin_config = None\nplugin_ae = None\nplugin_config_ae = None\n\n# model settings\npatch_size = 1\nmodel = dict(\n    from_pretrained=\"./ckpts/Open_Sora_v2_Video_DC_AE.safetensors\",\n    in_channels=128,\n    cond_embed=True,\n    patch_size=1,\n)\n\n# AE settings\nae = dict(\n    _delete_=True,\n    type=\"dc_ae\",\n    from_scratch=True,\n    model_name=\"dc-ae-f32t4c128\",\n    from_pretrained=\"./ckpts/F32T4C128_AE.safetensors\",\n    use_spatial_tiling=True,\n    use_temporal_tiling=True,\n    spatial_tile_size=256,\n    temporal_tile_size=32,\n    tile_overlap_factor=0.25,\n)\nae_spatial_compression = 32\n\nsampling_option = dict(\n    num_frames=128,\n)\n"
  },
  {
    "path": "configs/diffusion/inference/plugins/sp.py",
    "content": "plugin = \"hybrid\"\nplugin_config = dict(\n    tp_size=1,\n    pp_size=1,\n    sp_size=8,\n    sequence_parallelism_mode=\"ring_attn\",\n    enable_sequence_parallelism=True,\n    static_graph=True,\n    zero_stage=2,\n    overlap_allgather=False,\n)\n\nplugin_ae = \"hybrid\"\nplugin_config_ae = dict(\n    tp_size=8,\n    pp_size=1,\n    sp_size=1,\n    zero_stage=2,\n    overlap_allgather=False,\n)\n"
  },
  {
    "path": "configs/diffusion/inference/plugins/t2i2v.py",
    "content": "use_t2i2v = True\n\n# flux configurations\nimg_flux = dict(\n    type=\"flux\",\n    from_pretrained=\"./ckpts/flux1-dev.safetensors\",\n    guidance_embed=True,\n    # model architecture\n    in_channels=64,\n    vec_in_dim=768,\n    context_in_dim=4096,\n    hidden_size=3072,\n    mlp_ratio=4.0,\n    num_heads=24,\n    depth=19,\n    depth_single_blocks=38,\n    axes_dim=[16, 56, 56],\n    theta=10_000,\n    qkv_bias=True,\n    cond_embed=False,  # pass i2v & v2v info, for t2v need this layer too but with x_cond and mask all set to 0\n)\n\nimg_flux_ae = dict(\n    type=\"autoencoder_2d\",\n    from_pretrained=\"./ckpts/flux1-dev-ae.safetensors\",\n    resolution=256,\n    in_channels=3,\n    ch=128,\n    out_ch=3,\n    ch_mult=[1, 2, 4, 4],\n    num_res_blocks=2,\n    z_channels=16,\n    scale_factor=0.3611,\n    shift_factor=0.1159,\n)\nimg_resolution = \"768px\"\n"
  },
  {
    "path": "configs/diffusion/inference/plugins/tp.py",
    "content": "plugin = \"hybrid\"\nplugin_config = dict(\n    tp_size=8,\n    pp_size=1,\n    sp_size=1,\n    zero_stage=2,\n    overlap_allgather=False,\n)\n\nplugin_ae = \"hybrid\"\nplugin_config_ae = dict(\n    tp_size=8,\n    pp_size=1,\n    sp_size=1,\n    zero_stage=2,\n    overlap_allgather=False,\n)\n"
  },
  {
    "path": "configs/diffusion/inference/t2i2v_256px.py",
    "content": "_base_ = [  # inherit grammer from mmengine\n    \"256px.py\",\n    \"plugins/t2i2v.py\",\n]\n"
  },
  {
    "path": "configs/diffusion/inference/t2i2v_768px.py",
    "content": "_base_ = [  # inherit grammer from mmengine\n    \"768px.py\",\n    \"plugins/t2i2v.py\",\n]\n"
  },
  {
    "path": "configs/diffusion/train/demo.py",
    "content": "_base_ = [\"stage1.py\"]\n\n\nbucket_config = {\n    \"_delete_\": True,\n    \"256px\": {\n        1: (1.0, 1),\n        33: (1.0, 1),\n        97: (1.0, 1),\n        129: (1.0, 1),\n    },\n}\n"
  },
  {
    "path": "configs/diffusion/train/high_compression.py",
    "content": "_base_ = [\"image.py\"]\n\nbucket_config = {\n    \"_delete_\": True,\n    \"768px\": {\n        1: (1.0, 20),\n        16: (1.0, 8),\n        20: (1.0, 8),\n        24: (1.0, 8),\n        28: (1.0, 8),\n        32: (1.0, 8),\n        36: (1.0, 4),\n        40: (1.0, 4),\n        44: (1.0, 4),\n        48: (1.0, 4),\n        52: (1.0, 4),\n        56: (1.0, 4),\n        60: (1.0, 4),\n        64: (1.0, 4),\n        68: (1.0, 3),\n        72: (1.0, 3),\n        76: (1.0, 3),\n        80: (1.0, 3),\n        84: (1.0, 3),\n        88: (1.0, 3),\n        92: (1.0, 3),\n        96: (1.0, 3),\n        100: (1.0, 2),\n        104: (1.0, 2),\n        108: (1.0, 2),\n        112: (1.0, 2),\n        116: (1.0, 2),\n        120: (1.0, 2),\n        124: (1.0, 2),\n        128: (1.0, 2),  # 30s\n    },\n}\n\ncondition_config = dict(\n    t2v=1,\n    i2v_head=7,\n)\n\ngrad_ckpt_settings = (100, 100)\npatch_size = 1\nmodel = dict(\n    from_pretrained=None,\n    grad_ckpt_settings=grad_ckpt_settings,\n    in_channels=128,\n    cond_embed=True,\n    patch_size=patch_size,\n)\nae = dict(\n    _delete_=True,\n    type=\"dc_ae\",\n    model_name=\"dc-ae-f32t4c128\",\n    from_pretrained=\"./ckpts/F32T4C128_AE.safetensors\",\n    from_scratch=True,\n    scaling_factor=0.493,\n    use_spatial_tiling=True,\n    use_temporal_tiling=True,\n    spatial_tile_size=256,\n    temporal_tile_size=32,\n    tile_overlap_factor=0.25,\n)\nis_causal_vae = False\nae_spatial_compression = 32\n\nckpt_every = 250\nlr = 3e-5\noptim = dict(lr=lr)\n"
  },
  {
    "path": "configs/diffusion/train/image.py",
    "content": "# Dataset settings\ndataset = dict(\n    type=\"video_text\",\n    transform_name=\"resize_crop\",\n    fps_max=24,  # the desired fps for training\n    vmaf=True,  # load vmaf scores into text\n)\n\ngrad_ckpt_settings = (8, 100)  # set the grad checkpoint settings\nbucket_config = {\n    \"256px\": {1: (1.0, 50)},\n    \"768px\": {1: (0.5, 11)},\n    \"1024px\": {1: (0.5, 7)},\n}\n\n# Define model components\nmodel = dict(\n    type=\"flux\",\n    from_pretrained=None,\n    strict_load=False,\n    guidance_embed=False,\n    fused_qkv=False,\n    use_liger_rope=True,\n    grad_ckpt_settings=grad_ckpt_settings,\n    # model architecture\n    in_channels=64,\n    vec_in_dim=768,\n    context_in_dim=4096,\n    hidden_size=3072,\n    mlp_ratio=4.0,\n    num_heads=24,\n    depth=19,\n    depth_single_blocks=38,\n    axes_dim=[16, 56, 56],\n    theta=10_000,\n    qkv_bias=True,\n)\ndropout_ratio = {  # probability for dropout text embedding\n    \"t5\": 0.31622777,\n    \"clip\": 0.31622777,\n}\nae = dict(\n    type=\"hunyuan_vae\",\n    from_pretrained=\"./ckpts/hunyuan_vae.safetensors\",\n    in_channels=3,\n    out_channels=3,\n    layers_per_block=2,\n    latent_channels=16,\n    use_spatial_tiling=True,\n    use_temporal_tiling=False,\n)\nis_causal_vae = True\nt5 = dict(\n    type=\"text_embedder\",\n    from_pretrained=\"google/t5-v1_1-xxl\",\n    cache_dir=\"/mnt/ddn/sora/tmp_load/huggingface/hub/\",\n    max_length=512,\n    shardformer=True,\n)\nclip = dict(\n    type=\"text_embedder\",\n    from_pretrained=\"openai/clip-vit-large-patch14\",\n    cache_dir=\"/mnt/ddn/sora/tmp_load/huggingface/hub/\",\n    max_length=77,\n)\n\n# Optimization settings\nlr = 1e-5\neps = 1e-15\noptim = dict(\n    cls=\"HybridAdam\",\n    lr=lr,\n    eps=eps,\n    weight_decay=0.0,\n    adamw_mode=True,\n)\nwarmup_steps = 0\nupdate_warmup_steps = True\n\ngrad_clip = 1.0\naccumulation_steps = 1\nema_decay = None\n\n# Acceleration settings\nprefetch_factor = 2\nnum_workers = 12\nnum_bucket_build_workers = 64\ndtype = \"bf16\"\nplugin = \"zero2\"\ngrad_checkpoint = True\nplugin_config = dict(\n    reduce_bucket_size_in_m=128,\n    overlap_allgather=False,\n)\npin_memory_cache_pre_alloc_numels = [(260 + 20) * 1024 * 1024] * 24 + [\n    (34 + 20) * 1024 * 1024\n] * 4\nasync_io = False\n\n# Other settings\nseed = 42\noutputs = \"outputs\"\nepochs = 1000\nlog_every = 10\nckpt_every = 100\nkeep_n_latest = 20\nwandb_project = \"mmdit\"\n\nsave_master_weights = True\nload_master_weights = True\n\n# For debugging\n# record_time = True\n# record_barrier = True\n"
  },
  {
    "path": "configs/diffusion/train/stage1.py",
    "content": "_base_ = [\"image.py\"]\n\ndataset = dict(memory_efficient=False)\n\n# new config\ngrad_ckpt_settings = (8, 100)\nbucket_config = {\n    \"_delete_\": True,\n    \"256px\": {\n        1: (1.0, 45),\n        5: (1.0, 12),\n        9: (1.0, 12),\n        13: (1.0, 12),\n        17: (1.0, 12),\n        21: (1.0, 12),\n        25: (1.0, 12),\n        29: (1.0, 12),\n        33: (1.0, 12),\n        37: (1.0, 6),\n        41: (1.0, 6),\n        45: (1.0, 6),\n        49: (1.0, 6),\n        53: (1.0, 6),\n        57: (1.0, 6),\n        61: (1.0, 6),\n        65: (1.0, 6),\n        69: (1.0, 4),\n        73: (1.0, 4),\n        77: (1.0, 4),\n        81: (1.0, 4),\n        85: (1.0, 4),\n        89: (1.0, 4),\n        93: (1.0, 4),\n        97: (1.0, 4),\n        101: (1.0, 3),\n        105: (1.0, 3),\n        109: (1.0, 3),\n        113: (1.0, 3),\n        117: (1.0, 3),\n        121: (1.0, 3),\n        125: (1.0, 3),\n        129: (1.0, 3),\n    },\n    \"768px\": {\n        1: (0.5, 13),\n    },\n    \"1024px\": {\n        1: (0.5, 7),\n    },\n}\n\nmodel = dict(grad_ckpt_settings=grad_ckpt_settings)\nlr = 5e-5\noptim = dict(lr=lr)\nckpt_every = 2000\nkeep_n_latest = 20\n"
  },
  {
    "path": "configs/diffusion/train/stage1_i2v.py",
    "content": "_base_ = [\"stage1.py\"]\n\n# Define model components\nmodel = dict(cond_embed=True)\n\ncondition_config = dict(\n    t2v=1,\n    i2v_head=5,  # train i2v (image as first frame) with weight 5\n    i2v_loop=1,  # train image connection with weight 1\n    i2v_tail=1,  # train i2v (image as last frame) with weight 1\n)\n\nlr = 1e-5\noptim = dict(lr=lr)\n"
  },
  {
    "path": "configs/diffusion/train/stage2.py",
    "content": "_base_ = [\"image.py\"]\n\n# new config\ngrad_ckpt_settings = (100, 100)\n\nplugin = \"hybrid\"\nplugin_config = dict(\n    tp_size=1,\n    pp_size=1,\n    sp_size=4,\n    sequence_parallelism_mode=\"ring_attn\",\n    enable_sequence_parallelism=True,\n    static_graph=True,\n    zero_stage=2,\n)\n\nbucket_config = {\n    \"_delete_\": True,\n    \"256px\": {\n        1: (1.0, 130),\n        5: (1.0, 14),\n        9: (1.0, 14),\n        13: (1.0, 14),\n        17: (1.0, 14),\n        21: (1.0, 14),\n        25: (1.0, 14),\n        29: (1.0, 14),\n        33: (1.0, 14),\n        37: (1.0, 10),\n        41: (1.0, 10),\n        45: (1.0, 10),\n        49: (1.0, 10),\n        53: (1.0, 10),\n        57: (1.0, 10),\n        61: (1.0, 10),\n        65: (1.0, 10),\n        73: (1.0, 7),\n        77: (1.0, 7),\n        81: (1.0, 7),\n        85: (1.0, 7),\n        89: (1.0, 7),\n        93: (1.0, 7),\n        97: (1.0, 7),\n        101: (1.0, 6),\n        105: (1.0, 6),\n        109: (1.0, 6),\n        113: (1.0, 6),\n        117: (1.0, 6),\n        121: (1.0, 6),\n        125: (1.0, 6),\n        129: (1.0, 6),\n    },\n    \"768px\": {\n        1: (1.0, 38),\n        5: (1.0, 6),\n        9: (1.0, 6),\n        13: (1.0, 6),\n        17: (1.0, 6),\n        21: (1.0, 6),\n        25: (1.0, 6),\n        29: (1.0, 6),\n        33: (1.0, 6),\n        37: (1.0, 4),\n        41: (1.0, 4),\n        45: (1.0, 4),\n        49: (1.0, 4),\n        53: (1.0, 4),\n        57: (1.0, 4),\n        61: (1.0, 4),\n        65: (1.0, 4),\n        69: (1.0, 3),\n        73: (1.0, 3),\n        77: (1.0, 3),\n        81: (1.0, 3),\n        85: (1.0, 3),\n        89: (1.0, 3),\n        93: (1.0, 3),\n        97: (1.0, 3),\n        101: (1.0, 2),\n        105: (1.0, 2),\n        109: (1.0, 2),\n        113: (1.0, 2),\n        117: (1.0, 2),\n        121: (1.0, 2),\n        125: (1.0, 2),\n        129: (1.0, 2),\n    },\n}\n\nmodel = dict(grad_ckpt_settings=grad_ckpt_settings)\nlr = 5e-5\noptim = dict(lr=lr)\nckpt_every = 200\nkeep_n_latest = 20\n"
  },
  {
    "path": "configs/diffusion/train/stage2_i2v.py",
    "content": "_base_ = [\"stage2.py\"]\n\n# Define model components\nmodel = dict(cond_embed=True)\ngrad_ckpt_buffer_size = 25 * 1024**3\n\ncondition_config = dict(\n    t2v=1,\n    i2v_head=5,\n    i2v_loop=1,\n    i2v_tail=1,\n)\nis_causal_vae = True\n\nbucket_config = {\n    \"_delete_\": True,\n    \"256px\": {\n        1: (1.0, 195),\n        5: (1.0, 80),\n        9: (1.0, 80),\n        13: (1.0, 80),\n        17: (1.0, 80),\n        21: (1.0, 80),\n        25: (1.0, 80),\n        29: (1.0, 80),\n        33: (1.0, 80),\n        37: (1.0, 40),\n        41: (1.0, 40),\n        45: (1.0, 40),\n        49: (1.0, 40),\n        53: (1.0, 40),\n        57: (1.0, 40),\n        61: (1.0, 40),\n        65: (1.0, 40),\n        69: (1.0, 28),\n        73: (1.0, 28),\n        77: (1.0, 28),\n        81: (1.0, 28),\n        85: (1.0, 28),\n        89: (1.0, 28),\n        93: (1.0, 28),\n        97: (1.0, 28),\n        101: (1.0, 23),\n        105: (1.0, 23),\n        109: (1.0, 23),\n        113: (1.0, 23),\n        117: (1.0, 23),\n        121: (1.0, 23),\n        125: (1.0, 23),\n        129: (1.0, 23),\n    },\n    \"768px\": {\n        1: (0.5, 38),\n        5: (0.5, 10),\n        9: (0.5, 10),\n        13: (0.5, 10),\n        17: (0.5, 10),\n        21: (0.5, 10),\n        25: (0.5, 10),\n        29: (0.5, 10),\n        33: (0.5, 10),\n        37: (0.5, 5),\n        41: (0.5, 5),\n        45: (0.5, 5),\n        49: (0.5, 5),\n        53: (0.5, 5),\n        57: (0.5, 5),\n        61: (0.5, 5),\n        65: (0.5, 5),\n        69: (0.5, 3),\n        73: (0.5, 3),\n        77: (0.5, 3),\n        81: (0.5, 3),\n        85: (0.5, 3),\n        89: (0.5, 3),\n        93: (0.5, 3),\n        97: (0.5, 3),\n        101: (0.5, 2),\n        105: (0.5, 2),\n        109: (0.5, 2),\n        113: (0.5, 2),\n        117: (0.5, 2),\n        121: (0.5, 2),\n        125: (0.5, 2),\n        129: (0.5, 2),\n    },\n}\n"
  },
  {
    "path": "configs/vae/inference/hunyuanvideo_vae.py",
    "content": "dtype = \"bf16\"\nbatch_size = 1\nseed = 42\nsave_dir = \"samples/hunyuanvideo_vae\"\n\nplugin = \"zero2\"\ndataset = dict(\n    type=\"video_text\",\n    transform_name=\"resize_crop\",\n    fps_max=16,\n    data_path=\"datasets/pexels_45k_necessary.csv\",\n)\nbucket_config = {\n    \"512px_ar1:1\": {97: (1.0, 1)},\n}\n\nnum_workers = 24\nnum_bucket_build_workers = 16\nprefetch_factor = 4\n\nmodel = dict(\n    type=\"hunyuan_vae\",\n    from_pretrained=\"./ckpts/hunyuan_vae.safetensors\",\n    in_channels=3,\n    out_channels=3,\n    layers_per_block=2,\n    latent_channels=16,\n    scale_factor=0.476986,\n    shift_factor=0,\n    use_spatial_tiling=True,\n    use_temporal_tiling=True,\n    time_compression_ratio=4,\n)\n"
  },
  {
    "path": "configs/vae/inference/video_dc_ae.py",
    "content": "dtype = \"bf16\"\nbatch_size = 1\nseed = 42\n\ndataset = dict(\n    type=\"video_text\",\n    transform_name=\"resize_crop\",\n    fps_max=16,\n    data_path=\"datasets/pexels_45k_necessary.csv\",\n)\nbucket_config = {\n    \"512px_ar1:1\": {96: (1.0, 1)},\n}\n\nmodel = dict(\n    type=\"dc_ae\",\n    model_name=\"dc-ae-f32t4c128\",\n    from_pretrained=\"./ckpts/F32T4C128_AE.safetensors\",\n    from_scratch=True,\n    use_spatial_tiling=True,\n    use_temporal_tiling=True,\n    spatial_tile_size=256,\n    temporal_tile_size=32,\n    tile_overlap_factor=0.25,\n)\n\nsave_dir = \"samples/video_dc_ae\"\n\nnum_workers = 24\nnum_bucket_build_workers = 16\nprefetch_factor = 4\n\n"
  },
  {
    "path": "configs/vae/train/video_dc_ae.py",
    "content": "# ============\n# model config \n# ============\nmodel = dict(\n    type=\"dc_ae\",\n    model_name=\"dc-ae-f32t4c128\",\n    from_scratch=True,\n    from_pretrained=None,\n)\n\n# ============\n# data config \n# ============\ndataset = dict(\n    type=\"video_text\",\n    transform_name=\"resize_crop\",\n    data_path=\"datasets/pexels_45k_necessary.csv\",\n    fps_max=24,\n)\n\nbucket_config = {\n    \"256px_ar1:1\": {32: (1.0, 1)},\n}\n\nnum_bucket_build_workers = 64\nnum_workers = 12\nprefetch_factor = 2\n\n# ============\n# train config \n# ============\noptim = dict(\n    cls=\"HybridAdam\",\n    lr=5e-5,\n    eps=1e-8,\n    weight_decay=0.0,\n    adamw_mode=True,\n    betas=(0.9, 0.98),\n)\nlr_scheduler = dict(warmup_steps=0)\n\nmixed_strategy = \"mixed_video_image\"\nmixed_image_ratio = 0.2  # 1:4\n\ndtype = \"bf16\"\nplugin = \"zero2\"\nplugin_config = dict(\n    reduce_bucket_size_in_m=128,\n    overlap_allgather=False,\n)\n\ngrad_clip = 1.0\ngrad_checkpoint = False\npin_memory_cache_pre_alloc_numels = [50 * 1024 * 1024] * num_workers * prefetch_factor\n\nseed = 42\noutputs = \"outputs\"\nepochs = 100\nlog_every = 10\nckpt_every = 3000\nkeep_n_latest = 50\nema_decay = 0.99\nwandb_project = \"dcae\"\n\nupdate_warmup_steps = True\n\n# ============\n# loss config \n# ============\nvae_loss_config = dict(\n    perceptual_loss_weight=0.5,\n    kl_loss_weight=0,\n)\n\n"
  },
  {
    "path": "configs/vae/train/video_dc_ae_disc.py",
    "content": "_base_ = [\"video_dc_ae.py\"]\n\ndiscriminator = dict(\n    type=\"N_Layer_discriminator_3D\",\n    from_pretrained=None,\n    input_nc=3,\n    n_layers=5,\n    conv_cls=\"conv3d\"\n)\ndisc_lr_scheduler = dict(warmup_steps=0)\n\ngen_loss_config = dict(\n    gen_start=0,\n    disc_weight=0.05,\n)\n\ndisc_loss_config = dict(\n    disc_start=0,\n    disc_loss_type=\"hinge\",\n)\n\noptim_discriminator = dict(\n    cls=\"HybridAdam\",\n    lr=1e-4,\n    eps=1e-8,\n    weight_decay=0.0,\n    adamw_mode=True,\n    betas=(0.9, 0.98),\n)\n\ngrad_checkpoint = True\nmodel = dict(\n    disc_off_grad_ckpt = True, # set to true if your `grad_checkpoint` is True\n)\n"
  },
  {
    "path": "docs/ae.md",
    "content": "# Step by step to train and evaluate an video autoencoder (AE)\nInspired by [SANA](https://arxiv.org/abs/2410.10629), we aim to drastically increase the compression ratio in the AE. We propose a video autoencoder architecture based on [DC-AE](https://github.com/mit-han-lab/efficientvit), the __Video DC-AE__, which compression the video by 4x in the temporal dimension and 32x32 in the spatial dimension. Compared to [HunyuanVideo](https://github.com/Tencent/HunyuanVideo)'s VAE of 4x8x8, our proposed AE has a much higher spatial compression ratio.\nThus, we can effectively reduce the token length in the diffusion model by a total of 16x (assuming the same patch sizes), drastically increase both training and inference speed.\n\n## Data Preparation\n\nFollow this [guide](./train.md#prepare-dataset) to prepare the __DATASET__ for training and inference. You may use our provided dataset or custom ones.\n\nTo use custom dataset, pass the argument `--dataset.data_path <your_data_path>` to the following training or inference command.\n\n## Training\n\nWe train our __Video DC-AE__ from scratch on 8xGPUs for 3 weeks.\n\nWe first train with the following command:\n\n```bash\ntorchrun --nproc_per_node 8 scripts/vae/train.py configs/vae/train/video_dc_ae.py\n```\n\nWhen the model is almost converged, we add a discriminator and continue to train the model with the checkpoint `model_ckpt` using the following command:\n\n```bash\ntorchrun --nproc_per_node 8 scripts/vae/train.py configs/vae/train/video_dc_ae_disc.py --model.from_pretrained <model_ckpt>\n```\nYou may pass the flag `--wandb True` if you have a [wandb](https://wandb.ai/home) account and wish to track the training progress online.\n\n## Inference\n\nDownload the relevant weights following [this guide](../README.md#model-download). Alternatively, you may use your own trained model by passing the following flag `--model.from_pretrained <your_model_ckpt_path>`.\n\n### Video DC-AE\n\nUse the following code to reconstruct the videos using our trained `Video DC-AE`:\n\n```bash\ntorchrun --nproc_per_node 1 --standalone scripts/vae/inference.py configs/vae/inference/video_dc_ae.py --save-dir samples/dcae\n```\n\n### Hunyuan Video\n\nAlternatively, we have incorporated [HunyuanVideo vae](https://github.com/Tencent/HunyuanVideo) into our code, you may run inference with the following command:\n\n```bash\ntorchrun --nproc_per_node 1 --standalone scripts/vae/inference.py configs/vae/inference/hunyuanvideo_vae.py --save-dir samples/hunyuanvideo_vae\n```\n\n## Config Interpretation\n\nAll AE configs are located in `configs/vae/`, divided into configs for training (`configs/vae/train`) and for inference (`configs/vae/inference`).\n\n### Training Config\n\nFor training, the same config rules as [those](./train.md#config) for the diffusion model are applied.\n\n<details>\n<summary> <b>Loss Config</b> </summary>\nOur __Video DC-AE__ is based on the [DC-AE](https://github.com/mit-han-lab/efficientvit) architecture, which doesn't have a variational component. Thus, our training simply composes of the *reconstruction loss* and the *perceptual loss*.\nExperimentally, we found that setting a ratio of 0.5 for the perceptual loss is effective.\n\n```python\nvae_loss_config = dict(\n    perceptual_loss_weight=0.5, # weigh the perceptual loss by 0.5\n    kl_loss_weight=0,           # no KL loss\n)\n```\n\nIn a later stage, we include a discriminator, and the training loss for the ae has an additional generator loss component, where we use a small ratio of 0.05 to weigh the loss calculated:\n```python\ngen_loss_config = dict(\n    gen_start=0,                # include generator loss from step 0 onwards          \n    disc_weight=0.05,           # weigh the loss by 0.05\n)\n```\n\nThe discriminator we use is trained from scratch, and it's loss is simply the hinged loss:\n```python\ndisc_loss_config = dict(\n    disc_start=0,               # update the discriminator from step 0 onwards\n    disc_loss_type=\"hinge\",     # the discriminator loss type\n)\n```\n</details>\n\n<details>\n<summary> <b> Data Bucket Config </b> </summary>\nFor the data bucket, we used 32 frames of 256px videos to train our AE.\n```python\nbucket_config = {\n    \"256px_ar1:1\": {32: (1.0, 1)},\n}\n```\n</details>\n\n<details>\n<summary> <b>Train with more frames or higher resolutions</b> </summary>\n\nIf you train with longer frames or larger resolutions, you may increase the `spatial_tile_size` and `temporal_tile_size` during inference without degrading the AE performance (see [Inference Config](ae.md#inference-config)). This may give you advantage of faster AE inference such as when training the diffusion model (although at the cost of slower AE training). \n\nYou may increase the video frames to 96 (although multiples of 4 works, we generally recommend to use frame numbers of multiples of 32):\n\n```python\nbucket_config = {\n    \"256px_ar1:1\": {96: (1.0, 1)},\n}\ngrad_checkpoint = True\n```\nor train for higher resolution such as 512px:\n```python\nbucket_config = {\n    \"512px_ar1:1\": {32: (1.0, 1)},\n}\ngrad_checkpoint = True\n```\nNote that gradient checkpoint needs to be turned on in order to avoid prevent OOM error.\n\nMoreover, if `grad_checkpointing` is set to `True` in discriminator training, you need to pass the flag `--model.disc_off_grad_ckpt True` or simply set in the config:\n```python\ngrad_checkpoint = True\nmodel = dict(\n    disc_off_grad_ckpt = True, # set to true if your `grad_checkpoint` is True\n)\n```\nThis is to make sure the discriminator loss will have a gradient at the laster later during adaptive loss calculation.\n</details>\n\n\n\n\n### Inference Config\n\nFor AE inference, we have replicated the tiling mechanism in hunyuan to our Video DC-AE, which can be turned on with the following:\n\n```python\nmodel = dict(\n    ...,\n    use_spatial_tiling=True,\n    use_temporal_tiling=True,\n    spatial_tile_size=256,\n    temporal_tile_size=32,\n    tile_overlap_factor=0.25,\n    ...,\n)\n```\n\nBy default, both spatial tiling and temporal tiling are turned on for the best performance.\nSince our Video DC-AE is trained on 256px videos of 32 frames only, `spatial_tile_size` should be set to 256 and `temporal_tile_size` should be set to 32.\nIf you train your own Video DC-AE with other resolutions and length, you may adjust the values accordingly.\n\nYou can specify the directory to store output samples with `--save_dir <your_dir>` or setting it in config, for instance:\n\n```python\nsave_dir = \"./samples\"\n```\n"
  },
  {
    "path": "docs/hcae.md",
    "content": "# 10× inference speedup with high-compression autoencoder\n\n\nThe high computational cost of training video generation models arises from the\nlarge number of tokens and the dominance of attention computation. To further reduce training expenses,\nwe explore training video generation models with high-compression autoencoders (Video DC-AEs). As shown in the comparason below, by switching to the Video DC-AE with a much higher downsample ratio (4 x 32 x 32), we can afford to further reduce the patch size to 1 and still achieve __5.2× speedup in training throughput__ and __10x speedup during inference__:\n\n![opensorav2_speed](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/hcae_opensorav2_speed.png)\n\n\nNevertheless, despite the advantanges in drastically lower computation costs, other challenges remain. For instance, larger channels low down convergance. Our generation model adapted with a 128-channel Video DC-AE for 25K iterations achieves a loss level of 0.5, as compared to 0.1 from the initialization model. While the fast video generation model underperforms the original, it still captures spatial-temporal\nrelationships. We release this model to the research community for further exploration.\n\nCheckout more details in our [report](https://arxiv.org/abs/2503.09642v1).\n\n## Model Download\n\nDownload from 🤗 [Huggingface](https://huggingface.co/hpcai-tech/Open-Sora-v2-Video-DC-AE):\n\n```bash\npip install \"huggingface_hub[cli]\"\nhuggingface-cli download hpcai-tech/Open-Sora-v2-Video-DC-AE --local-dir ./ckpts\n```\n\n## Inference\n\nTo inference on our fast video generation model:\n\n```bash\ntorchrun --nproc_per_node 1 --standalone scripts/diffusion/inference.py configs/diffusion/inference/high_compression.py --prompt \"The story of a robot's life in a cyberpunk setting.\" \n```\n\n## Training\nFollow this [guide](./train.md#prepare-dataset) to parepare the __DATASET__ for training.\nThen, you may train your own fast generation model with the following command:\n```bash\ntorchrun --nproc_per_node 8 scripts/diffusion/train.py configs/diffusion/train/high_compression.py --dataset.data-path datasets/pexels_45k_necessary.csv\n```\n"
  },
  {
    "path": "docs/report_01.md",
    "content": "# Open-Sora 1.0 Report\n\nOpenAI's Sora is amazing at generating one minutes high quality videos. However, it reveals almost no information about its details. To make AI more \"open\", we are dedicated to build an open-source version of Sora. This report describes our first attempt to train a transformer-based video diffusion model.\n\n## Efficiency in choosing the architecture\n\nTo lower the computational cost, we want to utilize existing VAE models. Sora uses spatial-temporal VAE to reduce the temporal dimensions. However, we found that there is no open-source high-quality spatial-temporal VAE model. [MAGVIT](https://github.com/google-research/magvit)'s 4x4x4 VAE is not open-sourced, while [VideoGPT](https://wilson1yan.github.io/videogpt/index.html)'s 2x4x4 VAE has a low quality in our experiments. Thus, we decided to use a 2D VAE (from [Stability-AI](https://huggingface.co/stabilityai/sd-vae-ft-mse-original)) in our first version.\n\nThe video training involves a large amount of tokens. Considering 24fps 1min videos, we have 1440 frames. With VAE downsampling 4x and patch size downsampling 2x, we have 1440x1024≈1.5M tokens. Full attention on 1.5M tokens leads to a huge computational cost. Thus, we use spatial-temporal attention to reduce the cost following [Latte](https://github.com/Vchitect/Latte).\n\nAs shown in the figure, we insert a temporal attention right after each spatial attention in STDiT (ST stands for spatial-temporal). This is similar to variant 3 in Latte's paper. However, we do not control a similar number of parameters for these variants. While Latte's paper claims their variant is better than variant 3, our experiments on 16x256x256 videos show that with same number of iterations, the performance ranks as: DiT (full) > STDiT (Sequential) > STDiT (Parallel) ≈ Latte. Thus, we choose STDiT (Sequential) out of efficiency. Speed benchmark is provided [here](/docs/acceleration.md#efficient-stdit).\n\n![Architecture Comparison](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/report_arch_comp.png)\n\nTo focus on video generation, we hope to train the model based on a powerful image generation model. [PixArt-α](https://github.com/PixArt-alpha/PixArt-alpha) is an efficiently trained high-quality image generation model with T5-conditioned DiT structure. We initialize our model with PixArt-α and initialize the projection layer of inserted temporal attention with zero. This initialization preserves model's ability of image generation at beginning, while Latte's architecture cannot. The inserted attention increases the number of parameter from 580M to 724M.\n\n![Architecture](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/report_arch.jpg)\n\nDrawing from the success of PixArt-α and Stable Video Diffusion, we also adopt a progressive training strategy: 16x256x256 on 366K pretraining datasets, and then 16x256x256, 16x512x512, and 64x512x512 on 20K datasets. With scaled position embedding, this strategy greatly reduces the computational cost.\n\nWe also try to use a 3D patch embedder in DiT. However, with 2x downsampling on temporal dimension, the generated videos have a low quality. Thus, we leave the downsampling to temporal VAE in our next version. For now, we sample at every 3 frames with 16 frames training and every 2 frames with 64 frames training.\n\n## Data is the key to high quality\n\nWe find that the number and quality of data have a great impact on the quality of generated videos, even larger than the model architecture and training strategy. At this time, we only prepared the first split (366K video clips) from [HD-VG-130M](https://github.com/daooshee/HD-VG-130M). The quality of these videos varies greatly, and the captions are not that accurate. Thus, we further collect 20k relatively high quality videos from [Pexels](https://www.pexels.com/), which provides free license videos. We label the video with LLaVA, an image captioning model, with three frames and a designed prompt. With designed prompt, LLaVA can generate good quality of captions.\n\n![Caption](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/report_caption.png)\n\nAs we lay more emphasis on the quality of data, we prepare to collect more data and build a video preprocessing pipeline in our next version.\n\n## Training Details\n\nWith a limited training budgets, we made only a few exploration. We find learning rate 1e-4 is too large and scales down to 2e-5. When training with a large batch size, we find `fp16` less stable than `bf16` and may lead to generation failure. Thus, we switch to `bf16` for training on 64x512x512. For other hyper-parameters, we follow previous works.\n\n## Loss curves\n\n16x256x256 Pretraining Loss Curve\n\n![16x256x256 Pretraining Loss Curve](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/report_loss_curve_1.png)\n\n16x256x256 HQ Training Loss Curve\n\n![16x256x256 HQ Training Loss Curve](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/report_loss_curve_2.png)\n\n16x512x512 HQ Training Loss Curve\n\n![16x512x512 HQ Training Loss Curve](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/report_loss_curve_3.png)\n\n> Core Contributor: Zangwei Zheng*, Xiangyu Peng*, Shenggui Li, Hongxing Liu, Yang You\n"
  },
  {
    "path": "docs/report_02.md",
    "content": "# Open-Sora 1.1 Report\n\n- [Model Architecture Modification](#model-architecture-modification)\n- [Support for Multi-time/resolution/aspect ratio/fps Training](#support-for-multi-timeresolutionaspect-ratiofps-training)\n- [Masked DiT as Image/Video-to-Video Model](#masked-dit-as-imagevideo-to-video-model)\n- [Data Collection \\& Pipeline](#data-collection--pipeline)\n- [Training Details](#training-details)\n- [Limitation and Future Work](#limitation-and-future-work)\n\nIn Open-Sora 1.1 release, we train a 700M models on 10M data (Open-Sora 1.0 trained on 400K data) with a better STDiT architecture. We implement the following features mentioned in [sora's report](https://openai.com/research/video-generation-models-as-world-simulators):\n\n- Variable durations, resolutions, aspect ratios (Sampling flexibility, Improved framing and composition)\n- Prompting with images and videos (Animating images, Extending generated videos, Video-to-video editing, Connecting videos)\n- Image generation capabilities\n\nTo achieve this goal, we use multi-task learning in the pretraining stage. For diffusion models, training with different sampled timestep is already a multi-task learning. We further extend this idea to multi-resolution, aspect ratio, frame length, fps, and different mask strategies for image and video conditioned generation. We train the model on **0s~15s, 144p to 720p, various aspect ratios** videos. Although the quality of time consistency is not that high due to limit training FLOPs, we can still see the potential of the model.\n\n## Model Architecture Modification\n\nWe made the following modifications to the original ST-DiT for better training stability and performance (ST-DiT-2):\n\n- **[Rope embedding](https://arxiv.org/abs/2104.09864) for temporal attention**: Following LLM's best practice, we change the sinusoidal positional encoding to rope embedding for temporal attention since it is also a sequence prediction task.\n- **AdaIN and Layernorm for temporal attention**: we wrap the temporal attention with AdaIN and layernorm as the spatial attention to stabilize the training.\n- **[QK-normalization](https://arxiv.org/abs/2302.05442) with [RMSNorm](https://arxiv.org/abs/1910.07467)**: Following [SD3](https://arxiv.org/pdf/2403.03206.pdf), we apply QK-normalization to the all attention for better training stability in half-precision.\n- **Dynamic input size support and video infomation condition**: To support multi-resolution, aspect ratio, and fps training, we make ST-DiT-2 to accept any input size, and automatically scale positional embeddings. Extending [PixArt-alpha](https://github.com/PixArt-alpha/PixArt-alpha)'s idea, we conditioned on video's height, width, aspect ratio, frame length, and fps.\n- **Extending T5 tokens from 120 to 200**: our caption is usually less than 200 tokens, and we find the model can handle longer text well.\n\n## Support for Multi-time/resolution/aspect ratio/fps Training\n\nAs mentioned in the [sora's report](https://openai.com/research/video-generation-models-as-world-simulators), training with original video's resolution, aspect ratio, and length increase sampling flexibility and improve framing and composition. We found three ways to achieve this goal:\n\n- [NaViT](https://arxiv.org/abs/2307.06304): support dynamic size within the same batch by masking, with little efficiency loss. However, the system is a bit complex to implement, and may not benefit from optimized kernels such as flash attention.\n- Padding ([FiT](https://arxiv.org/abs/2402.12376), [Open-Sora-Plan](https://github.com/PKU-YuanGroup/Open-Sora-Plan)): support dynamic size within the same batch by padding. However, padding different resolutions to the same size is not efficient.\n- Bucket ([SDXL](https://arxiv.org/abs/2307.01952), [PixArt](https://arxiv.org/abs/2310.00426)): support dynamic size in different batches by bucketing, but the size must be the same within the same batch, and only a fixed number of size can be applied. With the same size in a batch, we do not need to implement complex masking or padding.\n\nFor the simplicity of implementation, we choose the bucket method. We pre-define some fixed resolution, and allocate different samples to different bucket. The concern for bucketing is listed below. But we can see that the concern is not a big issue in our case.\n\n<details>\n<summary>View the concerns</summary>\n\n- The bucket size is limited to a fixed number: First, in real-world applications, only a few aspect ratios (9:16, 3:4) and resolutions (240p, 1080p) are commonly used. Second, we find trained models can generalize well to unseen resolutions.\n- The size in each batch is the same, breaks the i.i.d. assumption: Since we are using multiple GPUs, the local batches on different GPUs have different sizes. We did not see a significant performance drop due to this issue.\n- The may not be enough samples to fill each bucket and the distribution may be biased: First, our dataset is large enough to fill each bucket when local batch size is not too large. Second, we should analyze the data's distribution on sizes and define the bucket size accordingly. Third, an unbalanced distribution did not affect the training process significantly.\n- Different resolutions and frame lengths may have different processing speed: Different from PixArt, which only deals with aspect ratios of similar resolutions (similar token numbers), we need to consider the processing speed of different resolutions and frame lengths. We can use the `bucket_config` to define the batch size for each bucket to ensure the processing speed is similar.\n\n</details>\n\n![bucket](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/report_bucket.png)\n\nAs shown in the figure, a bucket is a triplet of `(resolution, num_frame, aspect_ratio)`. We provide pre-defined aspect ratios for different resolution that covers most of the common video aspect ratios. Before each epoch, we shuffle the dataset and allocate the samples to different buckets as shown in the figure. We put a sample into a bucket with largest resolution and frame length that is smaller than the video's.\n\nConsidering our computational resource is limited, we further introduce two attributes `keep_prob` and `batch_size` for each `(resolution, num_frame)` to reduce the computational cost and enable multi-stage training. Specifically, a high-resolution video will be downsampled to a lower resolution with probability `1-keep_prob` and the batch size for each bucket is `batch_size`. In this way, we can control the number of samples in different buckets and balance the GPU load by search a good batch size for each bucket.\n\nA detailed explanation of the bucket usage in training is available in [docs/config.md](/docs/config.md#training-bucket-configs).\n\n## Masked DiT as Image/Video-to-Video Model\n\nTransformers can be easily extended to support image-to-image and video-to-video tasks. We propose a mask strategy to support image and video conditioning. The mask strategy is shown in the figure below.\n\n![mask strategy](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/report_mask.png)\n\nTypically, we unmask the frames to be conditioned on for image/video-to-video condition. During the ST-DiT forward, unmasked frames will have timestep 0, while others remain the same (t). We find directly apply the strategy to trained model yield poor results as the diffusion model did not learn to handle different timesteps in one sample during training.\n\nInspired by [UL2](https://arxiv.org/abs/2205.05131), we introduce random mask strategy during training. Specifically, we randomly unmask the frames during training, including unmask the first frame, the first k frames, the last frame, the last k frames, the first and last k frames, random frames, etc. Based on Open-Sora 1.0, with 50% probability of applying masking, we see the model can learn to handle image conditioning (while 30% yields worse ability) for 10k steps, with a little text-to-video performance drop. Thus, for Open-Sora 1.1, we pretrain the model from scratch with masking strategy.\n\nAn illustration of masking strategy config to use in inference is given as follow. A five number tuple provides great flexibility in defining the mask strategy. By conditioning on generated frames, we can autogressively generate infinite frames (although error propagates).\n\n![mask strategy config](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/report_mask_config.png)\n\nA detailed explanation of the mask strategy usage is available in [docs/config.md](/docs/config.md#advanced-inference-config).\n\n## Data Collection & Pipeline\n\nAs we found in Open-Sora 1.0, the data number and quality are crucial for training a good model, we work hard on scaling the dataset. First, we create an automatic pipeline following [SVD](https://arxiv.org/abs/2311.15127), inlcuding scene cutting, captioning, various scoring and filtering, and dataset management scripts and conventions. More infomation can be found in [docs/data_processing.md](/docs/data_processing.md).\n\n![pipeline](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/report_data_pipeline.png)\n\nWe plan to use [panda-70M](https://snap-research.github.io/Panda-70M/) and other data to traing the model, which is approximately 30M+ data. However, we find disk IO a botteleneck for training and data processing at the same time. Thus, we can only prepare a 10M dataset and did not go through all processing pipeline that we built. Finally, we use a dataset with 9.7M videos + 2.6M images for pre-training, and 560k videos + 1.6M images for fine-tuning. The pretraining dataset statistics are shown below. More information about the dataset can be found in [docs/datasets.md](/docs/datasets.md).\n\nImage text tokens (by T5 tokenizer):\n\n![image text tokens](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/report_image_textlen.png)\n\nVideo text tokens (by T5 tokenizer). We directly use panda's short caption for training, and caption other datasets by ourselves. The generated caption is usually less than 200 tokens.\n\n![video text tokens](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/report_video_textlen.png)\n\nVideo duration:\n\n![video duration](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/report_video_duration.png)\n\n## Training Details\n\nWith limited computational resources, we have to carefully monitor the training process, and change the training strategy if we speculate the model is not learning well since there is no computation for ablation study. Thus, Open-Sora 1.1's training includes multiple changes, and as a result, ema is not applied.\n\n1. First, we fine-tune **6k** steps with images of different resolution from `Pixart-alpha-1024` checkpoints. We find the model easily adapts to generate images with different resolutions. We use [SpeeDiT](https://github.com/1zeryu/SpeeDiT) (iddpm-speed) to accelerate the diffusion training.\n2. **[Stage 1]** Then, we pretrain the model with gradient-checkpointing for **24k** steps, which takes **4 days** on 64 H800 GPUs. Although the number of samples seen by the model is the same, we find the model learns slowly compared to a smaller batch size. We speculate that at an early stage, the number of steps is more important for training. The most videos are in **240p** resolution, and the config is similar to [stage2.py](/configs/opensora-v1-1/train/stage2.py). The video looking is good, but the model does not know much about the temporal knowledge. We use mask ratio of 10%.\n3. **[Stage 1]** To increase the number of steps, we switch to a smaller batch size without gradient-checkpointing. We also add fps conditioning at this point. We trained **40k** steps for **2 days**. The most videos are in **144p** resolution, and the config file is [stage1.py](/configs/opensora-v1-1/train/stage1.py). We use a lower resolution as we find in Open-Sora 1.0 that the model can learn temporal knowledge with relatively low resolution.\n4. **[Stage 1]** We find the model cannot learn well for long videos, and find a noised generation result as speculated to be half-precision problem found in Open-Sora 1.0 training. Thus, we adopt the QK-normalization to stabilize the training. Similar to SD3, we find the model quickly adapt to the QK-normalization. We also switch iddpm-speed to iddpm, and increase the mask ratio to 25% as we find image-condition not learning well. We trained for **17k** steps for **14 hours**. The most videos are in **144p** resolution, and the config file is [stage1.py](/configs/opensora-v1-1/train/stage1.py). The stage 1 training lasts for approximately one week, with total step **81k**.\n5. **[Stage 2]** We switch to a higher resolution, where most videos are in **240p and 480p** resolution ([stage2.py](/configs/opensora-v1-1/train/stage2.py)). We trained **22k** steps for **one day** on all pre-training data.\n6. **[Stage 3]** We switch to a higher resolution, where most videos are in **480p and 720p** resolution ([stage3.py](/configs/opensora-v1-1/train/stage3.py)). We trained **4k** with **one day** on high-quality data. We find loading previous stage's optimizer state can help the model learn faster.\n\nTo summarize, the training of Open-Sora 1.1 requires approximately **9 days** on 64 H800 GPUs.\n\n## Limitation and Future Work\n\nAs we get one step closer to the replication of Sora, we find many limitations for the current model, and these limitations point to the future work.\n\n- **Generation Failure**: we find many cases (especially when the total token number is large or the content is complex),  our model fails to generate the scene. There may be a collapse in the temporal attention and we have identified a potential bug in our code. We are working hard to fix it. Besides, we will increase our model size and training data to improve the generation quality in the next version.\n- **Noisy generation and influency**: we find the generated model is sometimes noisy and not fluent, especially for long videos. We think the problem is due to not using a temporal VAE. As [Pixart-Sigma](https://arxiv.org/abs/2403.04692) finds that adapting to a new VAE is simple, we plan to develop a temporal VAE for the model in the next version.\n- **Lack of time consistency**: we find the model cannot generate videos with high time consistency. We think the problem is due to the lack of training FLOPs. We plan to collect more data and continue training the model to improve the time consistency.\n- **Bad human generation**: We find the model cannot generate high-quality human videos. We think the problem is due to the lack of human data. We plan to collect more human data and continue training the model to improve the human generation.\n- **Low aesthetic score**: we find the model's aesthetic score is not high. The problem is due to the lack of aesthetic score filtering, which is not conducted due to IO bottleneck. We plan to filter the data by aesthetic score and finetuning the model to improve the aesthetic score.\n- **Worse quality for longer video generation**: we find with a same prompt, the longer video has worse quality. This means the image quality is not equally adapted to different lengths of sequences.\n\n> - **Algorithm & Acceleration**: Zangwei Zheng, Xiangyu Peng, Shenggui Li, Hongxing Liu, Yukun Zhou, Tianyi Li\n> - **Data Collection & Pipeline**: Xiangyu Peng, Zangwei Zheng, Chenhui Shen, Tom Young, Junjie Wang, Chenfeng Yu\n"
  },
  {
    "path": "docs/report_03.md",
    "content": "# Open-Sora 1.2 Report\n\n- [Video compression network](#video-compression-network)\n- [Rectified flow and model adaptation](#rectified-flow-and-model-adaptation)\n- [More data and better multi-stage training](#more-data-and-better-multi-stage-training)\n- [Easy and effective model conditioning](#easy-and-effective-model-conditioning)\n- [Evaluation](#evaluation)\n- [Sequence parallelism](#sequence-parallelism)\n\nIn Open-Sora 1.2 release, we train a 1.1B models on >30M data (\\~80k hours), with training cost 35k H100 GPU hours, supporting 0s\\~16s, 144p to 720p, various aspect ratios video generation. Our configurations is listed below. Following our 1.1 version, Open-Sora 1.2 can also do image-to-video generation and video extension.\n\n|      | image | 2s  | 4s  | 8s  | 16s |\n| ---- | ----- | --- | --- | --- | --- |\n| 240p | ✅     | ✅   | ✅   | ✅   | ✅   |\n| 360p | ✅     | ✅   | ✅   | ✅   | ✅   |\n| 480p | ✅     | ✅   | ✅   | ✅   | 🆗   |\n| 720p | ✅     | ✅   | ✅   | 🆗   | 🆗   |\n\nHere ✅ means that the data is seen during training, and 🆗 means although not trained, the model can inference at that config. Inference for 🆗 requires more than one 80G memory GPU and sequence parallelism.\n\nBesides features introduced in Open-Sora 1.1, Open-Sora 1.2 highlights:\n\n- Video compression network\n- Rectifie-flow training\n- More data and better multi-stage training\n- Easy and effective model conditioning\n- Better evaluation metrics\n\nAll implementations (both training and inference) of the above improvements are available in the Open-Sora 1.2 release. The following sections will introduce the details of the improvements. We also refine our codebase and documentation to make it easier to use and develop, and add a LLM to [refine input prompts](/README.md#gpt-4o-prompt-refinement) and support more languages.\n\n## Video compression network\n\nFor Open-Sora 1.0 & 1.1, we used stability-ai's 83M 2D VAE, which compress the video only in the spatial dimension by 8x8 times. To reduce the temporal dimension, we extracted one frame in every three frames. However, this method led to the low fluency of generated video as the generated fps is sacrificed. Thus, in this release, we introduce the video compression network as OpenAI's Sora does. With a 4 times compression in the temporal dimension, we do not need to extract frames and can generate videos with the original fps.\n\nConsidering the high computational cost of training a 3D VAE, we hope to re-use the knowledge learnt in the 2D VAE. We notice that after 2D VAE's compression, the features adjacent in the temporal dimension are still highly correlated. Thus, we propose a simple video compression network, which first compress the video in the spatial dimension by 8x8 times, then compress the video in the temporal dimension by 4x times. The network is shown below:\n\n![video_compression_network](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/report_3d_vae.png)\n\nWe initialize the 2D VAE with [SDXL's VAE](https://huggingface.co/stabilityai/sdxl-vae), which is better than our previously used one. For the 3D VAE, we adopt the structure of VAE in [Magvit-v2](https://magvit.cs.cmu.edu/v2/), which contains 300M parameters. Along with 83M 2D VAE, the total parameters of the video compression network is 384M. We train the 3D VAE for 1.2M steps with local batch size 1. The training data is videos from pixels and pixabay, and the training video size is mainly 17 frames, 256x256 resolution. Causal convolutions are used in the 3D VAE to make the image reconstruction more accurate.\n\nOur training involves three stages:\n\n1. For the first 380k steps, we train on 8 GPUs and freeze the 2D VAE. The training objective includes the reconstruction of the compressed features from 2D VAE (pink one in the figure) and also add a loss to make features from the 3D VAE similar to the features from the 2D VAE (pink one and green one, called identity loss). We find the latter loss can quickly make the whole VAE achieve a good performance for image and much faster to converge in the next stage.\n2. For the next 260k steps, We remove the identity loss and just learn the 3D VAE.\n3. For the last 540k steps , since we find only reconstruction 2D VAE's feature cannot lead to further improvement, we remove the loss and train the whole VAE to reconstruct the original videos. This stage is trained on on 24 GPUs.\n\nFor both stage 1 and stage 2 training, we adopt 20% images and 80% videos. Following [Magvit-v2](https://magvit.cs.cmu.edu/v2/), we train video using 17 frames, while zero-padding the first 16 frames for image. However, we find that this setting leads to blurring of videos with length different from 17 frames. Thus, in stage 3, we use a random number within 34 frames for mixed video length training (a.k.a., zero-pad the first  `43-n` frames if we want to train a `n` frame video), to make our VAE more robust to different video lengths. Our [training](/scripts/train_vae.py) and [inference](/scripts/inference_vae.py) code is available in the Open-Sora 1.2 release.\n\nWhen using the VAE for diffusion model, our stacked VAE requires small memory as the our VAE's input is already compressed. We also split the input videos input several 17 frames clips to make the inference more efficient.  The performance of our VAE is on par with another open-sourced 3D VAE in [Open-Sora-Plan](https://github.com/PKU-YuanGroup/Open-Sora-Plan/blob/main/docs/Report-v1.1.0.md).\n\n| Model              | SSIM↑ | PSNR↑  |\n| ------------------ | ----- | ------ |\n| Open-Sora-Plan 1.1 | 0.882 | 29.890 |\n| Open-Sora 1.2      | 0.880 | 30.590 |\n\n## Rectified flow and model adaptation\n\nLastest diffusion model like Stable Diffusion 3 adopts the [rectified flow](https://github.com/gnobitab/RectifiedFlow) instead of DDPM for better performance. Pitiably, SD3's rectified flow training code is not open-sourced. However, Open-Sora 1.2 provides the training code following SD3's paper, including:\n\n- Basic rectified flow training ([original rectified flow paper](https://arxiv.org/abs/2209.03003))\n- Logit-norm sampling for training acceleration ([SD3 paper](https://arxiv.org/pdf/2403.03206) Section 3.1, intuitively it is more likely to sample timesteps at middle noise level)\n- Resolution and video length aware timestep sampling ([SD3 paper](https://arxiv.org/pdf/2403.03206) Section 5.3.2, intuitively it is more likely to sample timesteps with more noise for larger resolution, and we extend it to longer video)\n\nFor the resolution-aware timestep sampling, we should use more noise for images with larger resolution. We extend this idea to video generation and use more noise for videos with longer length.\n\nOpen-Sora 1.2 starts from the [PixArt-Σ 2K](https://github.com/PixArt-alpha/PixArt-sigma) checkpoint. Note that this model is trained with DDPM and SDXL VAE, also a much higher resolution. We find finetuning on a small dataset can easily adapt the model for our video generation setting. The adaptation process is as follows, all training is done on 8 GPUs (the adaptation for the diffusion model is quite fast and straightforward):\n\n1. Multi-resolution image generation ability: we train the model to generate different resolution ranging from 144p to 2K for 20k steps.\n2. QK-norm: we add the QK-norm to the model and train for 18k steps.\n3. Rectified flow: we transform from discrete-time DDPM to continuous-time rectified flow and train for 10k steps.\n4. Rectified flow with logit-norm sampling and resolution-aware timestep sampling: we train for 33k steps.\n5. Smaller AdamW epsilon: following SD3, with QK-norm, we can use a smaller epsilon (1e-15) for AdamW, we train for 8k steps.\n6. New VAE and fps conditioning: we replace the original VAE with ours and add fps conditioning to the timestep conditioning, we train for 25k steps. Note that normalizing each channel is important for rectified flow training.\n7. Temporal attention blocks: we add temporal attention blocks with zero initialized projection layers. We train on images for 3k steps.\n8. Temporal blocks only for video with mask strategy: we train the temporal attention blocks only on videos for 38k steps.\n\nAfter the above adaptation, we are ready to train the model on videos. The adaptation above maintains the original model's ability to generate high-quality images, and brings multiple benefits for video generation:\n\n- With rectified flow, we can accelerate the training and reduce the number of sampling steps for video from 100 to 30, which greatly reduces the waiting time for inference.\n- With qk-norm, the training is more stablized and an aggressive optimizer can be used.\n- With new VAE, the temporal dimension is compressed by 4 times, which makes the training more efficient.\n- With multi-resolution image generation ability, the model can generate videos with different resolutions.\n\n## More data and better multi-stage training\n\nDue to a limited computational budget, we carefully arrange the training data from low to high quality and split our training into three stages. Our training involves 12x8 GPUs, and the total training time is about 2 weeks for about 70k steps.\n\n### First stage\n\nWe first train the model on Webvid-10M datasets (40k hours) for 30k steps (2 epochs). Since the video is all lower than 360p resolution and contains watermark, we train on this dataset first. The training mainly happens on 240p and 360p, with video length 2s~16s. We use the original caption in the dataset for training. The training config locates in [stage1.py](/configs/opensora-v1-2/train/stage1.py).\n\n### Second stage\n\nThen we train the model on Panda-70M datasets. This dataset is large but the quality varies. We use the official 30M subset which clips are more diverse, and filter out videos with aesthetic score lower than 4.5. This leads to a 20M subset with 41k hours. The captions in the dataset are directly used for our training. The training config locates in [stage2.py](/configs/opensora-v1-2/train/stage2.py).\n\nThe training mainly happens on 360p and 480p. We train the model for 23k steps, which is 0.5 epoch. The training is not fully done since we hope our new model can meet you earlier.\n\n### Third stage\n\nIn this stage, we collect ~2M video clips with a total length of 5K hours from all kinds of sources, including:\n\n- Free-license videos, sourced from Pexels, Pixabay, Mixkit, etc.\n- [MiraData](https://github.com/mira-space/MiraData): a high-quality dataset with long videos, mainly from games and city/scenic exploration.\n- [Vript](https://github.com/mutonix/Vript/tree/main): a densely annotated dataset.\n- And some other datasets.\n\nWhile MiraData and Vript have captions from GPT, we use [PLLaVA](https://github.com/magic-research/PLLaVA) to caption the rest ones. Compared with LLaVA, which is only capable of single frame/image captioning, PLLaVA is specially designed and trained for video captioning. The [accelerated PLLaVA](/tools/caption/README.md#pllava-captioning) is released in our `tools/`. In practice, we use the pretrained PLLaVA 13B model and select 4 frames from each video for captioning with a spatial pooling shape of 2*2.\n\nSome statistics of the video data used in this stage are shown below. We present basic statistics of duration and resolution, as well as aesthetic score and optical flow score distribution.\nWe also extract tags for objects and actions from video captions and count their frequencies.\n![stats](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/report-03_video_stats.png)\n![object_count](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/report-03_objects_count.png)\n![object_count](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/report-03_actions_count.png)\n\nWe mainly train 720p and 1080p videos in this stage, aiming to extend the model's ability to larger resolutions. We use a mask ratio of 25% during training. The training config locates in [stage3.py](/configs/opensora-v1-2/train/stage3.py). We train the model for 15k steps, which is approximately 2 epochs.\n\n## Easy and effective model conditioning\n\nFor stage 3, we calculate the aesthetic score and motion score for each video clip. However, since the number of video clips is small, we are not willing to filter out clips with low scores, which leads to a smaller dataset. Instead, we append the scores to the captions and use them as conditioning. We find this method can make model aware of the scores and follows the scores to generate videos with better quality.\n\nFor example, a video with aesthetic score 5.5, motion score 10, and a detected camera motion pan left, the caption will be:\n\n```plaintext\n[Original Caption] aesthetic score: 5.5, motion score: 10, camera motion: pan left.\n```\n\nDuring inference, we can also use the scores to condition the model. For camera motion, we only label 13k clips with high confidence, and the camera motion detection module is released in our tools.\n\n## Evaluation\n\nPreviously, we monitor the training process only by human evaluation, as DDPM traning loss is not well correlated with the quality of generated videos. However, for rectified flow, we find the training loss is well correlated with the quality of generated videos as stated in SD3. Thus, we keep track of rectified flow evaluation loss on 100 images and 1k videos.\n\nWe sampled 1k videos from pixabay as validation dataset. We calculate the evaluation loss for image and different lengths of videos (2s, 4s, 8s, 16s) for different resolution (144p, 240p, 360p, 480p, 720p). For each setting, we equidistantly sample 10 timesteps. Then all the losses are averaged. We also provide a [video](https://streamable.com/oqkkf1) showing the sampled videos with a fixed prompt for different steps.\n\n![Evaluation Loss](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/report_val_loss.png)\n![Video Evaluation Loss](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/report_vid_val_loss.png)\n\nIn addition, we also keep track of [VBench](https://vchitect.github.io/VBench-project/) scores during training. VBench is an automatic video evaluation benchmark for short video generation. We calcuate the vbench score with 240p 2s videos. The two metrics verify that our model continues to improve during training.\n\n![VBench](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/report_vbench_score.png)\n\nAll the evaluation code is released in `eval` folder. Check the [README](/eval/README.md) for more details.\n\n| Model          | Total Score | Quality Score | Semantic Score |\n| -------------- | ----------- | ------------- | -------------- |\n| Open-Sora V1.0 | 75.91%      | 78.81%        | 64.28%         |\n| Open-Sora V1.2 | 79.23%      | 80.71%        | 73.30%         |\n\n## Sequence parallelism\n\nWe use sequence parallelism to support long-sequence training and inference. Our implementation is based on Ulysses and the workflow is shown below. When sequence parallelism is enabled, we only need to apply the `all-to-all` communication to the spatial block in STDiT as only spatial computation is dependent on the sequence dimension.\n\n![SP](..https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/sequence_parallelism.jpeg)\n\nCurrently, we have not used sequence parallelism for training as data resolution is small and we plan to do so in the next release. As for inference, we can use sequence parallelism in case your GPU goes out of memory. A simple benchmark shows that sequence parallelism can achieve speedup\n\n| Resolution | Seconds | Number of GPUs | Enable SP | Time taken/s | Speedup per GPU |\n| ---------- | ------- | -------------- | --------- | ------------ | --------------- |\n| 720p       | 16s     | 1              | No        | 547.97       | -               |\n| 720p       | 16s     | 2              | Yes       | 244.38       | 12%             |\n"
  },
  {
    "path": "docs/report_04.md",
    "content": "# Open-Sora 1.3 Report\n\n- [Video compression network](#video-compression-network)\n- [Upgraded STDiT with shifted-window attention](#upgraded-stdit-with-shifted-window-attention)\n- [Easy and effective model conditioning](#easy-and-effective-model-conditioning)\n- [Evaluation](#evaluation)\n\nIn Open-Sora 1.3 release, we train a 1.1B models on >60M data (\\~85k hours), with training cost 35k H100 GPU hours, supporting 0s\\~113 frames, 360p & 720p, various aspect ratios video generation. Our configurations is listed below. Following our 1.2 version, Open-Sora 1.3 can also do image-to-video generation and video extension.\n\n|      | image | 49 frames  | 65 frames  | 81 frames  | 97 frames | 113 frames |\n| ---- | ----- | ---------- | ---------- | ---------- | --------- | ---------- |\n| 360p | ✅     | ✅         | ✅         | ✅         | ✅         |✅          |\n| 720p | ✅     | ✅         | ✅         | ✅         | ✅         |✅          |\n\nHere ✅ means that the data is seen during training.\n\nBesides features introduced in Open-Sora 1.2, Open-Sora 1.3 highlights:\n\n- Video compression network\n- Upgraded STDiT with shifted-window attention\n- More data and better multi-stage training\n- Easy and effective model conditioning\n- Better evaluation metrics\n\nAll implementations (both training and inference) of the above improvements are available in the Open-Sora 1.3 release. The following sections will introduce the details of the improvements. We also refine our codebase and documentation to make it easier to use and develop, and add a LLM refiner to [refine input prompts](/README.md#gpt-4o-prompt-refinement) and support more languages.\n\n## Video compression network\n\nIn Open-Sora 1.2, the video compression architecture employed a modular approach, where spatial and temporal dimensions were handled separately. The spatial VAE, based on Stability AI's SDXL VAE, compressed individual frames along the spatial dimensions. The temporal VAE then processed the latent representations from the spatial VAE to handle temporal compression. This two-stage design allowed effective spatial and temporal compression but introduced limitations. These included inefficiencies in handling long videos due to fixed-length input frames, a lack of seamless integration between spatial and temporal features, and higher memory requirements during both training and inference.\n\nOpen-Sora 1.3 introduces a unified approach to video compression. By combining spatial and temporal processing into a single framework and leveraging advanced features like tiled 3D convolutions and dynamic frame support, Open-Sora 1.3 achieves improved better efficiency, scalability, and reconstruction quality. Here are the key improvements in Open-Sora 1.3 VAE:\n\n**1. Unified Spatial-Temporal Processing:** Instead of using separate VAEs for spatial and temporal compression, Open-Sora 1.3 adopts a single encoder-decoder structure that simultaneously handles both dimensions. This approach eliminates the need for intermediate representations and redundant data transfers between spatial and temporal modules.\n\n**2. Tiled 3D Convolutions:** Open-Sora 1.3 incorporates tiled 3D convolution support for the temporal dimension. By breaking down videos into smaller temporal tiles, this feature enables efficient encoding and decoding of longer video sequences without increasing memory overhead. This improvement addresses the limitations of Open-Sora 1.2 in handling large frame counts and ensures higher flexibility in temporal compression.\n\n**3. Dynamic Micro-Batch and Micro-Frame Processing:** Open-Sora 1.3 introduces a new micro-batch and micro-frame processing mechanism. This allows for: (1) Adaptive temporal overlap: Overlapping frames during temporal encoding and decoding help reduce discontinuities at tile boundaries. (2) Dynamic frame size support: Instead of being restricted to fixed-length sequences (e.g., 17 frames in Open-Sora 1.2), Open-Sora 1.3 supports dynamic sequence lengths, making it robust for varied video lengths.\n\n**4. Unified Normalization Mechanism:** The normalization process in Open-Sora 1.3 has been refined with tunable scaling (scale) and shifting (shift) parameters that ensure consistent latent space distributions across diverse datasets. Unlike Open-Sora 1.2, where normalization was specific to fixed datasets, this version introduces more generalized parameters and support for frame-specific normalization strategies.\n\n\n#### Summary of Improvements\n\n| Feature                | Open-Sora 1.2                          | Open-Sora 1.3                          |\n|------------------------|-----------------------------------------|-----------------------------------------|\n| **Architecture**       | Separate spatial and temporal VAEs      | Unified spatial-temporal VAE            |\n| **Tiled Processing**   | Not supported                          | Supported (Tiled 3D Convolutions)       |\n| **Frame Length Support**| Fixed (17 frames)                      | Dynamic frame support with overlap      |\n| **Normalization**      | Fixed parameters                       | Tunable scaling and shifting            |\n\n\n## Upgraded STDiT with shifted-window attention\n\nFollowing the success of OpenSora 1.2, version 1.3 introduces several architectural improvements and new capabilities to enhance video generation quality and flexibility. This section outlines the key improvements and differences between these two versions.\n\nLatest diffusion models like Stable Diffusion 3 adopt the [rectified flow](https://github.com/gnobitab/RectifiedFlow) instead of DDPM for better performance. While SD3's rectified flow training code is not open-sourced, OpenSora provides the training code following SD3's paper. OpenSora 1.2 introduced several key strategies from SD3:\n\n1. Basic rectified flow training, which enables continuous-time diffusion\n2. Logit-norm sampling for training acceleration (following SD3 paper Section 3.1), preferentially sampling timesteps at middle noise levels\n3. Resolution and video length aware timestep sampling (following SD3 paper Section 5.3.2), using more noise for larger resolutions and longer videos\n\nFor OpenSora 1.3, we further enhance the model with significant improvements in architecture, capabilities, and performance:\n\n#### 1. Shift-Window Attention Mechanism\n- Introduced kernel-based local attention with configurable kernel_size for efficient computation\n- Implemented shift-window partitioning strategy similar to Swin Transformer\n- Added padding mask handling for window boundaries with extra_pad_on_dims support\n- Extended position encoding with 3D relative positions within local windows (temporal, height, width)\n#### 2. Enhanced Position Encoding\n- Improved RoPE implementation with reduced rotation_dim (1/3 of original) for 3D scenarios\n- Added separate rotary embeddings for temporal, height, and width dimensions\n- Implemented resolution-adaptive scaling for position encodings\n- Optional spatial RoPE for better spatial relationship modeling\n#### 3. Flexible Generation\n- Added I2V and V2V capabilities with dedicated conditioning mechanisms\n- Introduced conditional embedding modules (x_embedder_cond and x_embedder_cond_mask)\n- Zero-initialized condition embeddings for stable training\n- Flexible temporal modeling with skip_temporal option\n#### 4. Performance Optimization\n- Refined Flash Attention triggering conditions (N > 128) for better efficiency\n- Added support for torch.scaled_dot_product_attention (SDPA) as an alternative backend\n- Optimized memory usage through improved padding and window partitioning\n- Enhanced sequence parallelism with adaptive height padding\n\nThe adaptation process from [PixArt-Σ 2K](https://github.com/PixArt-alpha/PixArt-sigma) remains similar but with additional steps:\n1-7. [Same as v1.2: multi-resolution training, QK-norm, rectified flow, logit-norm sampling, smaller AdamW epsilon, new VAE, and basic temporal attention]\n#### 8. Enhanced temporal blocks\n   - Added kernel-based local attention with shift-window support\n   - Implemented 3D relative position encoding with resolution-adaptive scaling\n   - Zero-initialized projection layers with improved initialization strategy\n\nCompared to v1.2 which focused on basic video generation, v1.3 brings substantial improvements in three key areas: **1. Quality**: Enhanced spatial-temporal modeling through shift-window attention and 3D position encoding. **2. Flexibility**: Support for I2V/V2V tasks and configurable temporal modeling. **3. Efficiency**: Optimized attention computation and memory usage\n\nThese improvements maintain backward compatibility with v1.2's core features while extending the model's capabilities for real-world applications. The model retains its ability to generate high-quality images and videos using rectified flow, while gaining new strengths in conditional generation and long sequence modeling.\n\n## Easy and effective model conditioning\n\nWe calculate the aesthetic score and motion score for each video clip, and filter out those clips with low scores, which leads to a dataset with better video quality. Additionally, we append the scores to the captions and use them as conditioning. Specifically, we convert numerical scores into descriptive language based on predefined ranges. The aesthetic score transformation function converts numerical aesthetic scores into descriptive labels based on predefined ranges: scores below 4 are labeled \"terrible,\" progressing through \"very poor,\" \"poor,\" \"fair,\" \"good,\" and \"very good,\" with scores of 6.5 or higher labeled as \"excellent.\" Similarly, the motion score transformation function maps motion intensity scores to descriptors: scores below 0.5 are labeled \"very low,\" progressing through \"low,\" \"fair,\" \"high,\" and \"very high,\" with scores of 20 or more labeled as \"extremely high.\" We find this method can make model aware of the scores and follows the scores to generate videos with better quality.\n\nFor example, a video with aesthetic score 5.5, motion score 10, and a detected camera motion pan left, the caption will be:\n\n```plaintext\n[Original Caption] The aesthetic score is good, the motion strength is high, camera motion: pan left.\n```\n\nDuring inference, we can also use the scores to condition the model. For camera motion, we only label 13k clips with high confidence, and the camera motion detection module is released in our tools.\n\n## Evaluation\n\nPreviously, we monitor the training process only by human evaluation, as DDPM traning loss is not well correlated with the quality of generated videos. However, for rectified flow, we find the training loss is well correlated with the quality of generated videos as stated in SD3. Thus, we keep track of rectified flow evaluation loss on 100 images and 1k videos.\n\nWe sampled 1k videos from pixabay as validation dataset. We calculate the evaluation loss for image and different lengths of videos (49 frames, 65 frames, 81 frames, 97 frames, 113 frames) for different resolution (360p, 720p). For each setting, we equidistantly sample 10 timesteps. Then all the losses are averaged.\n\nIn addition, we also keep track of [VBench](https://vchitect.github.io/VBench-project/) scores during training. VBench is an automatic video evaluation benchmark for short video generation. We calcuate the vbench score with 360p 49-frame videos. The two metrics verify that our model continues to improve during training.\n\nAll the evaluation code is released in `eval` folder. Check the [README](/eval/README.md) for more details.\n"
  },
  {
    "path": "docs/train.md",
    "content": "# Step by step to train or finetune your own model\n\n## Installation\n\nBesides from the installation in the main page, you need to install the following packages:\n\n```bash\npip install git+https://github.com/hpcaitech/TensorNVMe.git # requires cmake, for checkpoint saving\npip install pandarallel # for parallel processing\n```\n\n## Prepare dataset\n\nThe dataset should be presented in a `csv` or `parquet` file. To better illustrate the process, we will use a 45k [pexels dataset](https://huggingface.co/datasets/hpcai-tech/open-sora-pexels-45k) as an example. This dataset contains clipped, score filtered high-quality videos from [Pexels](https://www.pexels.com/).\n\nFirst, download the dataset to your local machine:\n\n```bash\nmkdir datasets\ncd datasets\n# For Chinese users, export HF_ENDPOINT=https://hf-mirror.com to speed up the download\nhuggingface-cli download --repo-type dataset hpcai-tech/open-sora-pexels-45k --local-dir open-sora-pexels-45k # 250GB\n\ncd open-sora-pexels-45k\ncat tar/pexels_45k.tar.* > pexels_45k.tar\ntar -xvf pexels_45k.tar\nmv pexels_45k .. # make sure the path is Open-Sora/datasets/pexels_45k\n```\n\nThere are three `csv` files provided:\n\n- `pexels_45k.csv`: contains only path and text, which needs to be processed for training.\n- `pexels_45k_necessary.csv`: contains necessary information for training.\n- `pexels_45k_score.csv`: contains score information for each video. The 45k videos are filtered out based on the score. See tech report for more details.\n\nIf you want to use custom dataset, at least the following columns are required:\n\n```csv\npath,text,num_frames,height,width,aspect_ratio,resolution,fps\n```\n\nWe provide a script to process the `pexels_45k.csv` to `pexels_45k_necessary.csv`:\n\n```bash\n# single process\npython scripts/cnv/meta.py --input datasets/pexels_45k.csv --output datasets/pexels_45k_nec.csv --num_workers 0\n# parallel process\npython scripts/cnv/meta.py --input datasets/pexels_45k.csv --output datasets/pexels_45k_nec.csv --num_workers 64\n```\n\n> The process may take a while, depending on the number of videos in the dataset. The process is neccessary for training on arbitrary aspect ratio, resolution, and number of frames.\n\n## Training\n\nThe command format to launch training is as follows:\n\n```bash\ntorchrun --nproc_per_node 8 scripts/diffusion/train.py [path/to/config] --dataset.data-path [path/to/dataset] [override options]\n```\n\nFor example, to train a model with stage 1 config from scratch using pexels dataset:\n\n```bash\ntorchrun --nproc_per_node 8 scripts/diffusion/train.py configs/diffusion/train/stage1.py --dataset.data-path datasets/pexels_45k_necessary.csv\n```\n\n### Config\n\nAll configs are located in `configs/diffusion/train/`. The following rules are applied:\n\n- `_base_ = [\"config_to_inherit\"]`: inherit from another config by mmengine's support. Variables are overwritten by the new config. Dictionary is merged if `_delete_` key is not present.\n- command line arguments override the config file. For example, `--lr 1e-5` will override the `lr` in the config file. `--dataset.data-path datasets/pexels_45k_necessary.csv` will override the `data-path` value in the dictionary `dataset`.\n\nThe `bucket_config` is used to control different training stages. It is a dictionary of dictionaries. The tuple means (sampling probability, batch size). For example:\n\n```python\nbucket_config = {\n    \"256px\": {\n        1: (1.0, 45), # for 256px images, use 100% of the data with batch size 45\n        33: (1.0, 12), # for 256px videos with no less than 33 frames, use 100% of the data with batch size 12\n        65: (1.0, 6), # for 256px videos with no less than 65 frames, use 100% of the data with batch size 6\n        97: (1.0, 4), # for 256px videos with no less than 97 frames, use 100% of the data with batch size 4\n        129: (1.0, 3), # for 256px videos with no less than 129 frames, use 100% of the data with batch size 3\n    },\n    \"768px\": {\n        1: (0.5, 13), # for 768px images, use 50% of the data with batch size 13\n    },\n    \"1024px\": {\n        1: (0.5, 7), # for 1024px images, use 50% of the data with batch size 7\n    },\n}\n```\n\nWe provide the following configs, the batch size is searched on H200 GPUs with 140GB memory:\n\n- `image.py`: train on images only.\n- `stage1.py`: train on videos with 256px resolution.\n- `stage2.py`: train on videos with 768px resolution with sequence parallelism (default 4).\n- `stage1_i2v.py`: train t2v and i2v with 256px resolution.\n- `stage2_i2v.py`: train t2v and i2v with 768px resolution.\n\nWe also provide a demo config `demo.py` with small batch size for debugging.\n\n### Fine-tuning\n\nTo finetune from Open-Sora v2, run:\n\n```bash\ntorchrun --nproc_per_node 8 scripts/diffusion/train.py configs/diffusion/train/stage1.py --dataset.data-path datasets/pexels_45k_necessary.csv --model.from_pretrained ckpts/Open_Sora_v2.safetensors\n```\n\nTo finetune from flux-dev, we provided a transformed flux-dev [ckpts](https://huggingface.co/hpcai-tech/flux1-dev-fused-rope). Download it to `ckpts` and run:\n\n```bash\ntorchrun --nproc_per_node 8 scripts/diffusion/train.py configs/diffusion/train/stage1.py --dataset.data-path datasets/pexels_45k_necessary.csv --model.from_pretrained ckpts/flux1-dev-fused-rope.safetensors\n```\n\n### Multi-GPU\n\nTo train on multiple GPUs, use `colossalai run`:\n\n```bash\ncolossalai run --hostfile hostfiles --nproc_per_node 8 scripts/diffusion/train.py configs/diffusion/train/stage1.py --dataset.data-path datasets/pexels_45k_necessary.csv --model.from_pretrained ckpts/Open_Sora_v2.safetensors\n```\n\n`hostfiles` is a file that contains the IP addresses of the nodes. For example:\n\n```bash\nxxx.xxx.xxx.xxx\nyyy.yyy.yyy.yyy\nzzz.zzz.zzz.zzz\n```\n\nuse `--wandb True` to log the training process to [wandb](https://wandb.ai/).\n\n### Resume training\n\nTo resume training, use `--load`. It will load the optimizer state and dataloader state.\n\n```bash\ntorchrun --nproc_per_node 8 scripts/diffusion/train.py configs/diffusion/train/stage1.py --dataset.data-path datasets/pexels_45k_necessary.csv --load outputs/your_experiment/epoch*-global_step*\n```\n\nIf you want to load optimzer state but not dataloader state, use:\n\n```bash\ntorchrun --nproc_per_node 8 scripts/diffusion/train.py configs/diffusion/train/stage1.py --dataset.data-path datasets/pexels_45k_necessary.csv --load outputs/your_experiment/epoch*-global_step* --start-step 0 --start-epoch 0\n```\n\n> Note if dataset, batch size, and number of GPUs are changed, the dataloader state will not be meaningful.\n\n## Inference\n\nThe inference is the same as described in the main page. The command format is as follows:\n\n```bash\ntorchrun --nproc_per_node 1 --standalone scripts/diffusion/inference.py configs/diffusion/inference/t2i2v_256px.py --save-dir samples --prompt \"raining, sea\" --model.from_pretrained outputs/your_experiment/epoch*-global_step*\n```\n\n## Advanced Usage\n\nMore details are provided in the tech report. If explanation for some techiques is needed, feel free to open an issue.\n\n- Tensor parallelism and sequence parallelism\n- Zero 2\n- Pin memory organization\n- Garbage collection organization\n- Data prefetching\n- Communication bucket optimization\n- Shardformer for T5\n\n### Gradient Checkpointing\n\nWe support selective gradient checkpointing to save memory. The `grad_ckpt_setting` is a tuple, the first element is the number of dual layers to apply gradient checkpointing, the second element is the number of single layers to apply full gradient. A very large number will apply full gradient to all layers.\n\n```python\ngrad_ckpt_setting = (100, 100)\nmodel = dict(\n    grad_ckpt_setting=grad_ckpt_setting,\n)\n```\n\nTo further save memory, you can offload gradient checkpointing to CPU by:\n\n```python\ngrad_ckpt_buffer_size = 25 * 1024**3 # 25GB\n```\n\n### Asynchronous Checkpoint Saving\n\nWith `--async-io True`, the checkpoint will be saved asynchronously with the support of ColossalAI. This will save time for checkpoint saving.\n\n### Dataset\n\nWith a very large dataset, the `csv` file or even `parquet` file may be too large to fit in memory. We provide a script to split the dataset into smaller chunks:\n\n```bash\npython scripts/cnv/shard.py /path/to/dataset.parquet\n```\n\nThen a folder with shards will be created. You can use the `--dataset.memory_efficient True` to load the dataset shard by shard.\n"
  },
  {
    "path": "docs/zh_CN/report_v1.md",
    "content": "# Open-Sora v1 技术报告\n\nOpenAI的Sora在生成一分钟高质量视频方面非常出色。然而，它几乎没有透露任何关于其细节的信息。为了使人工智能更加“开放”，我们致力于构建一个开源版本的Sora。这份报告描述了我们第一次尝试训练一个基于Transformer的视频扩散模型。\n\n## 选择高效的架构\n\n为了降低计算成本，我们希望利用现有的VAE模型。Sora使用时空VAE来减少时间维度。然而，我们发现没有开源的高质量时空VAE模型。[MAGVIT](https://github.com/google-research/magvit)的4x4x4 VAE并未开源，而[VideoGPT](https://wilson1yan.github.io/videogpt/index.html)的2x4x4 VAE在我们的实验中质量较低。因此，我们决定在我们第一个版本中使用2D VAE（来自[Stability-AI](https://huggingface.co/stabilityai/sd-vae-ft-mse-original)）。\n\n视频训练涉及大量的token。考虑到24fps的1分钟视频，我们有1440帧。通过VAE下采样4倍和patch大小下采样2倍，我们得到了1440x1024≈150万个token。在150万个token上进行全注意力计算将带来巨大的计算成本。因此，我们使用时空注意力来降低成本，这是遵循[Latte](https://github.com/Vchitect/Latte)的方法。\n\n如图中所示，在STDiT（ST代表时空）中，我们在每个空间注意力之后立即插入一个时间注意力。这类似于Latte论文中的变种3。然而，我们并没有控制这些变体的相似数量的参数。虽然Latte的论文声称他们的变体比变种3更好，但我们在16x256x256视频上的实验表明，相同数量的迭代次数下，性能排名为：DiT（完整）> STDiT（顺序）> STDiT（并行）≈ Latte。因此，我们出于效率考虑选择了STDiT（顺序）。[这里](/docs/acceleration.md#efficient-stdit)提供了速度基准测试。\n\n\n![Architecture Comparison](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/report_arch_comp.png)\n\n为了专注于视频生成，我们希望基于一个强大的图像生成模型来训练我们的模型。PixArt-α是一个经过高效训练的高质量图像生成模型，具有T5条件化的DiT结构。我们使用[PixArt-α](https://github.com/PixArt-alpha/PixArt-alpha)初始化我们的模型，并将插入的时间注意力的投影层初始化为零。这种初始化在开始时保留了模型的图像生成能力，而Latte的架构则不能。插入的注意力将参数数量从5.8亿增加到7.24亿。\n\n![Architecture](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/report_arch.jpg)\n\n借鉴PixArt-α和Stable Video Diffusion的成功，我们还采用了渐进式训练策略：在366K预训练数据集上进行16x256x256的训练，然后在20K数据集上进行16x256x256、16x512x512和64x512x512的训练。通过扩展位置嵌入，这一策略极大地降低了计算成本。\n\n我们还尝试在DiT中使用3D patch嵌入器。然而，在时间维度上2倍下采样后，生成的视频质量较低。因此，我们将在下一版本中将下采样留给时间VAE。目前，我们在每3帧采样一次进行16帧训练，以及在每2帧采样一次进行64帧训练。\n\n\n## 数据是训练高质量模型的核心\n\n我们发现数据的数量和质量对生成视频的质量有很大的影响，甚至比模型架构和训练策略的影响还要大。目前，我们只从[HD-VG-130M](https://github.com/daooshee/HD-VG-130M)准备了第一批分割（366K个视频片段）。这些视频的质量参差不齐，而且字幕也不够准确。因此，我们进一步从提供免费许可视频的[Pexels](https://www.pexels.com/)收集了20k相对高质量的视频。我们使用LLaVA，一个图像字幕模型，通过三个帧和一个设计好的提示来标记视频。有了设计好的提示，LLaVA能够生成高质量的字幕。\n\n![Caption](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/report_caption.png)\n\n由于我们更加注重数据质量，我们准备收集更多数据，并在下一版本中构建一个视频预处理流程。\n\n## 训练细节\n\n在有限的训练预算下，我们只进行了一些探索。我们发现学习率1e-4过大，因此将其降低到2e-5。在进行大批量训练时，我们发现`fp16`比`bf16`不太稳定，可能会导致生成失败。因此，我们在64x512x512的训练中切换到`bf16`。对于其他超参数，我们遵循了之前的研究工作。\n\n## 损失曲线\n\n16x256x256 预训练损失曲线\n\n![16x256x256 Pretraining Loss Curve](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/report_loss_curve_1.png)\n\n16x256x256 高质量训练损失曲线\n\n![16x256x256 HQ Training Loss Curve](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/report_loss_curve_2.png)\n\n16x512x512 高质量训练损失曲线\n\n![16x512x512 HQ Training Loss Curve](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/report_loss_curve_3.png)\n"
  },
  {
    "path": "docs/zh_CN/report_v2.md",
    "content": "# Open-Sora 1.1 技术报告\n\n- [模型架构修改](#模型架构修改)\n- [支持不同视频长度/分辨率/宽高比/帧率（fps）训练](#支持不同视频长度分辨率宽高比帧率fps训练)\n- [使用Masked DiT作为图生视频/视频生视频模型](#使用masked-dit作为图生视频视频生视频模型)\n- [数据收集和流程](#数据收集和流程)\n- [训练详情](#训练详情)\n- [结果和评价](#结果和评价)\n- [不足和下一步计划](#不足和下一步计划)\n\n在Open-Sora1.1版本中，我们使用了10M数据来训练经过结构调优后的STDiT的700M模型（Open-Sora1.0版本仅用400K数据）。我们实现了[Sora报告](https://openai.com/research/video-generation-models-as-world-simulators)中提到的以下功能：\n\n- 可变的视频时长、分辨率、宽高比（包括采样灵活性、改进的取景范围和构图）\n- 提示词增加图片和视频选项（使图像动起来、生成式增长视频、视频到视频编辑、连接不同视频）\n- 图像生成功能\n\n为了实现这一目标，我们在预训练阶段使用了多任务学习。对于扩散模型来说，用不同的采样时间步长进行训练已经是一种多任务学习。我们将这一思想在图像和视频的条件生成模型上，进一步扩展到多分辨率、宽高比、帧长、fps以及不同的掩码策略。我们在**0~15s、144p到720p、各种宽高比的视频**上训练模型。虽然由于训练FLOPs不足的限制，生成的视频在时间一致性上的表现没有那么高，但我们仍然可以看到这个模型的巨大潜力。\n\n## 模型架构修改\n\n我们对原始ST-DiT模型进行了以下修改，以获得更好的训练稳定性和模型性能（ST-DiT-2）：\n\n- **在时间注意力模块中添加[旋转位置编码](https://arxiv.org/abs/2104.09864)**：遵循目前LLM的最佳实践，我们将时间注意力模块中的正弦位置编码更改为旋转位置编码，因为它也算一项序列预测任务。\n- **在时间注意力模块中添加AdaIN和Layernormal**：我们将时间注意力与AdaIN和Layer范数作为空间注意力包裹起来，以稳定训练。\n- **[QK归一化](https://arxiv.org/abs/2302.05442)与[RMSNorm](https://arxiv.org/abs/1910.07467)**：和[SD3](https://arxiv.org/pdf/2403.03206.pdf)类似地，我们应用QK归一化来提高半精度训练的稳定性。\n- **支持动态输入大小和视频条件限定**：为了支持多分辨率、宽高比和fps训练，我们ST-DiT-2来接受任何输入大小。延申[PixArt-alpha](https://github.com/PixArt-alpha/PixArt-alpha)的想法，我们支持限定视频的高度、宽度、宽高比、帧长和fps。\n- **将T5token数量从120扩展到200**：我们使用的视频描述通常少于200个token，我们发现模型也可以很好地处理更长的文本。\n\n## 支持不同视频长度/分辨率/宽高比/帧率（fps）训练\n\n正如[Sora报告](https://openai.com/research/video-generation-models-as-world-simulators)中提到的，使用原始无损视频的分辨率、宽高比和视频长度进行训练可以增加采样灵活性，改善取景和构图。我们找到了三种实现这一目标的方法：\n- [NaViT](https://arxiv.org/abs/2307.06304)：通过不同掩码策略支持在同一训练批次内使用不同大小的数据，并且训练效率下降很少。然而，该系统实现起来有点复杂，并且可能无法兼容kernal优化技术（如flashattention）。\n- 填充（[FiT](https://arxiv.org/abs/2402.12376)，[Open-Sora-Plan](https://github.com/PKU-YuanGroup/Open-Sora-Plan)）：通过填充支持同一批次内的不同大小的数据。然而，将不同的分辨率填充到相同的大小会导致效率降低。\n- 分桶训练（[SDXL](https://arxiv.org/abs/2307.01952)、[PixArt](https://arxiv.org/abs/2310.00426)）：支持通过分桶的方式在不同批次中动态调整大小，但在同一批次内数据大小必须相同，只能应用固定数量的数据大小。在一个批次中，我们不需要实现复杂的掩码或填充。\n\n为了更便捷的实现，我们选择分桶训练的方式。我们预先定义了一些固定的分辨率，并将不同的样本分配到不同的桶中。下面列出了分桶方案中值得注意的点。但我们可以看到，这些在我们的实验中并不是一个大问题。\n\n<details>\n<summary>查看注意事项</summary>\n\n- 桶大小被限制为固定数量：首先，在实际应用中，通常只使用少数宽高比（9:16、3:4）和分辨率（240p、1080p）。其次，我们发现经过训练的模型可以很好地推广到未见过的解决方案。\n- 每批的大小相同，打破了独立同分布（i.i.d.）假设：由于我们使用多个 GPU，因此不同 GPU 上的本地批次具有不同的大小。我们没有发现此问题导致性能显着下降。\n- 可能没有足够的样本来填充每个桶，并且分布可能有偏差：首先，当本地批量大小不太大时，我们的数据集足够大以填充每个桶。其次，我们应该分析数据大小的分布并相应地定义桶大小。第三，分配不平衡并没有显着影响训练过程。\n- 不同的分辨率和帧长可能有不同的处理速度：与PixArt只处理相似分辨率（相似token数）的宽高比不同，我们需要考虑不同分辨率和帧长的处理速度。我们可以使用“bucket_config”来定义每个桶的批量大小，以确保处理速度相似。\n\n</details>\n\n![bucket](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/report_bucket.png)\n\n如图所示，桶是（分辨率，帧数量，宽高比）的三元组。我们为不同的分辨率提供预定义的宽高比，涵盖了大多数常见的视频宽高比。在每个epoch之前，我们打乱数据集并将样本分配到不同的桶中，如图所示。我们将样本放入最大分辨率和帧长度小于视频的桶中。\n\n考虑到我们的计算资源有限，我们进一步为每个（分辨率，num_frame）二元组引入keep_prob和batch_size两个属性，以降低计算成本并实现多阶段训练。具体来说，高清视频将以概率1-keep_prob下采样到较低分辨率的桶中，并且每个桶的样本数量是由batch_size属性决定的。这样，我们可以控制不同桶中的样本数量，并通过为每个桶搜索合适的数据量来平衡GPU负载。\n\n有关训练中桶使用的详细说明，请参阅[配置文件](/docs/config.md#training-bucket-configs).\n\n## 使用Masked DiT作为图生视频/视频生视频模型\n\nTransformer可以很容易地扩展到支持图生图和视频生视频的任务。我们提出了一种蒙版策略来支持图像和视频的调节。蒙版策略如下图所示。\n\n![mask strategy](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/report_mask.png)\n\n在将图像或视频转换成另一个视频的过程中，我们通常会选择出需要作为条件的帧并取消其掩码（unmask）。在使用ST-DiT模型进行前向传播时，被选择取消掩码（unmask）的帧将被赋予时间步长0，而其他帧则保持它们原有的时间步长t。我们发现，如果直接将这种策略应用到训练好的模型上，会得到较差的结果，因为扩散模型在训练过程中并未学会如何处理一个样本中具有不同时间步长的帧。\n\n受[UL2](https://arxiv.org/abs/2205.05131)的启发，我们在训练期间引入了随机掩码策略。具体来说，我们在训练期间随机取消掩码帧，包括取消掩码第一帧，前k帧，最后k帧，最后k帧，第一和最后k帧，随机帧等。基于Open-Sora 1.0模型，以50%的概率应用掩码策略，我们发现模型能够在10,000步的训练中学会处理图像条件（而30%的概率会导致处理能力变差），同时文本到视频的性能略有下降。因此，在Open-Sora 1.1版本中，我们从头开始预训练模型，并采用了掩码策略。\n\n下图给出了用于推理的掩码策略配置的说明。五数字元组在定义掩码策略方面提供了极大的灵活性。\n\n![mask strategy config](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/report_mask_config.png)\n\n掩码策略用法的详细说明可在[配置文件](/docs/config.md#advanced-inference-config)中查看.\n\n\n## 数据收集和流程\n\n正如我们在Sora1.0版本中看见的那样，数据数量和质量对于训练一个好的模型至关重要，因此，我们努力扩展数据集。首先，我们创建了一个遵循[SVD](https://arxiv.org/abs/2311.15127)的自动流水线，包括场景切割、字幕、各种评分和过滤以及数据集管理脚本和通用惯例。\n\n![pipeline](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/report_data_pipeline.png)\n\n我们计划使用[panda-70M](https://snap-research.github.io/Panda-70M/)和其他数据来训练模型，大约包含3000万条数据。然而，我们发现磁盘输入输出（disk IO）在同时进行训练和数据处理时成为了一个瓶颈。因此，我们只能准备一个包含1000万条数据的数据集，并且没有完成我们构建的所有处理流程。最终，我们使用了包含970万视频和260万图像的数据集进行预训练，以及560,000视频和160万图像的数据集进行微调。预训练数据集的统计信息如下所示。\n\n图像文本标记 (使用T5分词器)：\n![image text tokens](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/report_image_textlen.png)\n\n视频文本标记 (使用T5分词器)。我们直接使用Panda的短视频描述进行训练，并自己给其他数据集加视频描述。生成的字幕通常少于200个token。\n![video text tokens](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/report_video_textlen.png)\n\n视频时长：\n![video duration](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/report_video_duration.png)\n\n## 训练详情\n\n由于计算资源有限，我们必须仔细监控训练过程，并在推测模型学习不佳时更改训练策略，因为没有消融研究的计算。因此，Open-Sora1.1版本的训练包括多个更改，所以，指数移动平均（EMA）未被应用。\n\n1. 首先，我们从`Pixart-alpha-1024`的模型checkpoint开始，使用不同分辨率的图像进行了6000步的微调。我们发现模型能够很容易地适应并生成不同分辨率的图像。为了加快扩散过程的训练，我们使用了[SpeeDiT](https://github.com/1zeryu/SpeeDiT)（iddpm-speed）技术。\n2. **[阶段一]** 然后，我们使用梯度检查点（gradient-checkpointing）技术对模型进行了**24,000**步的预训练，这个过程在64个H800 GPU上运行了**4天**。尽管模型看到的数据样本数量相同，我们发现与使用较小批量大小相比，模型的学习速度较慢。我们推测，在训练的早期阶段，步数的数量对于训练更为重要。大多数视频的分辨率是**240p**，预训练时使用的配置与[stage2.py](/configs/opensora-v1-1/train/stage2.py)相似。\n3. **[阶段一]** 为了增加训练步数，我们改用了更小的批量大小，并且没有使用梯度检查点技术。在这个阶段，我们还引入了帧率（fps）条件。模型训练了**40,000**步，持续了**2天**。训练中使用的视频大多数是**144p**分辨率，使用的配置文件是[stage1.py](/configs/opensora-v1-1/train/stage1.py)。我们使用较低的分辨率，因为我们在Open-Sora 1.0版本中发现模型可以以相对较低的分辨率学习时间知识。\n4. **[阶段一]** 我们发现模型不能很好地学习长视频，并在Open-Sora1.0训练中发现了一个噪声生成结果，推测是半精度问题。因此，我们采用QK-归一化来稳定训练。我们还将iddpm-speed切换成iddpm。我们训练了**17k**步**14小时**。大多数视频的分辨率是144p，预训练时使用的配置是[stage1.py](/configs/opensora-v1-1/train/stage1.py)。阶段1训练持续约一周，总步长**81k**。\n5. **[阶段二]** 我们切换到更高的分辨率，其中大多数视频是**240p和480p**分辨率（[stage2.py](/configs/opensora-v1-1/train/stage2.py)）。我们在所有预训练数据上训练了**22000**步，持续**一天**。\n6. **[阶段三]** 我们切换到更高的分辨率，大多数视频的分辨率是**480p和720p**（[stage3.py](/configs/opensora-v1-1/train/stage3.py)）。我们在高质量数据上训了**4000**步，用时**一天**。\n\n## 结果和评价\n\n## 不足和下一步计划\n\n随着我们离Sora的复现又近了一步，我们发现当前模型存在许多不足，这些不足将在我们下阶段工作中得到改善。\n\n- **噪音的生成和影响**：我们发现生成的模型，特别是长视频中，有时很多噪点，不流畅。我们认为问题在于没有使用时间VAE。由于[Pixart-Sigma](https://arxiv.org/abs/2403.04692)发现适应新VAE很容易，我们计划在下一个版本中为模型开发时间VAE。\n- **缺乏时间一致性**：我们发现模型无法生成具有高时间一致性的视频，我们认为问题是由于缺乏训练FLOPs，我们计划收集更多数据并继续训练模型以提高时间一致性。\n- **人像生成质量低**：我们发现模型无法生成高质量的人类视频，我们认为问题是由于缺乏人类数据，我们计划收集更多的人类数据，并继续训练模型以提高人类生成。\n- **美学得分低**：我们发现模型的美学得分不高。问题在于缺少美学得分过滤，由于IO瓶颈没我们没有进行这一步骤。我们计划通过美学得分和微调模型来过滤数据，以提高美学得分。\n- **长视频生成质量低**：我们发现，使用同样的提示词，视频越长，质量越差。这意味着图像质量不能同等地被不同长度的序列所适应。\n\n> - **算法与加速实现**：Zangwei Zheng, Xiangyu Peng, Shenggui Li, Hongxing Liu, Yukun Zhou\n> - **数据收集与处理**：Xiangyu Peng, Zangwei Zheng, Chenhui Shen, Tom Young, Junjie Wang, Chenfeng Yu\n"
  },
  {
    "path": "docs/zh_CN/report_v3.md",
    "content": "# Open-Sora 1.2 报告\n\n- [视频压缩网络](#视频压缩网络)\n- [整流流和模型适应](#整流流和模型适应)\n- [更多数据和更好的多阶段训练](#更多数据和更好的多阶段训练)\n- [简单有效的模型调节](#简单有效的模型调节)\n- [评估](#评估)\n\n在 Open-Sora 1.2 版本中，我们在 >30M 数据上训练了 一个1.1B 的模型，支持 0s~16s、144p 到 720p、各种宽高比的视频生成。我们的配置如下所列。继 1.1 版本之后，Open-Sora 1.2 还可以进行图像到视频的生成和视频扩展。\n\n|      | 图像 | 2秒  | 4秒  | 8秒  | 16秒 |\n| ---- | ----- | --- | --- | --- | --- |\n| 240p | ✅     | ✅   | ✅   | ✅   | ✅   |\n| 360p | ✅     | ✅   | ✅   | ✅   | ✅   |\n| 480p | ✅     | ✅   | ✅   | ✅   | 🆗   |\n| 720p | ✅     | ✅   | ✅   | 🆗   | 🆗   |\n\n这里✅表示在训练期间可以看到数据，🆗表示虽然没有经过训练，但模型可以在该配置下进行推理。🆗的推理需要多个80G内存的GPU和序列并行。\n\n除了 Open-Sora 1.1 中引入的功能外，Open-Sora 1.2 还有以下重磅更新：\n\n- 视频压缩网络\n- 整流流训练\n- 更多数据和更好的多阶段训练\n- 简单有效的模型调节\n- 更好的评估指标\n\n上述改进的所有实现（包括训练和推理）均可在 Open-Sora 1.2 版本中使用。以下部分将介绍改进的细节。我们还改进了代码库和文档，使其更易于使用。\n\n## 视频压缩网络\n\n对于 Open-Sora 1.0 & 1.1，我们使用了 stable-ai 的 83M 2D VAE，它仅在空间维度上压缩，将视频压缩 8x8 倍。为了减少时间维度，我们每三帧提取一帧。然而，这种方法导致生成的视频流畅度较低，因为牺牲了生成的帧率（fps）。因此，在这个版本中，我们引入了像 OpenAI 的 Sora 一样的视频压缩网络。该网络在时域上将视频大小压缩至四分之一，因此，我们不必再额外抽帧，而可以使用原有帧率生成模型。\n\n考虑到训练 3D VAE 的计算成本很高，我们希望重新利用在 2D VAE 中学到的知识。我们注意到，经过 2D VAE 压缩后，时间维度上相邻的特征仍然高度相关。因此，我们提出了一个简单的视频压缩网络，首先将视频在空间维度上压缩 8x8 倍，然后将视频在时间维度上压缩 4 倍。网络如下所示：\n\n![video_compression_network](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/report_3d_vae.png)\n\n我们用[SDXL 的 VAE](https://huggingface.co/stabilityai/sdxl-vae)初始化 2D VAE ，它比我们以前使用的更好。对于 3D VAE，我们采用[Magvit-v2](https://magvit.cs.cmu.edu/v2/)中的 VAE 结构，它包含 300M 个参数。加上 83M 的 2D VAE，视频压缩网络的总参数为 384M。我们设定batch size 为 1， 对 3D VAE 进行了 1.2M 步的训练。训练数据是来自 pixels 和 pixabay 的视频，训练视频大小主要是 17 帧，256x256 分辨率。3D VAE 中使用causal convolotions使图像重建更加准确。\n\n我们的训练包括三个阶段：\n\n1. 对于前 380k 步，我们冻结 2D VAE并在 8 个 GPU 上进行训练。训练目标包括重建 2D VAE 的压缩特征（图中粉红色），并添加损失以使 3D VAE 的特征与 2D VAE 的特征相似（粉红色和绿色，称为identity loss）。我们发现后者的损失可以快速使整个 VAE 在图像上取得良好的性能，并在下一阶段更快地收敛。\n2. 对于接下来的 260k 步，我们消除identity loss并仅学习 3D VAE。\n3. 对于最后 540k 步，由于我们发现仅重建 2D VAE 的特征无法带来进一步的改进，因此我们移除了loss并训练整个 VAE 来重建原始视频。此阶段在 24 个 GPU 上进行训练。\n\n对于训练的前半部分，我们采用 20% 的图像和 80% 的视频。按照[Magvit-v2](https://magvit.cs.cmu.edu/v2/)，我们使用 17 帧训练视频，同时对图像的前 16 帧进行零填充。然而，我们发现这种设置会导致长度不同于 17 帧的视频变得模糊。因此，在第 3 阶段，我们使用不超过34帧长度的任意帧长度视频进行混合视频长度训练,以使我们的 VAE 对不同视频长度更具鲁棒性（也就是说，如果我们希望训练含有n帧的视频，我们就把原视频中`34-n`帧用0进行填充）。我们的 [训练](/scripts/train_vae.py)和[推理](/scripts/inference_vae.py)代码可在 Open-Sora 1.2 版本中找到。\n\n当使用 VAE 进行扩散模型时，我们的堆叠 VAE 所需的内存较少，因为我们的 VAE 的输入已经经过压缩。我们还将输入视频拆分为几个 17 帧剪辑，以提高推理效率。我们的 VAE 与[Open-Sora-Plan](https://github.com/PKU-YuanGroup/Open-Sora-Plan/blob/main/docs/Report-v1.1.0.md)中的另一个开源 3D VAE 性能相当。\n\n| 模型          | 结构相似性↑ | 峰值信噪比↑  |\n| ------------------ | ----- | ------ |\n| Open-Sora-Plan 1.1 | 0.882 | 29.890 |\n| Open-Sora 1.2      | 0.880 | 30.590 |\n\n## 整流流和模型适应\n\n最新的扩散模型 Stable Diffusion 3 为了获得更好的性能，采用了[rectified flow](https://github.com/gnobitab/RectifiedFlow)替代了 DDPM。可惜 SD3 的 rectified flow 训练代码没有开源。不过 Open-Sora 1.2 提供了遵循 SD3 论文的训练代码，包括：\n\n- 基本整流流训练\n- 用于训练加速的 Logit-norm 采样\n- 分辨率和视频长度感知时间步长采样\n\n对于分辨率感知的时间步长采样，我们应该对分辨率较大的图像使用更多的噪声。我们将这个想法扩展到视频生成，对长度较长的视频使用更多的噪声。\n\nOpen-Sora 1.2 从[PixArt-Σ 2K](https://github.com/PixArt-alpha/PixArt-sigma) 模型checkpoint开始。请注意，此模型使用 DDPM 和 SDXL VAE 进行训练，分辨率也高得多。我们发现在小数据集上进行微调可以轻松地使模型适应我们的视频生成设置。适应过程如下，所有训练都在 8 个 GPU 上完成：\n\n1. 多分辨率图像生成能力：我们训练模型以 20k 步生成从 144p 到 2K 的不同分辨率。\n2. QK-norm：我们将 QK-norm 添加到模型中并训练 18k 步。\n3. 整流流：我们从离散时间 DDPM 转变为连续时间整流流并训练 10k 步。\n4. 使用 logit-norm 采样和分辨率感知时间步采样的整流流：我们训练 33k 步。\n5. 较小的 AdamW epsilon：按照 SD3，使用 QK-norm，我们可以对 AdamW 使用较小的 epsilon（1e-15），我们训练 8k 步。\n6. 新的 VAE 和 fps 调节：我们用自己的 VAE 替换原来的 VAE，并将 fps 调节添加到时间步调节中，我们训练 25k 步。请注意，对每个通道进行规范化对于整流流训练非常重要。\n7. 时间注意力模块：我们添加时间注意力模块，其中没有初始化投影层。我们在图像上进行 3k 步训练。\n8. 仅针对具有掩码策略的视频的时间块：我们仅在视频上训练时间注意力块，步长为 38k。\n\n经过上述调整后，我们就可以开始在视频上训练模型了。上述调整保留了原始模型生成高质量图像的能力，并未后续的视频生成提供了许多助力：\n\n- 通过整流，我们可以加速训练，将视频的采样步数从100步减少到30步，大大减少了推理的等待时间。\n- 使用 qk-norm，训练更加稳定，并且可以使用积极的优化器。\n- 采用新的VAE，时间维度压缩了4倍，使得训练更加高效。\n- 该模型具有多分辨率图像生成能力，可以生成不同分辨率的视频。\n\n## 更多数据和更好的多阶段训练\n\n由于计算预算有限，我们精心安排了训练数据的质量从低到高，并将训练分为三个阶段。我们的训练涉及 12x8 GPU，总训练时间约为 2 周， 约70k步。\n\n### 第一阶段\n\n我们首先在 Webvid-10M 数据集（40k 小时）上训练模型，共 30k 步（2 个 epoch）。由于视频分辨率均低于 360p 且包含水印，因此我们首先在此数据集上进行训练。训练主要在 240p 和 360p 上进行，视频长度为 2s~16s。我们使用数据集中的原始字幕进行训练。训练配置位于[stage1.py](/configs/opensora-v1-2/train/stage1.py)中。\n\n### 第二阶段\n\n然后我们在 Panda-70M 数据集上训练模型。这个数据集很大，但质量参差不齐。我们使用官方的 30M 子集，其中的片段更加多样化，并过滤掉美学评分低于 4.5 的视频。这产生了一个 20M 子集，包含 41k 小时。数据集中的字幕直接用于我们的训练。训练配置位于[stage2.py](/configs/opensora-v1-2/train/stage2.py)中。\n\n训练主要在 360p 和 480p 上进行。我们训练模型 23k 步，即 0.5 个 epoch。训练尚未完成，因为我们希望我们的新模型能早日与大家见面。\n\n### 第三阶段\n\n在此阶段，我们从各种来源收集了 200 万个视频片段，总时长 5000 小时，其中包括：\n\n- 来自 Pexels、Pixabay、Mixkit 等的免费授权视频。\n- [MiraData](https://github.com/mira-space/MiraData)：一个包含长视频的高质量数据集，主要来自游戏和城市/风景探索。\n- [Vript](https://github.com/mutonix/Vript/tree/main)：一个密集注释的数据集。\n- 还有一些其他数据集。\n\nMiraData 和 Vript 有来自 GPT 的字幕，而我们使用[PLLaVA](https://github.com/magic-research/PLLaVA)为其余字幕添加字幕。与只能进行单帧/图像字幕的 LLaVA 相比，PLLaVA 是专门为视频字幕设计和训练的。[加速版PLLaVA](/tools/caption/README.md#pllava-captioning)已在我们的`tools/`中发布。在实践中，我们使用预训练的 PLLaVA 13B 模型，并从每个视频中选择 4 帧生成字幕，空间池化形状为 2*2。\n\n下面显示了此阶段使用的视频数据的一些统计数据。我们提供了持续时间和分辨率的基本统计数据，以及美学分数和光流分数分布。我们还从视频字幕中提取了对象和动作的标签并计算了它们的频率。\n![stats](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/report-03_video_stats.png)\n![object_count](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/report-03_objects_count.png)\n![object_count](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/report-03_actions_count.png)\n\n此阶段我们主要在 720p 和 1080p 上进行训练，以提高模型在高清视频上的表现力。在训练中，我们使用的掩码率为25%。训练配置位于[stage3.py](/configs/opensora-v1-2/train/stage3.py)中。我们对模型进行 15k 步训练，大约为 2 个 epoch。\n\n## 简单有效的模型调节\n\n对于第 3 阶段，我们计算每个视频片段的美学分数和运动分数。但是，由于视频片段数量较少，我们不愿意过滤掉得分较低的片段，这会导致数据集较小。相反，我们将分数附加到字幕中并将其用作条件。我们发现这种方法可以让模型了解分数并遵循分数来生成质量更好的视频。\n\n例如，一段美学评分为 5.5、运动评分为 10 且检测到摄像头运动向左平移的视频，其字幕将为：\n\n```plaintext\n[Original Caption] aesthetic score: 5.5, motion score: 10, camera motion: pan left.\n```\n\n在推理过程中，我们还可以使用分数来调节模型。对于摄像机运动，我们仅标记了 13k 个具有高置信度的剪辑，并且摄像机运动检测模块已在我们的工具中发布。\n\n## 评估\n\n之前，我们仅通过人工评估来监控训练过程，因为 DDPM 训练损失与生成的视频质量没有很好的相关性。但是，对于校正流，如 SD3 中所述，我们发现训练损失与生成的视频质量有很好的相关性。因此，我们跟踪了 100 张图像和 1k 个视频的校正流评估损失。\n\n我们从 pixabay 中抽样了 1k 个视频作为验证数据集。我们计算了不同分辨率（144p、240p、360p、480p、720p）下图像和不同长度的视频（2s、4s、8s、16s）的评估损失。对于每个设置，我们等距采样 10 个时间步长。然后对所有损失取平均值。\n\n![Evaluation Loss](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/report_val_loss.png)\n![Video Evaluation Loss](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/report_vid_val_loss.png)\n\n此外，我们还会在训练过程中跟踪[VBench](https://vchitect.github.io/VBench-project/)得分。VBench 是用于短视频生成的自动视频评估基准。我们用 240p 2s 视频计算 vbench 得分。这两个指标验证了我们的模型在训练过程中持续改进。\n\n![VBench](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/report_vbench_score.png)\n\n所有评估代码均发布在`eval`文件夹中。查看[评估指南](/eval/README.md)了解更多详细信息。\n\n|模型        | 总得分 | 质量得分 | 语义分数 |\n| -------------- | ----------- | ------------- | -------------- |\n| Open-Sora V1.0 | 75.91%      | 78.81%        | 64.28%         |\n| Open-Sora V1.2 | 79.23%      | 80.71%        | 73.30%         |\n\n## 序列并行\n\n我们使用序列并行来支持长序列训练和推理。我们的实现基于Ulysses，工作流程如下所示。启用序列并行后，我们只需要将 `all-to-all` 通信应用于STDiT中的空间模块（spatial block），因为在序列维度上，只有对空间信息的计算是相互依赖的。\n\n![SP](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/sequence_parallelism.jpeg)\n\n目前，由于训练数据分辨率较小，我们尚未使用序列并行进行训练，我们计划在下一个版本中使用。至于推理，我们可以使用序列并行，以防您的 GPU 内存不足。下表显示，序列并行可以实现加速：\n\n| 分辨率 | 时长 | GPU数量 | 是否启用序列并行 |用时（秒） | 加速效果/GPU |\n| ---------- | ------- | -------------- | --------- | ------------ | --------------- |\n| 720p       | 16秒     | 1              | 否        | 547.97       | -               |\n| 720p       | 16s秒    | 2              | 是        | 244.38       | 12%             |\n\n"
  },
  {
    "path": "docs/zh_CN/report_v4.md",
    "content": "# Open-Sora 1.3 报告\n\n- [视频压缩网络](#视频压缩网络)\n- [升级版带位移窗口注意力的STDiT](#升级版带位移窗口注意力的STDiT)\n- [简单有效的模型条件控制](#简单有效的模型条件控制)\n- [评估方法](#评估方法)\n\n在Open-Sora 1.3版本中，我们在超过60M（约85k小时）的数据上训练了一个1.1B参数的模型，训练耗时35k H100 GPU小时，支持0~113帧、360p和720p分辨率以及多种宽高比的视频生成。我们的配置如下。延续1.2版本的特性，Open-Sora 1.3同样支持图像到视频的生成和视频延展。\n\n|      | image | 49 frames  | 65 frames  | 81 frames  | 97 frames | 113 frames |\n| ---- | ----- | ---------- | ---------- | ---------- | --------- | ---------- |\n| 360p | ✅     | ✅         | ✅         | ✅         | ✅         |✅          |\n| 720p | ✅     | ✅         | ✅         | ✅         | ✅         |✅          |\n\n这里✅表示在训练过程中已经见过的数据。\n\n除了Open-Sora 1.2中引入的特性外，Open-Sora 1.3的亮点包括：\n\n- 视频压缩网络\n- 升级版带位移窗口注意力的STDiT\n- 更多数据和更好的多阶段训练\n- 简单有效的模型条件控制\n- 更好的评估指标\n\n以上所有改进的实现（包括训练和推理）都在Open-Sora 1.3版本中提供。以下部分将详细介绍这些改进。我们还优化了代码库和文档以使其更易于使用和开发，并添加了LLM优化器来[优化输入提示词](/README.md#gpt-4o-prompt-refinement)并支持更多语言。\n\n## 视频压缩网络\n\n在Open-Sora 1.2中，视频压缩架构采用了模块化方法，分别处理空间和时间维度。基于Stability AI的SDXL VAE的空间VAE压缩单个帧的空间维度。时间VAE则处理来自空间VAE的潜在表示以实现时间压缩。这种两阶段设计实现了有效的空间和时间压缩，但也带来了一些限制。这些限制包括由于固定长度输入帧而导致的长视频处理效率低下、空间和时间特征之间缺乏无缝集成，以及在训练和推理过程中更高的内存需求。\n\nOpen-Sora 1.3引入了统一的视频压缩方法。通过将空间和时间处理结合到单一框架中，并利用诸如分块3D卷积和动态帧支持等高级特性，Open-Sora 1.3实现了更好的效率、可扩展性和重建质量。以下是Open-Sora 1.3 VAE的主要改进：\n\n**1. 统一的时空处理：** 不同于使用独立的VAE进行空间和时间压缩，Open-Sora 1.3采用单一的编码器-解码器结构同时处理这两个维度。这种方法消除了中间表示和空间-时间模块之间的冗余数据传输的需求。\n\n**2. 分块3D卷积：** Open-Sora 1.3在时间维度上引入了分块3D卷积支持。通过将视频分解成更小的时间块，该特性实现了对更长视频序列的高效编码和解码，而不会增加内存开销。这一改进解决了Open-Sora 1.2在处理大量帧时的限制，确保了更高的时间压缩灵活性。\n\n**3. 动态微批次和微帧处理：** Open-Sora 1.3引入了新的微批次和微帧处理机制。这实现了：(1) 自适应时间重叠：时间编码和解码过程中的重叠帧帮助减少块边界的不连续性。(2) 动态帧大小支持：不再局限于固定长度序列（如Open-Sora 1.2中的17帧），Open-Sora 1.3支持动态序列长度，使其能够适应不同的视频长度。\n\n**4. 统一的归一化机制：** Open-Sora 1.3中的归一化过程通过可调的缩放(scale)和平移(shift)参数得到了改进，确保了不同数据集间潜在空间分布的一致性。与Open-Sora 1.2特定于固定数据集的归一化不同，这个版本引入了更通用的参数并支持特定于帧的归一化策略。\n\n#### 改进总结\n\n| 特性           | Open-Sora 1.2                    | Open-Sora 1.3                     |\n|---------------|---------------------------------|----------------------------------|\n| **架构**       | 独立的空间和时间VAE                 | 统一的时空VAE                      |\n| **分块处理**    | 不支持                           | 支持（分块3D卷积）                   |\n| **帧长度支持**  | 固定（17帧）                      | 支持动态帧长度和重叠                 |\n| **归一化**     | 固定参数                         | 可调的缩放和平移参数                 |\n\n## 包含滑动窗口注意力的STDiT\n\n在Open-Sora 1.2取得成功的基础上，1.3版本引入了多项架构改进和新功能，以提升视频生成的质量和灵活性。本节概述了这两个版本之间的主要改进和差异。\n\n最新的扩散模型（如Stable Diffusion 3）采用[rectified flow](https://github.com/gnobitab/RectifiedFlow)代替DDPM以获得更好的性能。虽然SD3的rectified flow训练代码未开源，但OpenSora按照SD3论文提供了训练代码实现。OpenSora 1.2从SD3引入了几个关键策略：\n\n1. 基础的rectified flow训练，实现连续时间扩散\n2. Logit-norm采样用于加速训练（遵循SD3论文第3.1节），优先在中等噪声水平采样时间步\n3. 分辨率和视频长度感知的时间步采样（遵循SD3论文第5.3.2节），对更大分辨率和更长视频使用更多噪声\n\n在OpenSora 1.3中，我们在架构、功能和性能方面进行了显著改进：\n\n#### 1. 位移窗口注意力机制\n- 引入可配置kernel_size的基于核的局部注意力，提高计算效率\n- 实现类似Swin Transformer的位移窗口分区策略\n- 增加带extra_pad_on_dims支持的窗口边界填充掩码处理\n- 在局部窗口（时间、高度、宽度）内扩展3D相对位置编码\n\n#### 2. 增强的位置编码\n- 改进RoPE实现，将rotation_dim降至原来的1/3以适应3D场景\n- 为时间、高度和宽度维度添加独立的旋转嵌入\n- 实现分辨率自适应的位置编码缩放\n- 可选的空间RoPE以更好地建模空间关系\n\n#### 3. 灵活的生成能力\n- 添加I2V和V2V功能，配备专门的条件控制机制\n- 引入条件嵌入模块（x_embedder_cond和x_embedder_cond_mask）\n- 零初始化条件嵌入以实现稳定训练\n- 通过skip_temporal选项实现灵活的时序建模\n\n#### 4. 性能优化\n- 改进Flash Attention触发条件（N > 128）以提高效率\n- 添加torch.scaled_dot_product_attention (SDPA)作为替代后端\n- 通过改进的填充和窗口分区优化内存使用\n- 通过自适应高度填充增强序列并行性\n\n从[PixArt-Σ 2K](https://github.com/PixArt-alpha/PixArt-sigma)的适应过程保持相似，但增加了额外步骤：\n[第1-7点与v1.2相同：多分辨率训练、QK-norm、rectified flow、logit-norm采样、更小的AdamW epsilon、新VAE和基础时序注意力]\n#### 8. 增强的时序模块\n   - 添加带位移窗口支持的基于核的局部注意力\n   - 实现带分辨率自适应缩放的3D相对位置编码\n   - 采用改进的初始化策略进行投影层零初始化\n\n相比专注于基础视频生成的v1.2，v1.3在三个关键领域带来了实质性改进：**1. 质量**：通过位移窗口注意力和3D位置编码增强时空建模。**2. 灵活性**：支持I2V/V2V任务和可配置的时序建模。**3. 效率**：优化注意力计算和内存使用\n\n这些改进在保持v1.2核心功能的同时，扩展了模型在实际应用中的能力。模型保留了使用rectified flow生成高质量图像和视频的能力，同时在条件生成和长序列建模方面获得了新的优势。\n\n## 简单有效的模型条件控制\n\n我们对每个视频片段计算美学分数和运动分数，并过滤掉得分较低的片段，从而得到一个视频质量更好的数据集。此外，我们将这些分数附加到标题中并用作条件控制。具体来说，我们基于预定义的范围将数值分数转换为描述性语言。美学分数转换函数基于预定义范围将数值美学分数转换为描述标签：低于4分标记为\"terrible\"，依次通过\"very poor\"、\"poor\"、\"fair\"、\"good\"和\"very good\"，6.5分或更高标记为\"excellent\"。同样，运动分数转换函数将运动强度分数映射为描述符：低于0.5分标记为\"very low\"，依次通过\"low\"、\"fair\"、\"high\"和\"very high\"，20分或更高标记为\"extremely high\"。我们发现这种方法可以使模型意识到这些分数并遵循分数来生成更高质量的视频。\n\n例如，对于一个美学分数为5.5，运动分数为10，检测到的相机运动为向左平移的视频，其标题将是：\n\n```plaintext\n[Original Caption] The aesthetic score is good, the motion strength is high, camera motion: pan left.\n```\n\n在推理过程中，我们也可以使用这些分数来控制模型。对于相机运动，我们只标记了13k个高置信度的片段，相机运动检测模块已在我们的工具中发布。\n\n## 评估方法\n\n此前，我们仅通过人工评估来监控训练过程，因为DDPM训练损失与生成视频的质量相关性不高。然而，对于rectified flow，我们发现正如SD3所述，训练损失与生成视频的质量有很好的相关性。因此，我们持续跟踪100张图像和1k个视频的rectified flow评估损失。\n\n我们从pixabay采样了1k个视频作为验证数据集。我们计算了不同分辨率（360p，720p）下图像和不同长度视频（49帧、65帧、81帧、97帧、113帧）的评估损失。对于每种设置，我们等距采样10个时间步。然后对所有损失取平均值。\n\n此外，我们还在训练期间跟踪[VBench](https://vchitect.github.io/VBench-project/)分数。VBench是一个用于短视频生成的自动视频评估基准。我们使用360p 49帧视频计算vbench分数。这两个指标验证了我们的模型在训练过程中持续改进。\n\n所有评估代码都在`eval`文件夹中发布。查看[README](/eval/README.md)获取更多详细信息。"
  },
  {
    "path": "gradio/app.py",
    "content": "#!/usr/bin/env python\n\"\"\"\nThis script runs a Gradio App for the Open-Sora model.\n\nUsage:\n    python demo.py <config-path>\n\"\"\"\n\nimport argparse\nimport datetime\nimport importlib\nimport os\nimport subprocess\nimport sys\nfrom tempfile import NamedTemporaryFile\n\nimport spaces\nimport torch\n\nimport gradio as gr\n\nMODEL_TYPES = [\"v1.3\"]\nWATERMARK_PATH = \"./assets/images/watermark/watermark.png\"\nCONFIG_MAP = {\n    \"v1.3\": \"configs/opensora-v1-3/inference/t2v.py\",\n    \"v1.3_i2v\": \"configs/opensora-v1-3/inference/v2v.py\",\n}\nHF_STDIT_MAP = {\n    \"t2v\": {\n        \"360p\": \"hpcaitech/OpenSora-STDiT-v4-360p\",\n        \"720p\": \"hpcaitech/OpenSora-STDiT-v4\",\n    },\n    \"i2v\": \"hpcaitech/OpenSora-STDiT-v4-i2v\",\n}\n\n\n# ============================\n# Prepare Runtime Environment\n# ============================\ndef install_dependencies(enable_optimization=False):\n    \"\"\"\n    Install the required dependencies for the demo if they are not already installed.\n    \"\"\"\n\n    def _is_package_available(name) -> bool:\n        try:\n            importlib.import_module(name)\n            return True\n        except (ImportError, ModuleNotFoundError):\n            return False\n\n    if enable_optimization:\n        # install flash attention\n        if not _is_package_available(\"flash_attn\"):\n            subprocess.run(\n                f\"{sys.executable} -m pip install flash-attn --no-build-isolation\",\n                env={\"FLASH_ATTENTION_SKIP_CUDA_BUILD\": \"TRUE\"},\n                shell=True,\n            )\n\n        # install apex for fused layernorm\n        if not _is_package_available(\"apex\"):\n            subprocess.run(\n                f'{sys.executable} -m pip install -v --disable-pip-version-check --no-cache-dir --no-build-isolation --config-settings \"--build-option=--cpp_ext\" --config-settings \"--build-option=--cuda_ext\" git+https://github.com/NVIDIA/apex.git',\n                shell=True,\n            )\n\n        # install ninja\n        if not _is_package_available(\"ninja\"):\n            subprocess.run(f\"{sys.executable} -m pip install ninja\", shell=True)\n\n        # install xformers\n        if not _is_package_available(\"xformers\"):\n            subprocess.run(\n                f\"{sys.executable} -m pip install -v -U git+https://github.com/facebookresearch/xformers.git@main#egg=xformers\",\n                shell=True,\n            )\n\n\n# ============================\n# Model-related\n# ============================\ndef read_config(config_path):\n    \"\"\"\n    Read the configuration file.\n    \"\"\"\n    from mmengine.config import Config\n\n    return Config.fromfile(config_path)\n\n\ndef build_models(mode, resolution, enable_optimization=False):\n    \"\"\"\n    Build the models for the given mode, resolution, and configuration.\n    \"\"\"\n    # build vae\n    from opensora.registry import MODELS, build_module\n\n    if mode == \"i2v\":\n        config = read_config(CONFIG_MAP[\"v1.3_i2v\"])\n    else:\n        config = read_config(CONFIG_MAP[\"v1.3\"])\n\n    vae = build_module(config.vae, MODELS).cuda()\n\n    # build text encoder\n    text_encoder = build_module(config.text_encoder, MODELS)  # T5 must be fp32\n    text_encoder.t5.model = text_encoder.t5.model.cuda()\n\n    # Determine model weights based on mode and resolution\n    if mode == \"i2v\":\n        weight_path = HF_STDIT_MAP[\"i2v\"]\n    else:  # t2v\n        weight_path = HF_STDIT_MAP[\"t2v\"].get(resolution, None)\n        if not weight_path:\n            raise ValueError(f\"Unsupported resolution {resolution} for mode {mode}\")\n\n    # build stdit\n    from opensora.models.stdit.stdit3 import STDiT3\n\n    model_kwargs = {k: v for k, v in config.model.items() if k not in (\"type\", \"from_pretrained\", \"force_huggingface\")}\n\n    print(\"Load STDIT3 from \", weight_path)\n    stdit = STDiT3.from_pretrained(weight_path, **model_kwargs).cuda()\n\n    # build scheduler\n    from opensora.registry import SCHEDULERS\n\n    scheduler = build_module(config.scheduler, SCHEDULERS)\n\n    # hack for classifier-free guidance\n    text_encoder.y_embedder = stdit.y_embedder\n\n    # move models to device\n    vae = vae.to(torch.bfloat16).eval()\n    text_encoder.t5.model = text_encoder.t5.model.eval()  # t5 must be in fp32\n    stdit = stdit.to(torch.bfloat16).eval()\n\n    # clear cuda\n    torch.cuda.empty_cache()\n    return vae, text_encoder, stdit, scheduler, config\n\n\ndef parse_args():\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\n        \"--model-type\",\n        default=\"v1.3\",\n        choices=MODEL_TYPES,\n        help=f\"The type of model to run for the Gradio App, can only be {MODEL_TYPES}\",\n    )\n    parser.add_argument(\"--output\", default=\"./outputs\", type=str, help=\"The path to the output folder\")\n    parser.add_argument(\"--port\", default=None, type=int, help=\"The port to run the Gradio App on.\")\n    parser.add_argument(\"--host\", default=\"0.0.0.0\", type=str, help=\"The host to run the Gradio App on.\")\n    parser.add_argument(\"--share\", action=\"store_true\", help=\"Whether to share this gradio demo.\")\n    parser.add_argument(\n        \"--enable-optimization\",\n        action=\"store_true\",\n        help=\"Whether to enable optimization such as flash attention and fused layernorm\",\n    )\n    return parser.parse_args()\n\n\n# ============================\n# Main Gradio Script\n# ============================\n# as `run_inference` needs to be wrapped by `spaces.GPU` and the input can only be the prompt text\n# so we can't pass the models to `run_inference` as arguments.\n# instead, we need to define them globally so that we can access these models inside `run_inference`\n\n# read config\nargs = parse_args()\nconfig = read_config(CONFIG_MAP[args.model_type])\ntorch.backends.cuda.matmul.allow_tf32 = True\ntorch.backends.cudnn.allow_tf32 = True\n\n# make outputs dir\nos.makedirs(args.output, exist_ok=True)\n\n# disable torch jit as it can cause failure in gradio SDK\n# gradio sdk uses torch with cuda 11.3\ntorch.jit._state.disable()\n\n# set up\ninstall_dependencies(enable_optimization=args.enable_optimization)\n\n# import after installation\nfrom opensora.datasets import IMG_FPS, save_sample\nfrom opensora.datasets.aspect import get_image_size, get_num_frames\nfrom opensora.models.text_encoder.t5 import text_preprocessing\nfrom opensora.utils.inference_utils import (\n    add_watermark,\n    append_generated,\n    append_score_to_prompts,\n    apply_mask_strategy,\n    collect_references_batch,\n    dframe_to_frame,\n    extract_json_from_prompts,\n    extract_prompts_loop,\n    get_random_prompt_by_openai,\n    has_openai_key,\n    merge_prompt,\n    prepare_multi_resolution_info,\n    refine_prompts_by_openai,\n    split_prompt,\n    prep_ref_and_update_mask_in_loop,\n    prep_ref_and_mask\n)\nfrom opensora.utils.misc import to_torch_dtype\n\n# some global variables\ndtype = to_torch_dtype(config.dtype)\ndevice = torch.device(\"cuda\")\n\n# build model\ndef initialize_models(mode, resolution):\n    return build_models(mode, resolution, enable_optimization=args.enable_optimization)\n\n\ndef run_inference(\n    mode,\n    prompt_text,\n    resolution,\n    aspect_ratio,\n    length,\n    motion_strength,\n    aesthetic_score,\n    use_motion_strength,\n    use_aesthetic_score,\n    camera_motion,\n    reference_image,\n    refine_prompt,\n    fps,\n    num_loop,\n    seed,\n    sampling_steps,\n    cfg_scale,\n):\n    if prompt_text is None or prompt_text == \"\":\n        gr.Warning(\"Your prompt is empty, please enter a valid prompt\")\n        return None\n\n    # Dynamically choose mode based on reference image\n    if reference_image is not None and mode != \"Text2Image\":\n        mode = \"i2v\"\n\n    # Initialize models\n    vae, text_encoder, stdit, scheduler, config = initialize_models(mode, resolution)\n\n    torch.manual_seed(seed)\n    with torch.inference_mode():\n        # ======================\n        # 1. Preparation arguments\n        # ======================\n        # parse the inputs\n        # frame_interval must be 1 so  we ignore it here\n        image_size = get_image_size(resolution, aspect_ratio)\n\n        use_sdedit = config.get(\"use_sdedit\", False)\n        use_oscillation_guidance_for_text = config.get(\"use_oscillation_guidance_for_text\", None)\n        use_oscillation_guidance_for_image = config.get(\"use_oscillation_guidance_for_image\", None)\n\n        cond_type = config.get(\"cond_type\", None)\n        cond_type = None if cond_type == \"none\" else cond_type\n        mask_index = None\n        ref = None\n        image_cfg_scale = None\n\n        # compute generation parameters\n        if mode == \"Text2Image\":\n            num_frames = 1\n            fps = IMG_FPS\n        else:\n            num_frames = config.num_frames\n            num_frames = get_num_frames(length)\n\n        condition_frame_length = config.get(\"condition_frame_length\", 5)\n        condition_frame_edit = config.get(\"condition_frame_edit\", 0.0)\n\n        input_size = (num_frames, *image_size)\n        latent_size = vae.get_latent_size(input_size)\n        multi_resolution = \"OpenSora\"\n        align = 5\n\n        # == prepare mask strategy ==\n        if mode == \"Text2Image\":\n            mask_strategy = [None]\n            mask_index = []\n        elif mode == \"Text2Video\":\n            if reference_image is not None:\n                mask_strategy = [\"0\"]\n                mask_index = [0]\n            else:\n                mask_strategy = [None]\n                mask_index = []\n        elif mode == \"i2v\":\n            mask_strategy = [\"0\"]\n            mask_index = [0]\n        else:\n            raise ValueError(f\"Invalid mode: {mode}\")\n\n        # == prepare reference ==\n        if mode == \"Text2Image\":\n            refs = [\"\"]\n        elif mode == \"Text2Video\":\n            if reference_image is not None:\n                # save image to disk\n                from PIL import Image\n\n                im = Image.fromarray(reference_image)\n                temp_file = NamedTemporaryFile(suffix=\".png\")\n                im.save(temp_file.name)\n                refs = [temp_file.name]\n            else:\n                refs = [\"\"]\n        elif mode == \"i2v\":\n            if reference_image is not None:\n                # save image to disk\n                from PIL import Image\n\n                im = Image.fromarray(reference_image)\n                temp_file = NamedTemporaryFile(suffix=\".png\")\n                im.save(temp_file.name)\n                refs = [temp_file.name]\n            else:\n                refs = [\"\"]\n        else:\n            raise ValueError(f\"Invalid mode: {mode}\")\n\n        # == get json from prompts ==\n        batch_prompts = [prompt_text]\n        batch_prompts, refs, mask_strategy = extract_json_from_prompts(batch_prompts, refs, mask_strategy)\n\n        # == get reference for condition ==\n        refs = collect_references_batch(refs, vae, image_size)\n\n        target_shape = [len(batch_prompts), vae.out_channels, *latent_size]\n        if mode == \"i2v\":\n            image_cfg_scale = config.get(\"image_cfg_scale\", 7.5)\n            ref, mask_index = prep_ref_and_mask(\n                cond_type, condition_frame_length, refs, target_shape, num_loop, device, dtype\n            )\n\n        # == multi-resolution info ==\n        model_args = prepare_multi_resolution_info(\n            multi_resolution, len(batch_prompts), image_size, num_frames, fps, device, dtype\n        )\n\n        # == process prompts step by step ==\n        # 0. split prompt\n        # each element in the list is [prompt_segment_list, loop_idx_list]\n        batched_prompt_segment_list = []\n        batched_loop_idx_list = []\n        for prompt in batch_prompts:\n            prompt_segment_list, loop_idx_list = split_prompt(prompt)\n            batched_prompt_segment_list.append(prompt_segment_list)\n            batched_loop_idx_list.append(loop_idx_list)\n\n        # 1. refine prompt by openai\n        if refine_prompt:\n            # check if openai key is provided\n            if not has_openai_key():\n                gr.Warning(\"OpenAI API key is not provided, the prompt will not be enhanced.\")\n            else:\n                for idx, prompt_segment_list in enumerate(batched_prompt_segment_list):\n                    batched_prompt_segment_list[idx] = refine_prompts_by_openai(prompt_segment_list)\n\n        # process scores\n        aesthetic_score = aesthetic_score if use_aesthetic_score else None\n        motion_strength = motion_strength if use_motion_strength and mode != \"Text2Image\" else None\n        camera_motion = None if camera_motion == \"none\" or mode == \"Text2Image\" else camera_motion\n        # 2. append score\n        for idx, prompt_segment_list in enumerate(batched_prompt_segment_list):\n            batched_prompt_segment_list[idx] = append_score_to_prompts(\n                prompt_segment_list,\n                aes=aesthetic_score,\n                flow=motion_strength,\n                camera_motion=camera_motion,\n            )\n\n        # 3. clean prompt with T5\n        for idx, prompt_segment_list in enumerate(batched_prompt_segment_list):\n            batched_prompt_segment_list[idx] = [text_preprocessing(prompt) for prompt in prompt_segment_list]\n\n        # 4. merge to obtain the final prompt\n        batch_prompts = []\n        for prompt_segment_list, loop_idx_list in zip(batched_prompt_segment_list, batched_loop_idx_list):\n            batch_prompts.append(merge_prompt(prompt_segment_list, loop_idx_list))\n\n        # =========================\n        # Generate image/video\n        # =========================\n        video_clips = []\n        for loop_i in range(num_loop):\n            # 4.4 sample in hidden space\n            batch_prompts_loop = extract_prompts_loop(batch_prompts, loop_i)\n\n            # == loop ==\n            # if loop_i > 0:\n            #     refs, mask_strategy = append_generated(\n            #         vae, video_clips[-1], refs, mask_strategy, loop_i, condition_frame_length, condition_frame_edit\n            #     )\n\n            # == sampling ==\n            z = torch.randn(len(batch_prompts), vae.out_channels, *latent_size, device=device, dtype=dtype)\n            masks = apply_mask_strategy(z, refs, mask_strategy, loop_i, align=align) if mask_index is None else None\n            x_cond_mask = torch.zeros(len(batch_prompts), vae.out_channels, *latent_size, device=device).to(dtype) if mask_index is not None else None\n            if x_cond_mask is not None and mask_index is not None:\n                    x_cond_mask[:, :, mask_index, :, :] = 1.0\n\n            # 4.6. diffusion sampling\n            # hack to update num_sampling_steps and cfg_scale\n            scheduler_kwargs = config.scheduler.copy()\n            scheduler_kwargs.pop(\"type\")\n            scheduler_kwargs[\"num_sampling_steps\"] = sampling_steps\n            scheduler_kwargs[\"cfg_scale\"] = cfg_scale\n\n            scheduler.__init__(**scheduler_kwargs)\n            samples = scheduler.sample(\n                stdit,\n                text_encoder,\n                z=z,\n                z_cond=ref,\n                z_cond_mask=x_cond_mask,\n                prompts=batch_prompts_loop,\n                device=device,\n                additional_args=model_args,\n                progress=True,\n                mask=masks,\n                mask_index=mask_index,\n                image_cfg_scale=image_cfg_scale,\n                use_sdedit=use_sdedit,\n                use_oscillation_guidance_for_text=use_oscillation_guidance_for_text,\n                use_oscillation_guidance_for_image=use_oscillation_guidance_for_image,\n            )\n\n            if loop_i > 1:  # process conditions for subsequent loop\n                    if cond_type is not None:  # i2v or v2v\n                        is_last_loop = loop_i == loop_i - 1\n                        ref, mask_index = prep_ref_and_update_mask_in_loop(\n                            cond_type,\n                            condition_frame_length,\n                            samples,\n                            refs,\n                            target_shape,\n                            is_last_loop,\n                            device,\n                            dtype,\n                        )\n\n                    else:\n                        refs, mask_strategy = append_generated(\n                            vae,\n                            samples,\n                            refs,\n                            mask_strategy,\n                            loop_i,\n                            condition_frame_length,\n                            condition_frame_edit,\n                            is_latent=True,\n                        )\n\n            # samples = vae.decode(samples.to(dtype), num_frames=num_frames)\n            video_clips.append(samples)\n\n        # =========================\n        # Save output\n        # =========================\n        video_clips = [val[0] for val in video_clips]\n        for i in range(1, num_loop):\n            video_clips[i] = video_clips[i][:, condition_frame_length:]\n        video = torch.cat(video_clips, dim=1)\n\n        t_cut = max(video.size(1) // 5 * 5, 1)\n        if t_cut < video.size(1):\n            video = video[:, :t_cut]\n        \n        video = vae.decode(video.to(dtype), num_frames=t_cut * 17 // 5).squeeze(0)\n\n        current_datetime = datetime.datetime.now()\n        timestamp = current_datetime.timestamp()\n\n        save_path = os.path.join(args.output, f\"output_{timestamp}\")\n        saved_path = save_sample(video, save_path=save_path, fps=24)\n        torch.cuda.empty_cache()\n\n        # add watermark\n        if mode != \"Text2Image\" and os.path.exists(WATERMARK_PATH):\n            watermarked_path = saved_path.replace(\".mp4\", \"_watermarked.mp4\")\n            success = add_watermark(saved_path, WATERMARK_PATH, watermarked_path)\n            if success:\n                return watermarked_path\n            else:\n                return saved_path\n        else:\n            return saved_path\n\n\n\n@spaces.GPU(duration=200)\ndef run_image_inference(\n    prompt_text,\n    resolution,\n    aspect_ratio,\n    length,\n    motion_strength,\n    aesthetic_score,\n    use_motion_strength,\n    use_aesthetic_score,\n    camera_motion,\n    reference_image,\n    refine_prompt,\n    fps,\n    num_loop,\n    seed,\n    sampling_steps,\n    cfg_scale,\n):\n    return run_inference(\n                \"Text2Image\",\n                prompt_text,\n                resolution,\n                aspect_ratio,\n                length,\n                motion_strength,\n                aesthetic_score,\n                use_motion_strength,\n                use_aesthetic_score,\n                camera_motion,\n                reference_image,\n                refine_prompt,\n                fps,\n                num_loop,\n                seed,\n                sampling_steps,\n                cfg_scale,\n            )\n\n\n@spaces.GPU(duration=200)\ndef run_video_inference(\n    prompt_text,\n    resolution,\n    aspect_ratio,\n    length,\n    motion_strength,\n    aesthetic_score,\n    use_motion_strength,\n    use_aesthetic_score,\n    camera_motion,\n    reference_image,\n    refine_prompt,\n    fps,\n    num_loop,\n    seed,\n    sampling_steps,\n    cfg_scale,\n):\n    # if (resolution == \"480p\" and length == \"16s\") or \\\n    #     (resolution == \"720p\" and length in [\"8s\", \"16s\"]):\n    #     gr.Warning(\"Generation is interrupted as the combination of 480p and 16s will lead to CUDA out of memory\")\n    # else:\n    return run_inference(\n        \"Text2Video\",\n        prompt_text,\n        resolution,\n        aspect_ratio,\n        length,\n        motion_strength,\n        aesthetic_score,\n        use_motion_strength,\n        use_aesthetic_score,\n        camera_motion,\n        reference_image,\n        refine_prompt,\n        fps,\n        num_loop,\n        seed,\n        sampling_steps,\n        cfg_scale,\n    )\n\n\ndef generate_random_prompt():\n    if \"OPENAI_API_KEY\" not in os.environ:\n        gr.Warning(\"Your prompt is empty and the OpenAI API key is not provided, please enter a valid prompt\")\n        return None\n    else:\n        prompt_text = get_random_prompt_by_openai()\n        return prompt_text\n\n\ndef main():\n    # create demo\n    with gr.Blocks() as demo:\n        with gr.Row():\n            with gr.Column():\n                gr.HTML(\n                    \"\"\"\n                <div style='text-align: center;'>\n                    <p align=\"center\">\n                        <img src=\"https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/icon.png\" width=\"250\"/>\n                    </p>\n                    <div style=\"display: flex; gap: 10px; justify-content: center;\">\n                        <a href=\"https://github.com/hpcaitech/Open-Sora/stargazers\"><img src=\"https://img.shields.io/github/stars/hpcaitech/Open-Sora?style=social\"></a>\n                        <a href=\"https://hpcaitech.github.io/Open-Sora/\"><img src=\"https://img.shields.io/badge/Gallery-View-orange?logo=&amp\"></a>\n                        <a href=\"https://discord.gg/kZakZzrSUT\"><img src=\"https://img.shields.io/badge/Discord-join-blueviolet?logo=discord&amp\"></a>\n                        <a href=\"https://join.slack.com/t/colossalaiworkspace/shared_invite/zt-247ipg9fk-KRRYmUl~u2ll2637WRURVA\"><img src=\"https://img.shields.io/badge/Slack-ColossalAI-blueviolet?logo=slack&amp\"></a>\n                        <a href=\"https://twitter.com/yangyou1991/status/1769411544083996787?s=61&t=jT0Dsx2d-MS5vS9rNM5e5g\"><img src=\"https://img.shields.io/badge/Twitter-Discuss-blue?logo=twitter&amp\"></a>\n                        <a href=\"https://raw.githubusercontent.com/hpcaitech/public_assets/main/colossalai/img/WeChat.png\"><img src=\"https://img.shields.io/badge/微信-小助手加群-green?logo=wechat&amp\"></a>\n                        <a href=\"https://hpc-ai.com/blog/open-sora-v1.0\"><img src=\"https://img.shields.io/badge/Open_Sora-Blog-blue\"></a>\n                    </div>\n                    <h1 style='margin-top: 5px;'>Open-Sora: Democratizing Efficient Video Production for All</h1>\n                </div>\n                \"\"\"\n                )\n\n        with gr.Row():\n            with gr.Column():\n                prompt_text = gr.Textbox(label=\"Prompt\", placeholder=\"Describe your video here\", lines=4)\n                refine_prompt = gr.Checkbox(\n                    value=has_openai_key(), label=\"Refine prompt with GPT4o\", interactive=has_openai_key()\n                )\n                random_prompt_btn = gr.Button(\"Random Prompt By GPT4o\", interactive=has_openai_key())\n\n                gr.Markdown(\"## Basic Settings\")\n                resolution = gr.Radio(\n                    choices=[\"360p\", \"720p\"],\n                    value=\"720p\",\n                    label=\"Resolution\",\n                )\n                aspect_ratio = gr.Radio(\n                    choices=[\"9:16\", \"16:9\", \"3:4\", \"4:3\", \"1:1\"],\n                    value=\"9:16\",\n                    label=\"Aspect Ratio (H:W)\",\n                )\n                length = gr.Radio(\n                    choices=[1, 49, 65, 81, 97, 113],\n                    value=97,\n                    label=\"Video Length (Number of Frames)\",\n                    info=\"Setting the number of frames to 1 indicates image generation instead of video generation.\",\n                )\n\n                with gr.Row():\n                    seed = gr.Slider(value=1024, minimum=1, maximum=2048, step=1, label=\"Seed\")\n\n                    sampling_steps = gr.Slider(value=30, minimum=1, maximum=200, step=1, label=\"Sampling steps\")\n                    cfg_scale = gr.Slider(value=7.0, minimum=0.0, maximum=10.0, step=0.1, label=\"CFG Scale\")\n\n                with gr.Row():\n                    with gr.Column():\n                        motion_strength = gr.Radio(\n                            choices=[\"very low\", \"low\", \"fair\", \"high\", \"very high\", \"extremely high\"],\n                            value=\"fair\",\n                            label=\"Motion Strength\",\n                            info=\"Only effective for video generation\",\n                        )\n                        use_motion_strength = gr.Checkbox(value=True, label=\"Enable\")\n\n                    with gr.Column():\n                        aesthetic_score = gr.Radio(\n                            choices=[\"terrible\", \"very poor\", \"poor\", \"fair\", \"good\", \"very good\", \"excellent\"],\n                            value=\"excellent\",\n                            label=\"Aesthetic\",\n                            info=\"Effective for text & video generation\",\n                        )\n                        use_aesthetic_score = gr.Checkbox(value=True, label=\"Enable\")\n\n                camera_motion = gr.Radio(\n                    value=\"none\",\n                    label=\"Camera Motion\",\n                    choices=[\"none\", \"pan right\", \"pan left\", \"tilt up\", \"tilt down\", \"zoom in\", \"zoom out\", \"static\"],\n                    interactive=True,\n                )\n\n                gr.Markdown(\"## Advanced Settings\")\n                with gr.Row():\n                    fps = gr.Slider(\n                        value=24,\n                        minimum=1,\n                        maximum=60,\n                        step=1,\n                        label=\"FPS\",\n                        info=\"This is the frames per seconds for video generation, keep it to 24 if you are not sure\",\n                    )\n                    num_loop = gr.Slider(\n                        value=1,\n                        minimum=1,\n                        maximum=20,\n                        step=1,\n                        label=\"Number of Loops\",\n                        info=\"This will change the length of the generated video, keep it to 1 if you are not sure\",\n                    )\n\n                gr.Markdown(\"## Reference Image\")\n                reference_image = gr.Image(label=\"Image (optional)\", show_download_button=True)\n\n            with gr.Column():\n                output_video = gr.Video(label=\"Output Video\", height=\"100%\")\n\n        with gr.Row():\n            image_gen_button = gr.Button(\"Generate image\")\n            video_gen_button = gr.Button(\"Generate video\")\n\n        image_gen_button.click(\n            fn=run_image_inference,\n            inputs=[\n                prompt_text,\n                resolution,\n                aspect_ratio,\n                length,\n                motion_strength,\n                aesthetic_score,\n                use_motion_strength,\n                use_aesthetic_score,\n                camera_motion,\n                reference_image,\n                refine_prompt,\n                fps,\n                num_loop,\n                seed,\n                sampling_steps,\n                cfg_scale,\n            ],\n            outputs=reference_image,\n        )\n\n        video_gen_button.click(\n            fn=run_video_inference,\n            inputs=[\n                prompt_text,\n                resolution,\n                aspect_ratio,\n                length,\n                motion_strength,\n                aesthetic_score,\n                use_motion_strength,\n                use_aesthetic_score,\n                camera_motion,\n                reference_image,\n                refine_prompt,\n                fps,\n                num_loop,\n                seed,\n                sampling_steps,\n                cfg_scale,\n            ],\n            outputs=output_video,\n        )\n        random_prompt_btn.click(fn=generate_random_prompt, outputs=prompt_text)\n\n    # launch\n    demo.queue(max_size=5, default_concurrency_limit=1)\n    demo.launch(server_port=args.port, server_name=args.host, share=args.share, max_threads=1)\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "opensora/__init__.py",
    "content": ""
  },
  {
    "path": "opensora/acceleration/__init__.py",
    "content": ""
  },
  {
    "path": "opensora/acceleration/checkpoint.py",
    "content": "import warnings\nfrom collections.abc import Iterable\nfrom typing import Callable, ContextManager, Optional, Tuple\n\nimport torch\nimport torch.nn as nn\nfrom colossalai.utils import get_current_device\nfrom torch.utils.checkpoint import (\n    _DEFAULT_DETERMINISM_MODE,\n    CheckpointFunction,\n    _checkpoint_without_reentrant_generator,\n    checkpoint_sequential,\n    noop_context_fn,\n)\n\n\nclass ActivationManager:\n    def __init__(self):\n        self.enable = False\n        self.buffer = None\n        self.total_size = 0\n        self.avail_offset = 0\n        self.tensor_id_queue = []\n        self.ignore_tensor_id_set = set()\n\n    def setup_buffer(self, numel: int, dtype: torch.dtype):\n        self.buffer = torch.empty(numel, dtype=dtype, pin_memory=True)\n        self.total_size = numel\n        self.enable = True\n\n    def offload(self, x: torch.Tensor) -> None:\n        if not self.enable or id(x) in self.ignore_tensor_id_set:\n            return\n        size = x.numel()\n        if self.avail_offset + size > self.total_size:\n            raise RuntimeError(\"Activation buffer is full\")\n        assert x.dtype == self.buffer.dtype, f\"Wrong dtype of offload tensor\"\n        cpu_x = self.buffer[self.avail_offset : self.avail_offset + size].view_as(x)\n        cpu_x.copy_(x)\n        x.data = cpu_x\n        self.avail_offset += size\n        self.tensor_id_queue.append(id(x))\n\n    def onload(self, x: torch.Tensor) -> None:\n        if not self.enable or id(x) in self.ignore_tensor_id_set:\n            return\n        assert self.tensor_id_queue[-1] == id(x), f\"Wrong order of offload/onload\"\n        # current x is pinned memory\n        assert x.data.is_pinned()\n        x.data = x.data.to(get_current_device(), non_blocking=True)\n        self.tensor_id_queue.pop()\n        self.avail_offset -= x.numel()\n        if len(self.tensor_id_queue) == 0:\n            self.ignore_tensor_id_set.clear()\n\n    def add_ignore_tensor(self, x: torch.Tensor) -> None:\n        self.ignore_tensor_id_set.add(id(x))\n\n    def is_top_tensor(self, x: torch.Tensor) -> bool:\n        return len(self.tensor_id_queue) > 0 and self.tensor_id_queue[-1] == id(x)\n\n\nGLOBAL_ACTIVATION_MANAGER = ActivationManager()\n\n\nclass CheckpointFunctionWithOffload(torch.autograd.Function):\n    @staticmethod\n    def forward(ctx, run_function, preserve_rng_state, *args):\n        for x in args[::-1]:\n            # handle those tensors are used in multiple checkpoints\n            if GLOBAL_ACTIVATION_MANAGER.is_top_tensor(x):\n                GLOBAL_ACTIVATION_MANAGER.onload(x)\n                GLOBAL_ACTIVATION_MANAGER.add_ignore_tensor(x)\n        out = CheckpointFunction.forward(ctx, run_function, preserve_rng_state, *args)\n        for x in args:\n            if torch.is_tensor(x):\n                GLOBAL_ACTIVATION_MANAGER.offload(x)\n        return out\n\n    @staticmethod\n    def backward(ctx, *args):\n        # with stack-fashion, the last tensor is the first to be loaded\n        for tensor in ctx.saved_tensors[::-1]:\n            GLOBAL_ACTIVATION_MANAGER.onload(tensor)\n        return CheckpointFunction.backward(ctx, *args)\n\n\n# TorchDynamo does not step inside utils.checkpoint function.  The flow\n# looks likes this\n#  1) TorchDynamo tries to wrap utils.checkpoint in a HigherOrderOp by\n#     speculatively checking if the forward function is safe to trace.\n#  2) If yes, then Dynamo-generated Fx graph has the wrapped higher\n#     order op. As a result, TorchDynamo does not look inside utils.checkpoint.\n#  3) If not, then TorchDynamo falls back to eager by performing a graph\n#     break. And here, the following disable wrapper ensures that\n#     TorchDynamo does not trigger again on the frames created by\n#     utils.checkpoint innards.\n@torch._disable_dynamo\ndef checkpoint(\n    function,\n    *args,\n    use_reentrant: Optional[bool] = None,\n    context_fn: Callable[[], Tuple[ContextManager, ContextManager]] = noop_context_fn,\n    determinism_check: str = _DEFAULT_DETERMINISM_MODE,\n    debug: bool = False,\n    **kwargs,\n):\n    r\"\"\"Checkpoint a model or part of the model.\n\n    Activation checkpointing is a technique that trades compute for memory.\n    Instead of keeping tensors needed for backward alive until they are used in\n    gradient computation during backward, forward computation in checkpointed\n    regions omits saving tensors for backward and recomputes them during the\n    backward pass. Activation checkpointing can be applied to any part of a\n    model.\n\n    There are currently two checkpointing implementations available, determined\n    by the :attr:`use_reentrant` parameter. It is recommended that you use\n    ``use_reentrant=False``. Please refer the note below for a discussion of\n    their differences.\n\n    .. warning::\n\n        If the :attr:`function` invocation during the backward pass differs\n        from the forward pass, e.g., due to a global variable, the checkpointed\n        version may not be equivalent, potentially causing an\n        error being raised or leading to silently incorrect gradients.\n\n    .. warning::\n\n        The ``use_reentrant`` parameter should be passed explicitly. In version\n        2.4 we will raise an exception if ``use_reentrant`` is not passed.\n        If you are using the ``use_reentrant=True`` variant, please refer to the\n        note below for important considerations and potential limitations.\n\n    .. note::\n\n        The reentrant variant of checkpoint (``use_reentrant=True``) and\n        the non-reentrant variant of checkpoint (``use_reentrant=False``)\n        differ in the following ways:\n\n        * Non-reentrant checkpoint stops recomputation as soon as all needed\n          intermediate activations have been recomputed. This feature is enabled\n          by default, but can be disabled with :func:`set_checkpoint_early_stop`.\n          Reentrant checkpoint always recomputes :attr:`function` in its\n          entirety during the backward pass.\n\n        * The reentrant variant does not record the autograd graph during the\n          forward pass, as it runs with the forward pass under\n          :func:`torch.no_grad`. The non-reentrant version does record the\n          autograd graph, allowing one to perform backward on the graph within\n          checkpointed regions.\n\n        * The reentrant checkpoint only supports the\n          :func:`torch.autograd.backward` API for the backward pass without its\n          `inputs` argument, while the non-reentrant version supports all ways\n          of performing the backward pass.\n\n        * At least one input and output must have ``requires_grad=True`` for the\n          reentrant variant. If this condition is unmet, the checkpointed part\n          of the model will not have gradients. The non-reentrant version does\n          not have this requirement.\n\n        * The reentrant version does not consider tensors in nested structures\n          (e.g., custom objects, lists, dicts, etc) as participating in\n          autograd, while the non-reentrant version does.\n\n        * The reentrant checkpoint does not support checkpointed regions with\n          detached tensors from the computational graph, whereas the\n          non-reentrant version does. For the reentrant variant, if the\n          checkpointed segment contains tensors detached using ``detach()`` or\n          with :func:`torch.no_grad`, the backward pass will raise an error.\n          This is because ``checkpoint`` makes all the outputs require gradients\n          and this causes issues when a tensor is defined to have no gradient in\n          the model. To avoid this, detach the tensors outside of the\n          ``checkpoint`` function.\n\n    Args:\n        function: describes what to run in the forward pass of the model or\n            part of the model. It should also know how to handle the inputs\n            passed as the tuple. For example, in LSTM, if user passes\n            ``(activation, hidden)``, :attr:`function` should correctly use the\n            first input as ``activation`` and the second input as ``hidden``\n        preserve_rng_state(bool, optional):  Omit stashing and restoring\n            the RNG state during each checkpoint. Note that under torch.compile,\n            this flag doesn't take effect and we always preserve RNG state.\n            Default: ``True``\n        use_reentrant(bool):\n            specify whether to use the activation checkpoint variant that\n            requires reentrant autograd. This parameter should be passed\n            explicitly. In version 2.4 we will raise an exception if\n            ``use_reentrant`` is not passed. If ``use_reentrant=False``,\n            ``checkpoint`` will use an implementation that does not require\n            reentrant autograd. This allows ``checkpoint`` to support additional\n            functionality, such as working as expected with\n            ``torch.autograd.grad`` and support for keyword arguments input into\n            the checkpointed function.\n        context_fn(Callable, optional): A callable returning a tuple of two\n            context managers. The function and its recomputation will be run\n            under the first and second context managers respectively.\n            This argument is only supported if ``use_reentrant=False``.\n        determinism_check(str, optional): A string specifying the determinism\n            check to perform. By default it is set to ``\"default\"`` which\n            compares the shapes, dtypes, and devices of the recomputed tensors\n            against those the saved tensors. To turn off this check, specify\n            ``\"none\"``. Currently these are the only two supported values.\n            Please open an issue if you would like to see more determinism\n            checks. This argument is only supported if ``use_reentrant=False``,\n            if ``use_reentrant=True``, the determinism check is always disabled.\n        debug(bool, optional): If ``True``, error messages will also include\n            a trace of the operators ran during the original forward computation\n            as well as the recomputation. This argument is only supported if\n            ``use_reentrant=False``.\n        args: tuple containing inputs to the :attr:`function`\n\n    Returns:\n        Output of running :attr:`function` on :attr:`*args`\n    \"\"\"\n    if use_reentrant is None:\n        warnings.warn(\n            \"torch.utils.checkpoint: the use_reentrant parameter should be \"\n            \"passed explicitly. In version 2.4 we will raise an exception \"\n            \"if use_reentrant is not passed. use_reentrant=False is \"\n            \"recommended, but if you need to preserve the current default \"\n            \"behavior, you can pass use_reentrant=True. Refer to docs for more \"\n            \"details on the differences between the two variants.\",\n            stacklevel=2,\n        )\n        use_reentrant = True\n\n    # Hack to mix *args with **kwargs in a python 2.7-compliant way\n    preserve = kwargs.pop(\"preserve_rng_state\", True)\n    if kwargs and use_reentrant:\n        raise ValueError(\"Unexpected keyword arguments: \" + \",\".join(arg for arg in kwargs))\n\n    if use_reentrant:\n        if context_fn is not noop_context_fn or debug is not False:\n            raise ValueError(\"Passing `context_fn` or `debug` is only supported when \" \"use_reentrant=False.\")\n        return CheckpointFunctionWithOffload.apply(function, preserve, *args)\n    else:\n        gen = _checkpoint_without_reentrant_generator(\n            function, preserve, context_fn, determinism_check, debug, *args, **kwargs\n        )\n        # Runs pre-forward logic\n        next(gen)\n        ret = function(*args, **kwargs)\n        # Runs post-forward logic\n        try:\n            next(gen)\n        except StopIteration:\n            return ret\n\n\ndef set_grad_checkpoint(model, use_fp32_attention=False, gc_step=1):\n    assert isinstance(model, nn.Module)\n\n    def set_attr(module):\n        module.grad_checkpointing = True\n        module.fp32_attention = use_fp32_attention\n        module.grad_checkpointing_step = gc_step\n\n    model.apply(set_attr)\n\n\ndef auto_grad_checkpoint(module, *args, **kwargs):\n    if getattr(module, \"grad_checkpointing\", False):\n        if not isinstance(module, Iterable):\n            return checkpoint(module, *args, use_reentrant=True, **kwargs)\n        gc_step = module[0].grad_checkpointing_step\n        return checkpoint_sequential(module, gc_step, *args, use_reentrant=False, **kwargs)\n    return module(*args, **kwargs)\n"
  },
  {
    "path": "opensora/acceleration/communications.py",
    "content": "import torch\nimport torch.distributed as dist\n\n\n# ====================\n# All-To-All\n# ====================\ndef _all_to_all(\n    input_: torch.Tensor,\n    world_size: int,\n    group: dist.ProcessGroup,\n    scatter_dim: int,\n    gather_dim: int,\n):\n    input_list = [t.contiguous() for t in torch.tensor_split(input_, world_size, scatter_dim)]\n    output_list = [torch.empty_like(input_list[0]) for _ in range(world_size)]\n    dist.all_to_all(output_list, input_list, group=group)\n    return torch.cat(output_list, dim=gather_dim).contiguous()\n\n\nclass _AllToAll(torch.autograd.Function):\n    \"\"\"All-to-all communication.\n\n    Args:\n        input_: input matrix\n        process_group: communication group\n        scatter_dim: scatter dimension\n        gather_dim: gather dimension\n    \"\"\"\n\n    @staticmethod\n    def forward(ctx, input_, process_group, scatter_dim, gather_dim):\n        ctx.process_group = process_group\n        ctx.scatter_dim = scatter_dim\n        ctx.gather_dim = gather_dim\n        ctx.world_size = dist.get_world_size(process_group)\n        output = _all_to_all(input_, ctx.world_size, process_group, scatter_dim, gather_dim)\n        return output\n\n    @staticmethod\n    def backward(ctx, grad_output):\n        grad_output = _all_to_all(\n            grad_output,\n            ctx.world_size,\n            ctx.process_group,\n            ctx.gather_dim,\n            ctx.scatter_dim,\n        )\n        return (\n            grad_output,\n            None,\n            None,\n            None,\n        )\n\n\ndef all_to_all(\n    input_: torch.Tensor,\n    process_group: dist.ProcessGroup,\n    scatter_dim: int = 2,\n    gather_dim: int = 1,\n):\n    return _AllToAll.apply(input_, process_group, scatter_dim, gather_dim)\n\n\ndef _gather(\n    input_: torch.Tensor,\n    world_size: int,\n    group: dist.ProcessGroup,\n    gather_dim: int,\n):\n    if gather_list is None:\n        gather_list = [torch.empty_like(input_) for _ in range(world_size)]\n    dist.gather(input_, gather_list, group=group, gather_dim=gather_dim)\n    return gather_list\n\n\n# ====================\n# Gather-Split\n# ====================\n\n\ndef _split(input_, pg: dist.ProcessGroup, dim=-1):\n    # skip if only one rank involved\n    world_size = dist.get_world_size(pg)\n    rank = dist.get_rank(pg)\n    if world_size == 1:\n        return input_\n\n    # Split along last dimension.\n    dim_size = input_.size(dim)\n    assert dim_size % world_size == 0, (\n        f\"The dimension to split ({dim_size}) is not a multiple of world size ({world_size}), \"\n        f\"cannot split tensor evenly\"\n    )\n\n    tensor_list = torch.split(input_, dim_size // world_size, dim=dim)\n    output = tensor_list[rank].contiguous()\n\n    return output\n\n\ndef _gather(input_, pg: dist.ProcessGroup, dim=-1):\n    # skip if only one rank involved\n    input_ = input_.contiguous()\n    world_size = dist.get_world_size(pg)\n    dist.get_rank(pg)\n\n    if world_size == 1:\n        return input_\n\n    # all gather\n    tensor_list = [torch.empty_like(input_) for _ in range(world_size)]\n    assert input_.device.type == \"cuda\"\n    torch.distributed.all_gather(tensor_list, input_, group=pg)\n\n    # concat\n    output = torch.cat(tensor_list, dim=dim).contiguous()\n\n    return output\n\n\nclass _GatherForwardSplitBackward(torch.autograd.Function):\n    \"\"\"Gather the input from model parallel region and concatenate.\n\n    Args:\n        input_: input matrix.\n        process_group: parallel mode.\n        dim: dimension\n    \"\"\"\n\n    @staticmethod\n    def symbolic(graph, input_):\n        return _gather(input_)\n\n    @staticmethod\n    def forward(ctx, input_, process_group, dim, grad_scale):\n        ctx.mode = process_group\n        ctx.dim = dim\n        ctx.grad_scale = grad_scale\n        return _gather(input_, process_group, dim)\n\n    @staticmethod\n    def backward(ctx, grad_output):\n        if ctx.grad_scale == \"up\":\n            grad_output = grad_output * dist.get_world_size(ctx.mode)\n        elif ctx.grad_scale == \"down\":\n            grad_output = grad_output / dist.get_world_size(ctx.mode)\n\n        return _split(grad_output, ctx.mode, ctx.dim), None, None, None\n\n\nclass _SplitForwardGatherBackward(torch.autograd.Function):\n    \"\"\"\n    Split the input and keep only the corresponding chuck to the rank.\n\n    Args:\n        input_: input matrix.\n        process_group: parallel mode.\n        dim: dimension\n    \"\"\"\n\n    @staticmethod\n    def symbolic(graph, input_):\n        return _split(input_)\n\n    @staticmethod\n    def forward(ctx, input_, process_group, dim, grad_scale):\n        ctx.mode = process_group\n        ctx.dim = dim\n        ctx.grad_scale = grad_scale\n        return _split(input_, process_group, dim)\n\n    @staticmethod\n    def backward(ctx, grad_output):\n        if ctx.grad_scale == \"up\":\n            grad_output = grad_output * dist.get_world_size(ctx.mode)\n        elif ctx.grad_scale == \"down\":\n            grad_output = grad_output / dist.get_world_size(ctx.mode)\n        return _gather(grad_output, ctx.mode, ctx.dim), None, None, None\n\n\ndef split_forward_gather_backward(input_, process_group, dim, grad_scale=1.0):\n    return _SplitForwardGatherBackward.apply(input_, process_group, dim, grad_scale)\n\n\ndef gather_forward_split_backward(input_, process_group, dim, grad_scale=None):\n    return _GatherForwardSplitBackward.apply(input_, process_group, dim, grad_scale)\n"
  },
  {
    "path": "opensora/acceleration/parallel_states.py",
    "content": "import torch.distributed as dist\n\n_GLOBAL_PARALLEL_GROUPS = dict()\n\n\ndef set_data_parallel_group(group: dist.ProcessGroup):\n    _GLOBAL_PARALLEL_GROUPS[\"data\"] = group\n\n\ndef get_data_parallel_group(get_mixed_dp_pg : bool = False):\n    if get_mixed_dp_pg and \"mixed_dp_group\" in _GLOBAL_PARALLEL_GROUPS:\n        return _GLOBAL_PARALLEL_GROUPS[\"mixed_dp_group\"]\n    return _GLOBAL_PARALLEL_GROUPS.get(\"data\", dist.group.WORLD)\n\n\ndef set_sequence_parallel_group(group: dist.ProcessGroup):\n    _GLOBAL_PARALLEL_GROUPS[\"sequence\"] = group\n\n\ndef get_sequence_parallel_group():\n    return _GLOBAL_PARALLEL_GROUPS.get(\"sequence\", None)\n\n\ndef set_tensor_parallel_group(group: dist.ProcessGroup):\n    _GLOBAL_PARALLEL_GROUPS[\"tensor\"] = group\n\n\ndef get_tensor_parallel_group():\n    return _GLOBAL_PARALLEL_GROUPS.get(\"tensor\", None)\n"
  },
  {
    "path": "opensora/acceleration/shardformer/__init__.py",
    "content": ""
  },
  {
    "path": "opensora/acceleration/shardformer/modeling/__init__.py",
    "content": ""
  },
  {
    "path": "opensora/acceleration/shardformer/modeling/t5.py",
    "content": "import torch\nimport torch.nn as nn\n\n\nclass T5LayerNorm(nn.Module):\n    def __init__(self, hidden_size, eps=1e-6):\n        \"\"\"\n        Construct a layernorm module in the T5 style. No bias and no subtraction of mean.\n        \"\"\"\n        super().__init__()\n        self.weight = nn.Parameter(torch.ones(hidden_size))\n        self.variance_epsilon = eps\n\n    def forward(self, hidden_states):\n        # T5 uses a layer_norm which only scales and doesn't shift, which is also known as Root Mean\n        # Square Layer Normalization https://arxiv.org/abs/1910.07467 thus varience is calculated\n        # w/o mean and there is no bias. Additionally we want to make sure that the accumulation for\n        # half-precision inputs is done in fp32\n\n        variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True)\n        hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)\n\n        # convert into half-precision if necessary\n        if self.weight.dtype in [torch.float16, torch.bfloat16]:\n            hidden_states = hidden_states.to(self.weight.dtype)\n\n        return self.weight * hidden_states\n\n    @staticmethod\n    def from_native_module(module, *args, **kwargs):\n        assert module.__class__.__name__ == \"FusedRMSNorm\", (\n            \"Recovering T5LayerNorm requires the original layer to be apex's Fused RMS Norm.\"\n            \"Apex's fused norm is automatically used by Hugging Face Transformers https://github.com/huggingface/transformers/blob/main/src/transformers/models/t5/modeling_t5.py#L265C5-L265C48\"\n        )\n\n        layer_norm = T5LayerNorm(module.normalized_shape, eps=module.eps)\n        layer_norm.weight.data.copy_(module.weight.data)\n        layer_norm = layer_norm.to(module.weight.device)\n        return layer_norm\n"
  },
  {
    "path": "opensora/acceleration/shardformer/policy/__init__.py",
    "content": ""
  },
  {
    "path": "opensora/acceleration/shardformer/policy/t5_encoder.py",
    "content": "from colossalai.shardformer.modeling.jit import get_jit_fused_dropout_add_func\nfrom colossalai.shardformer.modeling.t5 import get_jit_fused_T5_layer_ff_forward, get_T5_layer_self_attention_forward\nfrom colossalai.shardformer.policies.base_policy import Policy, SubModuleReplacementDescription\n\n\nclass T5EncoderPolicy(Policy):\n    def config_sanity_check(self):\n        assert not self.shard_config.enable_tensor_parallelism\n        assert not self.shard_config.enable_flash_attention\n\n    def preprocess(self):\n        return self.model\n\n    def module_policy(self):\n        from transformers.models.t5.modeling_t5 import T5LayerFF, T5LayerSelfAttention, T5Stack\n\n        policy = {}\n\n        # use jit operator\n        if self.shard_config.enable_jit_fused:\n            self.append_or_create_method_replacement(\n                description={\n                    \"forward\": get_jit_fused_T5_layer_ff_forward(),\n                    \"dropout_add\": get_jit_fused_dropout_add_func(),\n                },\n                policy=policy,\n                target_key=T5LayerFF,\n            )\n            self.append_or_create_method_replacement(\n                description={\n                    \"forward\": get_T5_layer_self_attention_forward(),\n                    \"dropout_add\": get_jit_fused_dropout_add_func(),\n                },\n                policy=policy,\n                target_key=T5LayerSelfAttention,\n            )\n\n        return policy\n\n    def postprocess(self):\n        return self.model\n"
  },
  {
    "path": "opensora/models/__init__.py",
    "content": "from .dc_ae import *\nfrom .hunyuan_vae import *\nfrom .mmdit import *\nfrom .text import *\nfrom .vae import *\n"
  },
  {
    "path": "opensora/models/dc_ae/__init__.py",
    "content": "from .ae_model_zoo import DC_AE\n"
  },
  {
    "path": "opensora/models/dc_ae/ae_model_zoo.py",
    "content": "# Copyright 2024 MIT Han Lab\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# SPDX-License-Identifier: Apache-2.0\n\nfrom typing import Callable, Optional\n\nimport diffusers\nimport torch\nfrom huggingface_hub import PyTorchModelHubMixin\nfrom torch import nn\n\nfrom opensora.registry import MODELS\nfrom opensora.utils.ckpt import load_checkpoint\n\nfrom .models.dc_ae import DCAE, DCAEConfig, dc_ae_f32\n\n__all__ = [\"create_dc_ae_model_cfg\", \"DCAE_HF\", \"DC_AE\"]\n\n\nREGISTERED_DCAE_MODEL: dict[str, tuple[Callable, Optional[str]]] = {\n    \"dc-ae-f32t4c128\": (dc_ae_f32, None),\n}\n\n\ndef create_dc_ae_model_cfg(name: str, pretrained_path: Optional[str] = None) -> DCAEConfig:\n    assert name in REGISTERED_DCAE_MODEL, f\"{name} is not supported\"\n    dc_ae_cls, default_pt_path = REGISTERED_DCAE_MODEL[name]\n    pretrained_path = default_pt_path if pretrained_path is None else pretrained_path\n    model_cfg = dc_ae_cls(name, pretrained_path)\n    return model_cfg\n\n\nclass DCAE_HF(DCAE, PyTorchModelHubMixin):\n    def __init__(self, model_name: str):\n        cfg = create_dc_ae_model_cfg(model_name)\n        DCAE.__init__(self, cfg)\n\n\n@MODELS.register_module(\"dc_ae\")\ndef DC_AE(\n    model_name: str,\n    device_map: str | torch.device = \"cuda\",\n    torch_dtype: torch.dtype = torch.bfloat16,\n    from_scratch: bool = False,\n    from_pretrained: str | None = None,\n    is_training: bool = False,\n    use_spatial_tiling: bool = False,\n    use_temporal_tiling: bool = False,\n    spatial_tile_size: int = 256,\n    temporal_tile_size: int = 32,\n    tile_overlap_factor: float = 0.25,\n    scaling_factor: float = None,\n    disc_off_grad_ckpt: bool = False,\n) -> DCAE_HF:\n    if not from_scratch:\n        model = DCAE_HF.from_pretrained(model_name).to(device_map, torch_dtype)\n    else:\n        model = DCAE_HF(model_name).to(device_map, torch_dtype)\n\n    if from_pretrained is not None:\n        model = load_checkpoint(model, from_pretrained, device_map=device_map)\n        print(f\"loaded dc_ae from ckpt path: {from_pretrained}\")\n\n    model.cfg.is_training = is_training\n    model.use_spatial_tiling = use_spatial_tiling\n    model.use_temporal_tiling = use_temporal_tiling\n    model.spatial_tile_size = spatial_tile_size\n    model.temporal_tile_size = temporal_tile_size\n    model.tile_overlap_factor = tile_overlap_factor\n    if scaling_factor is not None:\n        model.scaling_factor = scaling_factor\n    model.decoder.disc_off_grad_ckpt = disc_off_grad_ckpt\n    return model"
  },
  {
    "path": "opensora/models/dc_ae/models/__init__.py",
    "content": "from .dc_ae import *\n"
  },
  {
    "path": "opensora/models/dc_ae/models/dc_ae.py",
    "content": "# Copyright 2024 MIT Han Lab\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# SPDX-License-Identifier: Apache-2.0\n\nfrom dataclasses import dataclass, field\nfrom typing import Any, Optional\n\nimport torch\nimport torch.nn as nn\nfrom omegaconf import MISSING, OmegaConf\nfrom torch import Tensor\n\nfrom opensora.acceleration.checkpoint import auto_grad_checkpoint\n\nfrom ..utils import init_modules\nfrom .nn.act import build_act\nfrom .nn.norm import build_norm\nfrom .nn.ops import (\n    ChannelDuplicatingPixelShuffleUpSampleLayer,\n    ConvLayer,\n    ConvPixelShuffleUpSampleLayer,\n    ConvPixelUnshuffleDownSampleLayer,\n    EfficientViTBlock,\n    IdentityLayer,\n    InterpolateConvUpSampleLayer,\n    OpSequential,\n    PixelUnshuffleChannelAveragingDownSampleLayer,\n    ResBlock,\n    ResidualBlock,\n)\n\n__all__ = [\"DCAE\", \"dc_ae_f32\"]\n\n\n@dataclass\nclass EncoderConfig:\n    in_channels: int = MISSING\n    latent_channels: int = MISSING\n    width_list: tuple[int, ...] = (128, 256, 512, 512, 1024, 1024)\n    depth_list: tuple[int, ...] = (2, 2, 2, 2, 2, 2)\n    block_type: Any = \"ResBlock\"\n    norm: str = \"rms2d\"\n    act: str = \"silu\"\n    downsample_block_type: str = \"ConvPixelUnshuffle\"\n    downsample_match_channel: bool = True\n    downsample_shortcut: Optional[str] = \"averaging\"\n    out_norm: Optional[str] = None\n    out_act: Optional[str] = None\n    out_shortcut: Optional[str] = \"averaging\"\n    double_latent: bool = False\n    is_video: bool = False\n    temporal_downsample: tuple[bool, ...] = ()\n\n\n@dataclass\nclass DecoderConfig:\n    in_channels: int = MISSING\n    latent_channels: int = MISSING\n    in_shortcut: Optional[str] = \"duplicating\"\n    width_list: tuple[int, ...] = (128, 256, 512, 512, 1024, 1024)\n    depth_list: tuple[int, ...] = (2, 2, 2, 2, 2, 2)\n    block_type: Any = \"ResBlock\"\n    norm: Any = \"rms2d\"\n    act: Any = \"silu\"\n    upsample_block_type: str = \"ConvPixelShuffle\"\n    upsample_match_channel: bool = True\n    upsample_shortcut: str = \"duplicating\"\n    out_norm: str = \"rms2d\"\n    out_act: str = \"relu\"\n    is_video: bool = False\n    temporal_upsample: tuple[bool, ...] = ()\n\n\n@dataclass\nclass DCAEConfig:\n    in_channels: int = 3\n    latent_channels: int = 32\n    time_compression_ratio: int = 1\n    spatial_compression_ratio: int = 32\n    encoder: EncoderConfig = field(\n        default_factory=lambda: EncoderConfig(in_channels=\"${..in_channels}\", latent_channels=\"${..latent_channels}\")\n    )\n    decoder: DecoderConfig = field(\n        default_factory=lambda: DecoderConfig(in_channels=\"${..in_channels}\", latent_channels=\"${..latent_channels}\")\n    )\n    use_quant_conv: bool = False\n\n    pretrained_path: Optional[str] = None\n    pretrained_source: str = \"dc-ae\"\n\n    scaling_factor: Optional[float] = None\n    is_image_model: bool = False\n\n    is_training: bool = False  # NOTE: set to True in vae train config\n\n    use_spatial_tiling: bool = False\n    use_temporal_tiling: bool = False\n    spatial_tile_size: int = 256\n    temporal_tile_size: int = 32\n    tile_overlap_factor: float = 0.25\n    \n\n\ndef build_block(\n    block_type: str, in_channels: int, out_channels: int, norm: Optional[str], act: Optional[str], is_video: bool\n) -> nn.Module:\n    if block_type == \"ResBlock\":\n        assert in_channels == out_channels\n        main_block = ResBlock(\n            in_channels=in_channels,\n            out_channels=out_channels,\n            kernel_size=3,\n            stride=1,\n            use_bias=(True, False),\n            norm=(None, norm),\n            act_func=(act, None),\n            is_video=is_video,\n        )\n        block = ResidualBlock(main_block, IdentityLayer())\n    elif block_type == \"EViT_GLU\":\n        assert in_channels == out_channels\n        block = EfficientViTBlock(\n            in_channels, norm=norm, act_func=act, local_module=\"GLUMBConv\", scales=(), is_video=is_video\n        )\n    elif block_type == \"EViTS5_GLU\":\n        assert in_channels == out_channels\n        block = EfficientViTBlock(\n            in_channels, norm=norm, act_func=act, local_module=\"GLUMBConv\", scales=(5,), is_video=is_video\n        )\n    else:\n        raise ValueError(f\"block_type {block_type} is not supported\")\n    return block\n\n\ndef build_stage_main(\n    width: int, depth: int, block_type: str | list[str], norm: str, act: str, input_width: int, is_video: bool\n) -> list[nn.Module]:\n    assert isinstance(block_type, str) or (isinstance(block_type, list) and depth == len(block_type))\n    stage = []\n    for d in range(depth):\n        current_block_type = block_type[d] if isinstance(block_type, list) else block_type\n        block = build_block(\n            block_type=current_block_type,\n            in_channels=width if d > 0 else input_width,\n            out_channels=width,\n            norm=norm,\n            act=act,\n            is_video=is_video,\n        )\n        stage.append(block)\n    return stage\n\n\ndef build_downsample_block(\n    block_type: str,\n    in_channels: int,\n    out_channels: int,\n    shortcut: Optional[str],\n    is_video: bool,\n    temporal_downsample: bool = False,\n) -> nn.Module:\n    \"\"\"\n    Spatial downsample is always performed. Temporal downsample is optional.\n    \"\"\"\n\n    if block_type == \"Conv\":\n        if is_video:\n            if temporal_downsample:\n                stride = (2, 2, 2)\n            else:\n                stride = (1, 2, 2)\n        else:\n            stride = 2\n        block = ConvLayer(\n            in_channels=in_channels,\n            out_channels=out_channels,\n            kernel_size=3,\n            stride=stride,\n            use_bias=True,\n            norm=None,\n            act_func=None,\n            is_video=is_video,\n        )\n    elif block_type == \"ConvPixelUnshuffle\":\n        if is_video:\n            raise NotImplementedError(\"ConvPixelUnshuffle downsample is not supported for video\")\n        block = ConvPixelUnshuffleDownSampleLayer(\n            in_channels=in_channels, out_channels=out_channels, kernel_size=3, factor=2\n        )\n    else:\n        raise ValueError(f\"block_type {block_type} is not supported for downsampling\")\n    if shortcut is None:\n        pass\n    elif shortcut == \"averaging\":\n        shortcut_block = PixelUnshuffleChannelAveragingDownSampleLayer(\n            in_channels=in_channels, out_channels=out_channels, factor=2, temporal_downsample=temporal_downsample\n        )\n        block = ResidualBlock(block, shortcut_block)\n    else:\n        raise ValueError(f\"shortcut {shortcut} is not supported for downsample\")\n    return block\n\n\ndef build_upsample_block(\n    block_type: str,\n    in_channels: int,\n    out_channels: int,\n    shortcut: Optional[str],\n    is_video: bool,\n    temporal_upsample: bool = False,\n) -> nn.Module:\n    if block_type == \"ConvPixelShuffle\":\n        if is_video:\n            raise NotImplementedError(\"ConvPixelShuffle upsample is not supported for video\")\n        block = ConvPixelShuffleUpSampleLayer(\n            in_channels=in_channels, out_channels=out_channels, kernel_size=3, factor=2\n        )\n    elif block_type == \"InterpolateConv\":\n        block = InterpolateConvUpSampleLayer(\n            in_channels=in_channels,\n            out_channels=out_channels,\n            kernel_size=3,\n            factor=2,\n            is_video=is_video,\n            temporal_upsample=temporal_upsample,\n        )\n    else:\n        raise ValueError(f\"block_type {block_type} is not supported for upsampling\")\n    if shortcut is None:\n        pass\n    elif shortcut == \"duplicating\":\n        shortcut_block = ChannelDuplicatingPixelShuffleUpSampleLayer(\n            in_channels=in_channels, out_channels=out_channels, factor=2, temporal_upsample=temporal_upsample\n        )\n        block = ResidualBlock(block, shortcut_block)\n    else:\n        raise ValueError(f\"shortcut {shortcut} is not supported for upsample\")\n    return block\n\n\ndef build_encoder_project_in_block(\n    in_channels: int, out_channels: int, factor: int, downsample_block_type: str, is_video: bool\n):\n    if factor == 1:\n        block = ConvLayer(\n            in_channels=in_channels,\n            out_channels=out_channels,\n            kernel_size=3,\n            stride=1,\n            use_bias=True,\n            norm=None,\n            act_func=None,\n            is_video=is_video,\n        )\n    elif factor == 2:\n        if is_video:\n            raise NotImplementedError(\"Downsample during project_in is not supported for video\")\n        block = build_downsample_block(\n            block_type=downsample_block_type, in_channels=in_channels, out_channels=out_channels, shortcut=None\n        )\n    else:\n        raise ValueError(f\"downsample factor {factor} is not supported for encoder project in\")\n    return block\n\n\ndef build_encoder_project_out_block(\n    in_channels: int,\n    out_channels: int,\n    norm: Optional[str],\n    act: Optional[str],\n    shortcut: Optional[str],\n    is_video: bool,\n):\n    block = OpSequential(\n        [\n            build_norm(norm),\n            build_act(act),\n            ConvLayer(\n                in_channels=in_channels,\n                out_channels=out_channels,\n                kernel_size=3,\n                stride=1,\n                use_bias=True,\n                norm=None,\n                act_func=None,\n                is_video=is_video,\n            ),\n        ]\n    )\n    if shortcut is None:\n        pass\n    elif shortcut == \"averaging\":\n        shortcut_block = PixelUnshuffleChannelAveragingDownSampleLayer(\n            in_channels=in_channels, out_channels=out_channels, factor=1\n        )\n        block = ResidualBlock(block, shortcut_block)\n    else:\n        raise ValueError(f\"shortcut {shortcut} is not supported for encoder project out\")\n    return block\n\n\ndef build_decoder_project_in_block(in_channels: int, out_channels: int, shortcut: Optional[str], is_video: bool):\n    block = ConvLayer(\n        in_channels=in_channels,\n        out_channels=out_channels,\n        kernel_size=3,\n        stride=1,\n        use_bias=True,\n        norm=None,\n        act_func=None,\n        is_video=is_video,\n    )\n    if shortcut is None:\n        pass\n    elif shortcut == \"duplicating\":\n        shortcut_block = ChannelDuplicatingPixelShuffleUpSampleLayer(\n            in_channels=in_channels, out_channels=out_channels, factor=1\n        )\n        block = ResidualBlock(block, shortcut_block)\n    else:\n        raise ValueError(f\"shortcut {shortcut} is not supported for decoder project in\")\n    return block\n\n\ndef build_decoder_project_out_block(\n    in_channels: int,\n    out_channels: int,\n    factor: int,\n    upsample_block_type: str,\n    norm: Optional[str],\n    act: Optional[str],\n    is_video: bool,\n):\n    layers: list[nn.Module] = [\n        build_norm(norm, in_channels),\n        build_act(act),\n    ]\n    if factor == 1:\n        layers.append(\n            ConvLayer(\n                in_channels=in_channels,\n                out_channels=out_channels,\n                kernel_size=3,\n                stride=1,\n                use_bias=True,\n                norm=None,\n                act_func=None,\n                is_video=is_video,\n            )\n        )\n    elif factor == 2:\n        if is_video:\n            raise NotImplementedError(\"Upsample during project_out is not supported for video\")\n        layers.append(\n            build_upsample_block(\n                block_type=upsample_block_type, in_channels=in_channels, out_channels=out_channels, shortcut=None\n            )\n        )\n    else:\n        raise ValueError(f\"upsample factor {factor} is not supported for decoder project out\")\n    return OpSequential(layers)\n\n\nclass Encoder(nn.Module):\n    def __init__(self, cfg: EncoderConfig):\n        super().__init__()\n        self.cfg = cfg\n        num_stages = len(cfg.width_list)\n        self.num_stages = num_stages\n        assert len(cfg.depth_list) == num_stages\n        assert len(cfg.width_list) == num_stages\n        assert isinstance(cfg.block_type, str) or (\n            isinstance(cfg.block_type, list) and len(cfg.block_type) == num_stages\n        )\n\n        self.project_in = build_encoder_project_in_block(\n            in_channels=cfg.in_channels,\n            out_channels=cfg.width_list[0] if cfg.depth_list[0] > 0 else cfg.width_list[1],\n            factor=1 if cfg.depth_list[0] > 0 else 2,\n            downsample_block_type=cfg.downsample_block_type,\n            is_video=cfg.is_video,\n        )\n\n        self.stages: list[OpSequential] = []\n        for stage_id, (width, depth) in enumerate(zip(cfg.width_list, cfg.depth_list)):\n            block_type = cfg.block_type[stage_id] if isinstance(cfg.block_type, list) else cfg.block_type\n            stage = build_stage_main(\n                width=width,\n                depth=depth,\n                block_type=block_type,\n                norm=cfg.norm,\n                act=cfg.act,\n                input_width=width,\n                is_video=cfg.is_video,\n            )\n\n            if stage_id < num_stages - 1 and depth > 0:\n                downsample_block = build_downsample_block(\n                    block_type=cfg.downsample_block_type,\n                    in_channels=width,\n                    out_channels=cfg.width_list[stage_id + 1] if cfg.downsample_match_channel else width,\n                    shortcut=cfg.downsample_shortcut,\n                    is_video=cfg.is_video,\n                    temporal_downsample=cfg.temporal_downsample[stage_id] if cfg.temporal_downsample != [] else False,\n                )\n                stage.append(downsample_block)\n            self.stages.append(OpSequential(stage))\n        self.stages = nn.ModuleList(self.stages)\n\n        self.project_out = build_encoder_project_out_block(\n            in_channels=cfg.width_list[-1],\n            out_channels=2 * cfg.latent_channels if cfg.double_latent else cfg.latent_channels,\n            norm=cfg.out_norm,\n            act=cfg.out_act,\n            shortcut=cfg.out_shortcut,\n            is_video=cfg.is_video,\n        )\n\n    def forward(self, x: torch.Tensor) -> torch.Tensor:\n        x = self.project_in(x)\n        # x = auto_grad_checkpoint(self.project_in, x)\n        for stage in self.stages:\n            if len(stage.op_list) == 0:\n                continue\n            x = auto_grad_checkpoint(stage, x)\n        # x = self.project_out(x)\n        x = auto_grad_checkpoint(self.project_out, x)\n        return x\n\n\nclass Decoder(nn.Module):\n    def __init__(self, cfg: DecoderConfig):\n        super().__init__()\n        self.cfg = cfg\n        num_stages = len(cfg.width_list)\n        self.num_stages = num_stages\n        assert len(cfg.depth_list) == num_stages\n        assert len(cfg.width_list) == num_stages\n        assert isinstance(cfg.block_type, str) or (\n            isinstance(cfg.block_type, list) and len(cfg.block_type) == num_stages\n        )\n        assert isinstance(cfg.norm, str) or (isinstance(cfg.norm, list) and len(cfg.norm) == num_stages)\n        assert isinstance(cfg.act, str) or (isinstance(cfg.act, list) and len(cfg.act) == num_stages)\n\n        self.project_in = build_decoder_project_in_block(\n            in_channels=cfg.latent_channels,\n            out_channels=cfg.width_list[-1],\n            shortcut=cfg.in_shortcut,\n            is_video=cfg.is_video,\n        )\n\n        self.stages: list[OpSequential] = []\n        for stage_id, (width, depth) in reversed(list(enumerate(zip(cfg.width_list, cfg.depth_list)))):\n            stage = []\n            if stage_id < num_stages - 1 and depth > 0:\n                upsample_block = build_upsample_block(\n                    block_type=cfg.upsample_block_type,\n                    in_channels=cfg.width_list[stage_id + 1],\n                    out_channels=width if cfg.upsample_match_channel else cfg.width_list[stage_id + 1],\n                    shortcut=cfg.upsample_shortcut,\n                    is_video=cfg.is_video,\n                    temporal_upsample=cfg.temporal_upsample[stage_id] if cfg.temporal_upsample != [] else False,\n                )\n                stage.append(upsample_block)\n\n            block_type = cfg.block_type[stage_id] if isinstance(cfg.block_type, list) else cfg.block_type\n            norm = cfg.norm[stage_id] if isinstance(cfg.norm, list) else cfg.norm\n            act = cfg.act[stage_id] if isinstance(cfg.act, list) else cfg.act\n            stage.extend(\n                build_stage_main(\n                    width=width,\n                    depth=depth,\n                    block_type=block_type,\n                    norm=norm,\n                    act=act,\n                    input_width=(\n                        width if cfg.upsample_match_channel else cfg.width_list[min(stage_id + 1, num_stages - 1)]\n                    ),\n                    is_video=cfg.is_video,\n                )\n            )\n            self.stages.insert(0, OpSequential(stage))\n        self.stages = nn.ModuleList(self.stages)\n\n        self.project_out = build_decoder_project_out_block(\n            in_channels=cfg.width_list[0] if cfg.depth_list[0] > 0 else cfg.width_list[1],\n            out_channels=cfg.in_channels,\n            factor=1 if cfg.depth_list[0] > 0 else 2,\n            upsample_block_type=cfg.upsample_block_type,\n            norm=cfg.out_norm,\n            act=cfg.out_act,\n            is_video=cfg.is_video,\n        )\n\n    def forward(self, x: torch.Tensor) -> torch.Tensor:\n        x = auto_grad_checkpoint(self.project_in, x)\n        for stage in reversed(self.stages):\n            if len(stage.op_list) == 0:\n                continue\n            # x = stage(x)\n            x = auto_grad_checkpoint(stage, x)\n\n        if self.disc_off_grad_ckpt:\n            x = self.project_out(x)\n        else:\n            x = auto_grad_checkpoint(self.project_out, x)\n        return x\n\n\nclass DCAE(nn.Module):\n    def __init__(self, cfg: DCAEConfig):\n        super().__init__()\n        self.cfg = cfg\n        self.encoder = Encoder(cfg.encoder)\n        self.decoder = Decoder(cfg.decoder)\n        self.scaling_factor = cfg.scaling_factor\n        self.time_compression_ratio = cfg.time_compression_ratio\n        self.spatial_compression_ratio = cfg.spatial_compression_ratio\n        self.use_spatial_tiling = cfg.use_spatial_tiling\n        self.use_temporal_tiling = cfg.use_temporal_tiling\n        self.spatial_tile_size = cfg.spatial_tile_size\n        self.temporal_tile_size = cfg.temporal_tile_size\n        assert (\n            cfg.spatial_tile_size // cfg.spatial_compression_ratio\n        ), f\"spatial tile size {cfg.spatial_tile_size} must be divisible by spatial compression of {cfg.spatial_compression_ratio}\"\n        self.spatial_tile_latent_size = cfg.spatial_tile_size // cfg.spatial_compression_ratio\n        assert (\n            cfg.temporal_tile_size // cfg.time_compression_ratio\n        ), f\"temporal tile size {cfg.temporal_tile_size} must be divisible by temporal compression of {cfg.time_compression_ratio}\"\n        self.temporal_tile_latent_size = cfg.temporal_tile_size // cfg.time_compression_ratio\n        self.tile_overlap_factor = cfg.tile_overlap_factor\n        if self.cfg.pretrained_path is not None:\n            self.load_model()\n\n        self.to(torch.float32)\n        init_modules(self, init_type=\"trunc_normal\")\n\n    def load_model(self):\n        if self.cfg.pretrained_source == \"dc-ae\":\n            state_dict = torch.load(self.cfg.pretrained_path, map_location=\"cpu\", weights_only=True)[\"state_dict\"]\n            self.load_state_dict(state_dict)\n        else:\n            raise NotImplementedError\n\n    def get_last_layer(self):\n        return self.decoder.project_out.op_list[2].conv.weight\n\n    # @property\n    # def spatial_compression_ratio(self) -> int:\n    #     return 2 ** (self.decoder.num_stages - 1)\n\n    def encode_single(self, x: torch.Tensor, is_video_encoder: bool = False) -> torch.Tensor:\n        assert x.shape[0] == 1\n        is_video = x.dim() == 5\n        if is_video and not is_video_encoder:\n            b, c, f, h, w = x.shape\n            x = x.permute(0, 2, 1, 3, 4).reshape(-1, c, h, w)\n        z = self.encoder(x)\n\n        if is_video and not is_video_encoder:\n            z = z.unsqueeze(dim=0).permute(0, 2, 1, 3, 4)\n\n        if self.scaling_factor is not None:\n            z = z / self.scaling_factor\n\n        return z\n\n    def _encode(self, x: torch.Tensor) -> torch.Tensor:\n        if self.cfg.is_training:\n            return self.encoder(x)\n        is_video_encoder = self.encoder.cfg.is_video if self.encoder.cfg.is_video is not None else False\n        x_ret = []\n        for i in range(x.shape[0]):\n            x_ret.append(self.encode_single(x[i : i + 1], is_video_encoder))\n        return torch.cat(x_ret, dim=0)\n\n    def blend_v(self, a: torch.Tensor, b: torch.Tensor, blend_extent: int) -> torch.Tensor:\n        blend_extent = min(a.shape[-2], b.shape[-2], blend_extent)\n        for y in range(blend_extent):\n            b[:, :, :, y, :] = a[:, :, :, -blend_extent + y, :] * (1 - y / blend_extent) + b[:, :, :, y, :] * (\n                y / blend_extent\n            )\n        return b\n\n    def blend_h(self, a: torch.Tensor, b: torch.Tensor, blend_extent: int) -> torch.Tensor:\n        blend_extent = min(a.shape[-1], b.shape[-1], blend_extent)\n        for x in range(blend_extent):\n            b[:, :, :, :, x] = a[:, :, :, :, -blend_extent + x] * (1 - x / blend_extent) + b[:, :, :, :, x] * (\n                x / blend_extent\n            )\n        return b\n\n    def blend_t(self, a: torch.Tensor, b: torch.Tensor, blend_extent: int) -> torch.Tensor:\n        blend_extent = min(a.shape[-3], b.shape[-3], blend_extent)\n        for x in range(blend_extent):\n            b[:, :, x, :, :] = a[:, :, -blend_extent + x, :, :] * (1 - x / blend_extent) + b[:, :, x, :, :] * (\n                x / blend_extent\n            )\n        return b\n\n    def spatial_tiled_encode(self, x: torch.Tensor) -> torch.Tensor:\n        net_size = int(self.spatial_tile_size * (1 - self.tile_overlap_factor))\n        blend_extent = int(self.spatial_tile_latent_size * self.tile_overlap_factor)\n        row_limit = self.spatial_tile_latent_size - blend_extent\n\n        # Split video into tiles and encode them separately.\n        rows = []\n        for i in range(0, x.shape[-2], net_size):\n            row = []\n            for j in range(0, x.shape[-1], net_size):\n                tile = x[:, :, :, i : i + self.spatial_tile_size, j : j + self.spatial_tile_size]\n                tile = self._encode(tile)\n                row.append(tile)\n            rows.append(row)\n        result_rows = []\n        for i, row in enumerate(rows):\n            result_row = []\n            for j, tile in enumerate(row):\n                # blend the above tile and the left tile\n                # to the current tile and add the current tile to the result row\n                if i > 0:\n                    tile = self.blend_v(rows[i - 1][j], tile, blend_extent)\n                if j > 0:\n                    tile = self.blend_h(row[j - 1], tile, blend_extent)\n                result_row.append(tile[:, :, :, :row_limit, :row_limit])\n            result_rows.append(torch.cat(result_row, dim=-1))\n\n        return torch.cat(result_rows, dim=-2)\n\n    def temporal_tiled_encode(self, x: torch.Tensor) -> torch.Tensor:\n        overlap_size = int(self.temporal_tile_size * (1 - self.tile_overlap_factor))\n        blend_extent = int(self.temporal_tile_latent_size * self.tile_overlap_factor)\n        t_limit = self.temporal_tile_latent_size - blend_extent\n\n        # Split the video into tiles and encode them separately.\n        row = []\n        for i in range(0, x.shape[2], overlap_size):\n            tile = x[:, :, i : i + self.temporal_tile_size, :, :]\n            if self.use_spatial_tiling and (\n                tile.shape[-1] > self.spatial_tile_size or tile.shape[-2] > self.spatial_tile_size\n            ):\n                tile = self.spatial_tiled_encode(tile)\n            else:\n                tile = self._encode(tile)\n            row.append(tile)\n        result_row = []\n        for i, tile in enumerate(row):\n            if i > 0:\n                tile = self.blend_t(row[i - 1], tile, blend_extent)\n            result_row.append(tile[:, :, :t_limit, :, :])\n\n        return torch.cat(result_row, dim=2)\n\n    def encode(self, x: torch.Tensor) -> torch.Tensor:\n        if self.use_temporal_tiling and x.shape[2] > self.temporal_tile_size:\n            return self.temporal_tiled_encode(x)\n        elif self.use_spatial_tiling and (x.shape[-1] > self.spatial_tile_size or x.shape[-2] > self.spatial_tile_size):\n            return self.spatial_tiled_encode(x)\n        else:\n            return self._encode(x)\n\n    def spatial_tiled_decode(self, z: torch.FloatTensor) -> torch.Tensor:\n        net_size = int(self.spatial_tile_latent_size * (1 - self.tile_overlap_factor))\n        blend_extent = int(self.spatial_tile_size * self.tile_overlap_factor)\n        row_limit = self.spatial_tile_size - blend_extent\n\n        # Split z into overlapping tiles and decode them separately.\n        # The tiles have an overlap to avoid seams between tiles.\n        rows = []\n        for i in range(0, z.shape[-2], net_size):\n            row = []\n            for j in range(0, z.shape[-1], net_size):\n                tile = z[:, :, :, i : i + self.spatial_tile_latent_size, j : j + self.spatial_tile_latent_size]\n                decoded = self._decode(tile)\n                row.append(decoded)\n            rows.append(row)\n        result_rows = []\n        for i, row in enumerate(rows):\n            result_row = []\n            for j, tile in enumerate(row):\n                # blend the above tile and the left tile\n                # to the current tile and add the current tile to the result row\n                if i > 0:\n                    tile = self.blend_v(rows[i - 1][j], tile, blend_extent)\n                if j > 0:\n                    tile = self.blend_h(row[j - 1], tile, blend_extent)\n                result_row.append(tile[:, :, :, :row_limit, :row_limit])\n            result_rows.append(torch.cat(result_row, dim=-1))\n\n        return torch.cat(result_rows, dim=-2)\n\n    def temporal_tiled_decode(self, z: torch.Tensor) -> torch.Tensor:\n        overlap_size = int(self.temporal_tile_latent_size * (1 - self.tile_overlap_factor))\n        blend_extent = int(self.temporal_tile_size * self.tile_overlap_factor)\n        t_limit = self.temporal_tile_size - blend_extent\n\n        row = []\n        for i in range(0, z.shape[2], overlap_size):\n            tile = z[:, :, i : i + self.temporal_tile_latent_size, :, :]\n            if self.use_spatial_tiling and (\n                tile.shape[-1] > self.spatial_tile_latent_size or tile.shape[-2] > self.spatial_tile_latent_size\n            ):\n                decoded = self.spatial_tiled_decode(tile)\n            else:\n                decoded = self._decode(tile)\n            row.append(decoded)\n        result_row = []\n        for i, tile in enumerate(row):\n            if i > 0:\n                tile = self.blend_t(row[i - 1], tile, blend_extent)\n            result_row.append(tile[:, :, :t_limit, :, :])\n\n        return torch.cat(result_row, dim=2)\n\n    def decode_single(self, z: torch.Tensor, is_video_decoder: bool = False) -> torch.Tensor:\n        assert z.shape[0] == 1\n        is_video = z.dim() == 5\n        if is_video and not is_video_decoder:\n            b, c, f, h, w = z.shape\n            z = z.permute(0, 2, 1, 3, 4).reshape(-1, c, h, w)\n        if self.scaling_factor is not None:\n            z = z * self.scaling_factor\n\n        x = self.decoder(z)\n\n        if is_video and not is_video_decoder:\n            x = x.unsqueeze(dim=0).permute(0, 2, 1, 3, 4)\n        return x\n\n    def _decode(self, z: torch.Tensor) -> torch.Tensor:\n        if self.cfg.is_training:\n            return self.decoder(z)\n        is_video_decoder = self.decoder.cfg.is_video if self.decoder.cfg.is_video is not None else False\n        x_ret = []\n        for i in range(z.shape[0]):\n            x_ret.append(self.decode_single(z[i : i + 1], is_video_decoder))\n        return torch.cat(x_ret, dim=0)\n\n    def decode(self, z: torch.Tensor) -> torch.Tensor:\n        if self.use_temporal_tiling and z.shape[2] > self.temporal_tile_latent_size:\n            return self.temporal_tiled_decode(z)\n        elif self.use_spatial_tiling and (\n            z.shape[-1] > self.spatial_tile_latent_size or z.shape[-2] > self.spatial_tile_latent_size\n        ):\n            return self.spatial_tiled_decode(z)\n        else:\n            return self._decode(z)\n\n    def forward(self, x: torch.Tensor) -> tuple[Any, Tensor, dict[Any, Any]]:\n        x_type = x.dtype\n        is_image_model = self.cfg.__dict__.get(\"is_image_model\", False)\n        x = x.to(self.encoder.project_in.conv.weight.dtype)\n\n        if is_image_model:\n            b, c, _, h, w = x.shape\n            x = x.permute(0, 2, 1, 3, 4).reshape(-1, c, h, w)\n\n        z = self.encode(x)\n        dec = self.decode(z)\n\n        if is_image_model:\n            dec = dec.reshape(b, 1, c, h, w).permute(0, 2, 1, 3, 4)\n            z = z.unsqueeze(dim=0).permute(0, 2, 1, 3, 4)\n\n        dec = dec.to(x_type)\n        return dec, None, z\n\n    def get_latent_size(self, input_size: list[int]) -> list[int]:\n        latent_size = []\n        # T\n        latent_size.append((input_size[0] - 1) // self.time_compression_ratio + 1)\n        # H, w\n        for i in range(1, 3):\n            latent_size.append((input_size[i] - 1) // self.spatial_compression_ratio + 1)\n        return latent_size\n\n\ndef dc_ae_f32(name: str, pretrained_path: str) -> DCAEConfig:\n    if name in [\"dc-ae-f32t4c128\"]:\n        cfg_str = (\n            \"time_compression_ratio=4 \"\n            \"spatial_compression_ratio=32 \"\n            \"encoder.block_type=[ResBlock,ResBlock,ResBlock,EViTS5_GLU,EViTS5_GLU,EViTS5_GLU] \"\n            \"encoder.width_list=[128,256,512,512,1024,1024] encoder.depth_list=[2,2,2,3,3,3] \"\n            \"encoder.downsample_block_type=Conv \"\n            \"encoder.norm=rms3d \"\n            \"encoder.is_video=True \"\n            \"decoder.block_type=[ResBlock,ResBlock,ResBlock,EViTS5_GLU,EViTS5_GLU,EViTS5_GLU] \"\n            \"decoder.width_list=[128,256,512,512,1024,1024] decoder.depth_list=[3,3,3,3,3,3] \"\n            \"decoder.upsample_block_type=InterpolateConv \"\n            \"decoder.norm=rms3d decoder.act=silu decoder.out_norm=rms3d \"\n            \"decoder.is_video=True \"\n            \"encoder.temporal_downsample=[False,False,False,True,True,False] \"\n            \"decoder.temporal_upsample=[False,False,False,True,True,False] \"\n            \"latent_channels=128\"\n        )  # make sure there is no trailing blankspace in the last line\n    else:\n        raise NotImplementedError\n    cfg = OmegaConf.from_dotlist(cfg_str.split(\" \"))\n    cfg: DCAEConfig = OmegaConf.to_object(OmegaConf.merge(OmegaConf.structured(DCAEConfig), cfg))\n    cfg.pretrained_path = pretrained_path\n    return cfg\n\n"
  },
  {
    "path": "opensora/models/dc_ae/models/nn/__init__.py",
    "content": "from .act import *\nfrom .norm import *\nfrom .ops import *\n"
  },
  {
    "path": "opensora/models/dc_ae/models/nn/act.py",
    "content": "# Copyright 2024 MIT Han Lab\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# SPDX-License-Identifier: Apache-2.0\n\nfrom functools import partial\nfrom typing import Optional\n\nimport torch.nn as nn\n\nfrom ..nn.vo_ops import build_kwargs_from_config\n\n\n__all__ = [\"build_act\"]\n\n\n# register activation function here\nREGISTERED_ACT_DICT: dict[str, type] = {\n    \"relu\": nn.ReLU,\n    \"relu6\": nn.ReLU6,\n    \"hswish\": nn.Hardswish,\n    \"silu\": nn.SiLU,\n    \"gelu\": partial(nn.GELU, approximate=\"tanh\"),\n}\n\n\ndef build_act(name: str, **kwargs) -> Optional[nn.Module]:\n    if name in REGISTERED_ACT_DICT:\n        act_cls = REGISTERED_ACT_DICT[name]\n        args = build_kwargs_from_config(kwargs, act_cls)\n        return act_cls(**args)\n    else:\n        return None\n"
  },
  {
    "path": "opensora/models/dc_ae/models/nn/norm.py",
    "content": "# Copyright 2024 MIT Han Lab\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# SPDX-License-Identifier: Apache-2.0\n\nfrom typing import Optional\n\nimport torch\nimport torch.nn as nn\nfrom torch.nn.modules.batchnorm import _BatchNorm\n\nfrom ..nn.vo_ops import build_kwargs_from_config\n\n__all__ = [\"LayerNorm2d\", \"build_norm\", \"set_norm_eps\"]\n\n\nclass LayerNorm2d(nn.LayerNorm):\n    def forward(self, x: torch.Tensor) -> torch.Tensor:\n        out = x - torch.mean(x, dim=1, keepdim=True)\n        out = out / torch.sqrt(torch.square(out).mean(dim=1, keepdim=True) + self.eps)\n        if self.elementwise_affine:\n            out = out * self.weight.view(1, -1, 1, 1) + self.bias.view(1, -1, 1, 1)\n        return out\n\n\n\nclass RMSNorm2d(nn.Module):\n    def __init__(\n        self, num_features: int, eps: float = 1e-5, elementwise_affine: bool = True, bias: bool = True\n    ) -> None:\n        super().__init__()\n        self.num_features = num_features\n        self.eps = eps\n        self.elementwise_affine = elementwise_affine\n        if self.elementwise_affine:\n            self.weight = torch.nn.parameter.Parameter(torch.empty(self.num_features))\n            if bias:\n                self.bias = torch.nn.parameter.Parameter(torch.empty(self.num_features))\n            else:\n                self.register_parameter(\"bias\", None)\n        else:\n            self.register_parameter(\"weight\", None)\n            self.register_parameter(\"bias\", None)\n\n    def forward(self, x: torch.Tensor) -> torch.Tensor:\n        x = (x / torch.sqrt(torch.square(x.float()).mean(dim=1, keepdim=True) + self.eps)).to(x.dtype)\n        if self.elementwise_affine:\n            x = x * self.weight.view(1, -1, 1, 1) + self.bias.view(1, -1, 1, 1)\n        return x\n\n\nclass RMSNorm3d(RMSNorm2d):\n    def forward(self, x: torch.Tensor) -> torch.Tensor:\n        x = (x / torch.sqrt(torch.square(x.float()).mean(dim=1, keepdim=True) + self.eps)).to(x.dtype)\n        if self.elementwise_affine:\n            x = x * self.weight.view(1, -1, 1, 1, 1) + self.bias.view(1, -1, 1, 1, 1)\n        return x\n\n\n# register normalization function here\nREGISTERED_NORM_DICT: dict[str, type] = {\n    \"bn2d\": nn.BatchNorm2d,\n    \"ln\": nn.LayerNorm,\n    \"ln2d\": LayerNorm2d,\n    \"rms2d\": RMSNorm2d,\n    \"rms3d\": RMSNorm3d,\n}\n\n\ndef build_norm(name=\"bn2d\", num_features=None, **kwargs) -> Optional[nn.Module]:\n    if name in [\"ln\", \"ln2d\"]:\n        kwargs[\"normalized_shape\"] = num_features\n    else:\n        kwargs[\"num_features\"] = num_features\n    if name in REGISTERED_NORM_DICT:\n        norm_cls = REGISTERED_NORM_DICT[name]\n        args = build_kwargs_from_config(kwargs, norm_cls)\n        return norm_cls(**args)\n    else:\n        return None\n\n\ndef set_norm_eps(model: nn.Module, eps: Optional[float] = None) -> None:\n    for m in model.modules():\n        if isinstance(m, (nn.GroupNorm, nn.LayerNorm, _BatchNorm)):\n            if eps is not None:\n                m.eps = eps\n"
  },
  {
    "path": "opensora/models/dc_ae/models/nn/ops.py",
    "content": "# Copyright 2024 MIT Han Lab\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# SPDX-License-Identifier: Apache-2.0 # upsample on the temporal dimension as well\n\nfrom typing import Optional\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom opensora.models.vae.utils import ChannelChunkConv3d\n\nfrom ...models.nn.act import build_act\nfrom ...models.nn.norm import build_norm\nfrom ...models.nn.vo_ops import chunked_interpolate, get_same_padding, pixel_shuffle_3d, pixel_unshuffle_3d, resize\nfrom ...utils import list_sum, val2list, val2tuple\n\n__all__ = [\n    \"ConvLayer\",\n    \"UpSampleLayer\",\n    \"ConvPixelUnshuffleDownSampleLayer\",\n    \"PixelUnshuffleChannelAveragingDownSampleLayer\",\n    \"ConvPixelShuffleUpSampleLayer\",\n    \"ChannelDuplicatingPixelShuffleUpSampleLayer\",\n    \"LinearLayer\",\n    \"IdentityLayer\",\n    \"DSConv\",\n    \"MBConv\",\n    \"FusedMBConv\",\n    \"ResBlock\",\n    \"LiteMLA\",\n    \"EfficientViTBlock\",\n    \"ResidualBlock\",\n    \"DAGBlock\",\n    \"OpSequential\",\n]\n\n\n#################################################################################\n#                             Basic Layers                                      #\n#################################################################################\n\n\nclass ConvLayer(nn.Module):\n    def __init__(\n        self,\n        in_channels: int,\n        out_channels: int,\n        kernel_size=3,\n        stride=1,\n        dilation=1,\n        groups=1,\n        use_bias=False,\n        dropout=0,\n        norm=\"bn2d\",\n        act_func=\"relu\",\n        is_video=False,\n        pad_mode_3d=\"constant\",\n    ):\n        super().__init__()\n        self.is_video = is_video\n\n        if self.is_video:\n            assert dilation == 1, \"only support dilation=1 for 3d conv\"\n            assert kernel_size % 2 == 1, \"only support odd kernel size for 3d conv\"\n            self.pad_mode_3d = pad_mode_3d  # 3d padding follows CausalConv3d by Hunyuan\n            # padding = (\n            #     kernel_size // 2,\n            #     kernel_size // 2,\n            #     kernel_size // 2,\n            #     kernel_size // 2,\n            #     kernel_size - 1,\n            #     0,\n            # )  # W, H, T\n            # non-causal padding\n            padding = (\n                kernel_size // 2,\n                kernel_size // 2,\n                kernel_size // 2,\n                kernel_size // 2,\n                kernel_size // 2,\n                kernel_size // 2,\n            )\n            self.padding = padding\n            self.dropout = nn.Dropout3d(dropout, inplace=False) if dropout > 0 else None\n            assert isinstance(stride, (int, tuple)), \"stride must be an integer or 3-tuple for 3d conv\"\n            self.conv = ChannelChunkConv3d(  # padding is handled by F.pad() in forward()\n                in_channels,\n                out_channels,\n                kernel_size=(kernel_size, kernel_size, kernel_size),\n                stride=(stride, stride, stride) if isinstance(stride, int) else stride,\n                groups=groups,\n                bias=use_bias,\n            )\n        else:\n            padding = get_same_padding(kernel_size)\n            padding *= dilation\n            self.dropout = nn.Dropout2d(dropout, inplace=False) if dropout > 0 else None\n            self.conv = nn.Conv2d(\n                in_channels,\n                out_channels,\n                kernel_size=(kernel_size, kernel_size),\n                stride=(stride, stride),\n                padding=padding,\n                dilation=(dilation, dilation),\n                groups=groups,\n                bias=use_bias,\n            )\n\n        self.norm = build_norm(norm, num_features=out_channels)\n        self.act = build_act(act_func)\n        self.pad = F.pad\n\n    def forward(self, x: torch.Tensor) -> torch.Tensor:\n        if self.dropout is not None:\n            x = self.dropout(x)\n        if self.is_video:  # custom padding for 3d conv\n            x = self.pad(x, self.padding, mode=self.pad_mode_3d)  # \"constant\" padding defaults to 0\n        x = self.conv(x)\n        if self.norm:\n            x = self.norm(x)\n        if self.act:\n            x = self.act(x)\n        return x\n\n\nclass UpSampleLayer(nn.Module):\n    def __init__(\n        self,\n        mode=\"bicubic\",\n        size: Optional[int | tuple[int, int] | list[int]] = None,\n        factor=2,\n        align_corners=False,\n    ):\n        super().__init__()\n        self.mode = mode\n        self.size = val2list(size, 2) if size is not None else None\n        self.factor = None if self.size is not None else factor\n        self.align_corners = align_corners\n\n    @torch.autocast(device_type=\"cuda\", enabled=False)\n    def forward(self, x: torch.Tensor) -> torch.Tensor:\n        if (self.size is not None and tuple(x.shape[-2:]) == self.size) or self.factor == 1:\n            return x\n        if x.dtype in [torch.float16, torch.bfloat16]:\n            x = x.float()\n        return resize(x, self.size, self.factor, self.mode, self.align_corners)\n\n\nclass ConvPixelUnshuffleDownSampleLayer(nn.Module):\n    def __init__(\n        self,\n        in_channels: int,\n        out_channels: int,\n        kernel_size: int,\n        factor: int,\n    ):\n        super().__init__()\n        self.factor = factor\n        out_ratio = factor**2\n        assert out_channels % out_ratio == 0\n        self.conv = ConvLayer(\n            in_channels=in_channels,\n            out_channels=out_channels // out_ratio,\n            kernel_size=kernel_size,\n            use_bias=True,\n            norm=None,\n            act_func=None,\n        )\n\n    def forward(self, x: torch.Tensor) -> torch.Tensor:\n        x = self.conv(x)\n        x = F.pixel_unshuffle(x, self.factor)\n        return x\n\n\nclass PixelUnshuffleChannelAveragingDownSampleLayer(nn.Module):\n    def __init__(\n        self,\n        in_channels: int,\n        out_channels: int,\n        factor: int,\n        temporal_downsample: bool = False,  # temporal downsample for 5d input tensor\n    ):\n        super().__init__()\n        self.in_channels = in_channels\n        self.out_channels = out_channels\n        self.factor = factor\n        self.temporal_downsample = temporal_downsample\n\n    def forward(self, x: torch.Tensor) -> torch.Tensor:\n        if x.dim() == 4:\n            assert self.in_channels * self.factor**2 % self.out_channels == 0\n            group_size = self.in_channels * self.factor**2 // self.out_channels\n            x = F.pixel_unshuffle(x, self.factor)\n            B, C, H, W = x.shape\n            x = x.view(B, self.out_channels, group_size, H, W)\n            x = x.mean(dim=2)\n        elif x.dim() == 5:  # [B, C, T, H, W]\n            _, _, T, _, _ = x.shape\n            if self.temporal_downsample and T != 1:  # 3d pixel unshuffle\n                x = pixel_unshuffle_3d(x, self.factor)\n                assert self.in_channels * self.factor**3 % self.out_channels == 0\n                group_size = self.in_channels * self.factor**3 // self.out_channels\n            else:  # 2d pixel unshuffle\n                x = x.permute(0, 2, 1, 3, 4)  # [B, T, C, H, W]\n                x = F.pixel_unshuffle(x, self.factor)\n                x = x.permute(0, 2, 1, 3, 4)  # [B, C, T, H, W]\n                assert self.in_channels * self.factor**2 % self.out_channels == 0\n                group_size = self.in_channels * self.factor**2 // self.out_channels\n            B, C, T, H, W = x.shape\n            x = x.view(B, self.out_channels, group_size, T, H, W)\n            x = x.mean(dim=2)\n        else:\n            raise ValueError(f\"Unsupported input dimension: {x.dim()}\")\n        return x\n\n    def __repr__(self):\n        return f\"PixelUnshuffleChannelAveragingDownSampleLayer(in_channels={self.in_channels}, out_channels={self.out_channels}, factor={self.factor}), temporal_downsample={self.temporal_downsample}\"\n\n\nclass ConvPixelShuffleUpSampleLayer(nn.Module):\n    def __init__(\n        self,\n        in_channels: int,\n        out_channels: int,\n        kernel_size: int,\n        factor: int,\n    ):\n        super().__init__()\n        self.factor = factor\n        out_ratio = factor**2\n        self.conv = ConvLayer(\n            in_channels=in_channels,\n            out_channels=out_channels * out_ratio,\n            kernel_size=kernel_size,\n            use_bias=True,\n            norm=None,\n            act_func=None,\n        )\n\n    def forward(self, x: torch.Tensor) -> torch.Tensor:\n        x = self.conv(x)\n        x = F.pixel_shuffle(x, self.factor)\n        return x\n\n\nclass InterpolateConvUpSampleLayer(nn.Module):\n    def __init__(\n        self,\n        in_channels: int,\n        out_channels: int,\n        kernel_size: int,\n        factor: int,\n        mode: str = \"nearest\",\n        is_video: bool = False,\n        temporal_upsample: bool = False,\n    ) -> None:\n        super().__init__()\n        self.factor = factor\n        self.mode = mode\n        self.temporal_upsample = temporal_upsample\n        self.conv = ConvLayer(\n            in_channels=in_channels,\n            out_channels=out_channels,\n            kernel_size=kernel_size,\n            use_bias=True,\n            norm=None,\n            act_func=None,\n            is_video=is_video,\n        )\n\n    def forward(self, x: torch.Tensor) -> torch.Tensor:\n        if x.dim() == 4:\n            x = F.interpolate(x, scale_factor=self.factor, mode=self.mode)\n        elif x.dim() == 5:\n            # [B, C, T, H, W] -> [B, C, T*factor, H*factor, W*factor]\n            if self.temporal_upsample and x.size(2) != 1:  # temporal upsample for video input\n                x = chunked_interpolate(x, scale_factor=[self.factor, self.factor, self.factor], mode=self.mode)\n            else:\n                x = chunked_interpolate(x, scale_factor=[1, self.factor, self.factor], mode=self.mode)\n        x = self.conv(x)\n        return x\n\n    def __repr__(self):\n        return f\"InterpolateConvUpSampleLayer(factor={self.factor}, mode={self.mode}, temporal_upsample={self.temporal_upsample})\"\n\n\nclass ChannelDuplicatingPixelShuffleUpSampleLayer(nn.Module):\n    def __init__(\n        self,\n        in_channels: int,\n        out_channels: int,\n        factor: int,\n        temporal_upsample: bool = False,  # upsample on the temporal dimension as well\n    ):\n        super().__init__()\n        self.in_channels = in_channels\n        self.out_channels = out_channels\n        self.factor = factor\n        assert out_channels * factor**2 % in_channels == 0\n        self.temporal_upsample = temporal_upsample\n\n    def forward(self, x: torch.Tensor) -> torch.Tensor:\n        if x.dim() == 5:\n            B, C, T, H, W = x.shape\n            assert C == self.in_channels\n\n        if self.temporal_upsample and T != 1:  # video input\n            repeats = self.out_channels * self.factor**3 // self.in_channels\n        else:\n            repeats = self.out_channels * self.factor**2 // self.in_channels\n\n        x = x.repeat_interleave(repeats, dim=1)\n\n        if x.dim() == 4:  # original image-only training\n            x = F.pixel_shuffle(x, self.factor)\n        elif x.dim() == 5:  # [B, C, T, H, W]\n            if self.temporal_upsample and T != 1:  # video input\n                x = pixel_shuffle_3d(x, self.factor)\n            else:\n                x = x.permute(0, 2, 1, 3, 4)  # [B, T, C, H, W]\n                x = F.pixel_shuffle(x, self.factor)  # on H and W only\n                x = x.permute(0, 2, 1, 3, 4)  # [B, C, T, H, W]\n        return x\n\n    def __repr__(self):\n        return f\"ChannelDuplicatingPixelShuffleUpSampleLayer(in_channels={self.in_channels}, out_channels={self.out_channels}, factor={self.factor}, temporal_upsample={self.temporal_upsample})\"\n\n\nclass LinearLayer(nn.Module):\n    def __init__(\n        self,\n        in_features: int,\n        out_features: int,\n        use_bias=True,\n        dropout=0,\n        norm=None,\n        act_func=None,\n    ):\n        super().__init__()\n\n        self.dropout = nn.Dropout(dropout, inplace=False) if dropout > 0 else None\n        self.linear = nn.Linear(in_features, out_features, use_bias)\n        self.norm = build_norm(norm, num_features=out_features)\n        self.act = build_act(act_func)\n\n    def _try_squeeze(self, x: torch.Tensor) -> torch.Tensor:\n        if x.dim() > 2:\n            x = torch.flatten(x, start_dim=1)\n        return x\n\n    def forward(self, x: torch.Tensor) -> torch.Tensor:\n        x = self._try_squeeze(x)\n        if self.dropout:\n            x = self.dropout(x)\n        x = self.linear(x)\n        if self.norm:\n            x = self.norm(x)\n        if self.act:\n            x = self.act(x)\n        return x\n\n\nclass IdentityLayer(nn.Module):\n    def forward(self, x: torch.Tensor) -> torch.Tensor:\n        return x\n\n\n#################################################################################\n#                             Basic Blocks                                      #\n#################################################################################\n\n\nclass DSConv(nn.Module):\n    def __init__(\n        self,\n        in_channels: int,\n        out_channels: int,\n        kernel_size=3,\n        stride=1,\n        use_bias=False,\n        norm=(\"bn2d\", \"bn2d\"),\n        act_func=(\"relu6\", None),\n    ):\n        super().__init__()\n\n        use_bias = val2tuple(use_bias, 2)\n        norm = val2tuple(norm, 2)\n        act_func = val2tuple(act_func, 2)\n\n        self.depth_conv = ConvLayer(\n            in_channels,\n            in_channels,\n            kernel_size,\n            stride,\n            groups=in_channels,\n            norm=norm[0],\n            act_func=act_func[0],\n            use_bias=use_bias[0],\n        )\n        self.point_conv = ConvLayer(\n            in_channels,\n            out_channels,\n            1,\n            norm=norm[1],\n            act_func=act_func[1],\n            use_bias=use_bias[1],\n        )\n\n    def forward(self, x: torch.Tensor) -> torch.Tensor:\n        x = self.depth_conv(x)\n        x = self.point_conv(x)\n        return x\n\n\nclass MBConv(nn.Module):\n    def __init__(\n        self,\n        in_channels: int,\n        out_channels: int,\n        kernel_size=3,\n        stride=1,\n        mid_channels=None,\n        expand_ratio=6,\n        use_bias=False,\n        norm=(\"bn2d\", \"bn2d\", \"bn2d\"),\n        act_func=(\"relu6\", \"relu6\", None),\n    ):\n        super().__init__()\n\n        use_bias = val2tuple(use_bias, 3)\n        norm = val2tuple(norm, 3)\n        act_func = val2tuple(act_func, 3)\n        mid_channels = round(in_channels * expand_ratio) if mid_channels is None else mid_channels\n\n        self.inverted_conv = ConvLayer(\n            in_channels,\n            mid_channels,\n            1,\n            stride=1,\n            norm=norm[0],\n            act_func=act_func[0],\n            use_bias=use_bias[0],\n        )\n        self.depth_conv = ConvLayer(\n            mid_channels,\n            mid_channels,\n            kernel_size,\n            stride=stride,\n            groups=mid_channels,\n            norm=norm[1],\n            act_func=act_func[1],\n            use_bias=use_bias[1],\n        )\n        self.point_conv = ConvLayer(\n            mid_channels,\n            out_channels,\n            1,\n            norm=norm[2],\n            act_func=act_func[2],\n            use_bias=use_bias[2],\n        )\n\n    def forward(self, x: torch.Tensor) -> torch.Tensor:\n        x = self.inverted_conv(x)\n        x = self.depth_conv(x)\n        x = self.point_conv(x)\n        return x\n\n\nclass FusedMBConv(nn.Module):\n    def __init__(\n        self,\n        in_channels: int,\n        out_channels: int,\n        kernel_size=3,\n        stride=1,\n        mid_channels=None,\n        expand_ratio=6,\n        groups=1,\n        use_bias=False,\n        norm=(\"bn2d\", \"bn2d\"),\n        act_func=(\"relu6\", None),\n    ):\n        super().__init__()\n        use_bias = val2tuple(use_bias, 2)\n        norm = val2tuple(norm, 2)\n        act_func = val2tuple(act_func, 2)\n\n        mid_channels = round(in_channels * expand_ratio) if mid_channels is None else mid_channels\n\n        self.spatial_conv = ConvLayer(\n            in_channels,\n            mid_channels,\n            kernel_size,\n            stride,\n            groups=groups,\n            use_bias=use_bias[0],\n            norm=norm[0],\n            act_func=act_func[0],\n        )\n        self.point_conv = ConvLayer(\n            mid_channels,\n            out_channels,\n            1,\n            use_bias=use_bias[1],\n            norm=norm[1],\n            act_func=act_func[1],\n        )\n\n    def forward(self, x: torch.Tensor) -> torch.Tensor:\n        x = self.spatial_conv(x)\n        x = self.point_conv(x)\n        return x\n\n\nclass GLUMBConv(nn.Module):\n    def __init__(\n        self,\n        in_channels: int,\n        out_channels: int,\n        kernel_size=3,\n        stride=1,\n        mid_channels=None,\n        expand_ratio=6,\n        use_bias=False,\n        norm=(None, None, \"ln2d\"),\n        act_func=(\"silu\", \"silu\", None),\n        is_video=False,\n    ):\n        super().__init__()\n        use_bias = val2tuple(use_bias, 3)\n        norm = val2tuple(norm, 3)\n        act_func = val2tuple(act_func, 3)\n\n        mid_channels = round(in_channels * expand_ratio) if mid_channels is None else mid_channels\n\n        self.glu_act = build_act(act_func[1], inplace=False)\n        self.inverted_conv = ConvLayer(\n            in_channels,\n            mid_channels * 2,\n            1,\n            use_bias=use_bias[0],\n            norm=norm[0],\n            act_func=act_func[0],\n            is_video=is_video,\n        )\n        self.depth_conv = ConvLayer(\n            mid_channels * 2,\n            mid_channels * 2,\n            kernel_size,\n            stride=stride,\n            groups=mid_channels * 2,\n            use_bias=use_bias[1],\n            norm=norm[1],\n            act_func=None,\n            is_video=is_video,\n        )\n        self.point_conv = ConvLayer(\n            mid_channels,\n            out_channels,\n            1,\n            use_bias=use_bias[2],\n            norm=norm[2],\n            act_func=act_func[2],\n            is_video=is_video,\n        )\n\n    def forward(self, x: torch.Tensor) -> torch.Tensor:\n        x = self.inverted_conv(x)\n        x = self.depth_conv(x)\n\n        x, gate = torch.chunk(x, 2, dim=1)\n        gate = self.glu_act(gate)\n        x = x * gate\n\n        x = self.point_conv(x)\n        return x\n\n\nclass ResBlock(nn.Module):\n    def __init__(\n        self,\n        in_channels: int,\n        out_channels: int,\n        kernel_size=3,\n        stride=1,\n        mid_channels=None,\n        expand_ratio=1,\n        use_bias=False,\n        norm=(\"bn2d\", \"bn2d\"),\n        act_func=(\"relu6\", None),\n        is_video=False,\n    ):\n        super().__init__()\n        use_bias = val2tuple(use_bias, 2)\n        norm = val2tuple(norm, 2)\n        act_func = val2tuple(act_func, 2)\n\n        mid_channels = round(in_channels * expand_ratio) if mid_channels is None else mid_channels\n\n        self.conv1 = ConvLayer(\n            in_channels,\n            mid_channels,\n            kernel_size,\n            stride,\n            use_bias=use_bias[0],\n            norm=norm[0],\n            act_func=act_func[0],\n            is_video=is_video,\n        )\n        self.conv2 = ConvLayer(\n            mid_channels,\n            out_channels,\n            kernel_size,\n            1,\n            use_bias=use_bias[1],\n            norm=norm[1],\n            act_func=act_func[1],\n            is_video=is_video,\n        )\n\n    def forward(self, x: torch.Tensor) -> torch.Tensor:\n        x = self.conv1(x)\n        x = self.conv2(x)\n        return x\n\n\nclass LiteMLA(nn.Module):\n    r\"\"\"Lightweight multi-scale linear attention\"\"\"\n\n    def __init__(\n        self,\n        in_channels: int,\n        out_channels: int,\n        heads: Optional[int] = None,\n        heads_ratio: float = 1.0,\n        dim=8,\n        use_bias=False,\n        norm=(None, \"bn2d\"),\n        act_func=(None, None),\n        kernel_func=\"relu\",\n        scales: tuple[int, ...] = (5,),\n        eps=1.0e-15,\n        is_video=False,\n    ):\n        super().__init__()\n        self.eps = eps\n        heads = int(in_channels // dim * heads_ratio) if heads is None else heads\n\n        total_dim = heads * dim\n\n        use_bias = val2tuple(use_bias, 2)\n        norm = val2tuple(norm, 2)\n        act_func = val2tuple(act_func, 2)\n\n        self.dim = dim\n        self.qkv = ConvLayer(\n            in_channels,\n            3 * total_dim,\n            1,\n            use_bias=use_bias[0],\n            norm=norm[0],\n            act_func=act_func[0],\n            is_video=is_video,\n        )\n        conv_class = nn.Conv2d if not is_video else ChannelChunkConv3d\n        self.aggreg = nn.ModuleList(\n            [\n                nn.Sequential(\n                    conv_class(\n                        3 * total_dim,\n                        3 * total_dim,\n                        scale,\n                        padding=get_same_padding(scale),\n                        groups=3 * total_dim,\n                        bias=use_bias[0],\n                    ),\n                    conv_class(3 * total_dim, 3 * total_dim, 1, groups=3 * heads, bias=use_bias[0]),\n                )\n                for scale in scales\n            ]\n        )\n        self.kernel_func = build_act(kernel_func, inplace=False)\n\n        self.proj = ConvLayer(\n            total_dim * (1 + len(scales)),\n            out_channels,\n            1,\n            use_bias=use_bias[1],\n            norm=norm[1],\n            act_func=act_func[1],\n            is_video=is_video,\n        )\n\n    @torch.autocast(device_type=\"cuda\", enabled=False)\n    def relu_linear_att(self, qkv: torch.Tensor) -> torch.Tensor:\n        if qkv.ndim == 5:\n            B, _, T, H, W = list(qkv.size())\n            is_video = True\n        else:\n            B, _, H, W = list(qkv.size())\n            is_video = False\n\n        if qkv.dtype == torch.float16:\n            qkv = qkv.float()\n\n        if qkv.ndim == 4:\n            qkv = torch.reshape(\n                qkv,\n                (\n                    B,\n                    -1,\n                    3 * self.dim,\n                    H * W,\n                ),\n            )\n        elif qkv.ndim == 5:\n            qkv = torch.reshape(\n                qkv,\n                (\n                    B,\n                    -1,\n                    3 * self.dim,\n                    H * W * T,\n                ),\n            )\n        q, k, v = (\n            qkv[:, :, 0 : self.dim],\n            qkv[:, :, self.dim : 2 * self.dim],\n            qkv[:, :, 2 * self.dim :],\n        )\n\n        # lightweight linear attention\n        q = self.kernel_func(q)\n        k = self.kernel_func(k)\n\n        # linear matmul\n        trans_k = k.transpose(-1, -2)\n\n        v = F.pad(v, (0, 0, 0, 1), mode=\"constant\", value=1)\n        vk = torch.matmul(v, trans_k)\n        out = torch.matmul(vk, q)\n        if out.dtype == torch.bfloat16:\n            out = out.float()\n        out = out[:, :, :-1] / (out[:, :, -1:] + self.eps)\n\n        if not is_video:\n            out = torch.reshape(out, (B, -1, H, W))\n        else:\n            out = torch.reshape(out, (B, -1, T, H, W))\n        return out\n\n    @torch.autocast(device_type=\"cuda\", enabled=False)\n    def relu_quadratic_att(self, qkv: torch.Tensor) -> torch.Tensor:\n        B, _, H, W = list(qkv.size())\n\n        qkv = torch.reshape(\n            qkv,\n            (\n                B,\n                -1,\n                3 * self.dim,\n                H * W,\n            ),\n        )\n        q, k, v = (\n            qkv[:, :, 0 : self.dim],\n            qkv[:, :, self.dim : 2 * self.dim],\n            qkv[:, :, 2 * self.dim :],\n        )\n\n        q = self.kernel_func(q)\n        k = self.kernel_func(k)\n\n        att_map = torch.matmul(k.transpose(-1, -2), q)  # b h n n\n        original_dtype = att_map.dtype\n        if original_dtype in [torch.float16, torch.bfloat16]:\n            att_map = att_map.float()\n        att_map = att_map / (torch.sum(att_map, dim=2, keepdim=True) + self.eps)  # b h n n\n        att_map = att_map.to(original_dtype)\n        out = torch.matmul(v, att_map)  # b h d n\n\n        out = torch.reshape(out, (B, -1, H, W))\n        return out\n\n    def forward(self, x: torch.Tensor) -> torch.Tensor:\n        # generate multi-scale q, k, v\n        qkv = self.qkv(x)\n        multi_scale_qkv = [qkv]\n        for op in self.aggreg:\n            multi_scale_qkv.append(op(qkv))\n        qkv = torch.cat(multi_scale_qkv, dim=1)\n\n        if qkv.ndim == 4:\n            H, W = list(qkv.size())[-2:]\n            # num_tokens = H * W\n        elif qkv.ndim == 5:\n            _, _, T, H, W = list(qkv.size())\n            # num_tokens = H * W * T\n\n        # if num_tokens > self.dim:\n        out = self.relu_linear_att(qkv).to(qkv.dtype)\n        # else:\n        #     if self.is_video:\n        #         raise NotImplementedError(\"Video is not supported for quadratic attention\")\n        #     out = self.relu_quadratic_att(qkv)\n        out = self.proj(out)\n\n        return out\n\n\nclass EfficientViTBlock(nn.Module):\n    def __init__(\n        self,\n        in_channels: int,\n        heads_ratio: float = 1.0,\n        dim=32,\n        expand_ratio: float = 4,\n        scales: tuple[int, ...] = (5,),\n        norm: str = \"bn2d\",\n        act_func: str = \"hswish\",\n        context_module: str = \"LiteMLA\",\n        local_module: str = \"MBConv\",\n        is_video: bool = False,\n    ):\n        super().__init__()\n        if context_module == \"LiteMLA\":\n            self.context_module = ResidualBlock(\n                LiteMLA(\n                    in_channels=in_channels,\n                    out_channels=in_channels,\n                    heads_ratio=heads_ratio,\n                    dim=dim,\n                    norm=(None, norm),\n                    scales=scales,\n                    is_video=is_video,\n                ),\n                IdentityLayer(),\n            )\n        else:\n            raise ValueError(f\"context_module {context_module} is not supported\")\n        if local_module == \"MBConv\":\n            self.local_module = ResidualBlock(\n                MBConv(\n                    in_channels=in_channels,\n                    out_channels=in_channels,\n                    expand_ratio=expand_ratio,\n                    use_bias=(True, True, False),\n                    norm=(None, None, norm),\n                    act_func=(act_func, act_func, None),\n                    is_video=is_video,\n                ),\n                IdentityLayer(),\n            )\n        elif local_module == \"GLUMBConv\":\n            self.local_module = ResidualBlock(\n                GLUMBConv(\n                    in_channels=in_channels,\n                    out_channels=in_channels,\n                    expand_ratio=expand_ratio,\n                    use_bias=(True, True, False),\n                    norm=(None, None, norm),\n                    act_func=(act_func, act_func, None),\n                    is_video=is_video,\n                ),\n                IdentityLayer(),\n            )\n        else:\n            raise NotImplementedError(f\"local_module {local_module} is not supported\")\n\n    def forward(self, x: torch.Tensor) -> torch.Tensor:\n        x = self.context_module(x)\n        x = self.local_module(x)\n        return x\n\n\n#################################################################################\n#                             Functional Blocks                                 #\n#################################################################################\n\n\nclass ResidualBlock(nn.Module):\n    def __init__(\n        self,\n        main: Optional[nn.Module],\n        shortcut: Optional[nn.Module],\n        post_act=None,\n        pre_norm: Optional[nn.Module] = None,\n    ):\n        super().__init__()\n\n        self.pre_norm = pre_norm\n        self.main = main\n        self.shortcut = shortcut\n        self.post_act = build_act(post_act)\n\n    def forward_main(self, x: torch.Tensor) -> torch.Tensor:\n        if self.pre_norm is None:\n            return self.main(x)\n        else:\n            return self.main(self.pre_norm(x))\n\n    def forward(self, x: torch.Tensor) -> torch.Tensor:\n        if self.main is None:\n            res = x\n        elif self.shortcut is None:\n            res = self.forward_main(x)\n        else:\n            res = self.forward_main(x) + self.shortcut(x)\n            if self.post_act:\n                res = self.post_act(res)\n        return res\n\n\nclass DAGBlock(nn.Module):\n    def __init__(\n        self,\n        inputs: dict[str, nn.Module],\n        merge: str,\n        post_input: Optional[nn.Module],\n        middle: nn.Module,\n        outputs: dict[str, nn.Module],\n    ):\n        super().__init__()\n\n        self.input_keys = list(inputs.keys())\n        self.input_ops = nn.ModuleList(list(inputs.values()))\n        self.merge = merge\n        self.post_input = post_input\n\n        self.middle = middle\n\n        self.output_keys = list(outputs.keys())\n        self.output_ops = nn.ModuleList(list(outputs.values()))\n\n    def forward(self, feature_dict: dict[str, torch.Tensor]) -> dict[str, torch.Tensor]:\n        feat = [op(feature_dict[key]) for key, op in zip(self.input_keys, self.input_ops)]\n        if self.merge == \"add\":\n            feat = list_sum(feat)\n        elif self.merge == \"cat\":\n            feat = torch.concat(feat, dim=1)\n        else:\n            raise NotImplementedError\n        if self.post_input is not None:\n            feat = self.post_input(feat)\n        feat = self.middle(feat)\n        for key, op in zip(self.output_keys, self.output_ops):\n            feature_dict[key] = op(feat)\n        return feature_dict\n\n\nclass OpSequential(nn.Module):\n    def __init__(self, op_list: list[Optional[nn.Module]]):\n        super().__init__()\n        valid_op_list = []\n        for op in op_list:\n            if op is not None:\n                valid_op_list.append(op)\n        self.op_list = nn.ModuleList(valid_op_list)\n\n    def forward(self, x: torch.Tensor) -> torch.Tensor:\n        for op in self.op_list:\n            x = op(x)\n        return x\n"
  },
  {
    "path": "opensora/models/dc_ae/models/nn/vo_ops.py",
    "content": "import math\nfrom inspect import signature\nfrom typing import Any, Callable, Optional, Union\n\nimport torch\nimport torch.nn.functional as F\n\nVERBOSE = False\n\n\ndef pixel_shuffle_3d(x, upscale_factor):\n    \"\"\"\n    3D pixelshuffle 操作。\n    \"\"\"\n    B, C, T, H, W = x.shape\n    r = upscale_factor\n    assert C % (r * r * r) == 0, \"通道数必须是上采样因子的立方倍数\"\n\n    C_new = C // (r * r * r)\n    x = x.view(B, C_new, r, r, r, T, H, W)\n    if VERBOSE:\n        print(\"x.view:\")\n        print(x)\n        print(\"x.view.shape:\")\n        print(x.shape)\n\n    x = x.permute(0, 1, 5, 2, 6, 3, 7, 4)\n    if VERBOSE:\n        print(\"x.permute:\")\n        print(x)\n        print(\"x.permute.shape:\")\n        print(x.shape)\n\n    y = x.reshape(B, C_new, T * r, H * r, W * r)\n    return y\n\n\ndef pixel_unshuffle_3d(x, downsample_factor):\n    \"\"\"\n    3D pixel unshuffle 操作。\n    \"\"\"\n    B, C, T, H, W = x.shape\n\n    r = downsample_factor\n    assert T % r == 0, f\"时间维度必须是下采样因子的倍数, got shape {x.shape}\"\n    assert H % r == 0, f\"高度维度必须是下采样因子的倍数, got shape {x.shape}\"\n    assert W % r == 0, f\"宽度维度必须是下采样因子的倍数, got shape {x.shape}\"\n    T_new = T // r\n    H_new = H // r\n    W_new = W // r\n    C_new = C * (r * r * r)\n\n    x = x.view(B, C, T_new, r, H_new, r, W_new, r)\n    x = x.permute(0, 1, 3, 5, 7, 2, 4, 6)\n    y = x.reshape(B, C_new, T_new, H_new, W_new)\n    return y\n\n\ndef test_pixel_shuffle_3d():\n    # 输入张量 (B, C, T, H, W) = (1, 16, 2, 4, 4)\n    x = torch.arange(1, 1 + 1 * 16 * 2 * 4 * 4).view(1, 16, 2, 4, 4).float()\n    print(\"x:\")\n    print(x)\n    print(\"x.shape:\")\n    print(x.shape)\n\n    upscale_factor = 2\n\n    # 使用自定义 pixelshuffle_3d\n    y = pixel_shuffle_3d(x, upscale_factor)\n    print(\"pixelshuffle_3d 结果:\")\n    print(y)\n    print(\"输出形状:\", y.shape)\n    # 预期输出形状: (1, 1, 4, 8, 8)\n    # 因为:\n    # - 通道数从8变为1 (8 /(2*2*2))\n    # - 时间维度从2变为4 (2*2)\n    # - 高度从4变为8 (4*2)\n    # - 宽度从4变为8 (4*2)\n\n    print(torch.allclose(x, pixel_unshuffle_3d(y, upscale_factor)))\n\n\ndef chunked_interpolate(x, scale_factor, mode=\"nearest\"):\n    \"\"\"\n    Interpolate large tensors by chunking along the channel dimension. https://discuss.pytorch.org/t/error-using-f-interpolate-for-large-3d-input/207859\n    Only supports 'nearest' interpolation mode.\n\n    Args:\n        x (torch.Tensor): Input tensor (B, C, D, H, W)\n        scale_factor: Tuple of scaling factors (d, h, w)\n\n    Returns:\n        torch.Tensor: Interpolated tensor\n    \"\"\"\n    assert (\n        mode == \"nearest\"\n    ), \"Only the nearest mode is supported\"  # actually other modes are theoretically supported but not tested\n    if len(x.shape) != 5:\n        raise ValueError(\"Expected 5D input tensor (B, C, D, H, W)\")\n\n    # Calculate max chunk size to avoid int32 overflow. num_elements < max_int32\n    # Max int32 is 2^31 - 1\n    max_elements_per_chunk = 2**31 - 1\n\n    # Calculate output spatial dimensions\n    out_d = math.ceil(x.shape[2] * scale_factor[0])\n    out_h = math.ceil(x.shape[3] * scale_factor[1])\n    out_w = math.ceil(x.shape[4] * scale_factor[2])\n\n    # Calculate max channels per chunk to stay under limit\n    elements_per_channel = out_d * out_h * out_w\n    max_channels = max_elements_per_chunk // (x.shape[0] * elements_per_channel)\n\n    # Use smaller of max channels or input channels\n    chunk_size = min(max_channels, x.shape[1])\n\n    # Ensure at least 1 channel per chunk\n    chunk_size = max(1, chunk_size)\n    if VERBOSE:\n        print(f\"Input channels: {x.shape[1]}\")\n        print(f\"Chunk size: {chunk_size}\")\n        print(f\"max_channels: {max_channels}\")\n        print(f\"num_chunks: {math.ceil(x.shape[1] / chunk_size)}\")\n\n    chunks = []\n    for i in range(0, x.shape[1], chunk_size):\n        start_idx = i\n        end_idx = min(i + chunk_size, x.shape[1])\n\n        chunk = x[:, start_idx:end_idx, :, :, :]\n\n        interpolated_chunk = F.interpolate(chunk, scale_factor=scale_factor, mode=\"nearest\")\n\n        chunks.append(interpolated_chunk)\n\n    if not chunks:\n        raise ValueError(f\"No chunks were generated. Input shape: {x.shape}\")\n\n    # Concatenate chunks along channel dimension\n    return torch.cat(chunks, dim=1)\n\n\ndef test_chunked_interpolate():\n    # Test case 1: Basic upscaling with scale_factor\n    x1 = torch.randn(2, 16, 16, 32, 32).cuda()\n    scale_factor = (2.0, 2.0, 2.0)\n    assert torch.allclose(\n        chunked_interpolate(x1, scale_factor=scale_factor), F.interpolate(x1, scale_factor=scale_factor, mode=\"nearest\")\n    )\n\n    # Test case 3: Downscaling with scale_factor\n    x3 = torch.randn(2, 16, 32, 64, 64).cuda()\n    scale_factor = (0.5, 0.5, 0.5)\n    assert torch.allclose(\n        chunked_interpolate(x3, scale_factor=scale_factor), F.interpolate(x3, scale_factor=scale_factor, mode=\"nearest\")\n    )\n\n    # Test case 4: Different scales per dimension\n    x4 = torch.randn(2, 16, 16, 32, 32).cuda()\n    scale_factor = (2.0, 1.5, 1.5)\n    assert torch.allclose(\n        chunked_interpolate(x4, scale_factor=scale_factor), F.interpolate(x4, scale_factor=scale_factor, mode=\"nearest\")\n    )\n\n    # Test case 5: Large input tensor\n    x5 = torch.randn(2, 16, 64, 128, 128).cuda()\n    scale_factor = (2.0, 2.0, 2.0)\n    assert torch.allclose(\n        chunked_interpolate(x5, scale_factor=scale_factor), F.interpolate(x5, scale_factor=scale_factor, mode=\"nearest\")\n    )\n\n    # Test case 7: Chunk size equal to input depth\n    x7 = torch.randn(2, 16, 8, 32, 32).cuda()\n    scale_factor = (2.0, 2.0, 2.0)\n    assert torch.allclose(\n        chunked_interpolate(x7, scale_factor=scale_factor), F.interpolate(x7, scale_factor=scale_factor, mode=\"nearest\")\n    )\n\n    # Test case 8: Single channel input\n    x8 = torch.randn(2, 1, 16, 32, 32).cuda()\n    scale_factor = (2.0, 2.0, 2.0)\n    assert torch.allclose(\n        chunked_interpolate(x8, scale_factor=scale_factor), F.interpolate(x8, scale_factor=scale_factor, mode=\"nearest\")\n    )\n\n    # Test case 9: Minimal batch size\n    x9 = torch.randn(1, 16, 32, 64, 64).cuda()\n    scale_factor = (0.5, 0.5, 0.5)\n    assert torch.allclose(\n        chunked_interpolate(x9, scale_factor=scale_factor), F.interpolate(x9, scale_factor=scale_factor, mode=\"nearest\")\n    )\n\n    # Test case 10: Non-power-of-2 dimensions\n    x10 = torch.randn(2, 16, 15, 31, 31).cuda()\n    scale_factor = (2.0, 2.0, 2.0)\n    assert torch.allclose(\n        chunked_interpolate(x10, scale_factor=scale_factor),\n        F.interpolate(x10, scale_factor=scale_factor, mode=\"nearest\"),\n    )\n\n    # Test case 11: large output tensor\n\n\ndef get_same_padding(kernel_size: Union[int, tuple[int, ...]]) -> Union[int, tuple[int, ...]]:\n    if isinstance(kernel_size, tuple):\n        return tuple([get_same_padding(ks) for ks in kernel_size])\n    else:\n        assert kernel_size % 2 > 0, \"kernel size should be odd number\"\n        return kernel_size // 2\n\n\ndef resize(\n    x: torch.Tensor,\n    size: Optional[Any] = None,\n    scale_factor: Optional[list[float]] = None,\n    mode: str = \"bicubic\",\n    align_corners: Optional[bool] = False,\n) -> torch.Tensor:\n    if mode in {\"bilinear\", \"bicubic\"}:\n        return F.interpolate(\n            x,\n            size=size,\n            scale_factor=scale_factor,\n            mode=mode,\n            align_corners=align_corners,\n        )\n    elif mode in {\"nearest\", \"area\"}:\n        return F.interpolate(x, size=size, scale_factor=scale_factor, mode=mode)\n    else:\n        raise NotImplementedError(f\"resize(mode={mode}) not implemented.\")\n\n\ndef build_kwargs_from_config(config: dict, target_func: Callable) -> dict[str, Any]:\n    valid_keys = list(signature(target_func).parameters)\n    kwargs = {}\n    for key in config:\n        if key in valid_keys:\n            kwargs[key] = config[key]\n    return kwargs\n\n\nif __name__ == \"__main__\":\n    test_chunked_interpolate()\n"
  },
  {
    "path": "opensora/models/dc_ae/utils/__init__.py",
    "content": "from .init import *\nfrom .list import *\n\n"
  },
  {
    "path": "opensora/models/dc_ae/utils/init.py",
    "content": "# Copyright 2024 MIT Han Lab\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# SPDX-License-Identifier: Apache-2.0\n\nfrom typing import Union\n\nimport torch\nimport torch.nn as nn\nfrom torch.nn.modules.batchnorm import _BatchNorm\n\n__all__ = [\"init_modules\"]\n\n\ndef init_modules(model: Union[nn.Module, list[nn.Module]], init_type=\"trunc_normal\") -> None:\n    _DEFAULT_INIT_PARAM = {\"trunc_normal\": 0.02}\n\n    if isinstance(model, list):\n        for sub_module in model:\n            init_modules(sub_module, init_type)\n    else:\n        init_params = init_type.split(\"@\")\n        init_params = float(init_params[1]) if len(init_params) > 1 else None\n\n        if init_type.startswith(\"trunc_normal\"):\n            init_func = lambda param: nn.init.trunc_normal_(\n                param, std=(_DEFAULT_INIT_PARAM[\"trunc_normal\"] if init_params is None else init_params)\n            )\n        elif init_type.startswith(\"normal\"):\n            init_func = lambda param: nn.init.normal_(\n                param, std=(_DEFAULT_INIT_PARAM[\"trunc_normal\"] if init_params is None else init_params)\n            )\n        else:\n            raise NotImplementedError\n\n        for m in model.modules():\n            if isinstance(m, (nn.Conv2d, nn.Linear, nn.ConvTranspose2d)):\n                init_func(m.weight)\n                if m.bias is not None:\n                    m.bias.data.zero_()\n            elif isinstance(m, nn.Embedding):\n                init_func(m.weight)\n            elif isinstance(m, (_BatchNorm, nn.GroupNorm, nn.LayerNorm)):\n                m.weight.data.fill_(1)\n                m.bias.data.zero_()\n            else:\n                weight = getattr(m, \"weight\", None)\n                bias = getattr(m, \"bias\", None)\n                if isinstance(weight, torch.nn.Parameter):\n                    init_func(weight)\n                if isinstance(bias, torch.nn.Parameter):\n                    bias.data.zero_()"
  },
  {
    "path": "opensora/models/dc_ae/utils/list.py",
    "content": "# Copyright 2024 MIT Han Lab\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# SPDX-License-Identifier: Apache-2.0\n\nfrom typing import Any, Optional, Union\n\n__all__ = [\n    \"list_sum\",\n    \"list_mean\",\n    \"weighted_list_sum\",\n    \"list_join\",\n    \"val2list\",\n    \"val2tuple\",\n    \"squeeze_list\",\n]\n\n\ndef list_sum(x: list) -> Any:\n    return x[0] if len(x) == 1 else x[0] + list_sum(x[1:])\n\n\ndef list_mean(x: list) -> Any:\n    return list_sum(x) / len(x)\n\n\ndef weighted_list_sum(x: list, weights: list) -> Any:\n    assert len(x) == len(weights)\n    return x[0] * weights[0] if len(x) == 1 else x[0] * weights[0] + weighted_list_sum(x[1:], weights[1:])\n\n\ndef list_join(x: list, sep=\"\\t\", format_str=\"%s\") -> str:\n    return sep.join([format_str % val for val in x])\n\n\ndef val2list(x: Union[list, tuple, Any], repeat_time=1) -> list:\n    if isinstance(x, (list, tuple)):\n        return list(x)\n    return [x for _ in range(repeat_time)]\n\n\ndef val2tuple(x: Union[list, tuple, Any], min_len: int = 1, idx_repeat: int = -1) -> tuple:\n    x = val2list(x)\n\n    # repeat elements if necessary\n    if len(x) > 0:\n        x[idx_repeat:idx_repeat] = [x[idx_repeat] for _ in range(min_len - len(x))]\n\n    return tuple(x)\n\n\ndef squeeze_list(x: Optional[list]) -> Union[list, Any]:\n    if x is not None and len(x) == 1:\n        return x[0]\n    else:\n        return x\n\n"
  },
  {
    "path": "opensora/models/hunyuan_vae/__init__.py",
    "content": "from pathlib import Path\n\nimport torch\n\nfrom .autoencoder_kl_causal_3d import CausalVAE3D_HUNYUAN\n"
  },
  {
    "path": "opensora/models/hunyuan_vae/autoencoder_kl_causal_3d.py",
    "content": "# Modified from diffusers==0.29.2 and HunyuanVideo\n#\n# Copyright 2024 The HuggingFace Team. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# Copyright 2024 HunyuanVideo\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\nfrom dataclasses import dataclass\nfrom typing import Dict, Optional, Tuple, Union\n\nimport torch\nimport torch.nn as nn\nfrom diffusers.configuration_utils import ConfigMixin, register_to_config\n\nfrom opensora.registry import MODELS\nfrom opensora.utils.ckpt import load_checkpoint\n\ntry:\n    # This diffusers is modified and packed in the mirror.\n    from diffusers.loaders import FromOriginalVAEMixin\nexcept ImportError:\n    # Use this to be compatible with the original diffusers.\n    from diffusers.loaders.single_file_model import FromOriginalModelMixin as FromOriginalVAEMixin\n\nfrom diffusers.models.attention_processor import (\n    ADDED_KV_ATTENTION_PROCESSORS,\n    CROSS_ATTENTION_PROCESSORS,\n    Attention,\n    AttentionProcessor,\n    AttnAddedKVProcessor,\n    AttnProcessor,\n)\nfrom diffusers.models.modeling_utils import ModelMixin\nfrom diffusers.utils.accelerate_utils import apply_forward_hook\n\nfrom opensora.models.hunyuan_vae.vae import (\n    DecoderCausal3D,\n    DecoderOutput,\n    DiagonalGaussianDistribution,\n    EncoderCausal3D,\n)\n\n\n@dataclass\nclass AutoEncoder3DConfig:\n    from_pretrained: str | None\n    act_fn: str = \"silu\"\n    in_channels: int = 3\n    out_channels: int = 3\n    latent_channels: int = 16\n    layers_per_block: int = 2\n    norm_num_groups: int = 32\n    scale_factor: float = 0.476986\n    shift_factor: float = 0\n    time_compression_ratio: int = 4\n    spatial_compression_ratio: int = 8\n    mid_block_add_attention: bool = True\n    block_out_channels: tuple[int] = (128, 256, 512, 512)\n    sample_size: int = 256\n    sample_tsize: int = 64\n    use_slicing: bool = False\n    use_spatial_tiling: bool = False\n    use_temporal_tiling: bool = False\n    tile_overlap_factor: float = 0.25\n    dropout: float = 0.0\n    channel: bool = False\n\n\nclass AutoencoderKLCausal3D(ModelMixin, ConfigMixin, FromOriginalVAEMixin):\n    r\"\"\"\n    A VAE model with KL loss for encoding images/videos into latents and decoding latent representations into images/videos.\n\n    This model inherits from [`ModelMixin`]. Check the superclass documentation for it's generic methods implemented\n    for all models (such as downloading or saving).\n    \"\"\"\n\n    _supports_gradient_checkpointing = True\n\n    @register_to_config\n    def __init__(self, config: AutoEncoder3DConfig):\n        super().__init__()\n\n        self.scale_factor = config.scale_factor\n        self.shift_factor = config.shift_factor\n\n        self.time_compression_ratio = config.time_compression_ratio\n        self.spatial_compression_ratio = config.spatial_compression_ratio\n        self.z_channels = config.latent_channels\n\n        self.encoder = EncoderCausal3D(\n            in_channels=config.in_channels,\n            out_channels=config.latent_channels,\n            block_out_channels=config.block_out_channels,\n            layers_per_block=config.layers_per_block,\n            act_fn=config.act_fn,\n            norm_num_groups=config.norm_num_groups,\n            double_z=True,\n            time_compression_ratio=config.time_compression_ratio,\n            spatial_compression_ratio=config.spatial_compression_ratio,\n            mid_block_add_attention=config.mid_block_add_attention,\n            dropout=config.dropout,\n        )\n\n        self.decoder = DecoderCausal3D(\n            in_channels=config.latent_channels,\n            out_channels=config.out_channels,\n            block_out_channels=config.block_out_channels,\n            layers_per_block=config.layers_per_block,\n            norm_num_groups=config.norm_num_groups,\n            act_fn=config.act_fn,\n            time_compression_ratio=config.time_compression_ratio,\n            spatial_compression_ratio=config.spatial_compression_ratio,\n            mid_block_add_attention=config.mid_block_add_attention,\n            dropout=config.dropout,\n        )\n\n        self.quant_conv = nn.Conv3d(2 * config.latent_channels, 2 * config.latent_channels, kernel_size=1)\n        self.post_quant_conv = nn.Conv3d(config.latent_channels, config.latent_channels, kernel_size=1)\n\n        self.use_slicing = config.use_slicing\n        self.use_spatial_tiling = config.use_spatial_tiling\n        self.use_temporal_tiling = config.use_temporal_tiling\n\n        # only relevant if vae tiling is enabled\n        self.tile_sample_min_tsize = config.sample_tsize\n        self.tile_latent_min_tsize = config.sample_tsize // config.time_compression_ratio\n\n        self.tile_sample_min_size = config.sample_size\n        sample_size = config.sample_size[0] if isinstance(config.sample_size, (list, tuple)) else config.sample_size\n        self.tile_latent_min_size = int(sample_size / (2 ** (len(config.block_out_channels) - 1)))\n        self.tile_overlap_factor = config.tile_overlap_factor\n\n    def enable_temporal_tiling(self, use_tiling: bool = True):\n        self.use_temporal_tiling = use_tiling\n\n    def disable_temporal_tiling(self):\n        self.enable_temporal_tiling(False)\n\n    def enable_spatial_tiling(self, use_tiling: bool = True):\n        self.use_spatial_tiling = use_tiling\n\n    def disable_spatial_tiling(self):\n        self.enable_spatial_tiling(False)\n\n    def enable_tiling(self, use_tiling: bool = True):\n        r\"\"\"\n        Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to\n        compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow\n        processing larger videos.\n        \"\"\"\n        self.enable_spatial_tiling(use_tiling)\n        self.enable_temporal_tiling(use_tiling)\n\n    def disable_tiling(self):\n        r\"\"\"\n        Disable tiled VAE decoding. If `enable_tiling` was previously enabled, this method will go back to computing\n        decoding in one step.\n        \"\"\"\n        self.disable_spatial_tiling()\n        self.disable_temporal_tiling()\n\n    def enable_slicing(self):\n        r\"\"\"\n        Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to\n        compute decoding in several steps. This is useful to save some memory and allow larger batch sizes.\n        \"\"\"\n        self.use_slicing = True\n\n    def disable_slicing(self):\n        r\"\"\"\n        Disable sliced VAE decoding. If `enable_slicing` was previously enabled, this method will go back to computing\n        decoding in one step.\n        \"\"\"\n        self.use_slicing = False\n\n    @property\n    # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors\n    def attn_processors(self) -> Dict[str, AttentionProcessor]:\n        r\"\"\"\n        Returns:\n            `dict` of attention processors: A dictionary containing all attention processors used in the model with\n            indexed by its weight name.\n        \"\"\"\n        # set recursively\n        processors = {}\n\n        def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]):\n            if hasattr(module, \"get_processor\"):\n                processors[f\"{name}.processor\"] = module.get_processor(return_deprecated_lora=True)\n\n            for sub_name, child in module.named_children():\n                fn_recursive_add_processors(f\"{name}.{sub_name}\", child, processors)\n\n            return processors\n\n        for name, module in self.named_children():\n            fn_recursive_add_processors(name, module, processors)\n\n        return processors\n\n    # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.set_attn_processor\n    def set_attn_processor(\n        self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]], _remove_lora=False\n    ):\n        r\"\"\"\n        Sets the attention processor to use to compute attention.\n\n        Parameters:\n            processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):\n                The instantiated processor class or a dictionary of processor classes that will be set as the processor\n                for **all** `Attention` layers.\n\n                If `processor` is a dict, the key needs to define the path to the corresponding cross attention\n                processor. This is strongly recommended when setting trainable attention processors.\n\n        \"\"\"\n        count = len(self.attn_processors.keys())\n\n        if isinstance(processor, dict) and len(processor) != count:\n            raise ValueError(\n                f\"A dict of processors was passed, but the number of processors {len(processor)} does not match the\"\n                f\" number of attention layers: {count}. Please make sure to pass {count} processor classes.\"\n            )\n\n        def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):\n            if hasattr(module, \"set_processor\"):\n                if not isinstance(processor, dict):\n                    module.set_processor(processor, _remove_lora=_remove_lora)\n                else:\n                    module.set_processor(processor.pop(f\"{name}.processor\"), _remove_lora=_remove_lora)\n\n            for sub_name, child in module.named_children():\n                fn_recursive_attn_processor(f\"{name}.{sub_name}\", child, processor)\n\n        for name, module in self.named_children():\n            fn_recursive_attn_processor(name, module, processor)\n\n    # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.set_default_attn_processor\n    def set_default_attn_processor(self):\n        \"\"\"\n        Disables custom attention processors and sets the default attention implementation.\n        \"\"\"\n        if all(proc.__class__ in ADDED_KV_ATTENTION_PROCESSORS for proc in self.attn_processors.values()):\n            processor = AttnAddedKVProcessor()\n        elif all(proc.__class__ in CROSS_ATTENTION_PROCESSORS for proc in self.attn_processors.values()):\n            processor = AttnProcessor()\n        else:\n            raise ValueError(\n                f\"Cannot call `set_default_attn_processor` when attention processors are of type {next(iter(self.attn_processors.values()))}\"\n            )\n\n        self.set_attn_processor(processor, _remove_lora=True)\n\n    @apply_forward_hook\n    def encode(\n        self,\n        x: torch.FloatTensor,\n        sample_posterior: bool = True,\n        return_posterior: bool = False,\n        generator: Optional[torch.Generator] = None,\n    ) -> Union[torch.FloatTensor, Tuple[DiagonalGaussianDistribution]]:\n        \"\"\"\n        Encode a batch of images/videos into latents.\n\n        Args:\n            x (`torch.FloatTensor`): Input batch of images/videos.\n            return_dict (`bool`, *optional*, defaults to `True`):\n                Whether to return a [`~models.autoencoder_kl.AutoencoderKLOutput`] instead of a plain tuple.\n\n        Returns:\n                The latent representations of the encoded images/videos. If `return_dict` is True, a\n                [`~models.autoencoder_kl.AutoencoderKLOutput`] is returned, otherwise a plain `tuple` is returned.\n        \"\"\"\n        assert len(x.shape) == 5, \"The input tensor should have 5 dimensions.\"\n\n        if self.use_temporal_tiling and x.shape[2] > self.tile_sample_min_tsize:\n            posterior = self.temporal_tiled_encode(x)\n        elif self.use_spatial_tiling and (\n            x.shape[-1] > self.tile_sample_min_size or x.shape[-2] > self.tile_sample_min_size\n        ):\n            posterior = self.spatial_tiled_encode(x)\n        else:\n            if self.use_slicing and x.shape[0] > 1:\n                encoded_slices = [self.encoder(x_slice) for x_slice in x.split(1)]\n                h = torch.cat(encoded_slices)\n            else:\n                h = self.encoder(x)\n            moments = self.quant_conv(h)\n            posterior = DiagonalGaussianDistribution(moments)\n\n        if sample_posterior:\n            z = posterior.sample(generator=generator)\n        else:\n            z = posterior.mode()\n\n        z = self.scale_factor * (z - self.shift_factor)  # shift & scale\n\n        if return_posterior:\n            return z, posterior\n        else:\n            return z\n\n    def _decode(self, z: torch.FloatTensor, return_dict: bool = True) -> Union[DecoderOutput, torch.FloatTensor]:\n        assert len(z.shape) == 5, \"The input tensor should have 5 dimensions.\"\n\n        if self.use_temporal_tiling and z.shape[2] > self.tile_latent_min_tsize:\n            return self.temporal_tiled_decode(z, return_dict=return_dict)\n\n        if self.use_spatial_tiling and (\n            z.shape[-1] > self.tile_latent_min_size or z.shape[-2] > self.tile_latent_min_size\n        ):\n            return self.spatial_tiled_decode(z, return_dict=return_dict)\n\n        z = self.post_quant_conv(z)\n        dec = self.decoder(z)\n\n        if not return_dict:\n            return (dec,)\n\n        return DecoderOutput(sample=dec)\n\n    @apply_forward_hook\n    def decode(self, z: torch.FloatTensor) -> torch.FloatTensor:\n        \"\"\"\n        Decode a batch of images/videos.\n\n        Args:\n            z (`torch.FloatTensor`): Input batch of latent vectors.\n\n        Returns:\n            [`~models.vae.DecoderOutput`] or `tuple`:\n                If return_dict is True, a [`~models.vae.DecoderOutput`] is returned, otherwise a plain `tuple` is\n                returned.\n\n        \"\"\"\n        z = z / self.scale_factor + self.shift_factor  # scale & shift\n\n        if self.use_slicing and z.shape[0] > 1:\n            decoded_slices = [self._decode(z_slice).sample for z_slice in z.split(1)]\n            decoded = torch.cat(decoded_slices)\n        else:\n            decoded = self._decode(z).sample\n        return decoded\n\n    def blend_v(self, a: torch.Tensor, b: torch.Tensor, blend_extent: int) -> torch.Tensor:\n        blend_extent = min(a.shape[-2], b.shape[-2], blend_extent)\n        for y in range(blend_extent):\n            b[:, :, :, y, :] = a[:, :, :, -blend_extent + y, :] * (1 - y / blend_extent) + b[:, :, :, y, :] * (\n                y / blend_extent\n            )\n        return b\n\n    def blend_h(self, a: torch.Tensor, b: torch.Tensor, blend_extent: int) -> torch.Tensor:\n        blend_extent = min(a.shape[-1], b.shape[-1], blend_extent)\n        for x in range(blend_extent):\n            b[:, :, :, :, x] = a[:, :, :, :, -blend_extent + x] * (1 - x / blend_extent) + b[:, :, :, :, x] * (\n                x / blend_extent\n            )\n        return b\n\n    def blend_t(self, a: torch.Tensor, b: torch.Tensor, blend_extent: int) -> torch.Tensor:\n        blend_extent = min(a.shape[-3], b.shape[-3], blend_extent)\n        for x in range(blend_extent):\n            b[:, :, x, :, :] = a[:, :, -blend_extent + x, :, :] * (1 - x / blend_extent) + b[:, :, x, :, :] * (\n                x / blend_extent\n            )\n        return b\n\n    def spatial_tiled_encode(self, x: torch.FloatTensor, return_moments: bool = False) -> DiagonalGaussianDistribution:\n        r\"\"\"Encode a batch of images/videos using a tiled encoder.\n\n        When this option is enabled, the VAE will split the input tensor into tiles to compute encoding in several\n        steps. This is useful to keep memory use constant regardless of image/videos size. The end result of tiled encoding is\n        different from non-tiled encoding because each tile uses a different encoder. To avoid tiling artifacts, the\n        tiles overlap and are blended together to form a smooth output. You may still see tile-sized changes in the\n        output, but they should be much less noticeable.\n\n        Args:\n            x (`torch.FloatTensor`): Input batch of images/videos.\n            return_dict (`bool`, *optional*, defaults to `True`):\n                Whether or not to return a [`~models.autoencoder_kl.AutoencoderKLOutput`] instead of a plain tuple.\n\n        Returns:\n            [`~models.autoencoder_kl.AutoencoderKLOutput`] or `tuple`:\n                If return_dict is True, a [`~models.autoencoder_kl.AutoencoderKLOutput`] is returned, otherwise a plain\n                `tuple` is returned.\n        \"\"\"\n        overlap_size = int(self.tile_sample_min_size * (1 - self.tile_overlap_factor))\n        blend_extent = int(self.tile_latent_min_size * self.tile_overlap_factor)\n        row_limit = self.tile_latent_min_size - blend_extent\n\n        # Split video into tiles and encode them separately.\n        rows = []\n        for i in range(0, x.shape[-2], overlap_size):\n            row = []\n            for j in range(0, x.shape[-1], overlap_size):\n                tile = x[:, :, :, i : i + self.tile_sample_min_size, j : j + self.tile_sample_min_size]\n                tile = self.encoder(tile)\n                tile = self.quant_conv(tile)\n                row.append(tile)\n            rows.append(row)\n        result_rows = []\n        for i, row in enumerate(rows):\n            result_row = []\n            for j, tile in enumerate(row):\n                # blend the above tile and the left tile\n                # to the current tile and add the current tile to the result row\n                if i > 0:\n                    tile = self.blend_v(rows[i - 1][j], tile, blend_extent)\n                if j > 0:\n                    tile = self.blend_h(row[j - 1], tile, blend_extent)\n                result_row.append(tile[:, :, :, :row_limit, :row_limit])\n            result_rows.append(torch.cat(result_row, dim=-1))\n\n        moments = torch.cat(result_rows, dim=-2)\n        if return_moments:\n            return moments\n        posterior = DiagonalGaussianDistribution(moments)\n        return posterior\n\n    def spatial_tiled_decode(\n        self, z: torch.FloatTensor, return_dict: bool = True\n    ) -> Union[DecoderOutput, torch.FloatTensor]:\n        r\"\"\"\n        Decode a batch of images/videos using a tiled decoder.\n\n        Args:\n            z (`torch.FloatTensor`): Input batch of latent vectors.\n            return_dict (`bool`, *optional*, defaults to `True`):\n                Whether or not to return a [`~models.vae.DecoderOutput`] instead of a plain tuple.\n\n        Returns:\n            [`~models.vae.DecoderOutput`] or `tuple`:\n                If return_dict is True, a [`~models.vae.DecoderOutput`] is returned, otherwise a plain `tuple` is\n                returned.\n        \"\"\"\n        overlap_size = int(self.tile_latent_min_size * (1 - self.tile_overlap_factor))\n        blend_extent = int(self.tile_sample_min_size * self.tile_overlap_factor)\n        row_limit = self.tile_sample_min_size - blend_extent\n\n        # Split z into overlapping tiles and decode them separately.\n        # The tiles have an overlap to avoid seams between tiles.\n        rows = []\n        for i in range(0, z.shape[-2], overlap_size):\n            row = []\n            for j in range(0, z.shape[-1], overlap_size):\n                tile = z[:, :, :, i : i + self.tile_latent_min_size, j : j + self.tile_latent_min_size]\n                tile = self.post_quant_conv(tile)\n                decoded = self.decoder(tile)\n                row.append(decoded)\n            rows.append(row)\n        result_rows = []\n        for i, row in enumerate(rows):\n            result_row = []\n            for j, tile in enumerate(row):\n                # blend the above tile and the left tile\n                # to the current tile and add the current tile to the result row\n                if i > 0:\n                    tile = self.blend_v(rows[i - 1][j], tile, blend_extent)\n                if j > 0:\n                    tile = self.blend_h(row[j - 1], tile, blend_extent)\n                result_row.append(tile[:, :, :, :row_limit, :row_limit])\n            result_rows.append(torch.cat(result_row, dim=-1))\n\n        dec = torch.cat(result_rows, dim=-2)\n        if not return_dict:\n            return (dec,)\n\n        return DecoderOutput(sample=dec)\n\n    def temporal_tiled_encode(self, x: torch.FloatTensor) -> DiagonalGaussianDistribution:\n        B, C, T, H, W = x.shape\n        overlap_size = int(self.tile_sample_min_tsize * (1 - self.tile_overlap_factor))\n        blend_extent = int(self.tile_latent_min_tsize * self.tile_overlap_factor)\n        t_limit = self.tile_latent_min_tsize - blend_extent\n\n        # Split the video into tiles and encode them separately.\n        row = []\n        for i in range(0, T, overlap_size):\n            tile = x[:, :, i : i + self.tile_sample_min_tsize + 1, :, :]\n            if self.use_spatial_tiling and (\n                tile.shape[-1] > self.tile_sample_min_size or tile.shape[-2] > self.tile_sample_min_size\n            ):\n                tile = self.spatial_tiled_encode(tile, return_moments=True)\n            else:\n                tile = self.encoder(tile)\n                tile = self.quant_conv(tile)\n            if i > 0:\n                tile = tile[:, :, 1:, :, :]\n            row.append(tile)\n        result_row = []\n        for i, tile in enumerate(row):\n            if i > 0:\n                tile = self.blend_t(row[i - 1], tile, blend_extent)\n                result_row.append(tile[:, :, :t_limit, :, :])\n            else:\n                result_row.append(tile[:, :, : t_limit + 1, :, :])\n        moments = torch.cat(result_row, dim=2)\n        posterior = DiagonalGaussianDistribution(moments)\n        return posterior\n\n    def temporal_tiled_decode(\n        self, z: torch.FloatTensor, return_dict: bool = True\n    ) -> Union[DecoderOutput, torch.FloatTensor]:\n        # Split z into overlapping tiles and decode them separately.\n\n        B, C, T, H, W = z.shape\n        overlap_size = int(self.tile_latent_min_tsize * (1 - self.tile_overlap_factor))\n        blend_extent = int(self.tile_sample_min_tsize * self.tile_overlap_factor)\n        t_limit = self.tile_sample_min_tsize - blend_extent\n\n        row = []\n        for i in range(0, T, overlap_size):\n            tile = z[:, :, i : i + self.tile_latent_min_tsize + 1, :, :]\n            if self.use_spatial_tiling and (\n                tile.shape[-1] > self.tile_latent_min_size or tile.shape[-2] > self.tile_latent_min_size\n            ):\n                decoded = self.spatial_tiled_decode(tile, return_dict=True).sample\n            else:\n                tile = self.post_quant_conv(tile)\n                decoded = self.decoder(tile)\n            if i > 0:\n                decoded = decoded[:, :, 1:, :, :]\n            row.append(decoded)\n        result_row = []\n        for i, tile in enumerate(row):\n            if i > 0:\n                tile = self.blend_t(row[i - 1], tile, blend_extent)\n                result_row.append(tile[:, :, :t_limit, :, :])\n            else:\n                result_row.append(tile[:, :, : t_limit + 1, :, :])\n\n        dec = torch.cat(result_row, dim=2)\n        if not return_dict:\n            return (dec,)\n\n        return DecoderOutput(sample=dec)\n\n    def forward(\n        self,\n        sample: torch.FloatTensor,\n        sample_posterior: bool = True,\n        generator: Optional[torch.Generator] = None,\n    ) -> Tuple[torch.FloatTensor, DiagonalGaussianDistribution, torch.FloatTensor]:\n        r\"\"\"\n        Args:\n            sample (`torch.FloatTensor`): Input sample.\n            sample_posterior (`bool`, *optional*, defaults to `False`):\n                Whether to sample from the posterior.\n            return_dict (`bool`, *optional*, defaults to `True`):\n                Whether or not to return a [`DecoderOutput`] instead of a plain tuple.\n        \"\"\"\n        x = sample\n        z, posterior = self.encode(x, return_posterior=True, sample_posterior=sample_posterior, generator=generator)\n        dec = self.decode(z)\n\n        return (dec, posterior, z)\n\n    # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.fuse_qkv_projections\n    def fuse_qkv_projections(self):\n        \"\"\"\n        Enables fused QKV projections. For self-attention modules, all projection matrices (i.e., query,\n        key, value) are fused. For cross-attention modules, key and value projection matrices are fused.\n\n        <Tip warning={true}>\n\n        This API is 🧪 experimental.\n\n        </Tip>\n        \"\"\"\n        self.original_attn_processors = None\n\n        for _, attn_processor in self.attn_processors.items():\n            if \"Added\" in str(attn_processor.__class__.__name__):\n                raise ValueError(\"`fuse_qkv_projections()` is not supported for models having added KV projections.\")\n\n        self.original_attn_processors = self.attn_processors\n\n        for module in self.modules():\n            if isinstance(module, Attention):\n                module.fuse_projections(fuse=True)\n\n    # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.unfuse_qkv_projections\n    def unfuse_qkv_projections(self):\n        \"\"\"Disables the fused QKV projection if enabled.\n\n        <Tip warning={true}>\n\n        This API is 🧪 experimental.\n\n        </Tip>\n\n        \"\"\"\n        if self.original_attn_processors is not None:\n            self.set_attn_processor(self.original_attn_processors)\n\n    def get_last_layer(self):\n        return self.decoder.conv_out.conv.weight\n\n    def get_latent_size(self, input_size: list[int]) -> list[int]:\n        latent_size = []\n        # T\n        latent_size.append((input_size[0] - 1) // self.time_compression_ratio + 1)\n        # H, w\n        for i in range(1, 3):\n            latent_size.append((input_size[i] - 1) // self.spatial_compression_ratio + 1)\n        return latent_size\n\n\n@MODELS.register_module(\"hunyuan_vae\")\ndef CausalVAE3D_HUNYUAN(\n    from_pretrained: str = None,\n    device_map: str | torch.device = \"cuda\",\n    torch_dtype: torch.dtype = torch.bfloat16,\n    **kwargs,\n) -> AutoencoderKLCausal3D:\n    config = AutoEncoder3DConfig(from_pretrained=from_pretrained, **kwargs)\n    with torch.device(device_map):\n        model = AutoencoderKLCausal3D(config).to(torch_dtype)\n    if from_pretrained:\n        model = load_checkpoint(model, from_pretrained, device_map=device_map, strict=True)\n\n    return model\n"
  },
  {
    "path": "opensora/models/hunyuan_vae/distributed.py",
    "content": "from typing import List, Optional, Tuple\n\nimport torch\nimport torch.distributed as dist\nfrom colossalai.shardformer.layer._operation import gather_forward_split_backward, split_forward_gather_backward\nfrom colossalai.shardformer.layer.attn import RingComm, _rescale_out_lse\nfrom colossalai.shardformer.layer.utils import SeqParallelUtils\nfrom diffusers.models.attention_processor import Attention\n\nfrom opensora.models.vae.tensor_parallel import Conv3dTPRow\nfrom opensora.models.vae.utils import get_conv3d_n_chunks\n\nfrom .unet_causal_3d_blocks import UpsampleCausal3D\n\ntry:\n    from xformers.ops.fmha import (\n        Context,\n        Inputs,\n        _memory_efficient_attention_backward,\n        _memory_efficient_attention_forward_requires_grad,\n    )\n\n    HAS_XFORMERS = True\nexcept ImportError:\n    HAS_XFORMERS = False\n\nSEQ_ALIGN = 32\nSEQ_LIMIT = 16 * 1024\n\n\ndef align_atten_bias(attn_bias):\n    B, N, S, S = attn_bias.shape\n    align_size = 8\n    if S % align_size != 0:\n        expand_S = (S // align_size + 1) * align_size\n        new_shape = [B, N, S, expand_S]\n        attn_bias = torch.empty(new_shape, dtype=attn_bias.dtype, device=attn_bias.device)[:, :, :, :S].copy_(attn_bias)\n    return attn_bias\n\n\ndef _attn_fwd(\n    q: torch.Tensor,\n    k: torch.Tensor,\n    v: torch.Tensor,\n    attn_bias: Optional[torch.Tensor] = None,\n    scale: Optional[float] = None,\n):\n    attn_bias = align_atten_bias(attn_bias)\n    inp = Inputs(q, k, v, attn_bias, p=0, scale=scale, is_partial=False)\n    out, ctx = _memory_efficient_attention_forward_requires_grad(inp, None)\n\n    S = attn_bias.shape[-2]\n    if ctx.lse.shape[-1] != S:\n        ctx.lse = ctx.lse[:, :, :S]\n    return out, ctx.lse, ctx.rng_state\n\n\ndef _attn_bwd(\n    grad: torch.Tensor,\n    q: torch.Tensor,\n    k: torch.Tensor,\n    v: torch.Tensor,\n    out: torch.Tensor,\n    lse: torch.Tensor,\n    rng_state: torch.Tensor,\n    attn_bias: Optional[torch.Tensor] = None,\n    scale: Optional[float] = None,\n):\n    attn_bias = align_atten_bias(attn_bias)\n    inp = Inputs(q, k, v, attn_bias, p=0, scale=scale, output_dtype=q.dtype, is_partial=False)\n    ctx = Context(lse, out, rng_state=rng_state)\n    grads = _memory_efficient_attention_backward(ctx, inp, grad, None)\n    return grads.dq, grads.dk, grads.dv\n\n\nclass MemEfficientRingAttention(torch.autograd.Function):\n    ATTN_DONE: torch.cuda.Event = None\n    SP_STREAM: torch.cuda.Stream = None\n\n    @staticmethod\n    def forward(\n        ctx,\n        q: torch.Tensor,\n        k: torch.Tensor,\n        v: torch.Tensor,\n        sp_group: dist.ProcessGroup,\n        sp_stream: torch.cuda.Stream,\n        softmax_scale: Optional[float] = None,\n        attn_mask: Optional[torch.Tensor] = None,\n    ) -> Tuple[torch.Tensor, torch.Tensor]:\n        \"\"\"Ring attention forward\n\n        Args:\n            ctx (_type_): self\n            q (torch.Tensor): shape [B, S/P, N, D]\n            k (torch.Tensor): shape [B, S/P, N, D]\n            v (torch.Tensor): shape [B, S/P, N, D]\n            sp_group (dist.ProcessGroup): sequence parallel group\n            sp_stream (torch.cuda.Stream): sequence parallel stream\n            softmax_scale (Optional[float], optional): softmax scale. Defaults to None.\n            attn_mask (Optional[torch.Tensor], optional): attention mask shape [B, N, S/P, S]. Defaults to None.\n\n        Returns:\n            Tuple[torch.Tensor, torch.Tensor]: output and log sum exp. Output's shape should be [B, S/P, N, D]. LSE's shape should be [B, N, S/P].\n        \"\"\"\n        if softmax_scale is None:\n            softmax_scale = q.shape[-1] ** (-0.5)\n        sp_size = dist.get_world_size(sp_group)\n        sp_rank = dist.get_rank(sp_group)\n        kv_comms: List[RingComm] = [RingComm(sp_group) for _ in range(2)]\n        block_attn_masks = [None] * sp_size\n        if attn_mask is not None:\n            # if attn_mask is splitted, uncomment the following line\n            # attn_mask = attn_mask.chunk(sp_size, dim=2)[sp_rank]\n            block_attn_masks = attn_mask.chunk(sp_size, dim=-1)\n\n        # [B, S, N, D]\n        q, k, v = [x.contiguous() for x in [q, k, v]]\n        # Pre-allocate double buffer for overlapping and receiving next step's inputs\n        kv_buffers = [torch.stack((k, v))]  # (2, B, S, N, D)\n        kv_buffers.append(torch.empty_like(kv_buffers[0]))\n        # outputs\n        out = None\n        block_out = [None, None]\n        softmax_lse = [None, None]\n        block_softmax_lse = [None, None]  # log sum exp, the denominator of softmax in attention\n        rng_states = [None for _ in range(sp_size)]\n        sp_streams = [torch.cuda.current_stream(), sp_stream]\n\n        def _kv_comm(i):\n            # Avoid overwriting attn input when it shares mem with buffer\n            if not MemEfficientRingAttention.ATTN_DONE.query():\n                kv_buffers[(i + 1) % 2] = torch.empty_like(kv_buffers[i % 2])\n            if i < sp_size - 1:\n                kv_comms[i % 2].send_recv(kv_buffers[i % 2], kv_buffers[(i + 1) % 2])\n\n        block_idx = sp_rank\n        for i in range(sp_size):\n            with torch.cuda.stream(sp_streams[i % 2]):\n                # Wait for current kv from prev rank\n                # NOTE: waiting outside the current stream will NOT correctly synchronize.\n                if i == 0:\n                    _kv_comm(i)\n                else:\n                    kv_comms[(i + 1) % 2].wait()\n                kv_block = kv_buffers[i % 2]\n                q_block = q\n                block_out[i % 2], block_softmax_lse[i % 2], rng_states[i] = _attn_fwd(\n                    q_block, kv_block[0], kv_block[1], attn_bias=block_attn_masks[block_idx], scale=softmax_scale\n                )\n                MemEfficientRingAttention.ATTN_DONE.record()\n                # Pipeline the next KV comm with output correction instead of the next flash attn\n                # to minimize idle time when comm takes longer than attn.\n                _kv_comm(i + 1)\n                block_softmax_lse[i % 2] = (\n                    block_softmax_lse[i % 2].transpose(1, 2).unsqueeze(-1).contiguous().float()\n                )  # [B, N, S] -> [B, S, N, 1]\n                assert (\n                    block_out[i % 2].shape[:-1] == block_softmax_lse[i % 2].shape[:-1]\n                ), f\"{block_out[i % 2].shape} != {block_softmax_lse[i % 2].shape}\"\n                # Output and log sum exp correction. Ideally overlap this with the next flash attn kernel.\n                # In reality this always finishes before next flash attn; no need for extra sync.\n                if i == 0:\n                    out = block_out[0]\n                    softmax_lse = block_softmax_lse[0]\n                else:\n                    out, softmax_lse = _rescale_out_lse(out, block_out[i % 2], softmax_lse, block_softmax_lse[i % 2])\n                block_idx = (block_idx - 1) % sp_size\n        torch.cuda.current_stream().wait_stream(sp_stream)\n        out = out.to(q.dtype)\n        softmax_lse = softmax_lse.squeeze(-1).transpose(1, 2).contiguous()\n\n        ctx.softmax_scale = softmax_scale\n        ctx.block_attn_masks = block_attn_masks\n        ctx.sp_group = sp_group\n        ctx.save_for_backward(q, k, v, out, softmax_lse, *rng_states)  # lse [B, N, S]\n        return out, softmax_lse\n\n    @staticmethod\n    def backward(ctx, grad_output, grad_softmax_lse):\n        # q, k, v, out: [B, S, N, D], softmax_lse: [B, N, S]\n        q, k, v, out, softmax_lse, *rng_states = ctx.saved_tensors\n\n        sp_group = ctx.sp_group\n        sp_size = dist.get_world_size(sp_group)\n        kv_comm = RingComm(sp_group)\n        dkv_comm = RingComm(sp_group)\n\n        grad_output = grad_output.contiguous()\n        kv_buffers = [torch.stack((k, v))]  # (2, B, S, N, D)\n        kv_buffers.append(torch.empty_like(kv_buffers[0]))\n        dq = None\n        dkv_buffers = [torch.empty_like(kv, dtype=torch.float) for kv in kv_buffers]\n        del k, v\n\n        block_idx = dist.get_rank(sp_group)\n        for i in range(sp_size):\n            if i > 0:\n                kv_comm.wait()\n            if i < sp_size - 1:\n                kv_comm.send_recv(kv_buffers[i % 2], kv_buffers[(i + 1) % 2])\n\n            k_block, v_block = kv_buffers[i % 2]\n            dq_block, dk_block, dv_block = _context_chunk_attn_bwd(\n                grad_output,\n                q,\n                k_block,\n                v_block,\n                out,\n                softmax_lse,\n                rng_states[i],\n                attn_bias=ctx.block_attn_masks[block_idx],\n                scale=ctx.softmax_scale,\n            )\n\n            if i == 0:\n                dq = dq_block.float()\n                dkv_buffers[i % 2][0] = dk_block.float()\n                dkv_buffers[i % 2][1] = dv_block.float()\n            else:\n                dq += dq_block\n                dkv_comm.wait()\n                dkv_buffers[i % 2][0] += dk_block\n                dkv_buffers[i % 2][1] += dv_block\n            dkv_comm.send_recv(dkv_buffers[i % 2], dkv_buffers[(i + 1) % 2])\n            block_idx = (block_idx - 1) % sp_size\n        dkv_comm.wait()\n        dkv = dkv_buffers[sp_size % 2]\n\n        dq, dk, dv = [x.to(q.dtype) for x in (dq, *dkv)]\n\n        torch.cuda.empty_cache()\n        return dq, dk, dv, None, None, None, None, None, None, None, None, None, None, None, None, None\n\n    @staticmethod\n    def attention(\n        q,\n        k,\n        v,\n        sp_group,\n        softmax_scale: Optional[float] = None,\n        attn_mask: Optional[torch.Tensor] = None,\n        return_softmax: bool = False,\n    ):\n        \"\"\"Ring attention\n\n        Args:\n            q (torch.Tensor): shape [B, S, N, D]\n            k (torch.Tensor): shape [B, S, N, D]\n            v (torch.Tensor): shape [B, S, N, D]\n            sp_group (dist.ProcessGroup): sequence parallel group\n            softmax_scale (Optional[float], optional): softmax scale. Defaults to None.\n            attn_mask (Optional[torch.Tensor], optional): attention mask. Defaults to None.\n            return_softmax (bool, optional): return softmax or not. Defaults to False.\n\n        Returns:\n            Tuple[torch.Tensor, torch.Tensor]: output and log sum exp. Output's shape should be [B, S, N, D]. LSE's shape should be [B, N, S].\n        \"\"\"\n        if MemEfficientRingAttention.ATTN_DONE is None:\n            MemEfficientRingAttention.ATTN_DONE = torch.cuda.Event()\n        if MemEfficientRingAttention.SP_STREAM is None:\n            MemEfficientRingAttention.SP_STREAM = torch.cuda.Stream()\n        out, softmax_lse = MemEfficientRingAttention.apply(\n            q, k, v, sp_group, MemEfficientRingAttention.SP_STREAM, softmax_scale, attn_mask\n        )\n        if return_softmax:\n            return out, softmax_lse\n        return out\n\n\nclass MemEfficientRingAttnProcessor:\n    def __init__(self, sp_group: dist.ProcessGroup):\n        self.sp_group = sp_group\n        if not HAS_XFORMERS:\n            raise ImportError(\"MemEfficientRingAttnProcessor requires xformers, to use it, please install xformers.\")\n\n    def __call__(\n        self,\n        attn: Attention,\n        hidden_states: torch.Tensor,\n        encoder_hidden_states: Optional[torch.Tensor] = None,\n        attention_mask: Optional[torch.Tensor] = None,\n        temb: Optional[torch.Tensor] = None,\n        *args,\n        **kwargs,\n    ) -> torch.Tensor:\n        sp_group = self.sp_group\n        assert sp_group is not None, \"sp_group must be provided for MemEfficientRingAttnProcessor\"\n\n        residual = hidden_states\n        if attn.spatial_norm is not None:\n            hidden_states = attn.spatial_norm(hidden_states, temb)\n\n        input_ndim = hidden_states.ndim\n\n        if input_ndim == 4:\n            batch_size, channel, height, width = hidden_states.shape\n            hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)\n\n        batch_size, sequence_length, _ = (\n            hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape\n        )\n\n        if attention_mask is not None:\n            attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)\n            # scaled_dot_product_attention expects attention_mask shape to be\n            # (batch, heads, source_length, target_length)\n            attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])\n\n        if attn.group_norm is not None:\n            hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)\n\n        hidden_states = split_forward_gather_backward(hidden_states, 1, sp_group)\n\n        query = attn.to_q(hidden_states)\n\n        if encoder_hidden_states is None:\n            encoder_hidden_states = hidden_states\n        elif attn.norm_cross:\n            encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)\n\n        key = attn.to_k(encoder_hidden_states)\n        value = attn.to_v(encoder_hidden_states)\n\n        inner_dim = key.shape[-1]\n        head_dim = inner_dim // attn.heads\n\n        query = query.view(batch_size, -1, attn.heads, head_dim)\n\n        key = key.view(batch_size, -1, attn.heads, head_dim)\n        value = value.view(batch_size, -1, attn.heads, head_dim)\n\n        assert (\n            query.shape[1] % dist.get_world_size(sp_group) == 0\n        ), f\"sequence length ({query.shape[1]}) must be divisible by sp_group size ({dist.get_world_size(sp_group)})\"\n\n        hidden_states = MemEfficientRingAttention.attention(query, key, value, sp_group, attn_mask=attention_mask)\n\n        hidden_states = hidden_states.reshape(batch_size, -1, attn.heads * head_dim)\n        hidden_states = hidden_states.to(query.dtype)\n\n        # linear proj\n        hidden_states = attn.to_out[0](hidden_states)\n        # dropout\n        hidden_states = attn.to_out[1](hidden_states)\n\n        hidden_states = gather_forward_split_backward(hidden_states, 1, sp_group)\n\n        if input_ndim == 4:\n            hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)\n\n        if attn.residual_connection:\n            hidden_states = hidden_states + residual\n\n        hidden_states = hidden_states / attn.rescale_output_factor\n\n        return hidden_states\n\n\nclass ContextParallelAttention:\n    def __init__(self):\n        raise ImportError(f\"ContextParallelAttention should not be initialized directly.\")\n\n    @staticmethod\n    def from_native_module(module: Attention, process_group, *args, **kwargs) -> Attention:\n        \"\"\"\n        Convert a native RMSNorm module to colossalai layer norm module,\n        and optionally mark parameters for gradient aggregation.\n\n        Args:\n            module (nn.Module): The native RMSNorm module to be converted.\n            sp_partial_derived (bool): Whether this module's gradients are partially derived in sequence parallelism.\n\n        Returns:\n            nn.Module: The RMSNorm module.\n        \"\"\"\n\n        # Since gradients are computed using only a subset of the data,\n        # aggregation of these gradients is necessary during backpropagation.\n        # Therefore, we annotate these parameters in advance to indicate the need for gradient aggregation.\n        SeqParallelUtils.marked_as_sp_partial_derived_param(module.to_q.weight)\n        SeqParallelUtils.marked_as_sp_partial_derived_param(module.to_k.weight)\n        SeqParallelUtils.marked_as_sp_partial_derived_param(module.to_v.weight)\n\n        if module.to_q.bias is not None:\n            SeqParallelUtils.marked_as_sp_partial_derived_param(module.to_q.bias)\n            SeqParallelUtils.marked_as_sp_partial_derived_param(module.to_k.bias)\n            SeqParallelUtils.marked_as_sp_partial_derived_param(module.to_v.bias)\n\n        module.set_processor(MemEfficientRingAttnProcessor(process_group))\n\n        return module\n\n\ndef _context_chunk_attn_fwd(\n    q: torch.Tensor,\n    k: torch.Tensor,\n    v: torch.Tensor,\n    attn_bias: Optional[torch.Tensor],\n    scale: Optional[float],\n    seq_align: int = SEQ_ALIGN,\n    seq_limit: int = SEQ_LIMIT,\n):\n    seq_len = q.shape[1]\n    n_chunks = get_conv3d_n_chunks(seq_len, seq_align, seq_limit)\n    q_chunks, k_chunks, v_chunks = q.chunk(n_chunks, dim=1), k.chunk(n_chunks, dim=1), v.chunk(n_chunks, dim=1)\n    attn_bias_chunks = attn_bias.chunk(n_chunks, dim=2) if attn_bias is not None else [None] * n_chunks\n    out_chunks = []\n    lse_chunks = []\n    rng_states = []\n    for q_chunk, attn_bias_chunk in zip(q_chunks, attn_bias_chunks):\n        inner_attn_bias_chunks = (\n            attn_bias_chunk.chunk(n_chunks, dim=3) if attn_bias_chunk is not None else [None] * n_chunks\n        )\n        out_chunk = None\n        for k_chunk, v_chunk, inner_attn_bias_chunk in zip(k_chunks, v_chunks, inner_attn_bias_chunks):\n            block_out, block_lse, rng_state = _attn_fwd(q_chunk, k_chunk, v_chunk, inner_attn_bias_chunk, scale)\n            block_lse = block_lse.transpose(1, 2).unsqueeze(-1).contiguous().float()  # [B, N, S] -> [B, S, N, 1]\n            rng_states.append(rng_state)\n            if out_chunk is None:\n                out_chunk = block_out\n                lse_chunk = block_lse\n            else:\n                out_chunk, lse_chunk = _rescale_out_lse(out_chunk, block_out, lse_chunk, block_lse)\n            lse_chunk = lse_chunk.squeeze(-1).transpose(1, 2).contiguous()  # [B, S, N, 1] -> [B, N, S]\n        out_chunks.append(out_chunk)\n        lse_chunks.append(lse_chunk)\n    out = torch.cat(out_chunks, dim=1)\n    lse = torch.cat(lse_chunks, dim=-1)\n    return out, lse, rng_states\n\n\ndef _context_chunk_attn_bwd(\n    grad: torch.Tensor,\n    q: torch.Tensor,\n    k: torch.Tensor,\n    v: torch.Tensor,\n    out: torch.Tensor,\n    lse: torch.Tensor,\n    rng_states: torch.Tensor,\n    attn_bias: Optional[torch.Tensor] = None,\n    scale: Optional[float] = None,\n    seq_align: int = SEQ_ALIGN,\n    seq_limit: int = SEQ_LIMIT,\n    fast_accum: bool = False,\n):\n    seq_len = q.shape[1]\n    n_chunks = get_conv3d_n_chunks(seq_len, seq_align, seq_limit)\n    if n_chunks == 1:\n        return _attn_bwd(grad, q, k, v, out, lse, rng_states, attn_bias, scale)\n\n    q_chunks, k_chunks, v_chunks = q.chunk(n_chunks, dim=1), k.chunk(n_chunks, dim=1), v.chunk(n_chunks, dim=1)\n    attn_bias_chunks = attn_bias.chunk(n_chunks, dim=2) if attn_bias is not None else [None] * n_chunks\n    out_chunks = out.chunk(n_chunks, dim=1)\n    dout_chunks = grad.chunk(n_chunks, dim=1)\n    lse_chunks = lse.chunk(n_chunks, dim=-1)\n    if rng_states is None:\n        rng_states = [None] * (n_chunks * n_chunks)\n\n    i = 0\n\n    acc_dtype = q.dtype if fast_accum else torch.float\n\n    dq = torch.zeros_like(q, dtype=acc_dtype)\n    dk = torch.zeros_like(k, dtype=acc_dtype)\n    dv = torch.zeros_like(v, dtype=acc_dtype)\n\n    dq_chunks = dq.chunk(n_chunks, dim=1)\n    dk_chunks = dk.chunk(n_chunks, dim=1)\n    dv_chunks = dv.chunk(n_chunks, dim=1)\n\n    for q_idx in range(n_chunks):\n        q_chunk = q_chunks[q_idx]\n        attn_bias_chunk = attn_bias_chunks[q_idx]\n        inner_attn_bias_chunks = (\n            attn_bias_chunk.chunk(n_chunks, dim=3) if attn_bias_chunk is not None else [None] * n_chunks\n        )\n        out_chunk = out_chunks[q_idx]\n        dout_chunk = dout_chunks[q_idx]\n        lse_chunk = lse_chunks[q_idx]\n        dq_acc = dq_chunks[q_idx]\n\n        for kv_idx in range(n_chunks):\n            k_chunk = k_chunks[kv_idx]\n            v_chunk = v_chunks[kv_idx]\n            inner_attn_bias_chunk = inner_attn_bias_chunks[kv_idx]\n            dk_acc = dk_chunks[kv_idx]\n            dv_acc = dv_chunks[kv_idx]\n\n            block_dq, block_dk, block_dv = _attn_bwd(\n                dout_chunk, q_chunk, k_chunk, v_chunk, out_chunk, lse_chunk, rng_states[i], inner_attn_bias_chunk, scale\n            )\n\n            dq_acc += block_dq\n            dk_acc += block_dk\n            dv_acc += block_dv\n            i += 1\n\n    return dq.to(q.dtype), dk.to(k.dtype), dv.to(v.dtype)\n\n\ndef prepare_parallel_causal_attention_mask(\n    parallel_rank: int, parallel_size: int, n_frame: int, n_hw: int, dtype, device, batch_size: int = None\n):\n    seq_len = n_frame * n_hw\n    assert seq_len % parallel_size == 0, f\"seq_len {seq_len} must be divisible by parallel_size {parallel_size}\"\n    local_seq_len = seq_len // parallel_size\n    local_seq_start = local_seq_len * parallel_rank\n    if dtype is torch.bfloat16:\n        # A trick to avoid nan of memory efficient attention, maybe introduce some bias\n        fmin = torch.finfo(torch.float16).min\n    else:\n        fmin = torch.finfo(dtype).min\n    mask = torch.full((local_seq_len, seq_len), fmin, dtype=dtype, device=device)\n    for i in range(local_seq_len):\n        i_frame = (i + local_seq_start) // n_hw\n        mask[i, : (i_frame + 1) * n_hw] = 0\n    if batch_size is not None:\n        mask = mask.unsqueeze(0).expand(batch_size, -1, -1)\n    return mask\n\n\ndef prepare_parallel_attention_mask(\n    self, hidden_states: torch.Tensor, cp_group: dist.ProcessGroup = None\n) -> torch.Tensor:\n    B, C, T, H, W = hidden_states.shape\n    attention_mask = prepare_parallel_causal_attention_mask(\n        dist.get_rank(cp_group),\n        dist.get_world_size(cp_group),\n        T,\n        H * W,\n        hidden_states.dtype,\n        hidden_states.device,\n        batch_size=B,\n    )\n    return attention_mask\n\n\nclass TPUpDecoderBlockCausal3D(UpsampleCausal3D):\n    def __init__(\n        self,\n        channels,\n        out_channels=None,\n        kernel_size=3,\n        bias=True,\n        upsample_factor=(2, 2, 2),\n        tp_group=None,\n        split_input: bool = False,\n        split_output: bool = False,\n        conv_=None,\n        shortcut_=None,\n    ):\n        assert tp_group is not None, \"tp_group must be provided\"\n        super().__init__(channels, out_channels, kernel_size, bias, upsample_factor)\n        conv = conv_ if conv_ is not None else self.conv.conv\n        self.conv.conv = Conv3dTPRow.from_native_module(\n            conv, tp_group, split_input=split_input, split_output=split_output\n        )\n        self.tp_group = tp_group\n        tp_size = dist.get_world_size(group=self.tp_group)\n        assert self.channels % tp_size == 0, f\"channels {self.channels} must be divisible by tp_size {tp_size}\"\n        self.channels = self.channels // tp_size\n\n    def forward(self, input_tensor):\n        input_tensor = split_forward_gather_backward(input_tensor, 1, self.tp_group)\n        return super().forward(input_tensor)\n\n    def from_native_module(module: UpsampleCausal3D, process_group, **kwargs):\n        conv = module.conv.conv\n        return TPUpDecoderBlockCausal3D(\n            module.channels,\n            module.out_channels,\n            conv.kernel_size[0],\n            conv.bias is not None,\n            module.upsample_factor,\n            conv_=conv,\n            shortcut_=getattr(module, \"shortcut\", None),\n            tp_group=process_group,\n            **kwargs,\n        )\n"
  },
  {
    "path": "opensora/models/hunyuan_vae/policy.py",
    "content": "from functools import partial\nfrom typing import Dict, Union\n\nimport torch.nn as nn\nfrom colossalai.shardformer.policies.base_policy import ModulePolicyDescription, Policy, SubModuleReplacementDescription\n\nfrom opensora.models.vae.tensor_parallel import Conv3dTPCol, Conv3dTPRow, GroupNormTP\n\nfrom .distributed import ContextParallelAttention, TPUpDecoderBlockCausal3D, prepare_parallel_attention_mask\nfrom .vae import DecoderCausal3D, EncoderCausal3D\n\n\ndef gen_resnets_replacements(prefix: str, with_shortcut: bool = False):\n    replacements = [\n        SubModuleReplacementDescription(\n            suffix=f\"{prefix}.norm1\",\n            target_module=GroupNormTP,\n        ),\n        SubModuleReplacementDescription(\n            suffix=f\"{prefix}.conv1.conv\",\n            target_module=Conv3dTPRow,\n            kwargs=dict(\n                split_output=True,\n            ),\n        ),\n        SubModuleReplacementDescription(\n            suffix=f\"{prefix}.norm2\",\n            target_module=GroupNormTP,\n        ),\n        SubModuleReplacementDescription(\n            suffix=f\"{prefix}.conv2.conv\",\n            target_module=Conv3dTPRow,\n            kwargs=dict(\n                split_output=True,\n            ),\n        ),\n    ]\n    if with_shortcut:\n        replacements.append(\n            SubModuleReplacementDescription(\n                suffix=f\"{prefix}.conv_shortcut.conv\",\n                target_module=Conv3dTPRow,\n                kwargs=dict(\n                    split_output=True,\n                ),\n            )\n        )\n    return replacements\n\n\nclass HunyuanVaePolicy(Policy):\n    def config_sanity_check(self):\n        pass\n\n    def preprocess(self):\n        return self.model\n\n    def module_policy(self) -> Dict[Union[str, nn.Module], ModulePolicyDescription]:\n        policy = {}\n\n        policy[EncoderCausal3D] = ModulePolicyDescription(\n            sub_module_replacement=[\n                SubModuleReplacementDescription(\n                    suffix=\"conv_in.conv\",\n                    target_module=Conv3dTPCol,\n                ),\n                *gen_resnets_replacements(\"down_blocks[0].resnets[0]\"),\n                *gen_resnets_replacements(\"down_blocks[0].resnets[1]\"),\n                SubModuleReplacementDescription(\n                    suffix=\"down_blocks[0].downsamplers[0].conv.conv\",\n                    target_module=Conv3dTPRow,\n                    kwargs=dict(\n                        split_output=True,\n                    ),\n                ),\n                *gen_resnets_replacements(\"down_blocks[1].resnets[0]\", with_shortcut=True),\n                *gen_resnets_replacements(\"down_blocks[1].resnets[1]\"),\n                SubModuleReplacementDescription(\n                    suffix=\"down_blocks[1].downsamplers[0].conv.conv\",\n                    target_module=Conv3dTPRow,\n                ),\n                SubModuleReplacementDescription(\n                    suffix=\"mid_block.attentions[0]\",\n                    target_module=ContextParallelAttention,\n                ),\n            ],\n            attribute_replacement={\n                \"down_blocks[0].downsamplers[0].channels\": self.model.encoder.down_blocks[0].downsamplers[0].channels\n                // self.shard_config.tensor_parallel_size,\n                \"down_blocks[1].downsamplers[0].channels\": self.model.encoder.down_blocks[1].downsamplers[0].channels\n                // self.shard_config.tensor_parallel_size,\n                # \"mid_block.attentions[0].processor\": MemEfficientRingAttnProcessor(\n                #     self.shard_config.tensor_parallel_process_group\n                # ),\n            },\n            method_replacement={\n                \"prepare_attention_mask\": partial(\n                    prepare_parallel_attention_mask, cp_group=self.shard_config.tensor_parallel_process_group\n                ),\n            },\n        )\n\n        policy[DecoderCausal3D] = ModulePolicyDescription(\n            sub_module_replacement=[\n                SubModuleReplacementDescription(\n                    suffix=\"up_blocks[1].upsamplers[0]\",\n                    target_module=TPUpDecoderBlockCausal3D,\n                    kwargs=dict(\n                        split_output=True,\n                    ),\n                ),\n                *gen_resnets_replacements(\"up_blocks[2].resnets[0]\", with_shortcut=True),\n                *gen_resnets_replacements(\"up_blocks[2].resnets[1]\"),\n                *gen_resnets_replacements(\"up_blocks[2].resnets[2]\"),\n                SubModuleReplacementDescription(\n                    suffix=\"up_blocks[2].upsamplers[0].conv.conv\",\n                    target_module=Conv3dTPRow,\n                    kwargs=dict(\n                        split_output=True,\n                    ),\n                ),\n                *gen_resnets_replacements(\"up_blocks[3].resnets[0]\", with_shortcut=True),\n                *gen_resnets_replacements(\"up_blocks[3].resnets[1]\"),\n                *gen_resnets_replacements(\"up_blocks[3].resnets[2]\"),\n                SubModuleReplacementDescription(\n                    suffix=\"conv_norm_out\",\n                    target_module=GroupNormTP,\n                ),\n                SubModuleReplacementDescription(\n                    suffix=\"conv_out.conv\",\n                    target_module=Conv3dTPRow,\n                ),\n                SubModuleReplacementDescription(\n                    suffix=\"mid_block.attentions[0]\",\n                    target_module=ContextParallelAttention,\n                ),\n            ],\n            attribute_replacement={\n                \"up_blocks[2].upsamplers[0].channels\": self.model.decoder.up_blocks[2].upsamplers[0].channels\n                // self.shard_config.tensor_parallel_size,\n                # \"mid_block.attentions[0].processor\": MemEfficientRingAttnProcessor(\n                #     self.shard_config.tensor_parallel_process_group\n                # ),\n            },\n            method_replacement={\n                \"prepare_attention_mask\": partial(\n                    prepare_parallel_attention_mask, cp_group=self.shard_config.tensor_parallel_process_group\n                ),\n            },\n        )\n\n        return policy\n\n    def postprocess(self):\n        return self.model\n"
  },
  {
    "path": "opensora/models/hunyuan_vae/unet_causal_3d_blocks.py",
    "content": "# Modified from diffusers==0.29.2 and HunyuanVideo\n# \n# Copyright 2024 The HuggingFace Team. All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# # \n# Copyright 2024 HunyuanVideo\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\nfrom typing import Optional, Tuple, Union\n\nimport numpy as np\nimport torch\nimport torch.nn.functional as F\nfrom diffusers.models.activations import get_activation\nfrom diffusers.models.attention_processor import Attention\nfrom diffusers.utils import logging\nfrom einops import rearrange\nfrom torch import nn\n\nfrom opensora.acceleration.checkpoint import auto_grad_checkpoint\nfrom opensora.models.vae.utils import ChannelChunkConv3d, get_conv3d_n_chunks\n\nlogger = logging.get_logger(__name__)  # pylint: disable=invalid-name\n\nINTERPOLATE_NUMEL_LIMIT = 2**31 - 1\n\n\ndef chunk_nearest_interpolate(\n    x: torch.Tensor,\n    scale_factor,\n):\n    limit = INTERPOLATE_NUMEL_LIMIT // np.prod(scale_factor)\n    n_chunks = get_conv3d_n_chunks(x.numel(), x.size(1), limit)\n    x_chunks = x.chunk(n_chunks, dim=1)\n    x_chunks = [F.interpolate(x_chunk, scale_factor=scale_factor, mode=\"nearest\") for x_chunk in x_chunks]\n    return torch.cat(x_chunks, dim=1)\n\n\ndef prepare_causal_attention_mask(n_frame: int, n_hw: int, dtype, device, batch_size: int = None):\n    seq_len = n_frame * n_hw\n    mask = torch.full((seq_len, seq_len), float(\"-inf\"), dtype=dtype, device=device)\n    for i in range(seq_len):\n        i_frame = i // n_hw\n        mask[i, : (i_frame + 1) * n_hw] = 0\n    if batch_size is not None:\n        mask = mask.unsqueeze(0).expand(batch_size, -1, -1)\n    return mask\n\n\nclass CausalConv3d(nn.Module):\n    \"\"\"\n    Implements a causal 3D convolution layer where each position only depends on previous timesteps and current spatial locations.\n    This maintains temporal causality in video generation tasks.\n    \"\"\"\n\n    def __init__(\n        self,\n        chan_in,\n        chan_out,\n        kernel_size: Union[int, Tuple[int, int, int]],\n        stride: Union[int, Tuple[int, int, int]] = 1,\n        dilation: Union[int, Tuple[int, int, int]] = 1,\n        pad_mode=\"replicate\",\n        **kwargs,\n    ):\n        super().__init__()\n\n        self.pad_mode = pad_mode\n        padding = (\n            kernel_size // 2,\n            kernel_size // 2,\n            kernel_size // 2,\n            kernel_size // 2,\n            kernel_size - 1,\n            0,\n        )  # W, H, T\n        self.time_causal_padding = padding\n\n        self.conv = ChannelChunkConv3d(chan_in, chan_out, kernel_size, stride=stride, dilation=dilation, **kwargs)\n\n    def forward(self, x):\n        x = F.pad(x, self.time_causal_padding, mode=self.pad_mode)\n        return self.conv(x)\n\nclass UpsampleCausal3D(nn.Module):\n    \"\"\"\n    A 3D upsampling layer with an optional convolution.\n    \"\"\"\n\n    def __init__(\n        self,\n        channels: int,\n        out_channels: Optional[int] = None,\n        kernel_size: int = 3,\n        bias=True,\n        upsample_factor=(2, 2, 2),\n    ):\n        super().__init__()\n        self.channels = channels\n        self.out_channels = out_channels or channels\n        self.upsample_factor = upsample_factor\n        self.conv = CausalConv3d(self.channels, self.out_channels, kernel_size=kernel_size, bias=bias)\n\n    def forward(\n        self,\n        input_tensor: torch.FloatTensor,\n    ) -> torch.FloatTensor:\n        assert input_tensor.shape[1] == self.channels\n\n        #######################\n        # handle hidden states\n        #######################\n        hidden_states = input_tensor\n        # Cast to float32 to as 'upsample_nearest2d_out_frame' op does not support bfloat16\n        # dtype = hidden_states.dtype\n        # if dtype == torch.bfloat16:\n        #     hidden_states = hidden_states.to(torch.float32)\n\n        # upsample_nearest_nhwc fails with large batch sizes. see https://github.com/huggingface/diffusers/issues/984\n        if hidden_states.shape[0] >= 64:\n            hidden_states = hidden_states.contiguous()\n\n        # interpolate H & W only for the first frame; interpolate T & H & W for the rest\n        T = hidden_states.size(2)\n        first_h, other_h = hidden_states.split((1, T - 1), dim=2)\n        # process non-1st frames\n        if T > 1:\n            other_h = chunk_nearest_interpolate(other_h, scale_factor=self.upsample_factor)\n        # proess 1st fram\n        first_h = first_h.squeeze(2)\n        first_h = chunk_nearest_interpolate(first_h, scale_factor=self.upsample_factor[1:])\n        first_h = first_h.unsqueeze(2)\n        # concat together\n        if T > 1:\n            hidden_states = torch.cat((first_h, other_h), dim=2)\n        else:\n            hidden_states = first_h\n\n        # If the input is bfloat16, we cast back to bfloat16\n        # if dtype == torch.bfloat16:\n        #     hidden_states = hidden_states.to(dtype)\n\n        hidden_states = self.conv(hidden_states)\n\n        return hidden_states\n\nclass DownsampleCausal3D(nn.Module):\n    \"\"\"\n    A 3D downsampling layer with an optional convolution.\n    \"\"\"\n\n    def __init__(\n        self,\n        channels: int,\n        kernel_size=3,\n        bias=True,\n        stride=2,\n    ):\n        super().__init__()\n        self.channels = channels\n        self.out_channels = channels\n        self.conv = CausalConv3d(self.channels, self.out_channels, kernel_size=kernel_size, stride=stride, bias=bias)\n\n    def forward(self, input_tensor: torch.FloatTensor) -> torch.FloatTensor:\n        assert input_tensor.shape[1] == self.channels\n        hidden_states = self.conv(input_tensor)\n\n        return hidden_states\n\n\nclass ResnetBlockCausal3D(nn.Module):\n    r\"\"\"\n    A Resnet block.\n    \"\"\"\n\n    def __init__(\n        self,\n        *,\n        in_channels: int,\n        out_channels: Optional[int] = None,\n        dropout: float = 0.0,\n        groups: int = 32,\n        groups_out: Optional[int] = None,\n        pre_norm: bool = True,\n        eps: float = 1e-6,\n        non_linearity: str = \"swish\",\n        output_scale_factor: float = 1.0,\n        use_in_shortcut: Optional[bool] = None,\n        conv_shortcut_bias: bool = True,\n        conv_3d_out_channels: Optional[int] = None,\n    ):\n        super().__init__()\n        self.pre_norm = pre_norm\n        self.pre_norm = True\n        self.in_channels = in_channels\n        out_channels = in_channels if out_channels is None else out_channels\n        self.out_channels = out_channels\n        self.output_scale_factor = output_scale_factor\n\n        if groups_out is None:\n            groups_out = groups\n\n        self.norm1 = torch.nn.GroupNorm(num_groups=groups, num_channels=in_channels, eps=eps, affine=True)\n        self.conv1 = CausalConv3d(in_channels, out_channels, kernel_size=3, stride=1)\n        self.norm2 = torch.nn.GroupNorm(num_groups=groups_out, num_channels=out_channels, eps=eps, affine=True)\n\n        self.dropout = torch.nn.Dropout(dropout)\n        conv_3d_out_channels = conv_3d_out_channels or out_channels\n        self.conv2 = CausalConv3d(out_channels, conv_3d_out_channels, kernel_size=3, stride=1)\n\n        self.nonlinearity = get_activation(non_linearity)\n\n        self.upsample = self.downsample = None\n\n        self.use_in_shortcut = self.in_channels != conv_3d_out_channels if use_in_shortcut is None else use_in_shortcut\n\n        self.conv_shortcut = None\n        if self.use_in_shortcut:\n            self.conv_shortcut = CausalConv3d(\n                in_channels,\n                conv_3d_out_channels,\n                kernel_size=1,\n                stride=1,\n                bias=conv_shortcut_bias,\n            )\n\n    def forward(\n        self,\n        input_tensor: torch.FloatTensor,\n    ) -> torch.FloatTensor:\n        hidden_states = input_tensor\n\n        hidden_states = self.norm1(hidden_states)\n        hidden_states = self.nonlinearity(hidden_states)\n        hidden_states = self.conv1(hidden_states)\n        hidden_states = self.norm2(hidden_states)\n        hidden_states = self.nonlinearity(hidden_states)\n        hidden_states = self.dropout(hidden_states)\n        hidden_states = self.conv2(hidden_states)\n\n        if self.conv_shortcut is not None:\n            input_tensor = self.conv_shortcut(input_tensor)\n\n        output_tensor = (input_tensor + hidden_states) / self.output_scale_factor\n\n        return output_tensor\n\n\nclass UNetMidBlockCausal3D(nn.Module):\n    \"\"\"\n    A 3D UNet mid-block [`UNetMidBlockCausal3D`] with multiple residual blocks and optional attention blocks.\n    \"\"\"\n\n    def __init__(\n        self,\n        in_channels: int,\n        dropout: float = 0.0,\n        num_layers: int = 1,\n        resnet_eps: float = 1e-6,\n        resnet_act_fn: str = \"swish\",\n        resnet_groups: int = 32,\n        attn_groups: Optional[int] = None,\n        resnet_pre_norm: bool = True,\n        add_attention: bool = True,\n        attention_head_dim: int = 1,\n        output_scale_factor: float = 1.0,\n    ):\n        super().__init__()\n        resnet_groups = resnet_groups if resnet_groups is not None else min(in_channels // 4, 32)\n        self.add_attention = add_attention\n\n        if attn_groups is None:\n            attn_groups = resnet_groups\n\n        # there is always at least one resnet\n        resnets = [\n            ResnetBlockCausal3D(\n                in_channels=in_channels,\n                out_channels=in_channels,\n                eps=resnet_eps,\n                groups=resnet_groups,\n                dropout=dropout,\n                non_linearity=resnet_act_fn,\n                output_scale_factor=output_scale_factor,\n                pre_norm=resnet_pre_norm,\n            )\n        ]\n        attentions = []\n\n        if attention_head_dim is None:\n            logger.warn(\n                f\"It is not recommend to pass `attention_head_dim=None`. Defaulting `attention_head_dim` to `in_channels`: {in_channels}.\"\n            )\n            attention_head_dim = in_channels\n\n        for _ in range(num_layers):\n            if self.add_attention:\n                attentions.append(\n                    Attention(\n                        in_channels,\n                        heads=in_channels // attention_head_dim,\n                        dim_head=attention_head_dim,\n                        rescale_output_factor=output_scale_factor,\n                        eps=resnet_eps,\n                        norm_num_groups=attn_groups,\n                        spatial_norm_dim=None,\n                        residual_connection=True,\n                        bias=True,\n                        upcast_softmax=True,\n                        _from_deprecated_attn_block=True,\n                    )\n                )\n            else:\n                attentions.append(None)\n\n            resnets.append(\n                ResnetBlockCausal3D(\n                    in_channels=in_channels,\n                    out_channels=in_channels,\n                    eps=resnet_eps,\n                    groups=resnet_groups,\n                    dropout=dropout,\n                    non_linearity=resnet_act_fn,\n                    output_scale_factor=output_scale_factor,\n                    pre_norm=resnet_pre_norm,\n                )\n            )\n\n        self.attentions = nn.ModuleList(attentions)\n        self.resnets = nn.ModuleList(resnets)\n\n    def forward(self, hidden_states: torch.FloatTensor, attention_mask: Optional[torch.Tensor]) -> torch.FloatTensor:\n        hidden_states = self.resnets[0](hidden_states)\n        for attn, resnet in zip(self.attentions, self.resnets[1:]):\n            if attn is not None:\n                B, C, T, H, W = hidden_states.shape\n                hidden_states = rearrange(hidden_states, \"b c f h w -> b (f h w) c\")\n                hidden_states = attn(hidden_states, attention_mask=attention_mask)\n                hidden_states = rearrange(hidden_states, \"b (f h w) c -> b c f h w\", f=T, h=H, w=W)\n            hidden_states = resnet(hidden_states)\n\n        return hidden_states\n\n\nclass DownEncoderBlockCausal3D(nn.Module):\n    def __init__(\n        self,\n        in_channels: int,\n        out_channels: int,\n        dropout: float = 0.0,\n        num_layers: int = 1,\n        resnet_eps: float = 1e-6,\n        resnet_act_fn: str = \"swish\",\n        resnet_groups: int = 32,\n        resnet_pre_norm: bool = True,\n        output_scale_factor: float = 1.0,\n        add_downsample: bool = True,\n        downsample_stride: int = 2,\n    ):\n        super().__init__()\n        resnets = []\n\n        for i in range(num_layers):\n            in_channels = in_channels if i == 0 else out_channels\n            resnets.append(\n                ResnetBlockCausal3D(\n                    in_channels=in_channels,\n                    out_channels=out_channels,\n                    eps=resnet_eps,\n                    groups=resnet_groups,\n                    dropout=dropout,\n                    non_linearity=resnet_act_fn,\n                    output_scale_factor=output_scale_factor,\n                    pre_norm=resnet_pre_norm,\n                )\n            )\n\n        self.resnets = nn.ModuleList(resnets)\n\n        if add_downsample:\n            self.downsamplers = nn.ModuleList(\n                [\n                    DownsampleCausal3D(\n                        out_channels,\n                        stride=downsample_stride,\n                    )\n                ]\n            )\n        else:\n            self.downsamplers = None\n\n    def forward(self, hidden_states: torch.FloatTensor) -> torch.FloatTensor:\n        for resnet in self.resnets:\n            hidden_states = auto_grad_checkpoint(resnet, hidden_states)\n\n        if self.downsamplers is not None:\n            for downsampler in self.downsamplers:\n                hidden_states = auto_grad_checkpoint(downsampler, hidden_states)\n\n        return hidden_states\n\n\nclass UpDecoderBlockCausal3D(nn.Module):\n    def __init__(\n        self,\n        in_channels: int,\n        out_channels: int,\n        resolution_idx: Optional[int] = None,\n        dropout: float = 0.0,\n        num_layers: int = 1,\n        resnet_eps: float = 1e-6,\n        resnet_act_fn: str = \"swish\",\n        resnet_groups: int = 32,\n        resnet_pre_norm: bool = True,\n        output_scale_factor: float = 1.0,\n        add_upsample: bool = True,\n        upsample_scale_factor=(2, 2, 2),\n    ):\n        super().__init__()\n        resnets = []\n\n        for i in range(num_layers):\n            input_channels = in_channels if i == 0 else out_channels\n\n            resnets.append(\n                ResnetBlockCausal3D(\n                    in_channels=input_channels,\n                    out_channels=out_channels,\n                    eps=resnet_eps,\n                    groups=resnet_groups,\n                    dropout=dropout,\n                    non_linearity=resnet_act_fn,\n                    output_scale_factor=output_scale_factor,\n                    pre_norm=resnet_pre_norm,\n                )\n            )\n\n        self.resnets = nn.ModuleList(resnets)\n\n        if add_upsample:\n            self.upsamplers = nn.ModuleList(\n                [\n                    UpsampleCausal3D(\n                        out_channels,\n                        out_channels=out_channels,\n                        upsample_factor=upsample_scale_factor,\n                    )\n                ]\n            )\n        else:\n            self.upsamplers = None\n\n        self.resolution_idx = resolution_idx\n\n    def forward(self, hidden_states: torch.FloatTensor) -> torch.FloatTensor:\n        for resnet in self.resnets:\n            hidden_states = auto_grad_checkpoint(resnet, hidden_states)\n\n        if self.upsamplers is not None:\n            for upsampler in self.upsamplers:\n                hidden_states = auto_grad_checkpoint(upsampler, hidden_states)\n\n        return hidden_states\n"
  },
  {
    "path": "opensora/models/hunyuan_vae/vae.py",
    "content": "# Modified from HunyuanVideo\n# \n# Copyright 2024 HunyuanVideo\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\nfrom dataclasses import dataclass\nfrom typing import Optional, Tuple\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\nfrom diffusers.utils import BaseOutput\nfrom diffusers.utils.torch_utils import randn_tensor\n\nfrom opensora.acceleration.checkpoint import auto_grad_checkpoint, checkpoint\nfrom opensora.models.hunyuan_vae.unet_causal_3d_blocks import (\n    CausalConv3d,\n    DownEncoderBlockCausal3D,\n    UNetMidBlockCausal3D,\n    UpDecoderBlockCausal3D,\n    prepare_causal_attention_mask,\n)\n\n\n@dataclass\nclass DecoderOutput(BaseOutput):\n    r\"\"\"\n    Output of decoding method.\n\n    Args:\n        sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n            The decoded output sample from the last layer of the model.\n    \"\"\"\n\n    sample: torch.FloatTensor\n\n\nclass EncoderCausal3D(nn.Module):\n    r\"\"\"\n    The `EncoderCausal3D` layer of a variational autoencoder that encodes its input into a latent representation.\n    \"\"\"\n\n    def __init__(\n        self,\n        in_channels: int = 3,\n        out_channels: int = 3,\n        block_out_channels: Tuple[int, ...] = (64,),\n        layers_per_block: int = 2,\n        norm_num_groups: int = 32,\n        act_fn: str = \"silu\",\n        double_z: bool = True,\n        mid_block_add_attention=True,\n        time_compression_ratio: int = 4,\n        spatial_compression_ratio: int = 8,\n        dropout: float = 0.0,\n    ):\n        super().__init__()\n        self.layers_per_block = layers_per_block\n\n        self.conv_in = CausalConv3d(in_channels, block_out_channels[0], kernel_size=3, stride=1)\n        self.mid_block = None\n        self.down_blocks = nn.ModuleList([])\n\n        # down\n        output_channel = block_out_channels[0]\n        for i, _ in enumerate(block_out_channels):\n            input_channel = output_channel\n            output_channel = block_out_channels[i]\n            is_final_block = i == len(block_out_channels) - 1\n            num_spatial_downsample_layers = int(np.log2(spatial_compression_ratio))\n            num_time_downsample_layers = int(np.log2(time_compression_ratio))\n\n            if time_compression_ratio == 4:\n                add_spatial_downsample = bool(i < num_spatial_downsample_layers)\n                add_time_downsample = bool(\n                    i >= (len(block_out_channels) - 1 - num_time_downsample_layers) and not is_final_block\n                )\n            elif time_compression_ratio == 8:\n                add_spatial_downsample = bool(i < num_spatial_downsample_layers)\n                add_time_downsample = bool(i < num_spatial_downsample_layers)\n            else:\n                raise ValueError(f\"Unsupported time_compression_ratio: {time_compression_ratio}.\")\n\n            downsample_stride_HW = (2, 2) if add_spatial_downsample else (1, 1)\n            downsample_stride_T = (2,) if add_time_downsample else (1,)\n            downsample_stride = tuple(downsample_stride_T + downsample_stride_HW)\n            down_block = DownEncoderBlockCausal3D(\n                num_layers=self.layers_per_block,\n                in_channels=input_channel,\n                out_channels=output_channel,\n                dropout=dropout,\n                add_downsample=bool(add_spatial_downsample or add_time_downsample),\n                downsample_stride=downsample_stride,\n                resnet_eps=1e-6,\n                resnet_act_fn=act_fn,\n                resnet_groups=norm_num_groups,\n            )\n\n            self.down_blocks.append(down_block)\n\n        # mid\n        self.mid_block = UNetMidBlockCausal3D(\n            in_channels=block_out_channels[-1],\n            resnet_eps=1e-6,\n            resnet_act_fn=act_fn,\n            output_scale_factor=1,\n            attention_head_dim=block_out_channels[-1],\n            resnet_groups=norm_num_groups,\n            add_attention=mid_block_add_attention,\n        )\n\n        # out\n        self.conv_norm_out = nn.GroupNorm(num_channels=block_out_channels[-1], num_groups=norm_num_groups, eps=1e-6)\n        self.conv_act = nn.SiLU()\n\n        conv_out_channels = 2 * out_channels if double_z else out_channels\n        self.conv_out = CausalConv3d(block_out_channels[-1], conv_out_channels, kernel_size=3)\n\n    def prepare_attention_mask(self, hidden_states: torch.Tensor) -> torch.Tensor:\n        B, C, T, H, W = hidden_states.shape\n        attention_mask = prepare_causal_attention_mask(\n            T, H * W, hidden_states.dtype, hidden_states.device, batch_size=B\n        )\n        return attention_mask\n\n    def forward(self, sample: torch.FloatTensor) -> torch.FloatTensor:\n        r\"\"\"The forward method of the `EncoderCausal3D` class.\"\"\"\n        assert len(sample.shape) == 5, \"The input tensor should have 5 dimensions\"\n\n        sample = self.conv_in(sample)\n\n        # down\n        for down_block in self.down_blocks:\n            sample = down_block(sample)\n\n        # middle\n        if self.mid_block.add_attention:\n            attention_mask = self.prepare_attention_mask(sample)\n        else:\n            attention_mask = None\n        sample = auto_grad_checkpoint(self.mid_block, sample, attention_mask)\n\n        # post-process\n        sample = self.conv_norm_out(sample)\n        sample = self.conv_act(sample)\n        sample = self.conv_out(sample)\n\n        return sample\n\n\nclass DecoderCausal3D(nn.Module):\n    r\"\"\"\n    The `DecoderCausal3D` layer of a variational autoencoder that decodes its latent representation into an output sample.\n    \"\"\"\n\n    def __init__(\n        self,\n        in_channels: int = 3,\n        out_channels: int = 3,\n        block_out_channels: Tuple[int, ...] = (64,),\n        layers_per_block: int = 2,\n        norm_num_groups: int = 32,\n        act_fn: str = \"silu\",\n        mid_block_add_attention=True,\n        time_compression_ratio: int = 4,\n        spatial_compression_ratio: int = 8,\n        dropout: float = 0.0,\n    ):\n        super().__init__()\n        self.layers_per_block = layers_per_block\n\n        self.conv_in = CausalConv3d(in_channels, block_out_channels[-1], kernel_size=3, stride=1)\n        self.mid_block = None\n        self.up_blocks = nn.ModuleList([])\n\n        # mid\n        self.mid_block = UNetMidBlockCausal3D(\n            in_channels=block_out_channels[-1],\n            resnet_eps=1e-6,\n            resnet_act_fn=act_fn,\n            output_scale_factor=1,\n            attention_head_dim=block_out_channels[-1],\n            resnet_groups=norm_num_groups,\n            add_attention=mid_block_add_attention,\n        )\n\n        # up\n        reversed_block_out_channels = list(reversed(block_out_channels))\n        output_channel = reversed_block_out_channels[0]\n        for i, _ in enumerate(block_out_channels):\n            prev_output_channel = output_channel\n            output_channel = reversed_block_out_channels[i]\n            is_final_block = i == len(block_out_channels) - 1\n            num_spatial_upsample_layers = int(np.log2(spatial_compression_ratio))\n            num_time_upsample_layers = int(np.log2(time_compression_ratio))\n\n            if time_compression_ratio == 4:\n                add_spatial_upsample = bool(i < num_spatial_upsample_layers)\n                add_time_upsample = bool(\n                    i >= len(block_out_channels) - 1 - num_time_upsample_layers and not is_final_block\n                )\n            elif time_compression_ratio == 8:\n                add_spatial_upsample = bool(i < num_spatial_upsample_layers)\n                add_time_upsample = bool(i < num_spatial_upsample_layers)\n            else:\n                raise ValueError(f\"Unsupported time_compression_ratio: {time_compression_ratio}.\")\n\n            upsample_scale_factor_HW = (2, 2) if add_spatial_upsample else (1, 1)\n            upsample_scale_factor_T = (2,) if add_time_upsample else (1,)\n            upsample_scale_factor = tuple(upsample_scale_factor_T + upsample_scale_factor_HW)\n            up_block = UpDecoderBlockCausal3D(\n                num_layers=self.layers_per_block + 1,\n                in_channels=prev_output_channel,\n                out_channels=output_channel,\n                resolution_idx=None,\n                dropout=dropout,\n                add_upsample=bool(add_spatial_upsample or add_time_upsample),\n                upsample_scale_factor=upsample_scale_factor,\n                resnet_eps=1e-6,\n                resnet_act_fn=act_fn,\n                resnet_groups=norm_num_groups,\n            )\n\n            self.up_blocks.append(up_block)\n            prev_output_channel = output_channel\n\n        self.conv_norm_out = nn.GroupNorm(num_channels=block_out_channels[0], num_groups=norm_num_groups, eps=1e-6)\n        self.conv_act = nn.SiLU()\n        self.conv_out = CausalConv3d(block_out_channels[0], out_channels, kernel_size=3)\n\n    def post_process(self, sample: torch.Tensor) -> torch.Tensor:\n        sample = self.conv_norm_out(sample)\n        sample = self.conv_act(sample)\n        return sample\n\n    def prepare_attention_mask(self, hidden_states: torch.Tensor) -> torch.Tensor:\n        B, C, T, H, W = hidden_states.shape\n        attention_mask = prepare_causal_attention_mask(\n            T, H * W, hidden_states.dtype, hidden_states.device, batch_size=B\n        )\n        return attention_mask\n\n    def forward(\n        self,\n        sample: torch.FloatTensor,\n    ) -> torch.FloatTensor:\n        r\"\"\"The forward method of the `DecoderCausal3D` class.\"\"\"\n        assert len(sample.shape) == 5, \"The input tensor should have 5 dimensions.\"\n\n        sample = self.conv_in(sample)\n\n        upscale_dtype = next(iter(self.up_blocks.parameters())).dtype\n\n        # middle\n        if self.mid_block.add_attention:\n            attention_mask = self.prepare_attention_mask(sample)\n        else:\n            attention_mask = None\n\n        sample = auto_grad_checkpoint(self.mid_block, sample, attention_mask)\n        sample = sample.to(upscale_dtype)\n\n        # up\n        for up_block in self.up_blocks:\n            sample = up_block(sample)\n\n        # post-process\n        if getattr(self, \"grad_checkpointing\", False):\n            sample = checkpoint(self.post_process, sample, use_reentrant=True)\n        else:\n            sample = self.post_process(sample)\n\n        sample = self.conv_out(sample)\n\n        return sample\n\n\nclass DiagonalGaussianDistribution(object):\n    def __init__(self, parameters: torch.Tensor, deterministic: bool = False):\n        if parameters.ndim == 3:\n            dim = 2  # (B, L, C)\n        elif parameters.ndim == 5 or parameters.ndim == 4:\n            dim = 1  # (B, C, T, H ,W) / (B, C, H, W)\n        else:\n            raise NotImplementedError\n        self.parameters = parameters\n        self.mean, self.logvar = torch.chunk(parameters, 2, dim=dim)\n        self.logvar = torch.clamp(self.logvar, -30.0, 20.0)\n        self.deterministic = deterministic\n        self.std = torch.exp(0.5 * self.logvar)\n        self.var = torch.exp(self.logvar)\n        if self.deterministic:\n            self.var = self.std = torch.zeros_like(\n                self.mean, device=self.parameters.device, dtype=self.parameters.dtype\n            )\n\n    def sample(self, generator: Optional[torch.Generator] = None) -> torch.FloatTensor:\n        # make sure sample is on the same device as the parameters and has same dtype\n        sample = randn_tensor(\n            self.mean.shape,\n            generator=generator,\n            device=self.parameters.device,\n            dtype=self.parameters.dtype,\n        )\n        x = self.mean + self.std * sample\n        return x\n\n    def kl(self, other: \"DiagonalGaussianDistribution\" = None) -> torch.Tensor:\n        if self.deterministic:\n            return torch.Tensor([0.0])\n        else:\n            reduce_dim = list(range(1, self.mean.ndim))\n            if other is None:\n                return 0.5 * torch.sum(\n                    torch.pow(self.mean, 2) + self.var - 1.0 - self.logvar,\n                    dim=reduce_dim,\n                )\n            else:\n                return 0.5 * torch.sum(\n                    torch.pow(self.mean - other.mean, 2) / other.var\n                    + self.var / other.var\n                    - 1.0\n                    - self.logvar\n                    + other.logvar,\n                    dim=reduce_dim,\n                )\n\n    def nll(self, sample: torch.Tensor, dims: Tuple[int, ...] = [1, 2, 3]) -> torch.Tensor:\n        if self.deterministic:\n            return torch.Tensor([0.0])\n        logtwopi = np.log(2.0 * np.pi)\n        return 0.5 * torch.sum(\n            logtwopi + self.logvar + torch.pow(sample - self.mean, 2) / self.var,\n            dim=dims,\n        )\n\n    def mode(self) -> torch.Tensor:\n        return self.mean\n"
  },
  {
    "path": "opensora/models/mmdit/__init__.py",
    "content": "from .model import Flux\n"
  },
  {
    "path": "opensora/models/mmdit/distributed.py",
    "content": "from functools import partial\nfrom typing import Dict, List, Optional, Tuple, Union\n\nimport torch\nimport torch.distributed as dist\nimport torch.nn as nn\nfrom colossalai.shardformer.layer import (FusedLinear1D_Col, FusedLinear1D_Row,\n                                          Linear1D_Col, Linear1D_Row)\nfrom colossalai.shardformer.layer._operation import all_to_all_comm\nfrom colossalai.shardformer.layer.attn import RingComm, _rescale_out_lse\nfrom colossalai.shardformer.layer.utils import is_share_sp_tp\nfrom colossalai.shardformer.policies.base_policy import (\n    ModulePolicyDescription, Policy, SubModuleReplacementDescription)\nfrom colossalai.shardformer.shard import ShardConfig\nfrom einops import rearrange\nfrom flash_attn.flash_attn_interface import (_flash_attn_backward,\n                                             _flash_attn_forward)\nfrom liger_kernel.ops.rope import LigerRopeFunction\n\ntry:\n    from flash_attn_interface import \\\n        _flash_attn_backward as _flash_attn_backward_v3\n    from flash_attn_interface import \\\n        _flash_attn_forward as _flash_attn_forward_v3\n\n    SUPPORT_FA3 = True\nexcept:\n    SUPPORT_FA3 = False\n\nfrom torch import Tensor\n\nfrom opensora.acceleration.checkpoint import auto_grad_checkpoint\n\nfrom .layers import DoubleStreamBlock, SingleStreamBlock\nfrom .math import apply_rope, attention\nfrom .model import MMDiTModel\n\n\nclass _SplitForwardGatherBackwardVarLen(torch.autograd.Function):\n    \"\"\"\n    Split the input and keep only the corresponding chuck to the rank.\n\n    Args:\n        input_ (`torch.Tensor`): input matrix.\n        dim (int): the dimension to perform split and gather\n        process_group (`torch.distributed.ProcessGroup`): the process group used for collective communication\n\n    \"\"\"\n\n    @staticmethod\n    def forward(ctx, input_, dim, process_group, splits: List[int]):\n        ctx.process_group = process_group\n        ctx.dim = dim\n        rank = dist.get_rank(process_group)\n        ctx.grad_scale = splits[rank] / sum(splits)\n        ctx.splits = splits\n        return torch.split(input_, splits, dim=dim)[rank].clone()\n\n    @staticmethod\n    def backward(ctx, grad_output):\n        grad_output = grad_output * ctx.grad_scale\n        grad_output = grad_output.contiguous()\n        world_size = dist.get_world_size(ctx.process_group)\n        shapes = [list(grad_output.shape) for _ in range(world_size)]\n        for i, shape in enumerate(shapes):\n            shape[ctx.dim] = ctx.splits[i]\n        tensor_list = [torch.empty(shape, dtype=grad_output.dtype, device=grad_output.device) for shape in shapes]\n        dist.all_gather(tensor_list, grad_output, group=ctx.process_group)\n        return torch.cat(tensor_list, dim=ctx.dim), None, None, None\n\n\ndef split_forward_gather_backward_var_len(input_, dim, process_group, splits: List[int]):\n    return _SplitForwardGatherBackwardVarLen.apply(input_, dim, process_group, splits)\n\n\nclass _GatherForwardSplitBackwardVarLen(torch.autograd.Function):\n    \"\"\"\n    Split the input and keep only the corresponding chuck to the rank.\n\n    Args:\n        input_ (`torch.Tensor`): input matrix.\n        dim (int): the dimension to perform split and gather\n        process_group (`torch.distributed.ProcessGroup`): the process group used for collective communication\n\n    \"\"\"\n\n    @staticmethod\n    def forward(ctx, input_, dim, process_group, splits: List[int]):\n        input_ = input_.contiguous()\n        ctx.process_group = process_group\n        ctx.dim = dim\n        rank = dist.get_rank(process_group)\n\n        ctx.grad_scale = sum(splits) / splits[rank]\n        ctx.splits = splits\n        world_size = dist.get_world_size(ctx.process_group)\n        shapes = [list(input_.shape) for _ in range(world_size)]\n        for i, shape in enumerate(shapes):\n            shape[dim] = splits[i]\n        tensor_list = [torch.empty(shape, dtype=input_.dtype, device=input_.device) for shape in shapes]\n        dist.all_gather(tensor_list, input_, group=ctx.process_group)\n        return torch.cat(tensor_list, dim=dim)\n\n    @staticmethod\n    def backward(ctx, grad_output):\n        grad_output = grad_output * ctx.grad_scale\n        rank = dist.get_rank(ctx.process_group)\n        return torch.split(grad_output, ctx.splits, dim=ctx.dim)[rank].clone(), None, None, None\n\n\ndef gather_forward_split_backward_var_len(input_, dim, process_group, splits: List[int]):\n    return _GatherForwardSplitBackwardVarLen.apply(input_, dim, process_group, splits)\n\n\ndef _fa_forward(\n    q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, dropout_p: float = 0.0, softmax_scale: Optional[float] = None\n) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:\n    if SUPPORT_FA3:\n        out, softmax_lse, *_ = _flash_attn_forward_v3(\n            q,\n            k,\n            v,\n            None,\n            None,\n            None,\n            None,  # k_new, q_new, qv, out\n            None,\n            None,\n            None,  # cu_seqlens_q, cu_seqlens_k, cu_seqlens_k_new\n            None,\n            None,\n            None,\n            None,  # seqused_q, seqused_k, max_seqlen_q, max_seqlen_k\n            None,\n            None,\n            None,  # page_table, kv_batch_idx, leftpad_k\n            None,\n            None,  # rotary_cos/sin\n            None,\n            None,\n            None,  # q_descale, k_descale, v_descale\n            softmax_scale,\n            False,  # causal\n            (-1, -1),\n        )\n        rng_state = None\n    else:\n        out, softmax_lse, _, rng_state = _flash_attn_forward(\n            q,\n            k,\n            v,\n            dropout_p,\n            softmax_scale,\n            causal=False,\n            window_size_left=-1,\n            window_size_right=-1,\n            softcap=0.0,\n            alibi_slopes=None,\n            return_softmax=False,\n        )\n    return out, softmax_lse, rng_state\n\n\ndef _fa_backward(\n    dout: torch.Tensor,\n    q: torch.Tensor,\n    k: torch.Tensor,\n    v: torch.Tensor,\n    out: torch.Tensor,\n    softmax_lse: torch.Tensor,\n    dq: torch.Tensor,\n    dk: torch.Tensor,\n    dv: torch.Tensor,\n    rng_state: torch.Tensor,\n    dropout_p: float = 0.0,\n    softmax_scale: Optional[float] = None,\n    deterministic: bool = False,\n) -> None:\n    if SUPPORT_FA3:\n        _flash_attn_backward_v3(\n            dout,\n            q,\n            k,\n            v,\n            out,\n            softmax_lse,\n            None, None, None, None, None, None,\n            dq,\n            dk,\n            dv,\n            softmax_scale,\n            False,  # causal\n            (-1, -1),\n            deterministic=deterministic,\n        )\n    else:\n        _flash_attn_backward(\n            dout,\n            q,\n            k,\n            v,\n            out,\n            softmax_lse,\n            dq,\n            dk,\n            dv,\n            dropout_p=dropout_p,\n            softmax_scale=softmax_scale,\n            causal=False,\n            window_size_left=-1,\n            window_size_right=-1,\n            softcap=0.0,\n            alibi_slopes=None,\n            deterministic=deterministic,\n            rng_state=rng_state,\n        )\n\n\nclass RingAttention(torch.autograd.Function):\n    ATTN_DONE: torch.cuda.Event = None\n    SP_STREAM: torch.cuda.Stream = None\n\n    @staticmethod\n    def forward(\n        ctx,\n        q: torch.Tensor,\n        k: torch.Tensor,\n        v: torch.Tensor,\n        sp_group: dist.ProcessGroup,\n        sp_stream: torch.cuda.Stream,\n        dropout_p: float = 0.0,\n        softmax_scale: Optional[float] = None,\n        deterministic: Optional[bool] = False,\n    ) -> Tuple[torch.Tensor, torch.Tensor]:\n        \"\"\"Ring attention forward\n\n        Args:\n            ctx (_type_): self\n            q (torch.Tensor): shape [B, S, N, D]\n            k (torch.Tensor): shape [B, S, N, D]\n            v (torch.Tensor): shape [B, S, N, D]\n            sp_group (dist.ProcessGroup): sequence parallel group\n            sp_stream (torch.cuda.Stream): sequence parallel stream\n            dropout_p (float, optional): dropout prob. Defaults to 0.0.\n            softmax_scale (Optional[float], optional): softmax scale. Defaults to None.\n            deterministic (Optional[bool], optional): backward deterministic mode. Defaults to False.\n\n        Returns:\n            Tuple[torch.Tensor, torch.Tensor]: output and log sum exp. Output's shape should be [B, S, N, D]. LSE's shape should be [B, N, S].\n        \"\"\"\n        if softmax_scale is None:\n            softmax_scale = q.shape[-1] ** (-0.5)\n        sp_size = dist.get_world_size(sp_group)\n        kv_comms: List[RingComm] = [RingComm(sp_group) for _ in range(2)]\n\n        # [B, S, N, D]\n        q, k, v = [x.contiguous() for x in [q, k, v]]\n        # Pre-allocate double buffer for overlapping and receiving next step's inputs\n        kv_buffers = [torch.stack((k, v))]  # (2, B, S, N, D)\n        kv_buffers.append(torch.empty_like(kv_buffers[0]))\n        # outputs\n        out = None\n        block_out = [None, None]\n        softmax_lse = [None, None]\n        block_softmax_lse = [None, None]  # log sum exp, the denominator of softmax in attention\n        rng_states = [None for _ in range(sp_size)]\n        sp_streams = [torch.cuda.current_stream(), sp_stream]\n\n        def _kv_comm(i):\n            # Avoid overwriting attn input when it shares mem with buffer\n            if not RingAttention.ATTN_DONE.query():\n                kv_buffers[(i + 1) % 2] = torch.empty_like(kv_buffers[i % 2])\n            if i < sp_size - 1:\n                kv_comms[i % 2].send_recv(kv_buffers[i % 2], kv_buffers[(i + 1) % 2])\n\n        for i in range(sp_size):\n            with torch.cuda.stream(sp_streams[i % 2]):\n                # Wait for current kv from prev rank\n                # NOTE: waiting outside the current stream will NOT correctly synchronize.\n                if i == 0:\n                    _kv_comm(i)\n                else:\n                    kv_comms[(i + 1) % 2].wait()\n                kv_block = kv_buffers[i % 2]\n                q_block = q\n                block_out[i % 2], block_softmax_lse[i % 2], rng_states[i] = _fa_forward(\n                    q_block, kv_block[0], kv_block[1], dropout_p, softmax_scale\n                )\n                RingAttention.ATTN_DONE.record()\n                # Pipeline the next KV comm with output correction instead of the next flash attn\n                # to minimize idle time when comm takes longer than attn.\n                _kv_comm(i + 1)\n                block_softmax_lse[i % 2] = (\n                    block_softmax_lse[i % 2].transpose(1, 2).unsqueeze(-1).contiguous().float()\n                )  # [B, N, S] -> [B, S, N, 1]\n                assert block_out[i % 2].shape[:-1] == block_softmax_lse[i % 2].shape[:-1]\n                # Output and log sum exp correction. Ideally overlap this with the next flash attn kernel.\n                # In reality this always finishes before next flash attn; no need for extra sync.\n                if i == 0:\n                    out = block_out[0]\n                    softmax_lse = block_softmax_lse[0]\n                else:\n                    out, softmax_lse = _rescale_out_lse(out, block_out[i % 2], softmax_lse, block_softmax_lse[i % 2])\n        torch.cuda.current_stream().wait_stream(sp_stream)\n        out = out.to(q.dtype)\n        softmax_lse = softmax_lse.squeeze(-1).transpose(1, 2).contiguous()\n\n        ctx.dropout_p = dropout_p\n        ctx.softmax_scale = softmax_scale\n        ctx.deterministic = deterministic\n        ctx.sp_group = sp_group\n        ctx.save_for_backward(q, k, v, out, softmax_lse, *rng_states)  # lse [B, N, S]\n        return out, softmax_lse\n\n    @staticmethod\n    def backward(ctx, grad_output, grad_softmax_lse):\n        # q, k, v, out: [B, S, N, D], softmax_lse: [B, N, S]\n        q, k, v, out, softmax_lse, *rng_states = ctx.saved_tensors\n\n        sp_group = ctx.sp_group\n        sp_size = dist.get_world_size(sp_group)\n        kv_comm = RingComm(sp_group)\n        dkv_comm = RingComm(sp_group)\n\n        grad_output = grad_output.contiguous()\n        kv_buffers = [torch.stack((k, v))]  # (2, B, S, N, D)\n        kv_buffers.append(torch.empty_like(kv_buffers[0]))\n        dq = None\n        dq_block = torch.empty_like(q)\n        dk_block = torch.empty_like(k)\n        dv_block = torch.empty_like(v)\n        dkv_buffers = [torch.empty_like(kv, dtype=torch.float) for kv in kv_buffers]\n        del k, v\n\n        for i in range(sp_size):\n            if i > 0:\n                kv_comm.wait()\n            if i < sp_size - 1:\n                kv_comm.send_recv(kv_buffers[i % 2], kv_buffers[(i + 1) % 2])\n\n            k_block, v_block = kv_buffers[i % 2]\n            _fa_backward(\n                grad_output,\n                q,\n                k_block,\n                v_block,\n                out,\n                softmax_lse,\n                dq_block,\n                dk_block,\n                dv_block,\n                rng_states[i],\n                dropout_p=ctx.dropout_p,\n                softmax_scale=ctx.softmax_scale,\n                deterministic=ctx.deterministic,\n            )\n\n            if i == 0:\n                dq = dq_block.float()\n                dkv_buffers[i % 2][0] = dk_block.float()\n                dkv_buffers[i % 2][1] = dv_block.float()\n            else:\n                dq += dq_block\n                dkv_comm.wait()\n                dkv_buffers[i % 2][0] += dk_block\n                dkv_buffers[i % 2][1] += dv_block\n            dkv_comm.send_recv(dkv_buffers[i % 2], dkv_buffers[(i + 1) % 2])\n        dkv_comm.wait()\n        dkv = dkv_buffers[sp_size % 2]\n\n        dq, dk, dv = [x.to(q.dtype) for x in (dq, *dkv)]\n\n        return dq, dk, dv, None, None, None, None, None, None, None, None, None, None, None, None, None, None\n\n    @staticmethod\n    def attention(\n        q,\n        k,\n        v,\n        sp_group,\n        dropout_p: float = 0.0,\n        softmax_scale: Optional[float] = None,\n        deterministic: bool = False,\n        return_softmax: bool = False,\n    ):\n        \"\"\"Ring attention\n\n        Args:\n            q (torch.Tensor): shape [B, S, N, D]\n            k (torch.Tensor): shape [B, S, N, D]\n            v (torch.Tensor): shape [B, S, N, D]\n            sp_group (dist.ProcessGroup): sequence parallel group\n            dropout_p (float, optional): dropout prob. Defaults to 0.0.\n            softmax_scale (Optional[float], optional): softmax scale. Defaults to None.\n            deterministic (Optional[bool], optional): backward deterministic mode. Defaults to False.\n            return_softmax (bool, optional): return softmax or not. Defaults to False.\n\n        Returns:\n            Tuple[torch.Tensor, torch.Tensor]: output and log sum exp. Output's shape should be [B, S, N, D]. LSE's shape should be [B, N, S].\n        \"\"\"\n        if RingAttention.ATTN_DONE is None:\n            RingAttention.ATTN_DONE = torch.cuda.Event()\n        if RingAttention.SP_STREAM is None:\n            RingAttention.SP_STREAM = torch.cuda.Stream()\n        out, softmax_lse = RingAttention.apply(\n            q, k, v, sp_group, RingAttention.SP_STREAM, dropout_p, softmax_scale, deterministic\n        )\n        if return_softmax:\n            return out, softmax_lse\n        return out\n\n\ndef ring_attention(q: Tensor, k: Tensor, v: Tensor, pe: Tensor, sp_group: dist.ProcessGroup) -> Tensor:\n    if isinstance(pe, torch.Tensor):\n        q, k = apply_rope(q, k, pe)\n    else:\n        cos, sin = pe\n        q, k = LigerRopeFunction.apply(q, k, cos, sin)\n    q, k, v = [x.transpose(1, 2) for x in (q, k, v)]  # [B, H, L, D] -> [B, L, H, D]\n    x = RingAttention.attention(q, k, v, sp_group)\n    x = rearrange(x, \"B L H D -> B L (H D)\")\n    return x\n\n\nclass DistributedDoubleStreamBlockProcessor:\n    def __init__(self, shard_config: ShardConfig) -> None:\n        self.shard_config = shard_config\n\n    def __call__(\n        self, attn: DoubleStreamBlock, img: Tensor, txt: Tensor, vec: Tensor, pe: Tensor\n    ) -> tuple[Tensor, Tensor]:\n        img_mod1, img_mod2 = attn.img_mod(vec)\n        txt_mod1, txt_mod2 = attn.txt_mod(vec)\n\n        # prepare image for attention\n        img_modulated = attn.img_norm1(img)\n        img_modulated = (1 + img_mod1.scale) * img_modulated + img_mod1.shift\n        if attn.img_attn.fused_qkv:\n            img_qkv = attn.img_attn.qkv(img_modulated)\n            img_q, img_k, img_v = rearrange(img_qkv, \"B L (K H D) -> K B H L D\", K=3, H=attn.num_heads, D=attn.head_dim)\n        else:\n            img_q = rearrange(attn.img_attn.q_proj(img_modulated), \"B L (H D) -> B L H D\", H=attn.num_heads)\n            img_k = rearrange(attn.img_attn.k_proj(img_modulated), \"B L (H D) -> B L H D\", H=attn.num_heads)\n            img_v = rearrange(attn.img_attn.v_proj(img_modulated), \"B L (H D) -> B L H D\", H=attn.num_heads)\n        img_q, img_k = attn.img_attn.norm(img_q, img_k, img_v)\n        if not attn.img_attn.fused_qkv:\n            img_q = rearrange(img_q, \"B L H D -> B H L D\")\n            img_k = rearrange(img_k, \"B L H D -> B H L D\")\n            img_v = rearrange(img_v, \"B L H D -> B H L D\")\n\n        # prepare txt for attention\n        txt_modulated = attn.txt_norm1(txt)\n        txt_modulated = (1 + txt_mod1.scale) * txt_modulated + txt_mod1.shift\n        if attn.txt_attn.fused_qkv:\n            txt_qkv = attn.txt_attn.qkv(txt_modulated)\n            txt_q, txt_k, txt_v = rearrange(txt_qkv, \"B L (K H D) -> K B H L D\", K=3, H=attn.num_heads, D=attn.head_dim)\n        else:\n            txt_q = rearrange(attn.txt_attn.q_proj(txt_modulated), \"B L (H D) -> B L H D\", H=attn.num_heads)\n            txt_k = rearrange(attn.txt_attn.k_proj(txt_modulated), \"B L (H D) -> B L H D\", H=attn.num_heads)\n            txt_v = rearrange(attn.txt_attn.v_proj(txt_modulated), \"B L (H D) -> B L H D\", H=attn.num_heads)\n        txt_q, txt_k = attn.txt_attn.norm(txt_q, txt_k, txt_v)\n        if not attn.txt_attn.fused_qkv:\n            txt_q = rearrange(txt_q, \"B L H D -> B H L D\")\n            txt_k = rearrange(txt_k, \"B L H D -> B H L D\")\n            txt_v = rearrange(txt_v, \"B L H D -> B H L D\")\n\n        txt_len = txt_q.size(2)\n        # run actual attention\n        q = torch.cat((txt_q, img_q), dim=2)\n        k = torch.cat((txt_k, img_k), dim=2)\n        v = torch.cat((txt_v, img_v), dim=2)\n\n        if (\n            self.shard_config.enable_sequence_parallelism\n            and self.shard_config.sequence_parallelism_mode == \"all_to_all\"\n        ):\n            assert (\n                attn.num_heads % self.shard_config.sequence_parallel_size == 0\n            ), f\"Expected num heads({attn.num_heads}) % sp size({self.shard_config.sequence_parallel_size}) == 0\"\n            # TODO: overlap the communication with computation\n            q = all_to_all_comm(q, self.shard_config.sequence_parallel_process_group, scatter_dim=1, gather_dim=2)\n            k = all_to_all_comm(k, self.shard_config.sequence_parallel_process_group, scatter_dim=1, gather_dim=2)\n            v = all_to_all_comm(v, self.shard_config.sequence_parallel_process_group, scatter_dim=1, gather_dim=2)\n\n        if self.shard_config.enable_sequence_parallelism and self.shard_config.sequence_parallelism_mode == \"ring_attn\":\n            attn1 = ring_attention(q, k, v, pe, self.shard_config.sequence_parallel_process_group)\n        else:\n            attn1 = attention(q, k, v, pe=pe)\n        if (\n            self.shard_config.enable_sequence_parallelism\n            and self.shard_config.sequence_parallelism_mode == \"all_to_all\"\n        ):\n            attn1 = all_to_all_comm(\n                attn1, self.shard_config.sequence_parallel_process_group, scatter_dim=1, gather_dim=2\n            )\n        txt_attn, img_attn = attn1[:, :txt_len], attn1[:, txt_len:]\n\n        # calculate the img bloks\n        img = img + img_mod1.gate * attn.img_attn.proj(img_attn)\n        img = img + img_mod2.gate * attn.img_mlp((1 + img_mod2.scale) * attn.img_norm2(img) + img_mod2.shift)\n\n        # calculate the txt bloks\n        txt = txt + txt_mod1.gate * attn.txt_attn.proj(txt_attn)\n        txt = txt + txt_mod2.gate * attn.txt_mlp((1 + txt_mod2.scale) * attn.txt_norm2(txt) + txt_mod2.shift)\n        return img, txt\n\n\nclass DistributedSingleStreamBlockProcessor:\n    def __init__(self, shard_config: ShardConfig) -> None:\n        self.shard_config = shard_config\n\n    def __call__(self, attn: SingleStreamBlock, x: Tensor, vec: Tensor, pe: Tensor) -> Tensor:\n        mod, _ = attn.modulation(vec)\n        x_mod = (1 + mod.scale) * attn.pre_norm(x) + mod.shift\n\n        if attn.fused_qkv:\n            qkv, mlp = torch.split(attn.linear1(x_mod), [3 * attn.hidden_size, attn.mlp_hidden_dim], dim=-1)\n            q, k, v = rearrange(qkv, \"B L (K H D) -> K B H L D\", K=3, H=attn.num_heads)\n        else:\n            q = rearrange(attn.q_proj(x_mod), \"B L (H D) -> B L H D\", H=attn.num_heads)\n            k = rearrange(attn.k_proj(x_mod), \"B L (H D) -> B L H D\", H=attn.num_heads)\n            v, mlp = torch.split(attn.v_mlp(x_mod), [attn.hidden_size, attn.mlp_hidden_dim], dim=-1)\n            v = rearrange(v, \"B L (H D) -> B L H D\", H=attn.num_heads)\n        q, k = attn.norm(q, k, v)\n        if not attn.fused_qkv:\n            q = rearrange(q, \"B L H D -> B H L D\")\n            k = rearrange(k, \"B L H D -> B H L D\")\n            v = rearrange(v, \"B L H D -> B H L D\")\n\n        if (\n            self.shard_config.enable_sequence_parallelism\n            and self.shard_config.sequence_parallelism_mode == \"all_to_all\"\n        ):\n            assert (\n                attn.num_heads % self.shard_config.sequence_parallel_size == 0\n            ), f\"Expected num heads({attn.num_heads}) % sp size({self.shard_config.sequence_parallel_size}) == 0\"\n            q = all_to_all_comm(q, self.shard_config.sequence_parallel_process_group, scatter_dim=1, gather_dim=2)\n            k = all_to_all_comm(k, self.shard_config.sequence_parallel_process_group, scatter_dim=1, gather_dim=2)\n            v = all_to_all_comm(v, self.shard_config.sequence_parallel_process_group, scatter_dim=1, gather_dim=2)\n\n        # compute attention\n        if self.shard_config.enable_sequence_parallelism and self.shard_config.sequence_parallelism_mode == \"ring_attn\":\n            attn_1 = ring_attention(q, k, v, pe, self.shard_config.sequence_parallel_process_group)\n        else:\n            attn_1 = attention(q, k, v, pe=pe)\n\n        if (\n            self.shard_config.enable_sequence_parallelism\n            and self.shard_config.sequence_parallelism_mode == \"all_to_all\"\n        ):\n            attn_1 = all_to_all_comm(\n                attn_1, self.shard_config.sequence_parallel_process_group, scatter_dim=1, gather_dim=2\n            )\n\n        # compute activation in mlp stream, cat again and run second linear layer\n        output = attn.linear2(torch.cat((attn_1, attn.mlp_act(mlp)), 2))\n        output = x + mod.gate * output\n        return output\n\n\nclass _TempSwitchCP(torch.autograd.Function):\n    @staticmethod\n    def forward(ctx, input_, shard_config: ShardConfig, value: bool):\n        ctx.old_value = shard_config.enable_sequence_parallelism\n        ctx.shard_config = shard_config\n        shard_config.enable_sequence_parallelism = value\n        return input_\n\n    @staticmethod\n    def backward(ctx, grad_output):\n        print(f\"in backward, sp mode: {ctx.shard_config.enable_sequence_parallelism}\")\n        ctx.shard_config.enable_sequence_parallelism = ctx.old_value\n        return grad_output, None, None\n\n\ndef switch_sequence_parallelism(input_, shard_config: ShardConfig, value: bool):\n    return _TempSwitchCP.apply(input_, shard_config, value)\n\n\ndef mmdit_model_forward(\n    self: MMDiTModel,\n    img: Tensor,\n    img_ids: Tensor,\n    txt: Tensor,\n    txt_ids: Tensor,\n    timesteps: Tensor,\n    y_vec: Tensor,\n    cond: Tensor = None,\n    guidance: Tensor | None = None,\n    shard_config: ShardConfig = None,\n    stage_index: Optional[List[int]] = None,\n    internal_img: Optional[Tensor] = None,\n    internal_txt: Optional[Tensor] = None,\n    internal_pe: Optional[Tensor] = None,\n    internal_vec: Optional[Tensor] = None,\n    **kwargs,\n):\n    txt_len = txt.shape[1]\n    if shard_config.pipeline_stage_manager is None or shard_config.pipeline_stage_manager.is_first_stage():\n        img, txt, vec, pe = self.prepare_block_inputs(img, img_ids, txt, txt_ids, timesteps, y_vec, cond, guidance)\n        has_grad = img.grad_fn is not None\n        old_sequence_parallelism = shard_config.enable_sequence_parallelism\n        if shard_config.enable_sequence_parallelism:\n            assert (\n                txt.shape[1] + img.shape[1]\n            ) % shard_config.sequence_parallel_size == 0, (\n                f\"Expected {txt.shape[1] +img.shape[1]} % {shard_config.sequence_parallel_size} == 0\"\n            )\n            mask = torch.zeros(txt.shape[1] + img.shape[1], dtype=bool)\n            mask[txt.shape[1] :] = 1\n            mask_chunks = mask.chunk(shard_config.sequence_parallel_size)\n            cur_mask = mask_chunks[dist.get_rank(shard_config.sequence_parallel_process_group)]\n            txt_splits = [len(c) - c.sum().item() for c in mask_chunks]\n            img_splits = [c.sum().item() for c in mask_chunks]\n            if 0 in img_splits:\n                # temporarily disable sequence parallelism to avoid stucking\n                img = switch_sequence_parallelism(img, shard_config, False)\n            else:\n                img = split_forward_gather_backward_var_len(\n                    img, 1, shard_config.sequence_parallel_process_group, img_splits\n                )\n                txt = split_forward_gather_backward_var_len(\n                    txt, 1, shard_config.sequence_parallel_process_group, txt_splits\n                )\n                if shard_config.sequence_parallelism_mode == \"ring_attn\":\n                    # pe does not require grad\n                    sp_rank = dist.get_rank(shard_config.sequence_parallel_process_group)\n                    if isinstance(pe, torch.Tensor):\n                        pe = pe.chunk(shard_config.sequence_parallel_size, dim=2)[sp_rank].clone()\n                    else:\n                        cos, sin = pe\n                        cos = cos.chunk(shard_config.sequence_parallel_size, dim=1)[sp_rank].clone()\n                        sin = sin.chunk(shard_config.sequence_parallel_size, dim=1)[sp_rank].clone()\n                        pe = (cos, sin)\n    else:\n        img, txt, vec, pe = internal_img, internal_txt, internal_vec, internal_pe\n\n    double_start, double_end = 0, len(self.double_blocks)\n    if shard_config.pipeline_stage_manager is not None:\n        double_start = stage_index[0]\n        double_end = min(stage_index[1], len(self.double_blocks))\n\n    for block in self.double_blocks[double_start:double_end]:\n        img, txt = auto_grad_checkpoint(block, img, txt, vec, pe)\n\n    if shard_config.pipeline_stage_manager is not None and stage_index[1] <= len(self.double_blocks):\n        return {\n            \"internal_img\": img,\n            \"internal_txt\": txt,\n            \"internal_pe\": pe,\n            \"internal_vec\": vec,\n        }\n    single_start, single_end = 0, len(self.single_blocks)\n    if shard_config.pipeline_stage_manager is not None:\n        single_start = max(stage_index[0] - len(self.double_blocks), 0)\n        single_end = stage_index[1] - len(self.double_blocks)\n\n    if single_start == 0:\n        img = torch.cat((txt, img), 1)\n\n    for block in self.single_blocks[single_start:single_end]:\n        img = auto_grad_checkpoint(block, img, vec, pe)\n\n    if shard_config.pipeline_stage_manager is not None and single_end < len(self.single_blocks):\n        return {\n            \"internal_img\": img,\n            \"internal_pe\": pe,\n            \"internal_vec\": vec,\n        }\n\n    if shard_config.enable_sequence_parallelism:\n        img = img[:, cur_mask]\n    else:\n        img = img[:, txt_len:]\n\n    img = self.final_layer(img, vec)  # (N, T, patch_size ** 2 * out_channels)\n\n    if shard_config.enable_sequence_parallelism:\n        img = gather_forward_split_backward_var_len(img, 1, shard_config.sequence_parallel_process_group, img_splits)\n\n    if not has_grad:\n        shard_config.enable_sequence_parallelism = old_sequence_parallelism\n    return img\n\n\nclass MMDiTPolicy(Policy):\n    def config_sanity_check(self):\n        if self.shard_config.enable_sequence_parallelism and is_share_sp_tp(\n            self.shard_config.sequence_parallelism_mode\n        ):\n            assert self.shard_config.enable_tensor_parallelism, \"Tensor parallelism should be enabled\"\n\n    def preprocess(self) -> nn.Module:\n        return self.model\n\n    def postprocess(self) -> nn.Module:\n        return self.model\n\n    def tie_weight_check(self) -> bool:\n        return False\n\n    def module_policy(self) -> Dict[Union[str, nn.Module], ModulePolicyDescription]:\n        policy = {\n            DoubleStreamBlock: ModulePolicyDescription(attribute_replacement={}, sub_module_replacement=[]),\n            SingleStreamBlock: ModulePolicyDescription(attribute_replacement={}, sub_module_replacement=[]),\n        }\n\n        if self.shard_config.enable_sequence_parallelism:\n            if not is_share_sp_tp(self.shard_config.sequence_parallelism_mode):\n                policy[DoubleStreamBlock].attribute_replacement[\"processor\"] = DistributedDoubleStreamBlockProcessor(\n                    self.shard_config\n                )\n                policy[SingleStreamBlock].attribute_replacement[\"processor\"] = DistributedSingleStreamBlockProcessor(\n                    self.shard_config\n                )\n        if self.shard_config.enable_sequence_parallelism or self.shard_config.pipeline_stage_manager is not None:\n            fwd_fn = partial(mmdit_model_forward, shard_config=self.shard_config)\n            if self.shard_config.pipeline_stage_manager is not None:\n                layers_per_stage = self.shard_config.pipeline_stage_manager.distribute_layers(\n                    len(self.model.double_blocks) + len(self.model.single_blocks)\n                )\n                if self.shard_config.pipeline_stage_manager.is_interleave:\n                    self.shard_config.pipeline_stage_manager.stage_indices = (\n                        self.shard_config.pipeline_stage_manager.get_stage_index(layers_per_stage)\n                    )\n                else:\n                    stage_index = self.shard_config.pipeline_stage_manager.get_stage_index(layers_per_stage)\n                    fwd_fn = partial(mmdit_model_forward, shard_config=self.shard_config, stage_index=stage_index)\n            self.append_or_create_method_replacement(\n                description={\n                    \"forward\": fwd_fn,\n                },\n                policy=policy,\n                target_key=MMDiTModel,\n            )\n\n        if self.shard_config.enable_tensor_parallelism:\n            mlp_hidden_size = int(self.model.config.hidden_size * self.model.config.mlp_ratio)\n            assert (\n                self.model.config.num_heads % self.shard_config.tensor_parallel_size == 0\n                and mlp_hidden_size % self.shard_config.tensor_parallel_size == 0\n            ), \"num_heads and hidden_size should be divisible by tensor_parallel_size\"\n            for n in [\"img\", \"txt\"]:\n                if self.model.config.fused_qkv:\n                    policy[DoubleStreamBlock].sub_module_replacement.append(\n                        SubModuleReplacementDescription(\n                            suffix=f\"{n}_attn.qkv\",\n                            target_module=FusedLinear1D_Col,\n                            kwargs={\n                                \"split_sizes\": [self.model.config.hidden_size] * 3,\n                                \"seq_parallel_mode\": self.shard_config.sequence_parallelism_mode,\n                            },\n                        ),\n                    )\n                else:\n                    policy[DoubleStreamBlock].sub_module_replacement.extend(\n                        [\n                            SubModuleReplacementDescription(\n                                suffix=f\"{n}_attn.q_proj\",\n                                target_module=Linear1D_Col,\n                                kwargs={\"seq_parallel_mode\": self.shard_config.sequence_parallelism_mode},\n                            ),\n                            SubModuleReplacementDescription(\n                                suffix=f\"{n}_attn.k_proj\",\n                                target_module=Linear1D_Col,\n                                kwargs={\"seq_parallel_mode\": self.shard_config.sequence_parallelism_mode},\n                            ),\n                            SubModuleReplacementDescription(\n                                suffix=f\"{n}_attn.v_proj\",\n                                target_module=Linear1D_Col,\n                                kwargs={\"seq_parallel_mode\": self.shard_config.sequence_parallelism_mode},\n                            ),\n                        ]\n                    )\n                policy[DoubleStreamBlock].sub_module_replacement.extend(\n                    [\n                        SubModuleReplacementDescription(\n                            suffix=f\"{n}_attn.proj\",\n                            target_module=Linear1D_Row,\n                            kwargs={\"seq_parallel_mode\": self.shard_config.sequence_parallelism_mode},\n                        ),\n                        SubModuleReplacementDescription(\n                            suffix=f\"{n}_mlp[0]\",\n                            target_module=Linear1D_Col,\n                            kwargs={\"seq_parallel_mode\": self.shard_config.sequence_parallelism_mode},\n                        ),\n                        SubModuleReplacementDescription(\n                            suffix=f\"{n}_mlp[2]\",\n                            target_module=Linear1D_Row,\n                            kwargs={\"seq_parallel_mode\": self.shard_config.sequence_parallelism_mode},\n                        ),\n                    ]\n                )\n            policy[DoubleStreamBlock].attribute_replacement[\"num_heads\"] = (\n                self.model.config.num_heads // self.shard_config.tensor_parallel_size\n            )\n            policy[SingleStreamBlock].attribute_replacement.update(\n                {\n                    \"num_heads\": self.model.config.num_heads // self.shard_config.tensor_parallel_size,\n                    \"hidden_size\": self.model.config.hidden_size // self.shard_config.tensor_parallel_size,\n                    \"mlp_hidden_dim\": mlp_hidden_size // self.shard_config.tensor_parallel_size,\n                }\n            )\n            if self.model.config.fused_qkv:\n                policy[SingleStreamBlock].sub_module_replacement.append(\n                    SubModuleReplacementDescription(\n                        suffix=\"linear1\",\n                        target_module=FusedLinear1D_Col,\n                        kwargs={\n                            \"split_sizes\": [self.model.config.hidden_size] * 3 + [mlp_hidden_size],\n                            \"seq_parallel_mode\": self.shard_config.sequence_parallelism_mode,\n                        },\n                    ),\n                )\n            else:\n                policy[SingleStreamBlock].sub_module_replacement.extend(\n                    [\n                        SubModuleReplacementDescription(\n                            suffix=\"q_proj\",\n                            target_module=Linear1D_Col,\n                            kwargs={\"seq_parallel_mode\": self.shard_config.sequence_parallelism_mode},\n                        ),\n                        SubModuleReplacementDescription(\n                            suffix=\"k_proj\",\n                            target_module=Linear1D_Col,\n                            kwargs={\"seq_parallel_mode\": self.shard_config.sequence_parallelism_mode},\n                        ),\n                        SubModuleReplacementDescription(\n                            suffix=\"v_mlp\",\n                            target_module=FusedLinear1D_Col,\n                            kwargs={\n                                \"split_sizes\": [self.model.config.hidden_size] + [mlp_hidden_size],\n                                \"seq_parallel_mode\": self.shard_config.sequence_parallelism_mode,\n                            },\n                        ),\n                    ]\n                )\n            policy[SingleStreamBlock].sub_module_replacement.extend(\n                [\n                    SubModuleReplacementDescription(\n                        suffix=\"linear2\",\n                        target_module=FusedLinear1D_Row,\n                        kwargs={\n                            \"split_sizes\": [self.model.config.hidden_size, mlp_hidden_size],\n                            \"seq_parallel_mode\": self.shard_config.sequence_parallelism_mode,\n                        },\n                    ),\n                ],\n            )\n\n        return policy\n\n    def get_held_layers(self) -> List[nn.Module]:\n        stage_manager = self.shard_config.pipeline_stage_manager\n        assert stage_manager is not None, \"Pipeline stage manager is not set\"\n\n        held_layers = []\n        total_blocks = [*self.model.double_blocks, *self.model.single_blocks]\n        if stage_manager.is_first_stage(ignore_chunk=stage_manager.is_interleave):\n            held_layers.extend(\n                [\n                    self.model.pe_embedder,\n                    self.model.img_in,\n                    self.model.time_in,\n                    self.model.vector_in,\n                    self.model.guidance_in,\n                    self.model.cond_in,\n                    self.model.txt_in,\n                ]\n            )\n\n        layers_per_stage = stage_manager.distribute_layers(len(total_blocks))\n        if stage_manager.is_interleave:\n            assert stage_manager.num_model_chunks is not None\n            stage_indices = stage_manager.get_stage_index(layers_per_stage)\n            for start_idx, end_idx in stage_indices:\n                held_layers.extend(total_blocks[start_idx:end_idx])\n        else:\n            start_idx, end_idx = stage_manager.get_stage_index(layers_per_stage)\n            held_layers.extend(total_blocks[start_idx:end_idx])\n        if stage_manager.is_last_stage(ignore_chunk=stage_manager.is_interleave):\n            held_layers.append(self.model.final_layer)\n        return held_layers\n"
  },
  {
    "path": "opensora/models/mmdit/layers.py",
    "content": "# Modified from Flux\n#\n# Copyright 2024 Black Forest Labs\n\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n\n#     http://www.apache.org/licenses/LICENSE-2.0\n\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# This source code is licensed under the license found in the\n# LICENSE file in the root directory of this source tree.\n\nimport math\nfrom dataclasses import dataclass\n\nimport torch\nfrom einops import rearrange\nfrom liger_kernel.ops.rms_norm import LigerRMSNormFunction\nfrom torch import Tensor, nn\n\nfrom .math import attention, liger_rope, rope\n\n\nclass EmbedND(nn.Module):\n    def __init__(self, dim: int, theta: int, axes_dim: list[int]):\n        super().__init__()\n        self.dim = dim\n        self.theta = theta\n        self.axes_dim = axes_dim\n\n    def forward(self, ids: Tensor) -> Tensor:\n        n_axes = ids.shape[-1]\n        emb = torch.cat(\n            [rope(ids[..., i], self.axes_dim[i], self.theta) for i in range(n_axes)],\n            dim=-3,\n        )\n        return emb.unsqueeze(1)\n\n\nclass LigerEmbedND(nn.Module):\n    def __init__(self, dim: int, theta: int, axes_dim: list[int]):\n        super().__init__()\n        self.dim = dim\n        self.theta = theta\n        self.axes_dim = axes_dim\n\n    def forward(self, ids: Tensor) -> Tensor:\n        n_axes = ids.shape[-1]\n        cos_list = []\n        sin_list = []\n        for i in range(n_axes):\n            cos, sin = liger_rope(ids[..., i], self.axes_dim[i], self.theta)\n            cos_list.append(cos)\n            sin_list.append(sin)\n        cos_emb = torch.cat(cos_list, dim=-1).repeat(1, 1, 2).contiguous()\n        sin_emb = torch.cat(sin_list, dim=-1).repeat(1, 1, 2).contiguous()\n\n        return (cos_emb, sin_emb)\n\n\n@torch.compile(mode=\"max-autotune-no-cudagraphs\", dynamic=True)\ndef timestep_embedding(t: Tensor, dim, max_period=10000, time_factor: float = 1000.0):\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    t = time_factor * t\n    half = dim // 2\n    freqs = torch.exp(-math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half).to(t.device)\n\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    if torch.is_floating_point(t):\n        embedding = embedding.to(t)\n    return embedding\n\n\nclass MLPEmbedder(nn.Module):\n    def __init__(self, in_dim: int, hidden_dim: int):\n        super().__init__()\n        self.in_layer = nn.Linear(in_dim, hidden_dim, bias=True)\n        self.silu = nn.SiLU()\n        self.out_layer = nn.Linear(hidden_dim, hidden_dim, bias=True)\n\n    def forward(self, x: Tensor) -> Tensor:\n        return self.out_layer(self.silu(self.in_layer(x)))\n\n\nclass RMSNorm(torch.nn.Module):\n    def __init__(self, dim: int):\n        super().__init__()\n        self.scale = nn.Parameter(torch.ones(dim))\n\n    def forward(self, x: Tensor):\n        x_dtype = x.dtype\n        x = x.float()\n        rrms = torch.rsqrt(torch.mean(x**2, dim=-1, keepdim=True) + 1e-6)\n        return (x * rrms).to(dtype=x_dtype) * self.scale\n\n\nclass FusedRMSNorm(RMSNorm):\n    def forward(self, x: Tensor):\n        return LigerRMSNormFunction.apply(\n            x,\n            self.scale,\n            1e-6,\n            0.0,\n            \"llama\",\n            False,\n        )\n\n\nclass QKNorm(torch.nn.Module):\n    def __init__(self, dim: int):\n        super().__init__()\n        self.query_norm = FusedRMSNorm(dim)\n        self.key_norm = FusedRMSNorm(dim)\n\n    def forward(self, q: Tensor, k: Tensor, v: Tensor) -> tuple[Tensor, Tensor]:\n        q = self.query_norm(q)\n        k = self.key_norm(k)\n        return q.to(v), k.to(v)\n\n\nclass SelfAttention(nn.Module):\n    def __init__(self, dim: int, num_heads: int = 8, qkv_bias: bool = False, fused_qkv: bool = True):\n        super().__init__()\n        self.num_heads = num_heads\n        self.fused_qkv = fused_qkv\n        head_dim = dim // num_heads\n\n        if fused_qkv:\n            self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)\n        else:\n            self.q_proj = nn.Linear(dim, dim, bias=qkv_bias)\n            self.k_proj = nn.Linear(dim, dim, bias=qkv_bias)\n            self.v_proj = nn.Linear(dim, dim, bias=qkv_bias)\n        self.norm = QKNorm(head_dim)\n        self.proj = nn.Linear(dim, dim)\n\n    def forward(self, x: Tensor, pe: Tensor) -> Tensor:\n        if self.fused_qkv:\n            qkv = self.qkv(x)\n            q, k, v = rearrange(qkv, \"B L (K H D) -> K B H L D\", K=3, H=self.num_heads)\n        else:\n            q = rearrange(self.q_proj(x), \"B L (H D) -> B L H D\", H=self.num_heads)\n            k = rearrange(self.k_proj(x), \"B L (H D) -> B L H D\", H=self.num_heads)\n            v = rearrange(self.v_proj(x), \"B L (H D) -> B L H D\", H=self.num_heads)\n        q, k = self.norm(q, k, v)\n        if not self.fused_qkv:\n            q = rearrange(q, \"B L H D -> B H L D\")\n            k = rearrange(k, \"B L H D -> B H L D\")\n            v = rearrange(v, \"B L H D -> B H L D\")\n        x = attention(q, k, v, pe=pe)\n        x = self.proj(x)\n        return x\n\n\n@dataclass\nclass ModulationOut:\n    shift: Tensor\n    scale: Tensor\n    gate: Tensor\n\n\nclass Modulation(nn.Module):\n    def __init__(self, dim: int, double: bool):\n        super().__init__()\n        self.is_double = double\n        self.multiplier = 6 if double else 3\n        self.lin = nn.Linear(dim, self.multiplier * dim, bias=True)\n\n    def forward(self, vec: Tensor) -> tuple[ModulationOut, ModulationOut | None]:\n        out = self.lin(nn.functional.silu(vec))[:, None, :].chunk(self.multiplier, dim=-1)\n\n        return (\n            ModulationOut(*out[:3]),\n            ModulationOut(*out[3:]) if self.is_double else None,\n        )\n\n\nclass DoubleStreamBlockProcessor:\n    def __call__(self, attn: nn.Module, img: Tensor, txt: Tensor, vec: Tensor, pe: Tensor) -> tuple[Tensor, Tensor]:\n        # attn is the DoubleStreamBlock;\n        # process img and txt separately while both is influenced by text vec\n\n        # vec will interact with image latent and text context\n        img_mod1, img_mod2 = attn.img_mod(vec)  # get shift, scale, gate for each mod\n        txt_mod1, txt_mod2 = attn.txt_mod(vec)\n\n        # prepare image for attention\n        img_modulated = attn.img_norm1(img)\n        img_modulated = (1 + img_mod1.scale) * img_modulated + img_mod1.shift\n\n        if attn.img_attn.fused_qkv:\n            img_qkv = attn.img_attn.qkv(img_modulated)\n            img_q, img_k, img_v = rearrange(img_qkv, \"B L (K H D) -> K B H L D\", K=3, H=attn.num_heads, D=attn.head_dim)\n        else:\n            img_q = rearrange(attn.img_attn.q_proj(img_modulated), \"B L (H D) -> B L H D\", H=attn.num_heads)\n            img_k = rearrange(attn.img_attn.k_proj(img_modulated), \"B L (H D) -> B L H D\", H=attn.num_heads)\n            img_v = rearrange(attn.img_attn.v_proj(img_modulated), \"B L (H D) -> B L H D\", H=attn.num_heads)\n\n        img_q, img_k = attn.img_attn.norm(img_q, img_k, img_v)  # RMSNorm for QK Norm as in SD3 paper\n        if not attn.img_attn.fused_qkv:\n            img_q = rearrange(img_q, \"B L H D -> B H L D\")\n            img_k = rearrange(img_k, \"B L H D -> B H L D\")\n            img_v = rearrange(img_v, \"B L H D -> B H L D\")\n\n        # prepare txt for attention\n        txt_modulated = attn.txt_norm1(txt)\n        txt_modulated = (1 + txt_mod1.scale) * txt_modulated + txt_mod1.shift\n        if attn.txt_attn.fused_qkv:\n            txt_qkv = attn.txt_attn.qkv(txt_modulated)\n            txt_q, txt_k, txt_v = rearrange(txt_qkv, \"B L (K H D) -> K B H L D\", K=3, H=attn.num_heads, D=attn.head_dim)\n        else:\n            txt_q = rearrange(attn.txt_attn.q_proj(txt_modulated), \"B L (H D) -> B L H D\", H=attn.num_heads)\n            txt_k = rearrange(attn.txt_attn.k_proj(txt_modulated), \"B L (H D) -> B L H D\", H=attn.num_heads)\n            txt_v = rearrange(attn.txt_attn.v_proj(txt_modulated), \"B L (H D) -> B L H D\", H=attn.num_heads)\n        txt_q, txt_k = attn.txt_attn.norm(txt_q, txt_k, txt_v)\n        if not attn.txt_attn.fused_qkv:\n            txt_q = rearrange(txt_q, \"B L H D -> B H L D\")\n            txt_k = rearrange(txt_k, \"B L H D -> B H L D\")\n            txt_v = rearrange(txt_v, \"B L H D -> B H L D\")\n\n        # run actual attention, image and text attention are calculated together by concat different attn heads\n        q = torch.cat((txt_q, img_q), dim=2)\n        k = torch.cat((txt_k, img_k), dim=2)\n        v = torch.cat((txt_v, img_v), dim=2)\n\n        attn1 = attention(q, k, v, pe=pe)\n        txt_attn, img_attn = attn1[:, : txt_q.shape[2]], attn1[:, txt_q.shape[2] :]\n\n        # calculate the img bloks\n        img = img + img_mod1.gate * attn.img_attn.proj(img_attn)\n        img = img + img_mod2.gate * attn.img_mlp((1 + img_mod2.scale) * attn.img_norm2(img) + img_mod2.shift)\n\n        # calculate the txt bloks\n        txt = txt + txt_mod1.gate * attn.txt_attn.proj(txt_attn)\n        txt = txt + txt_mod2.gate * attn.txt_mlp((1 + txt_mod2.scale) * attn.txt_norm2(txt) + txt_mod2.shift)\n        return img, txt\n\n\nclass DoubleStreamBlock(nn.Module):\n    def __init__(\n        self,\n        hidden_size: int,\n        num_heads: int,\n        mlp_ratio: float,\n        qkv_bias: bool = False,\n        fused_qkv: bool = True,\n    ):\n        super().__init__()\n        mlp_hidden_dim = int(hidden_size * mlp_ratio)\n        self.num_heads = num_heads\n        self.hidden_size = hidden_size\n        self.head_dim = hidden_size // num_heads\n\n        # image stream\n        self.img_mod = Modulation(hidden_size, double=True)\n        self.img_norm1 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)\n        self.img_attn = SelfAttention(dim=hidden_size, num_heads=num_heads, qkv_bias=qkv_bias, fused_qkv=fused_qkv)\n\n        self.img_norm2 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)\n        self.img_mlp = nn.Sequential(\n            nn.Linear(hidden_size, mlp_hidden_dim, bias=True),\n            nn.GELU(approximate=\"tanh\"),\n            nn.Linear(mlp_hidden_dim, hidden_size, bias=True),\n        )\n\n        # text stream\n        self.txt_mod = Modulation(hidden_size, double=True)\n        self.txt_norm1 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)\n        self.txt_attn = SelfAttention(dim=hidden_size, num_heads=num_heads, qkv_bias=qkv_bias, fused_qkv=fused_qkv)\n\n        self.txt_norm2 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)\n        self.txt_mlp = nn.Sequential(\n            nn.Linear(hidden_size, mlp_hidden_dim, bias=True),\n            nn.GELU(approximate=\"tanh\"),\n            nn.Linear(mlp_hidden_dim, hidden_size, bias=True),\n        )\n\n        # processor\n        processor = DoubleStreamBlockProcessor()\n        self.set_processor(processor)\n\n    def set_processor(self, processor) -> None:\n        self.processor = processor\n\n    def get_processor(self):\n        return self.processor\n\n    def forward(self, img: Tensor, txt: Tensor, vec: Tensor, pe: Tensor, **kwargs) -> tuple[Tensor, Tensor]:\n        return self.processor(self, img, txt, vec, pe)\n\n\nclass SingleStreamBlockProcessor:\n    def __call__(self, attn: nn.Module, x: Tensor, vec: Tensor, pe: Tensor) -> Tensor:\n        mod, _ = attn.modulation(vec)\n        x_mod = (1 + mod.scale) * attn.pre_norm(x) + mod.shift\n        if attn.fused_qkv:\n            qkv, mlp = torch.split(attn.linear1(x_mod), [3 * attn.hidden_size, attn.mlp_hidden_dim], dim=-1)\n            q, k, v = rearrange(qkv, \"B L (K H D) -> K B H L D\", K=3, H=attn.num_heads)\n        else:\n            q = rearrange(attn.q_proj(x_mod), \"B L (H D) -> B L H D\", H=attn.num_heads)\n            k = rearrange(attn.k_proj(x_mod), \"B L (H D) -> B L H D\", H=attn.num_heads)\n            v, mlp = torch.split(attn.v_mlp(x_mod), [attn.hidden_size, attn.mlp_hidden_dim], dim=-1)\n            v = rearrange(v, \"B L (H D) -> B L H D\", H=attn.num_heads)\n\n        q, k = attn.norm(q, k, v)\n        if not attn.fused_qkv:\n            q = rearrange(q, \"B L H D -> B H L D\")\n            k = rearrange(k, \"B L H D -> B H L D\")\n            v = rearrange(v, \"B L H D -> B H L D\")\n\n        # compute attention\n        attn_1 = attention(q, k, v, pe=pe)\n\n        # compute activation in mlp stream, cat again and run second linear layer\n        output = attn.linear2(torch.cat((attn_1, attn.mlp_act(mlp)), 2))\n        output = x + mod.gate * output\n        return output\n\n\nclass SingleStreamBlock(nn.Module):\n    \"\"\"\n    A DiT block with parallel linear layers as described in\n    https://arxiv.org/abs/2302.05442 and adapted modulation interface.\n    \"\"\"\n\n    def __init__(\n        self,\n        hidden_size: int,\n        num_heads: int,\n        mlp_ratio: float = 4.0,\n        qk_scale: float | None = None,\n        fused_qkv: bool = True,\n    ):\n        super().__init__()\n        self.hidden_dim = hidden_size\n        self.num_heads = num_heads\n        self.head_dim = hidden_size // num_heads\n        self.scale = qk_scale or self.head_dim**-0.5\n        self.fused_qkv = fused_qkv\n\n        self.mlp_hidden_dim = int(hidden_size * mlp_ratio)\n        if fused_qkv:\n            # qkv and mlp_in\n            self.linear1 = nn.Linear(hidden_size, hidden_size * 3 + self.mlp_hidden_dim)\n        else:\n            self.q_proj = nn.Linear(hidden_size, hidden_size)\n            self.k_proj = nn.Linear(hidden_size, hidden_size)\n            self.v_mlp = nn.Linear(hidden_size, hidden_size + self.mlp_hidden_dim)\n\n        # proj and mlp_out\n        self.linear2 = nn.Linear(hidden_size + self.mlp_hidden_dim, hidden_size)\n\n        self.norm = QKNorm(self.head_dim)\n\n        self.hidden_size = hidden_size\n        self.pre_norm = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)\n\n        self.mlp_act = nn.GELU(approximate=\"tanh\")\n        self.modulation = Modulation(hidden_size, double=False)\n\n        processor = SingleStreamBlockProcessor()\n        self.set_processor(processor)\n\n    def set_processor(self, processor) -> None:\n        self.processor = processor\n\n    def get_processor(self):\n        return self.processor\n\n    def forward(self, x: Tensor, vec: Tensor, pe: Tensor, **kwargs) -> Tensor:\n        return self.processor(self, x, vec, pe)\n\n\nclass LastLayer(nn.Module):\n    def __init__(self, hidden_size: int, patch_size: int, out_channels: int):\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(nn.SiLU(), nn.Linear(hidden_size, 2 * hidden_size, bias=True))\n\n    def forward(self, x: Tensor, vec: Tensor) -> Tensor:\n        shift, scale = self.adaLN_modulation(vec).chunk(2, dim=1)\n        x = (1 + scale[:, None, :]) * self.norm_final(x) + shift[:, None, :]\n        x = self.linear(x)\n        return x\n"
  },
  {
    "path": "opensora/models/mmdit/math.py",
    "content": "import torch\nfrom einops import rearrange\nfrom flash_attn import flash_attn_func as flash_attn_func_v2\nfrom liger_kernel.ops.rope import LigerRopeFunction\nfrom torch import Tensor\nfrom typing import Tuple\n\ntry:\n    from flash_attn_interface import flash_attn_func as flash_attn_func_v3\n\n    SUPPORT_FA3 = True\nexcept:\n    SUPPORT_FA3 = False\n\n\ndef flash_attn_func(q: Tensor, k: Tensor, v: Tensor) -> Tensor:\n    if SUPPORT_FA3:\n        return flash_attn_func_v3(q, k, v)[0]\n    return flash_attn_func_v2(q, k, v)\n\n\ndef attention(q: Tensor, k: Tensor, v: Tensor, pe) -> Tensor:\n    if isinstance(pe, torch.Tensor):\n        q, k = apply_rope(q, k, pe)\n    else:\n        cos, sin = pe\n        q, k = LigerRopeFunction.apply(q, k, cos, sin)\n        # to compare with the original implementation\n        # k = reverse_rearrange_tensor(k)\n    q = rearrange(q, \"B H L D -> B L H D\")\n    k = rearrange(k, \"B H L D -> B L H D\")\n    v = rearrange(v, \"B H L D -> B L H D\")\n    x = flash_attn_func(q, k, v)\n    x = rearrange(x, \"B L H D -> B L (H D)\")\n\n    return x\n\n\ndef liger_rope(pos: Tensor, dim: int, theta: int) -> Tuple:\n    assert dim % 2 == 0\n    scale = torch.arange(0, dim, 2, dtype=torch.float32, device=pos.device) / dim\n    omega = 1.0 / (theta**scale)\n    out = torch.einsum(\"...n,d->...nd\", pos, omega)  # (b, seq, dim//2)\n    cos = out.cos()\n    sin = out.sin()\n\n    return (cos, sin)\n\n\ndef rope(pos: Tensor, dim: int, theta: int) -> Tuple:\n    assert dim % 2 == 0\n    scale = torch.arange(0, dim, 2, dtype=torch.float64, device=pos.device) / dim\n    omega = 1.0 / (theta**scale)\n    out = torch.einsum(\"...n,d->...nd\", pos, omega)\n    out = torch.stack([torch.cos(out), -torch.sin(out), torch.sin(out), torch.cos(out)], dim=-1)\n    out = rearrange(out, \"b n d (i j) -> b n d i j\", i=2, j=2)\n    return out.float()\n\n\ndef apply_rope(xq: Tensor, xk: Tensor, freqs_cis: Tensor) -> tuple[Tensor, Tensor]:\n    xq_ = xq.float().reshape(*xq.shape[:-1], -1, 1, 2)\n    xk_ = xk.float().reshape(*xk.shape[:-1], -1, 1, 2)\n    xq_out = freqs_cis[..., 0] * xq_[..., 0] + freqs_cis[..., 1] * xq_[..., 1]\n    xk_out = freqs_cis[..., 0] * xk_[..., 0] + freqs_cis[..., 1] * xk_[..., 1]\n    return xq_out.reshape(*xq.shape).type_as(xq), xk_out.reshape(*xk.shape).type_as(xk)\n\n\ndef rearrange_tensor(tensor):\n    \"\"\"\n    Rearranges the last dimension (D) of the input tensor based on the specified mapping:\n    2d -> d, 2d+1 -> D/2 + d.\n\n    Args:\n        tensor (torch.Tensor): Input tensor of shape [B, H, L, D], where D is even.\n\n    Returns:\n        torch.Tensor: Tensor with rearranged last dimension, same shape as input.\n    \"\"\"\n    B, H, L, D = tensor.shape\n    if D % 2 != 0:\n        raise ValueError(\"The last dimension D must be even.\")\n\n    half_D = D // 2\n    indices = torch.empty(D, dtype=torch.long, device=tensor.device)\n\n    # Fill the indices based on the mapping rule\n    indices[:half_D] = torch.arange(0, D, 2, device=tensor.device)\n    indices[half_D:] = torch.arange(1, D, 2, device=tensor.device)\n\n    # Rearrange the tensor based on the computed indices\n    return tensor.index_select(dim=-1, index=indices)\n\n\ndef reverse_rearrange_tensor(tensor):\n    \"\"\"\n    Restores the original order of the last dimension (D) of the input tensor based on the reverse mapping:\n    d -> 2d, D/2 + d -> 2d + 1.\n\n    Args:\n        tensor (torch.Tensor): Input tensor of shape [B, H, L, D], where D is even.\n\n    Returns:\n        torch.Tensor: Tensor with restored original last dimension order, same shape as input.\n    \"\"\"\n    B, H, L, D = tensor.shape\n    if D % 2 != 0:\n        raise ValueError(\"The last dimension D must be even.\")\n\n    half_D = D // 2\n    reverse_indices = torch.empty(D, dtype=torch.long, device=tensor.device)\n\n    # Fill the reverse indices to restore the original order\n    reverse_indices[::2] = torch.arange(half_D, device=tensor.device)\n    reverse_indices[1::2] = torch.arange(half_D, D, device=tensor.device)\n\n    # Rearrange the tensor based on the reverse indices\n    return tensor.index_select(dim=-1, index=reverse_indices)\n"
  },
  {
    "path": "opensora/models/mmdit/model.py",
    "content": "# Modified from Flux\n#\n# Copyright 2024 Black Forest Labs\n\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n\n#     http://www.apache.org/licenses/LICENSE-2.0\n\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# This source code is licensed under the license found in the\n# LICENSE file in the root directory of this source tree.\n\nfrom dataclasses import dataclass\n\nimport torch\nfrom torch import Tensor, nn\n\nfrom opensora.acceleration.checkpoint import auto_grad_checkpoint\nfrom opensora.models.mmdit.layers import (\n    DoubleStreamBlock,\n    EmbedND,\n    LastLayer,\n    LigerEmbedND,\n    MLPEmbedder,\n    SingleStreamBlock,\n    timestep_embedding,\n)\nfrom opensora.registry import MODELS\nfrom opensora.utils.ckpt import load_checkpoint\n\n\n@dataclass\nclass MMDiTConfig:\n    model_type = \"MMDiT\"\n    from_pretrained: str\n    cache_dir: str\n    in_channels: int\n    vec_in_dim: int\n    context_in_dim: int\n    hidden_size: int\n    mlp_ratio: float\n    num_heads: int\n    depth: int\n    depth_single_blocks: int\n    axes_dim: list[int]\n    theta: int\n    qkv_bias: bool\n    guidance_embed: bool\n    cond_embed: bool = False\n    fused_qkv: bool = True\n    grad_ckpt_settings: tuple[int, int] | None = None\n    use_liger_rope: bool = False\n    patch_size: int = 2\n\n    def get(self, attribute_name, default=None):\n        return getattr(self, attribute_name, default)\n\n    def __contains__(self, attribute_name):\n        return hasattr(self, attribute_name)\n\n\nclass MMDiTModel(nn.Module):\n    config_class = MMDiTConfig\n\n    def __init__(self, config: MMDiTConfig):\n        super().__init__()\n\n        self.config = config\n        self.in_channels = config.in_channels\n        self.out_channels = self.in_channels\n        self.patch_size = config.patch_size\n\n        if config.hidden_size % config.num_heads != 0:\n            raise ValueError(\n                f\"Hidden size {config.hidden_size} must be divisible by num_heads {config.num_heads}\"\n            )\n\n        pe_dim = config.hidden_size // config.num_heads\n        if sum(config.axes_dim) != pe_dim:\n            raise ValueError(\n                f\"Got {config.axes_dim} but expected positional dim {pe_dim}\"\n            )\n\n        self.hidden_size = config.hidden_size\n        self.num_heads = config.num_heads\n        pe_embedder_cls = LigerEmbedND if config.use_liger_rope else EmbedND\n        self.pe_embedder = pe_embedder_cls(\n            dim=pe_dim, theta=config.theta, axes_dim=config.axes_dim\n        )\n\n        self.img_in = nn.Linear(self.in_channels, self.hidden_size, bias=True)\n        self.time_in = MLPEmbedder(in_dim=256, hidden_dim=self.hidden_size)\n        self.vector_in = MLPEmbedder(config.vec_in_dim, self.hidden_size)\n        self.guidance_in = (\n            MLPEmbedder(in_dim=256, hidden_dim=self.hidden_size)\n            if config.guidance_embed\n            else nn.Identity()\n        )\n        self.cond_in = (\n            nn.Linear(\n                self.in_channels + self.patch_size**2, self.hidden_size, bias=True\n            )\n            if config.cond_embed\n            else nn.Identity()\n        )\n        self.txt_in = nn.Linear(config.context_in_dim, self.hidden_size)\n\n        self.double_blocks = nn.ModuleList(\n            [\n                DoubleStreamBlock(\n                    self.hidden_size,\n                    self.num_heads,\n                    mlp_ratio=config.mlp_ratio,\n                    qkv_bias=config.qkv_bias,\n                    fused_qkv=config.fused_qkv,\n                )\n                for _ in range(config.depth)\n            ]\n        )\n\n        self.single_blocks = nn.ModuleList(\n            [\n                SingleStreamBlock(\n                    self.hidden_size,\n                    self.num_heads,\n                    mlp_ratio=config.mlp_ratio,\n                    fused_qkv=config.fused_qkv,\n                )\n                for _ in range(config.depth_single_blocks)\n            ]\n        )\n\n        self.final_layer = LastLayer(self.hidden_size, 1, self.out_channels)\n        self.initialize_weights()\n\n        if self.config.grad_ckpt_settings:\n            self.forward = self.forward_selective_ckpt\n        else:\n            self.forward = self.forward_ckpt\n        self._input_requires_grad = False\n\n    def initialize_weights(self):\n        if self.config.cond_embed:\n            nn.init.zeros_(self.cond_in.weight)\n            nn.init.zeros_(self.cond_in.bias)\n\n    def prepare_block_inputs(\n        self,\n        img: Tensor,\n        img_ids: Tensor,\n        txt: Tensor,  # t5 encoded vec\n        txt_ids: Tensor,\n        timesteps: Tensor,\n        y_vec: Tensor,  # clip encoded vec\n        cond: Tensor = None,\n        guidance: Tensor | None = None,\n    ):\n        \"\"\"\n        obtain the processed:\n            img: projected noisy img latent,\n            txt: text context (from t5),\n            vec: clip encoded vector,\n            pe: the positional embeddings for concatenated img and txt\n        \"\"\"\n        if img.ndim != 3 or txt.ndim != 3:\n            raise ValueError(\"Input img and txt tensors must have 3 dimensions.\")\n\n        # running on sequences img\n        img = self.img_in(img)\n        if self.config.cond_embed:\n            if cond is None:\n                raise ValueError(\"Didn't get conditional input for conditional model.\")\n            img = img + self.cond_in(cond)\n\n        vec = self.time_in(timestep_embedding(timesteps, 256))\n        if self.config.guidance_embed:\n            if guidance is None:\n                raise ValueError(\n                    \"Didn't get guidance strength for guidance distilled model.\"\n                )\n            vec = vec + self.guidance_in(timestep_embedding(guidance, 256))\n        vec = vec + self.vector_in(y_vec)\n\n        txt = self.txt_in(txt)\n\n        # concat: 4096 + t*h*2/4\n        ids = torch.cat((txt_ids, img_ids), dim=1)\n        pe = self.pe_embedder(ids)\n\n        if self._input_requires_grad:\n            # we only apply lora to double/single blocks, thus we only need to enable grad for these inputs\n            img.requires_grad_()\n            txt.requires_grad_()\n\n        return img, txt, vec, pe\n\n    def enable_input_require_grads(self):\n        \"\"\"Fit peft lora. This method should not be called manually.\"\"\"\n        self._input_requires_grad = True\n\n    def forward_ckpt(\n        self,\n        img: Tensor,\n        img_ids: Tensor,\n        txt: Tensor,\n        txt_ids: Tensor,\n        timesteps: Tensor,\n        y_vec: Tensor,\n        cond: Tensor = None,\n        guidance: Tensor | None = None,\n        **kwargs,\n    ) -> Tensor:\n        img, txt, vec, pe = self.prepare_block_inputs(\n            img, img_ids, txt, txt_ids, timesteps, y_vec, cond, guidance\n        )\n\n        for block in self.double_blocks:\n            img, txt = auto_grad_checkpoint(block, img, txt, vec, pe)\n\n        img = torch.cat((txt, img), 1)\n        for block in self.single_blocks:\n            img = auto_grad_checkpoint(block, img, vec, pe)\n        img = img[:, txt.shape[1] :, ...]\n\n        img = self.final_layer(img, vec)  # (N, T, patch_size ** 2 * out_channels)\n        return img\n\n    def forward_selective_ckpt(\n        self,\n        img: Tensor,\n        img_ids: Tensor,\n        txt: Tensor,\n        txt_ids: Tensor,\n        timesteps: Tensor,\n        y_vec: Tensor,\n        cond: Tensor = None,\n        guidance: Tensor | None = None,\n        **kwargs,\n    ) -> Tensor:\n        img, txt, vec, pe = self.prepare_block_inputs(\n            img, img_ids, txt, txt_ids, timesteps, y_vec, cond, guidance\n        )\n\n        ckpt_depth_double = self.config.grad_ckpt_settings[0]\n        for block in self.double_blocks[:ckpt_depth_double]:\n            img, txt = auto_grad_checkpoint(block, img, txt, vec, pe)\n\n        for block in self.double_blocks[ckpt_depth_double:]:\n            img, txt = block(img, txt, vec, pe)\n\n        ckpt_depth_single = self.config.grad_ckpt_settings[1]\n        img = torch.cat((txt, img), 1)\n        for block in self.single_blocks[:ckpt_depth_single]:\n            img = auto_grad_checkpoint(block, img, vec, pe)\n        for block in self.single_blocks[ckpt_depth_single:]:\n            img = block(img, vec, pe)\n\n        img = img[:, txt.shape[1] :, ...]\n\n        img = self.final_layer(img, vec)  # (N, T, patch_size ** 2 * out_channels)\n        return img\n\n\n@MODELS.register_module(\"flux\")\ndef Flux(\n    cache_dir: str = None,\n    from_pretrained: str = None,\n    device_map: str | torch.device = \"cuda\",\n    torch_dtype: torch.dtype = torch.bfloat16,\n    strict_load: bool = False,\n    **kwargs,\n) -> MMDiTModel:\n    config = MMDiTConfig(\n        from_pretrained=from_pretrained,\n        cache_dir=cache_dir,\n        **kwargs,\n    )\n    low_precision_init = from_pretrained is not None and len(from_pretrained) > 0\n    if low_precision_init:\n        default_dtype = torch.get_default_dtype()\n        torch.set_default_dtype(torch_dtype)\n    with torch.device(device_map):\n        model = MMDiTModel(config)\n    if low_precision_init:\n        torch.set_default_dtype(default_dtype)\n    else:\n        model = model.to(torch_dtype)\n    if from_pretrained:\n        model = load_checkpoint(\n            model,\n            from_pretrained,\n            cache_dir=cache_dir,\n            device_map=device_map,\n            strict=strict_load,\n        )\n    return model\n"
  },
  {
    "path": "opensora/models/mmdit/policy.py",
    "content": "from functools import partial\nfrom typing import Dict, Union\n\nimport torch.nn as nn\nfrom colossalai.shardformer.policies.base_policy import ModulePolicyDescription, Policy, SubModuleReplacementDescription\n\nfrom opensora.models.vae.tensor_parallel import Conv3dTPCol, Conv3dTPRow, GroupNormTP\n\nfrom .distributed import ContextParallelAttention, TPUpDecoderBlockCausal3D, prepare_parallel_attention_mask\nfrom .vae import DecoderCausal3D, EncoderCausal3D\n\n\ndef gen_resnets_replacements(prefix: str, with_shortcut: bool = False):\n    replacements = [\n        SubModuleReplacementDescription(\n            suffix=f\"{prefix}.norm1\",\n            target_module=GroupNormTP,\n        ),\n        SubModuleReplacementDescription(\n            suffix=f\"{prefix}.conv1.conv\",\n            target_module=Conv3dTPRow,\n            kwargs=dict(\n                split_output=True,\n            ),\n        ),\n        SubModuleReplacementDescription(\n            suffix=f\"{prefix}.norm2\",\n            target_module=GroupNormTP,\n        ),\n        SubModuleReplacementDescription(\n            suffix=f\"{prefix}.conv2.conv\",\n            target_module=Conv3dTPRow,\n            kwargs=dict(\n                split_output=True,\n            ),\n        ),\n    ]\n    if with_shortcut:\n        replacements.append(\n            SubModuleReplacementDescription(\n                suffix=f\"{prefix}.conv_shortcut.conv\",\n                target_module=Conv3dTPRow,\n                kwargs=dict(\n                    split_output=True,\n                ),\n            )\n        )\n    return replacements\n\n\nclass HunyuanVaePolicy(Policy):\n    def config_sanity_check(self):\n        pass\n\n    def preprocess(self):\n        return self.model\n\n    def module_policy(self) -> Dict[Union[str, nn.Module], ModulePolicyDescription]:\n        policy = {}\n\n        policy[EncoderCausal3D] = ModulePolicyDescription(\n            sub_module_replacement=[\n                SubModuleReplacementDescription(\n                    suffix=\"conv_in.conv\",\n                    target_module=Conv3dTPCol,\n                ),\n                *gen_resnets_replacements(\"down_blocks[0].resnets[0]\"),\n                *gen_resnets_replacements(\"down_blocks[0].resnets[1]\"),\n                SubModuleReplacementDescription(\n                    suffix=\"down_blocks[0].downsamplers[0].conv.conv\",\n                    target_module=Conv3dTPRow,\n                    kwargs=dict(\n                        split_output=True,\n                    ),\n                ),\n                *gen_resnets_replacements(\"down_blocks[1].resnets[0]\", with_shortcut=True),\n                *gen_resnets_replacements(\"down_blocks[1].resnets[1]\"),\n                SubModuleReplacementDescription(\n                    suffix=\"down_blocks[1].downsamplers[0].conv.conv\",\n                    target_module=Conv3dTPRow,\n                ),\n                SubModuleReplacementDescription(\n                    suffix=\"mid_block.attentions[0]\",\n                    target_module=ContextParallelAttention,\n                ),\n            ],\n            attribute_replacement={\n                \"down_blocks[0].downsamplers[0].channels\": self.model.encoder.down_blocks[0].downsamplers[0].channels\n                // self.shard_config.tensor_parallel_size,\n                \"down_blocks[1].downsamplers[0].channels\": self.model.encoder.down_blocks[1].downsamplers[0].channels\n                // self.shard_config.tensor_parallel_size,\n                # \"mid_block.attentions[0].processor\": MemEfficientRingAttnProcessor(\n                #     self.shard_config.tensor_parallel_process_group\n                # ),\n            },\n            method_replacement={\n                \"prepare_attention_mask\": partial(\n                    prepare_parallel_attention_mask, cp_group=self.shard_config.tensor_parallel_process_group\n                ),\n            },\n        )\n\n        policy[DecoderCausal3D] = ModulePolicyDescription(\n            sub_module_replacement=[\n                SubModuleReplacementDescription(\n                    suffix=\"up_blocks[1].upsamplers[0]\",\n                    target_module=TPUpDecoderBlockCausal3D,\n                    kwargs=dict(\n                        split_output=True,\n                    ),\n                ),\n                *gen_resnets_replacements(\"up_blocks[2].resnets[0]\", with_shortcut=True),\n                *gen_resnets_replacements(\"up_blocks[2].resnets[1]\"),\n                *gen_resnets_replacements(\"up_blocks[2].resnets[2]\"),\n                SubModuleReplacementDescription(\n                    suffix=\"up_blocks[2].upsamplers[0].conv.conv\",\n                    target_module=Conv3dTPRow,\n                    kwargs=dict(\n                        split_output=True,\n                    ),\n                ),\n                *gen_resnets_replacements(\"up_blocks[3].resnets[0]\", with_shortcut=True),\n                *gen_resnets_replacements(\"up_blocks[3].resnets[1]\"),\n                *gen_resnets_replacements(\"up_blocks[3].resnets[2]\"),\n                SubModuleReplacementDescription(\n                    suffix=\"conv_norm_out\",\n                    target_module=GroupNormTP,\n                ),\n                SubModuleReplacementDescription(\n                    suffix=\"conv_out.conv\",\n                    target_module=Conv3dTPRow,\n                ),\n                SubModuleReplacementDescription(\n                    suffix=\"mid_block.attentions[0]\",\n                    target_module=ContextParallelAttention,\n                ),\n            ],\n            attribute_replacement={\n                \"up_blocks[2].upsamplers[0].channels\": self.model.decoder.up_blocks[2].upsamplers[0].channels\n                // self.shard_config.tensor_parallel_size,\n                # \"mid_block.attentions[0].processor\": MemEfficientRingAttnProcessor(\n                #     self.shard_config.tensor_parallel_process_group\n                # ),\n            },\n            method_replacement={\n                \"prepare_attention_mask\": partial(\n                    prepare_parallel_attention_mask, cp_group=self.shard_config.tensor_parallel_process_group\n                ),\n            },\n        )\n\n        return policy\n\n    def postprocess(self):\n        return self.model\n"
  },
  {
    "path": "opensora/models/text/__init__.py",
    "content": "from .conditioner import HFEmbedder\n"
  },
  {
    "path": "opensora/models/text/conditioner.py",
    "content": "from colossalai.shardformer import ShardConfig, ShardFormer\nfrom torch import Tensor, nn\nfrom transformers import CLIPTextModel, CLIPTokenizer, T5EncoderModel, T5Tokenizer\n\nfrom opensora.acceleration.shardformer.policy.t5_encoder import T5EncoderPolicy\nfrom opensora.registry import MODELS\n\n\n@MODELS.register_module(\"text_embedder\")\nclass HFEmbedder(nn.Module):\n    def __init__(self, from_pretrained: str, max_length: int, shardformer: bool = False, **hf_kwargs):\n        super().__init__()\n        self.is_clip = \"openai\" in from_pretrained\n        self.max_length = max_length\n        self.output_key = \"pooler_output\" if self.is_clip else \"last_hidden_state\"\n\n        if self.is_clip:\n            self.tokenizer: CLIPTokenizer = CLIPTokenizer.from_pretrained(from_pretrained, max_length=max_length)\n            self.hf_module: CLIPTextModel = CLIPTextModel.from_pretrained(from_pretrained, **hf_kwargs)\n            assert not shardformer, \"Shardformer is not supported for CLIP\"\n        else:\n            self.tokenizer: T5Tokenizer = T5Tokenizer.from_pretrained(\n                from_pretrained, max_length=max_length, legacy=True\n            )\n            self.hf_module: T5EncoderModel = T5EncoderModel.from_pretrained(from_pretrained, **hf_kwargs)\n            if shardformer:\n                self.hf_module = shardformer_t5(self.hf_module)\n\n        self.hf_module = self.hf_module.eval().requires_grad_(False)\n\n    def forward(self, text: list[str], added_tokens: int = 0, seq_align: int = 1) -> Tensor:\n        batch_encoding = self.tokenizer(\n            text,\n            truncation=True,\n            max_length=self.max_length,\n            return_length=False,\n            return_overflowing_tokens=False,\n            padding=\"max_length\",\n            return_tensors=\"pt\",\n        )\n        seq_len = batch_encoding[\"input_ids\"].shape[1]\n        if (added_tokens + seq_len) % seq_align != 0:\n            num_pad_tokens = seq_align - (added_tokens + seq_len) % seq_align\n            batch_encoding[\"input_ids\"] = nn.functional.pad(\n                batch_encoding[\"input_ids\"], (0, num_pad_tokens), value=self.tokenizer.pad_token_id\n            )\n\n        outputs = self.hf_module(\n            input_ids=batch_encoding[\"input_ids\"].to(self.hf_module.device),\n            attention_mask=None,\n            output_hidden_states=False,\n        )\n        return outputs[self.output_key]\n\n\ndef shardformer_t5(t5: T5EncoderModel) -> T5EncoderModel:\n    \"\"\"\n    Shardformer for T5 model\n\n    Args:\n        t5: T5 model to be optimized\n\n    Returns:\n        optimized T5 model\n    \"\"\"\n    dtype = t5.shared.weight.dtype\n    shard_config = ShardConfig(\n        enable_tensor_parallelism=False,\n        enable_jit_fused=True,\n    )\n    shard_former = ShardFormer(shard_config=shard_config)\n    optim_model, _ = shard_former.optimize(t5, policy=T5EncoderPolicy())\n    optim_model = optim_model.to(dtype).eval().requires_grad_(False)\n    return optim_model\n"
  },
  {
    "path": "opensora/models/vae/__init__.py",
    "content": "from .autoencoder_2d import AutoEncoderFlux\nfrom .discriminator import N_LAYER_DISCRIMINATOR_3D\n"
  },
  {
    "path": "opensora/models/vae/autoencoder_2d.py",
    "content": "# Modified from Flux\n#\n# Copyright 2024 Black Forest Labs\n\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n\n#     http://www.apache.org/licenses/LICENSE-2.0\n\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# This source code is licensed under the license found in the\n# LICENSE file in the root directory of this source tree.\n\nfrom dataclasses import dataclass\n\nimport torch\nfrom einops import rearrange\nfrom torch import Tensor, nn\nfrom torch.nn.functional import silu as swish\n\nfrom opensora.registry import MODELS\nfrom opensora.utils.ckpt import load_checkpoint\n\nfrom .utils import DiagonalGaussianDistribution\n\n\n@dataclass\nclass AutoEncoderConfig:\n    from_pretrained: str | None\n    cache_dir: str | None\n    resolution: int\n    in_channels: int\n    ch: int\n    out_ch: int\n    ch_mult: list[int]\n    num_res_blocks: int\n    z_channels: int\n    scale_factor: float\n    shift_factor: float\n    sample: bool = True\n\n\nclass AttnBlock(nn.Module):\n    def __init__(self, in_channels: int):\n        super().__init__()\n        self.norm = nn.GroupNorm(num_groups=32, num_channels=in_channels, eps=1e-6, affine=True)\n        self.q = nn.Conv2d(in_channels, in_channels, kernel_size=1)\n        self.k = nn.Conv2d(in_channels, in_channels, kernel_size=1)\n        self.v = nn.Conv2d(in_channels, in_channels, kernel_size=1)\n        self.proj_out = nn.Conv2d(in_channels, in_channels, kernel_size=1)\n\n    def attention(self, h_: Tensor) -> Tensor:\n        h_ = self.norm(h_)\n        q = self.q(h_)\n        k = self.k(h_)\n        v = self.v(h_)\n        b, c, h, w = q.shape\n        q = rearrange(q, \"b c h w -> b 1 (h w) c\").contiguous()\n        k = rearrange(k, \"b c h w -> b 1 (h w) c\").contiguous()\n        v = rearrange(v, \"b c h w -> b 1 (h w) c\").contiguous()\n        h_ = nn.functional.scaled_dot_product_attention(q, k, v)\n        return rearrange(h_, \"b 1 (h w) c -> b c h w\", h=h, w=w)\n\n    def forward(self, x: Tensor) -> Tensor:\n        return x + self.proj_out(self.attention(x))\n\n\nclass ResnetBlock(nn.Module):\n    def __init__(self, in_channels: int, out_channels: int):\n        super().__init__()\n        self.in_channels = in_channels\n        out_channels = in_channels if out_channels is None else out_channels\n        self.out_channels = out_channels\n\n        self.norm1 = nn.GroupNorm(num_groups=32, num_channels=in_channels, eps=1e-6, affine=True)\n        self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=1, padding=1)\n        self.norm2 = nn.GroupNorm(num_groups=32, num_channels=out_channels, eps=1e-6, affine=True)\n        self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=3, stride=1, padding=1)\n        if self.in_channels != self.out_channels:\n            self.nin_shortcut = nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=1, padding=0)\n\n    def forward(self, x):\n        h = x\n        h = self.norm1(h)\n        h = swish(h)\n        h = self.conv1(h)\n\n        h = self.norm2(h)\n        h = swish(h)\n        h = self.conv2(h)\n\n        if self.in_channels != self.out_channels:\n            x = self.nin_shortcut(x)\n\n        return x + h\n\n\nclass Downsample(nn.Module):\n    def __init__(self, in_channels: int):\n        super().__init__()\n        self.conv = nn.Conv2d(in_channels, in_channels, kernel_size=3, stride=2, padding=0)\n\n    def forward(self, x: Tensor) -> Tensor:\n        pad = (0, 1, 0, 1)\n        x = nn.functional.pad(x, pad, mode=\"constant\", value=0)\n        return self.conv(x)\n\n\nclass Upsample(nn.Module):\n    def __init__(self, in_channels: int):\n        super().__init__()\n        self.conv = nn.Conv2d(in_channels, in_channels, kernel_size=3, stride=1, padding=1)\n\n    def forward(self, x: Tensor) -> Tensor:\n        x = nn.functional.interpolate(x, scale_factor=2.0, mode=\"nearest\")\n        return self.conv(x)\n\n\nclass Encoder(nn.Module):\n    def __init__(self, config: AutoEncoderConfig):\n        super().__init__()\n        self.ch = config.ch\n        self.num_resolutions = len(config.ch_mult)\n        self.num_res_blocks = config.num_res_blocks\n        self.resolution = config.resolution\n        self.in_channels = config.in_channels\n\n        # downsampling\n        self.conv_in = nn.Conv2d(config.in_channels, self.ch, kernel_size=3, stride=1, padding=1)\n\n        curr_res = config.resolution\n        in_ch_mult = (1,) + tuple(config.ch_mult)\n        self.in_ch_mult = in_ch_mult\n        self.down = nn.ModuleList()\n        block_in = self.ch\n        for i_level in range(self.num_resolutions):\n            block = nn.ModuleList()\n            attn = nn.ModuleList()\n            block_in = config.ch * in_ch_mult[i_level]\n            block_out = config.ch * config.ch_mult[i_level]\n            for _ in range(self.num_res_blocks):\n                block.append(ResnetBlock(in_channels=block_in, out_channels=block_out))\n                block_in = block_out\n            down = nn.Module()\n            down.block = block\n            down.attn = attn\n            if i_level != self.num_resolutions - 1:\n                down.downsample = Downsample(block_in)\n                curr_res = curr_res // 2\n            self.down.append(down)\n\n        # middle\n        self.mid = nn.Module()\n        self.mid.block_1 = ResnetBlock(in_channels=block_in, out_channels=block_in)\n        self.mid.attn_1 = AttnBlock(block_in)\n        self.mid.block_2 = ResnetBlock(in_channels=block_in, out_channels=block_in)\n\n        # end\n        self.norm_out = nn.GroupNorm(num_groups=32, num_channels=block_in, eps=1e-6, affine=True)\n        self.conv_out = nn.Conv2d(block_in, 2 * config.z_channels, kernel_size=3, stride=1, padding=1)\n\n    def forward(self, x: Tensor) -> Tensor:\n        # downsampling\n        hs = [self.conv_in(x)]\n        for i_level in range(self.num_resolutions):\n            for i_block in range(self.num_res_blocks):\n                h = self.down[i_level].block[i_block](hs[-1])\n                if len(self.down[i_level].attn) > 0:\n                    h = self.down[i_level].attn[i_block](h)\n                hs.append(h)\n            if i_level != self.num_resolutions - 1:\n                hs.append(self.down[i_level].downsample(hs[-1]))\n\n        # middle\n        h = hs[-1]\n        h = self.mid.block_1(h)\n        h = self.mid.attn_1(h)\n        h = self.mid.block_2(h)\n        # end\n        h = self.norm_out(h)\n        h = swish(h)\n        h = self.conv_out(h)\n        return h\n\n\nclass Decoder(nn.Module):\n    def __init__(self, config: AutoEncoderConfig):\n        super().__init__()\n        self.ch = config.ch\n        self.num_resolutions = len(config.ch_mult)\n        self.num_res_blocks = config.num_res_blocks\n        self.resolution = config.resolution\n        self.in_channels = config.in_channels\n        self.ffactor = 2 ** (self.num_resolutions - 1)\n\n        block_in = config.ch * config.ch_mult[self.num_resolutions - 1]\n        curr_res = config.resolution // 2 ** (self.num_resolutions - 1)\n        self.z_shape = (1, config.z_channels, curr_res, curr_res)\n\n        # z to block_in\n        self.conv_in = nn.Conv2d(config.z_channels, block_in, kernel_size=3, stride=1, padding=1)\n\n        # middle\n        self.mid = nn.Module()\n        self.mid.block_1 = ResnetBlock(in_channels=block_in, out_channels=block_in)\n        self.mid.attn_1 = AttnBlock(block_in)\n        self.mid.block_2 = ResnetBlock(in_channels=block_in, out_channels=block_in)\n\n        # upsampling\n        self.up = nn.ModuleList()\n        for i_level in reversed(range(self.num_resolutions)):\n            block = nn.ModuleList()\n            attn = nn.ModuleList()\n            block_out = config.ch * config.ch_mult[i_level]\n            for _ in range(self.num_res_blocks + 1):\n                block.append(ResnetBlock(in_channels=block_in, out_channels=block_out))\n                block_in = block_out\n            up = nn.Module()\n            up.block = block\n            up.attn = attn\n            if i_level != 0:\n                up.upsample = Upsample(block_in)\n                curr_res = curr_res * 2\n            self.up.insert(0, up)  # prepend to get consistent order\n\n        # end\n        self.norm_out = nn.GroupNorm(num_groups=32, num_channels=block_in, eps=1e-6, affine=True)\n        self.conv_out = nn.Conv2d(block_in, config.out_ch, kernel_size=3, stride=1, padding=1)\n\n    def forward(self, z: Tensor) -> Tensor:\n        # z to block_in\n        h = self.conv_in(z)\n\n        # middle\n        h = self.mid.block_1(h)\n        h = self.mid.attn_1(h)\n        h = self.mid.block_2(h)\n\n        # upsampling\n        for i_level in reversed(range(self.num_resolutions)):\n            for i_block in range(self.num_res_blocks + 1):\n                h = self.up[i_level].block[i_block](h)\n                if len(self.up[i_level].attn) > 0:\n                    h = self.up[i_level].attn[i_block](h)\n            if i_level != 0:\n                h = self.up[i_level].upsample(h)\n\n        # end\n        h = self.norm_out(h)\n        h = swish(h)\n        return self.conv_out(h)\n\n\nclass AutoEncoder(nn.Module):\n    def __init__(self, config: AutoEncoderConfig):\n        super().__init__()\n        self.encoder = Encoder(config)\n        self.decoder = Decoder(config)\n        self.scale_factor = config.scale_factor\n        self.shift_factor = config.shift_factor\n        self.sample = config.sample\n\n    def encode_(self, x: Tensor) -> tuple[Tensor, DiagonalGaussianDistribution]:\n        T = x.shape[2]\n        x = rearrange(x, \"b c t h w -> (b t) c h w\")\n        params = self.encoder(x)\n        params = rearrange(params, \"(b t) c h w -> b c t h w\", t=T)\n        posterior = DiagonalGaussianDistribution(params)\n        if self.sample:\n            z = posterior.sample()\n        else:\n            z = posterior.mode()\n        z = self.scale_factor * (z - self.shift_factor)\n        return z, posterior\n\n    def encode(self, x: Tensor) -> Tensor:\n        return self.encode_(x)[0]\n\n    def decode(self, z: Tensor) -> Tensor:\n        T = z.shape[2]\n        z = rearrange(z, \"b c t h w -> (b t) c h w\")\n        z = z / self.scale_factor + self.shift_factor\n        x = self.decoder(z)\n        x = rearrange(x, \"(b t) c h w -> b c t h w\", t=T)\n        return x\n\n    def forward(self, x: Tensor) -> tuple[Tensor, DiagonalGaussianDistribution, Tensor]:\n        # encode\n        x.shape[2]\n        z, posterior = self.encode_(x)\n        # decode\n        x_rec = self.decode(z)\n\n        return x_rec, posterior, z\n\n    def get_last_layer(self):\n        return self.decoder.conv_out.weight\n\n\n@MODELS.register_module(\"autoencoder_2d\")\ndef AutoEncoderFlux(\n    from_pretrained: str,\n    cache_dir=None,\n    resolution=256,\n    in_channels=3,\n    ch=128,\n    out_ch=3,\n    ch_mult=[1, 2, 4, 4],\n    num_res_blocks=2,\n    z_channels=16,\n    scale_factor=0.3611,\n    shift_factor=0.1159,\n    device_map: str | torch.device = \"cuda\",\n    torch_dtype: torch.dtype = torch.bfloat16,\n) -> AutoEncoder:\n    config = AutoEncoderConfig(\n        from_pretrained=from_pretrained,\n        cache_dir=cache_dir,\n        resolution=resolution,\n        in_channels=in_channels,\n        ch=ch,\n        out_ch=out_ch,\n        ch_mult=ch_mult,\n        num_res_blocks=num_res_blocks,\n        z_channels=z_channels,\n        scale_factor=scale_factor,\n        shift_factor=shift_factor,\n    )\n    with torch.device(device_map):\n        model = AutoEncoder(config).to(torch_dtype)\n    if from_pretrained:\n        model = load_checkpoint(model, from_pretrained, cache_dir=cache_dir, device_map=device_map)\n    return model\n"
  },
  {
    "path": "opensora/models/vae/discriminator.py",
    "content": "import os\n\nimport torch.nn as nn\n\nfrom opensora.registry import MODELS\nfrom opensora.utils.ckpt import load_checkpoint\n\n\ndef weights_init(m):\n    classname = m.__class__.__name__\n    if classname.find(\"Conv\") != -1:\n        nn.init.normal_(m.weight.data, 0.0, 0.02)\n    elif classname.find(\"BatchNorm\") != -1:\n        nn.init.normal_(m.weight.data, 1.0, 0.02)\n        nn.init.constant_(m.bias.data, 0)\n\n\ndef weights_init_conv(m):\n    if hasattr(m, \"conv\"):\n        m = m.conv\n    classname = m.__class__.__name__\n    if classname.find(\"Conv\") != -1:\n        nn.init.normal_(m.weight.data, 0.0, 0.02)\n    elif classname.find(\"BatchNorm\") != -1:\n        nn.init.normal_(m.weight.data, 1.0, 0.02)\n        nn.init.constant_(m.bias.data, 0)\n\n\nclass NLayerDiscriminator3D(nn.Module):\n    \"\"\"Defines a 3D PatchGAN discriminator as in Pix2Pix but for 3D inputs.\"\"\"\n\n    def __init__(\n        self,\n        input_nc=1,\n        ndf=64,\n        n_layers=5,\n        norm_layer=nn.BatchNorm3d,\n        conv_cls=\"conv3d\",\n        dropout=0.30,\n    ):\n        \"\"\"\n        Construct a 3D PatchGAN discriminator\n\n        Parameters:\n            input_nc (int)  -- the number of channels in input volumes\n            ndf (int)       -- the number of filters in the last conv layer\n            n_layers (int)  -- the number of conv layers in the discriminator\n            use_actnorm (bool) -- flag to use actnorm instead of batchnorm\n        \"\"\"\n        super(NLayerDiscriminator3D, self).__init__()\n        assert conv_cls == \"conv3d\"\n        use_bias = False\n\n        kw = 3\n        padw = 1\n        sequence = [nn.Conv3d(input_nc, ndf, kernel_size=kw, stride=2, padding=padw), nn.LeakyReLU(0.2, True)]\n        nf_mult = 1\n        nf_mult_prev = 1\n        for n in range(1, n_layers):  # gradually increase the number of filters\n            nf_mult_prev = nf_mult\n            nf_mult = min(2**n, 8)\n\n            sequence += [\n                nn.Conv3d(\n                    ndf * nf_mult_prev,\n                    ndf * nf_mult,\n                    kernel_size=(kw, kw, kw),\n                    stride=2 if n == 1 else (1, 2, 2),\n                    padding=padw,\n                    bias=use_bias,\n                ),\n                norm_layer(ndf * nf_mult),\n                nn.LeakyReLU(0.2, True),\n                nn.Dropout(dropout),\n            ]\n\n        nf_mult_prev = nf_mult\n        nf_mult = min(2**n_layers, 8)\n        sequence += [\n            nn.Conv3d(\n                ndf * nf_mult_prev,\n                ndf * nf_mult,\n                kernel_size=(kw, kw, kw),\n                stride=1,\n                padding=padw,\n                bias=use_bias,\n            ),\n            norm_layer(ndf * nf_mult),\n            nn.LeakyReLU(0.2, True),\n            nn.Dropout(dropout),\n            nn.Conv3d(ndf * nf_mult, 1, kernel_size=kw, stride=1, padding=padw),\n        ]\n        self.main = nn.Sequential(*sequence)\n\n    def forward(self, x):\n        \"\"\"Standard forward.\"\"\"\n        return self.main(x)\n\n\n@MODELS.register_module(\"N_Layer_discriminator_3D\")\ndef N_LAYER_DISCRIMINATOR_3D(from_pretrained=None, force_huggingface=None, **kwargs):\n    model = NLayerDiscriminator3D(**kwargs).apply(weights_init)\n    if from_pretrained is not None:\n        if force_huggingface or from_pretrained is not None and not os.path.exists(from_pretrained):\n            raise NotImplementedError\n        else:\n            load_checkpoint(model, from_pretrained)\n        print(f\"loaded model from: {from_pretrained}\")\n    return model\n"
  },
  {
    "path": "opensora/models/vae/losses.py",
    "content": "import torch\nimport torch.nn.functional as F\nfrom einops import rearrange\nfrom torch import Tensor, nn\n\nfrom opensora.models.vae.lpips import LPIPS\n\n\ndef hinge_d_loss(logits_real, logits_fake):\n    loss_real = torch.mean(F.relu(1.0 - logits_real))\n    loss_fake = torch.mean(F.relu(1.0 + logits_fake))\n    d_loss = 0.5 * (loss_real + loss_fake)\n    return d_loss\n\n\ndef vanilla_d_loss(logits_real, logits_fake):\n    d_loss = 0.5 * (\n        torch.mean(torch.nn.functional.softplus(-logits_real)) + torch.mean(torch.nn.functional.softplus(logits_fake))\n    )\n    return d_loss\n\n\ndef wgan_gp_loss(logits_real, logits_fake):\n    d_loss = 0.5 * (-logits_real.mean() + logits_fake.mean())\n    return d_loss\n\n\ndef adopt_weight(weight, global_step, threshold=0, value=0.0):\n    if global_step < threshold:\n        weight = value\n    return weight\n\n\ndef measure_perplexity(predicted_indices, n_embed):\n    # src: https://github.com/karpathy/deep-vector-quantization/blob/main/model.py\n    # eval cluster perplexity. when perplexity == num_embeddings then all clusters are used exactly equally\n    encodings = F.one_hot(predicted_indices, n_embed).float().reshape(-1, n_embed)\n    avg_probs = encodings.mean(0)\n    perplexity = (-(avg_probs * torch.log(avg_probs + 1e-10)).sum()).exp()\n    cluster_use = torch.sum(avg_probs > 0)\n    return perplexity, cluster_use\n\n\ndef l1(x, y):\n    return torch.abs(x - y)\n\n\ndef l2(x, y):\n    return torch.pow((x - y), 2)\n\n\ndef batch_mean(x):\n    return torch.sum(x) / x.shape[0]\n\n\ndef sigmoid_cross_entropy_with_logits(labels, logits):\n    # The final formulation is: max(x, 0) - x * z + log(1 + exp(-abs(x)))\n    zeros = torch.zeros_like(logits, dtype=logits.dtype)\n    condition = logits >= zeros\n    relu_logits = torch.where(condition, logits, zeros)\n    neg_abs_logits = torch.where(condition, -logits, logits)\n    return relu_logits - logits * labels + torch.log1p(torch.exp(neg_abs_logits))\n\n\ndef lecam_reg(real_pred, fake_pred, ema_real_pred, ema_fake_pred):\n    assert real_pred.ndim == 0 and ema_fake_pred.ndim == 0\n    lecam_loss = torch.mean(torch.pow(nn.ReLU()(real_pred - ema_fake_pred), 2))\n    lecam_loss += torch.mean(torch.pow(nn.ReLU()(ema_real_pred - fake_pred), 2))\n    return lecam_loss\n\n\ndef gradient_penalty_fn(images, output):\n    gradients = torch.autograd.grad(\n        outputs=output,\n        inputs=images,\n        grad_outputs=torch.ones(output.size(), device=images.device),\n        create_graph=True,\n        retain_graph=True,\n        only_inputs=True,\n    )[0]\n\n    gradients = rearrange(gradients, \"b ... -> b (...)\")\n    return ((gradients.norm(2, dim=1) - 1) ** 2).mean()\n\n\nclass VAELoss(nn.Module):\n    def __init__(\n        self,\n        logvar_init=0.0,\n        perceptual_loss_weight=1.0,\n        kl_loss_weight=5e-4,\n        device=\"cpu\",\n        dtype=\"bf16\",\n    ):\n        super().__init__()\n\n        if type(dtype) == str:\n            if dtype == \"bf16\":\n                dtype = torch.bfloat16\n            elif dtype == \"fp16\":\n                dtype = torch.float16\n            elif dtype == \"fp32\":\n                dtype = torch.float32\n            else:\n                raise NotImplementedError(f\"dtype: {dtype}\")\n\n        # KL Loss\n        self.kl_weight = kl_loss_weight\n        # Perceptual Loss\n        self.perceptual_loss_fn = LPIPS().eval().to(device, dtype)\n        self.perceptual_loss_fn.requires_grad_(False)\n        self.perceptual_loss_weight = perceptual_loss_weight\n        self.logvar = nn.Parameter(torch.ones(size=()) * logvar_init)\n\n    def forward(\n        self,\n        video,\n        recon_video,\n        posterior,\n    ) -> dict:\n        video.size(0)\n        video = rearrange(video, \"b c t h w -> (b t) c h w\").contiguous()\n        recon_video = rearrange(recon_video, \"b c t h w -> (b t) c h w\").contiguous()\n\n        # reconstruction loss\n        recon_loss = l1(video, recon_video)\n\n        # perceptual loss\n        perceptual_loss = self.perceptual_loss_fn(video, recon_video)\n        # nll loss (from reconstruction loss and perceptual loss)\n        nll_loss = recon_loss + perceptual_loss * self.perceptual_loss_weight\n        nll_loss = nll_loss / torch.exp(self.logvar) + self.logvar\n\n        # Batch Mean\n        nll_loss = batch_mean(nll_loss)\n        recon_loss = batch_mean(recon_loss)\n        numel_elements = video.numel() // video.size(0)\n        perceptual_loss = batch_mean(perceptual_loss) * numel_elements\n\n        # KL Loss\n        if posterior is None:\n            kl_loss = torch.tensor(0.0).to(video.device, video.dtype)\n        else:\n            kl_loss = posterior.kl()\n            kl_loss = batch_mean(kl_loss)\n        weighted_kl_loss = kl_loss * self.kl_weight\n\n        return {\n            \"nll_loss\": nll_loss,\n            \"kl_loss\": weighted_kl_loss,\n            \"recon_loss\": recon_loss,\n            \"perceptual_loss\": perceptual_loss,\n        }\n\n\nclass GeneratorLoss(nn.Module):\n    def __init__(self, gen_start=2001, disc_factor=1.0, disc_weight=0.5):\n        super().__init__()\n        self.disc_factor = disc_factor\n        self.gen_start = gen_start\n        self.disc_weight = disc_weight\n\n    def calculate_adaptive_weight(self, nll_loss, g_loss, last_layer):\n        nll_grads = torch.autograd.grad(nll_loss, last_layer, retain_graph=True)[0]\n        g_grads = torch.autograd.grad(g_loss, last_layer, retain_graph=True)[0]\n        d_weight = torch.norm(nll_grads) / (torch.norm(g_grads) + 1e-4)\n        d_weight = torch.clamp(d_weight, 0.0, 1e4).detach()\n        d_weight = d_weight * self.disc_weight\n        return d_weight\n\n    def forward(\n        self,\n        logits_fake,\n        nll_loss,\n        last_layer,\n        global_step,\n        is_training=True,\n    ):\n        g_loss = -torch.mean(logits_fake)\n\n        if self.disc_factor is not None and self.disc_factor > 0.0:\n            d_weight = self.calculate_adaptive_weight(nll_loss, g_loss, last_layer)\n        else:\n            d_weight = torch.tensor(1.0)\n\n        disc_factor = adopt_weight(self.disc_factor, global_step, threshold=self.gen_start)\n        weighted_gen_loss = d_weight * disc_factor * g_loss\n\n        return weighted_gen_loss, g_loss\n\n\nclass DiscriminatorLoss(nn.Module):\n    def __init__(self, disc_start=2001, disc_factor=1.0, disc_loss_type=\"hinge\"):\n        super().__init__()\n\n        assert disc_loss_type in [\"hinge\", \"vanilla\", \"wgan-gp\"]\n        self.disc_factor = disc_factor\n        self.disc_start = disc_start\n        self.disc_loss_type = disc_loss_type\n\n        if self.disc_loss_type == \"hinge\":\n            self.loss_fn = hinge_d_loss\n        elif self.disc_loss_type == \"vanilla\":\n            self.loss_fn = vanilla_d_loss\n        elif self.disc_loss_type == \"wgan-gp\":\n            self.loss_fn = wgan_gp_loss\n        else:\n            raise ValueError(f\"Unknown GAN loss '{self.disc_loss_type}'.\")\n\n    def forward(\n        self,\n        real_logits,\n        fake_logits,\n        global_step,\n    ):\n        if self.disc_factor is not None and self.disc_factor > 0.0:\n            disc_factor = adopt_weight(self.disc_factor, global_step, threshold=self.disc_start)\n            disc_loss = self.loss_fn(real_logits, fake_logits)\n            weighted_discriminator_loss = disc_factor * disc_loss\n        else:\n            weighted_discriminator_loss = 0\n\n        return weighted_discriminator_loss\n"
  },
  {
    "path": "opensora/models/vae/lpips.py",
    "content": "import hashlib\nimport os\nfrom collections import namedtuple\n\nimport requests\nimport torch\nimport torch.nn as nn\nfrom torchvision import models\nfrom tqdm import tqdm\n\nfrom opensora.acceleration.checkpoint import checkpoint\n\nURL_MAP = {\"vgg_lpips\": \"https://heibox.uni-heidelberg.de/f/607503859c864bc1b30b/?dl=1\"}\n\nCKPT_MAP = {\"vgg_lpips\": \"vgg.pth\"}\n\nMD5_MAP = {\"vgg_lpips\": \"d507d7349b931f0638a25a48a722f98a\"}\n\n\ndef md5_hash(path):\n    with open(path, \"rb\") as f:\n        content = f.read()\n    return hashlib.md5(content).hexdigest()\n\n\ndef download(url, local_path, chunk_size=1024):\n    os.makedirs(os.path.split(local_path)[0], exist_ok=True)\n    with requests.get(url, stream=True) as r:\n        total_size = int(r.headers.get(\"content-length\", 0))\n        with tqdm(total=total_size, unit=\"B\", unit_scale=True) as pbar:\n            with open(local_path, \"wb\") as f:\n                for data in r.iter_content(chunk_size=chunk_size):\n                    if data:\n                        f.write(data)\n                        pbar.update(chunk_size)\n\n\ndef get_ckpt_path(name, root=\".\", check=False):\n    assert name in URL_MAP\n    path = os.path.join(root, CKPT_MAP[name])\n    if not os.path.exists(path) or (check and not md5_hash(path) == MD5_MAP[name]):\n        print(\"Downloading {} model from {} to {}\".format(name, URL_MAP[name], path))\n        download(URL_MAP[name], path)\n        md5 = md5_hash(path)\n        assert md5 == MD5_MAP[name], md5\n    return path\n\n\nclass LPIPS(nn.Module):\n    # Learned perceptual metric\n    def __init__(self, use_dropout=True):\n        super().__init__()\n        self.scaling_layer = ScalingLayer()\n        self.chns = [64, 128, 256, 512, 512]  # vg16 features\n        self.net = vgg16(pretrained=True, requires_grad=False)\n        self.lin0 = NetLinLayer(self.chns[0], use_dropout=use_dropout)\n        self.lin1 = NetLinLayer(self.chns[1], use_dropout=use_dropout)\n        self.lin2 = NetLinLayer(self.chns[2], use_dropout=use_dropout)\n        self.lin3 = NetLinLayer(self.chns[3], use_dropout=use_dropout)\n        self.lin4 = NetLinLayer(self.chns[4], use_dropout=use_dropout)\n        self.lins = [self.lin0, self.lin1, self.lin2, self.lin3, self.lin4]\n        self.load_from_pretrained()\n        for param in self.parameters():\n            param.requires_grad = False\n\n    def load_from_pretrained(self, name=\"vgg_lpips\"):\n        path = os.path.expanduser(\"~/.cache/opensora/taming/modules/autoencoder/lpips\")\n        ckpt = get_ckpt_path(name, path)\n        self.load_state_dict(torch.load(ckpt, map_location=torch.device(\"cpu\")), strict=False)\n\n    @classmethod\n    def from_pretrained(cls, name=\"vgg_lpips\"):\n        if name != \"vgg_lpips\":\n            raise NotImplementedError\n        model = cls()\n        ckpt = get_ckpt_path(name)\n        model.load_state_dict(torch.load(ckpt, map_location=torch.device(\"cpu\")), strict=False)\n        return model\n\n    def forward_old(self, input, target):\n        in0_input, in1_input = (self.scaling_layer(input), self.scaling_layer(target))\n        outs0, outs1 = self.net(in0_input), self.net(in1_input)\n        feats0, feats1, diffs = {}, {}, {}\n        lins = [self.lin0, self.lin1, self.lin2, self.lin3, self.lin4]\n        for kk in range(len(self.chns)):\n            feats0[kk], feats1[kk] = normalize_tensor(outs0[kk]), normalize_tensor(outs1[kk])\n            diffs[kk] = (feats0[kk] - feats1[kk]) ** 2\n\n        res = [spatial_average(lins[kk].model(diffs[kk]), keepdim=True) for kk in range(len(self.chns))]\n        val = res[0]\n        for l in range(1, len(self.chns)):\n            val += res[l]\n        return val\n\n    def get_layer_loss(self, input, target, i):\n        input, target = getattr(self.net, f\"slice{i+1}\")(input), getattr(self.net, f\"slice{i+1}\")(target)\n        feats0, feats1 = normalize_tensor(input), normalize_tensor(target)\n        diff = (feats0 - feats1) ** 2\n        avg = spatial_average(self.lins[i].model(diff), keepdim=True)\n        return avg, input, target\n\n    def forward(self, input, target):\n        input, target = (self.scaling_layer(input), self.scaling_layer(target))\n\n        val = None\n        for i in range(len(self.chns)):\n            avg, input, target = checkpoint(self.get_layer_loss, input, target, i, use_reentrant=False)\n            val = avg if val is None else val + avg\n        return val\n\n\nclass ScalingLayer(nn.Module):\n    def __init__(self):\n        super(ScalingLayer, self).__init__()\n        self.register_buffer(\"shift\", torch.Tensor([-0.030, -0.088, -0.188])[None, :, None, None])\n        self.register_buffer(\"scale\", torch.Tensor([0.458, 0.448, 0.450])[None, :, None, None])\n\n    def forward(self, inp):\n        return (inp - self.shift) / self.scale\n\n\nclass NetLinLayer(nn.Module):\n    \"\"\"A single linear layer which does a 1x1 conv\"\"\"\n\n    def __init__(self, chn_in, chn_out=1, use_dropout=False):\n        super(NetLinLayer, self).__init__()\n        layers = (\n            [\n                nn.Dropout(),\n            ]\n            if (use_dropout)\n            else []\n        )\n        layers += [\n            nn.Conv2d(chn_in, chn_out, 1, stride=1, padding=0, bias=False),\n        ]\n        self.model = nn.Sequential(*layers)\n\n\nclass vgg16(torch.nn.Module):\n    def __init__(self, requires_grad=False, pretrained=True):\n        super(vgg16, self).__init__()\n        vgg_pretrained_features = models.vgg16(pretrained=pretrained).features\n        self.slice1 = torch.nn.Sequential()\n        self.slice2 = torch.nn.Sequential()\n        self.slice3 = torch.nn.Sequential()\n        self.slice4 = torch.nn.Sequential()\n        self.slice5 = torch.nn.Sequential()\n        self.N_slices = 5\n        for x in range(4):\n            self.slice1.add_module(str(x), vgg_pretrained_features[x])\n        for x in range(4, 9):\n            self.slice2.add_module(str(x), vgg_pretrained_features[x])\n        for x in range(9, 16):\n            self.slice3.add_module(str(x), vgg_pretrained_features[x])\n        for x in range(16, 23):\n            self.slice4.add_module(str(x), vgg_pretrained_features[x])\n        for x in range(23, 30):\n            self.slice5.add_module(str(x), vgg_pretrained_features[x])\n        if not requires_grad:\n            for param in self.parameters():\n                param.requires_grad = False\n\n    def forward(self, X):\n        h = self.slice1(X)\n        h_relu1_2 = h\n        h = self.slice2(h)\n        h_relu2_2 = h\n        h = self.slice3(h)\n        h_relu3_3 = h\n        h = self.slice4(h)\n        h_relu4_3 = h\n        h = self.slice5(h)\n        h_relu5_3 = h\n        vgg_outputs = namedtuple(\"VggOutputs\", [\"relu1_2\", \"relu2_2\", \"relu3_3\", \"relu4_3\", \"relu5_3\"])\n        out = vgg_outputs(h_relu1_2, h_relu2_2, h_relu3_3, h_relu4_3, h_relu5_3)\n        return out\n\n\ndef normalize_tensor(x, eps=1e-10):\n    norm_factor = torch.sqrt(torch.sum(x**2, dim=1, keepdim=True))\n    return x / (norm_factor + eps)\n\n\ndef spatial_average(x, keepdim=True):\n    return x.mean([2, 3], keepdim=keepdim)\n"
  },
  {
    "path": "opensora/models/vae/tensor_parallel.py",
    "content": "from typing import List, Optional, Union\n\nimport torch\nimport torch.distributed as dist\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom colossalai.device.device_mesh import DeviceMesh\nfrom colossalai.shardformer.layer._operation import (\n    gather_forward_split_backward,\n    reduce_forward,\n    split_forward_gather_backward,\n)\nfrom colossalai.shardformer.layer.parallel_module import ParallelModule\nfrom colossalai.tensor.d_tensor.api import (\n    distribute_tensor,\n    is_distributed_tensor,\n    shard_rowwise,\n    sharded_tensor_to_existing_param,\n)\nfrom colossalai.tensor.d_tensor.sharding_spec import ShardingSpec\nfrom torch.distributed import ProcessGroup\nfrom torch.nn.parameter import Parameter\n\nfrom .utils import ChannelChunkConv3d, channel_chunk_conv3d\n\n\ndef shard_channelwise(\n    tensor: torch.Tensor, group_or_device_mesh: Union[ProcessGroup, DeviceMesh] = None\n) -> torch.Tensor:\n    \"\"\"\n    Shard the second dim of the given tensor.\n\n    Args:\n        tensor (torch.Tensor): The tensor to be sharded.\n        group_or_device_mesh (Union[ProcessGroup, DeviceMesh], optional): The group or device mesh to shard the tensor.\n            If None, the tensor will be sharded with respect to the global process group.\n            Defaults to None.\n        inplace (bool, optional): Whether to shard the tensor in-place. Defaults to False.\n\n    Returns:\n        torch.Tensor: The sharded tensor.\n    \"\"\"\n    # if the group_or_device_mesh is None, we shard the tensor with respect to the global process group\n    if group_or_device_mesh is None:\n        group_or_device_mesh = dist.GroupMember.WORLD\n\n    if isinstance(group_or_device_mesh, ProcessGroup):\n        device_mesh = DeviceMesh.from_process_group(group_or_device_mesh)\n    else:\n        assert len(group_or_device_mesh.shape) == 1, \"Only 1D DeviceMesh is accepted for row-wise sharding.\"\n        device_mesh = group_or_device_mesh\n    sharding_spec = ShardingSpec(dim_size=tensor.dim(), dim_partition_dict={1: [0]})\n\n    return distribute_tensor(tensor, device_mesh, sharding_spec)\n\n\nclass Conv3dTPCol(nn.Conv3d):\n    \"\"\"Conv3d with column-wise tensor parallelism. This is only for inference.\"\"\"\n\n    def __init__(\n        self,\n        in_channels: int,\n        out_channels: int,\n        kernel_size: int,\n        stride: int = 1,\n        padding: int = 0,\n        dilation: int = 1,\n        groups: int = 1,\n        bias: bool = True,\n        padding_mode: str = \"zeros\",\n        device=None,\n        dtype=None,\n        tp_group=None,\n        gather_output: bool = False,\n        weight: Optional[Parameter] = None,\n        bias_: Optional[Parameter] = None,\n    ) -> None:\n        super().__init__(\n            in_channels, out_channels, kernel_size, stride, padding, dilation, groups, bias, padding_mode, device, dtype\n        )\n        self.tp_group = tp_group\n        self.gather_output = gather_output\n        self.tp_size = dist.get_world_size(tp_group)\n        self.tp_rank = dist.get_rank(tp_group)\n\n        # sanity check\n        if weight is not None:\n            assert not bias or bias_ is not None, \"bias_ must be provided if bias is True when weight is not None\"\n        else:\n            assert bias_ is None, \"bias_ must be None if weight is None\"\n\n        # Parameters.\n        if weight is None:\n            assert weight is not None, \"weight must be provided\"\n        else:\n            weight.data = weight.data.to(device=device, dtype=dtype)\n            self.weight = weight\n\n        if not is_distributed_tensor(self.weight):\n            sharded_weight = shard_rowwise(self.weight.data, self.tp_group)\n            sharded_tensor_to_existing_param(sharded_weight, self.weight)\n\n        if bias:\n            if bias_ is None:\n                assert bias is not None, \"bias must be provided\"\n            else:\n                bias_.data = bias_.data.to(device=device, dtype=dtype)\n                self.bias = bias_\n            if not is_distributed_tensor(self.bias):\n                sharded_bias = shard_rowwise(self.bias.data, self.tp_group)\n                sharded_tensor_to_existing_param(sharded_bias, self.bias)\n        else:\n            self.bias = None\n\n    @staticmethod\n    def from_native_module(\n        module: nn.Conv3d, process_group: Union[ProcessGroup, List[ProcessGroup]], **kwargs\n    ) -> ParallelModule:\n        r\"\"\"\n        Convert a native PyTorch conv3d layer to a tensor parallelized layer.\n        \"\"\"\n\n        # ensure only one process group is passed\n        if isinstance(process_group, (list, tuple)):\n            assert len(process_group) == 1, f\"Expected only one process group, got {len(process_group)}.\"\n            process_group = process_group[0]\n\n        conv3d_tp = Conv3dTPCol(\n            in_channels=module.in_channels,\n            out_channels=module.out_channels,\n            kernel_size=module.kernel_size,\n            stride=module.stride,\n            padding=module.padding,\n            dilation=module.dilation,\n            groups=module.groups,\n            bias=module.bias is not None,\n            padding_mode=module.padding_mode,\n            device=module.weight.device,\n            dtype=module.weight.dtype,\n            tp_group=process_group,\n            weight=module.weight,\n            bias_=module.bias,\n            **kwargs,\n        )\n        return conv3d_tp\n\n    def forward(self, input: torch.Tensor) -> torch.Tensor:\n        weight = self.weight\n        bias = None\n        if self.bias is not None:\n            bias = self.bias\n        out = channel_chunk_conv3d(\n            input,\n            weight,\n            bias,\n            self.stride,\n            self.padding,\n            self.dilation,\n            self.groups,\n            ChannelChunkConv3d.CONV3D_NUMEL_LIMIT,\n        )\n        if not self.gather_output:\n            return out\n        gathered_out = gather_forward_split_backward(out, 1, self.tp_group)\n        return gathered_out\n\n\nclass Conv3dTPRow(nn.Conv3d):\n    \"\"\"Conv3d with row-wise tensor parallelism. This is only for inference.\"\"\"\n\n    def __init__(\n        self,\n        in_channels: int,\n        out_channels: int,\n        kernel_size: int,\n        stride: int = 1,\n        padding: int = 0,\n        dilation: int = 1,\n        groups: int = 1,\n        bias: bool = True,\n        padding_mode: str = \"zeros\",\n        device=None,\n        dtype=None,\n        tp_group=None,\n        split_input: bool = False,\n        split_output: bool = False,\n        weight: Optional[Parameter] = None,\n        bias_: Optional[Parameter] = None,\n    ) -> None:\n        super().__init__(\n            in_channels, out_channels, kernel_size, stride, padding, dilation, groups, bias, padding_mode, device, dtype\n        )\n        self.tp_group = tp_group\n        self.split_input = split_input\n        self.split_output = split_output\n        self.tp_size = dist.get_world_size(tp_group)\n        self.tp_rank = dist.get_rank(tp_group)\n\n        # sanity check\n        if weight is not None:\n            assert not bias or bias_ is not None, \"bias_ must be provided if bias is True when weight is not None\"\n        else:\n            assert bias_ is None, \"bias_ must be None if weight is None\"\n\n        # Parameters.\n        if weight is None:\n            assert weight is not None, \"weight must be provided\"\n        else:\n            weight.data = weight.data.to(device=device, dtype=dtype)\n            self.weight = weight\n\n        if not is_distributed_tensor(self.weight):\n            sharded_weight = shard_channelwise(self.weight.data, self.tp_group)\n            sharded_tensor_to_existing_param(sharded_weight, self.weight)\n\n        if bias:\n            if bias_ is None:\n                assert bias is not None, \"bias must be provided\"\n            else:\n                bias_.data = bias_.data.to(device=device, dtype=dtype)\n                self.bias = bias_\n        else:\n            self.bias = None\n\n    @staticmethod\n    def from_native_module(\n        module: nn.Conv3d, process_group: Union[ProcessGroup, List[ProcessGroup]], **kwargs\n    ) -> ParallelModule:\n        r\"\"\"\n        Convert a native PyTorch conv3d layer to a tensor parallelized layer.\n        \"\"\"\n\n        conv3d_tp = Conv3dTPRow(\n            in_channels=module.in_channels,\n            out_channels=module.out_channels,\n            kernel_size=module.kernel_size,\n            stride=module.stride,\n            padding=module.padding,\n            dilation=module.dilation,\n            groups=module.groups,\n            bias=module.bias is not None,\n            padding_mode=module.padding_mode,\n            device=module.weight.device,\n            dtype=module.weight.dtype,\n            tp_group=process_group,\n            weight=module.weight,\n            bias_=module.bias,\n            **kwargs,\n        )\n\n        return conv3d_tp\n\n    def forward(self, input: torch.Tensor) -> torch.Tensor:\n        if self.split_input:\n            input = split_forward_gather_backward(input, 1, self.tp_group)\n        weight = self.weight\n        out = channel_chunk_conv3d(\n            input,\n            weight,\n            None,\n            self.stride,\n            self.padding,\n            self.dilation,\n            self.groups,\n            ChannelChunkConv3d.CONV3D_NUMEL_LIMIT,\n        )\n        # del input\n        out = reduce_forward(out, self.tp_group)\n        if self.bias is not None:\n            out = out + self.bias[:, None, None, None]\n        if self.split_output:\n            out = split_forward_gather_backward(out, 1, self.tp_group)\n        return out\n\n\nclass Conv2dTPRow(nn.Conv2d):\n    \"\"\"Conv2d with row-wise tensor parallelism. This is only for inference.\"\"\"\n\n    def __init__(\n        self,\n        in_channels: int,\n        out_channels: int,\n        kernel_size: int,\n        stride: int = 1,\n        padding: int = 0,\n        dilation: int = 1,\n        groups: int = 1,\n        bias: bool = True,\n        padding_mode: str = \"zeros\",\n        device=None,\n        dtype=None,\n        tp_group=None,\n        split_input: bool = False,\n        split_output: bool = False,\n        weight: Optional[Parameter] = None,\n        bias_: Optional[Parameter] = None,\n    ) -> None:\n        super().__init__(\n            in_channels, out_channels, kernel_size, stride, padding, dilation, groups, bias, padding_mode, device, dtype\n        )\n        self.tp_group = tp_group\n        self.split_input = split_input\n        self.split_output = split_output\n        self.tp_size = dist.get_world_size(tp_group)\n        self.tp_rank = dist.get_rank(tp_group)\n\n        # sanity check\n        if weight is not None:\n            assert not bias or bias_ is not None, \"bias_ must be provided if bias is True when weight is not None\"\n        else:\n            assert bias_ is None, \"bias_ must be None if weight is None\"\n\n        # Parameters.\n        if weight is None:\n            assert weight is not None, \"weight must be provided\"\n        else:\n            weight.data = weight.data.to(device=device, dtype=dtype)\n            self.weight = weight\n\n        if not is_distributed_tensor(self.weight):\n            sharded_weight = shard_channelwise(self.weight.data, self.tp_group)\n            sharded_tensor_to_existing_param(sharded_weight, self.weight)\n\n        if bias:\n            if bias_ is None:\n                assert bias is not None, \"bias must be provided\"\n            else:\n                bias_.data = bias_.data.to(device=device, dtype=dtype)\n                self.bias = bias_\n        else:\n            self.bias = None\n\n    def forward(self, input: torch.Tensor) -> torch.Tensor:\n        if self.split_input:\n            input = split_forward_gather_backward(input, 1, self.tp_group)\n        weight = self.weight\n        out = F.conv2d(\n            input,\n            weight,\n            None,\n            self.stride,\n            self.padding,\n            self.dilation,\n            self.groups,\n        )\n        # del input\n        dist.all_reduce(out, group=self.tp_group)\n        if self.bias is not None:\n            out += self.bias[:, None, None]\n        if self.split_output:\n            out = split_forward_gather_backward(out, 1, self.tp_group)\n        return out\n\n    @staticmethod\n    def from_native_module(\n        module: nn.Conv2d, process_group: Union[ProcessGroup, List[ProcessGroup]], **kwargs\n    ) -> ParallelModule:\n        r\"\"\"\n        Convert a native PyTorch conv2d layer to a tensor parallelized layer.\n        \"\"\"\n\n        conv2d_tp = Conv2dTPRow(\n            in_channels=module.in_channels,\n            out_channels=module.out_channels,\n            kernel_size=module.kernel_size,\n            stride=module.stride,\n            padding=module.padding,\n            dilation=module.dilation,\n            groups=module.groups,\n            bias=module.bias is not None,\n            padding_mode=module.padding_mode,\n            device=module.weight.device,\n            dtype=module.weight.dtype,\n            tp_group=process_group,\n            weight=module.weight,\n            bias_=module.bias,\n            **kwargs,\n        )\n        conv2d_tp.weight = module.weight\n        conv2d_tp.bias = module.bias\n        return conv2d_tp\n\n\nclass Conv1dTPRow(nn.Conv1d):\n    \"\"\"Conv1d with row-wise tensor parallelism. This is only for inference.\"\"\"\n\n    def __init__(\n        self,\n        in_channels: int,\n        out_channels: int,\n        kernel_size: int,\n        stride: int = 1,\n        padding: int = 0,\n        dilation: int = 1,\n        groups: int = 1,\n        bias: bool = True,\n        padding_mode: str = \"zeros\",\n        device=None,\n        dtype=None,\n        tp_group=None,\n        split_input: bool = False,\n        split_output: bool = False,\n        weight: Optional[Parameter] = None,\n        bias_: Optional[Parameter] = None,\n    ) -> None:\n        super().__init__(\n            in_channels, out_channels, kernel_size, stride, padding, dilation, groups, bias, padding_mode, device, dtype\n        )\n        self.tp_group = tp_group\n        self.split_input = split_input\n        self.split_output = split_output\n        self.tp_size = dist.get_world_size(tp_group)\n        self.tp_rank = dist.get_rank(tp_group)\n\n        # sanity check\n        if weight is not None:\n            assert not bias or bias_ is not None, \"bias_ must be provided if bias is True when weight is not None\"\n        else:\n            assert bias_ is None, \"bias_ must be None if weight is None\"\n\n        # Parameters.\n        if weight is None:\n            assert weight is not None, \"weight must be provided\"\n        else:\n            weight.data = weight.data.to(device=device, dtype=dtype)\n            self.weight = weight\n\n        if not is_distributed_tensor(self.weight):\n            sharded_weight = shard_channelwise(self.weight.data, self.tp_group)\n            sharded_tensor_to_existing_param(sharded_weight, self.weight)\n\n        if bias:\n            if bias_ is None:\n                assert bias is not None, \"bias must be provided\"\n            else:\n                bias_.data = bias_.data.to(device=device, dtype=dtype)\n                self.bias = bias_\n        else:\n            self.bias = None\n\n    def forward(self, input: torch.Tensor) -> torch.Tensor:\n        if self.split_input:\n            input = split_forward_gather_backward(input, 1, self.tp_group)\n\n        weight = self.weight\n        out = F.conv1d(\n            input,\n            weight,\n            None,\n            self.stride,\n            self.padding,\n            self.dilation,\n            self.groups,\n        )\n        # del input\n        dist.all_reduce(out, group=self.tp_group)\n        if self.bias is not None:\n            out += self.bias[:, None]\n        if self.split_output:\n            out = split_forward_gather_backward(out, 1, self.tp_group)\n        return out\n\n    @staticmethod\n    def from_native_module(\n        module: nn.Conv1d, process_group: Union[ProcessGroup, List[ProcessGroup]], **kwargs\n    ) -> ParallelModule:\n        r\"\"\"\n        Convert a native PyTorch conv1d layer to a tensor parallelized layer.\n        \"\"\"\n\n        conv1d_tp = Conv1dTPRow(\n            in_channels=module.in_channels,\n            out_channels=module.out_channels,\n            kernel_size=module.kernel_size,\n            stride=module.stride,\n            padding=module.padding,\n            dilation=module.dilation,\n            groups=module.groups,\n            bias=module.bias is not None,\n            padding_mode=module.padding_mode,\n            device=module.weight.device,\n            dtype=module.weight.dtype,\n            tp_group=process_group,\n            weight=module.weight,\n            bias_=module.bias,\n            **kwargs,\n        )\n        conv1d_tp.weight = module.weight\n        conv1d_tp.bias = module.bias\n        return conv1d_tp\n\n\nclass GroupNormTP(nn.GroupNorm):\n    def __init__(\n        self,\n        num_groups: int,\n        num_channels: int,\n        eps: float = 0.00001,\n        affine: bool = True,\n        device=None,\n        dtype=None,\n        tp_group=None,\n        weight: Optional[Parameter] = None,\n        bias: Optional[Parameter] = None,\n    ) -> None:\n        super().__init__(num_groups, num_channels, eps, affine, device, dtype)\n        self.tp_group = tp_group\n        self.tp_size = dist.get_world_size(tp_group)\n        self.tp_rank = dist.get_rank(tp_group)\n\n        if affine:\n            assert weight is not None, \"weight must be provided\"\n            weight.data = weight.data.to(device=device, dtype=dtype)\n            self.weight = weight\n            if not is_distributed_tensor(self.weight):\n                sharded_weight = shard_rowwise(self.weight.data, self.tp_group)\n                sharded_tensor_to_existing_param(sharded_weight, self.weight)\n\n            assert bias is not None, \"bias must be provided\"\n            bias.data = bias.data.to(device=device, dtype=dtype)\n            self.bias = bias\n            if not is_distributed_tensor(self.bias):\n                sharded_bias = shard_rowwise(self.bias.data, self.tp_group)\n                sharded_tensor_to_existing_param(sharded_bias, self.bias)\n        else:\n            self.weight = None\n            self.bias = None\n\n    def forward(self, input: torch.Tensor) -> torch.Tensor:\n        return F.group_norm(\n            input,\n            self.num_groups // self.tp_size,\n            self.weight,\n            self.bias,\n            self.eps,\n        )\n\n    @staticmethod\n    def from_native_module(\n        module: nn.GroupNorm, process_group: Union[ProcessGroup, List[ProcessGroup]], **kwargs\n    ) -> ParallelModule:\n        r\"\"\"\n        Convert a native PyTorch nn.GroupNorm layer to a tensor parallelized layer.\n        \"\"\"\n\n        group_norm_tp = GroupNormTP(\n            num_groups=module.num_groups,\n            num_channels=module.num_channels,\n            eps=module.eps,\n            affine=module.affine,\n            device=module.weight.device,\n            dtype=module.weight.dtype,\n            tp_group=process_group,\n            weight=module.weight,\n            bias=module.bias,\n            **kwargs,\n        )\n        return group_norm_tp\n"
  },
  {
    "path": "opensora/models/vae/utils.py",
    "content": "import math\n\nimport numpy as np\nimport torch\nimport torch.nn.functional as F\nfrom torch import Tensor, nn\n\nNUMEL_LIMIT = 2**30\n\n\ndef ceil_to_divisible(n: int, dividend: int) -> int:\n    return math.ceil(dividend / (dividend // n))\n\n\ndef chunked_avg_pool1d(input, kernel_size, stride=None, padding=0, ceil_mode=False, count_include_pad=True):\n    n_chunks = math.ceil(input.numel() / NUMEL_LIMIT)\n    if n_chunks == 1:\n        return F.avg_pool1d(input, kernel_size, stride, padding, ceil_mode, count_include_pad)\n    else:\n        l_in = input.shape[-1]\n        l_out = math.floor((l_in + 2 * padding - kernel_size) / stride + 1)\n        output_shape = list(input.shape)\n        output_shape[-1] = l_out\n        out_list = []\n\n        for inp_chunk in input.chunk(n_chunks, dim=0):\n            out_chunk = F.avg_pool1d(inp_chunk, kernel_size, stride, padding, ceil_mode, count_include_pad)\n            out_list.append(out_chunk)\n        return torch.cat(out_list, dim=0)\n\n\ndef chunked_interpolate(input, scale_factor):\n    output_shape = list(input.shape)\n    output_shape = output_shape[:2] + [int(i * scale_factor) for i in output_shape[2:]]\n    n_chunks = math.ceil(torch.Size(output_shape).numel() / NUMEL_LIMIT)\n    if n_chunks == 1:\n        return F.interpolate(input, scale_factor=scale_factor)\n    else:\n        out_list = []\n        n_chunks += 1\n        for inp_chunk in input.chunk(n_chunks, dim=1):\n            out_chunk = F.interpolate(inp_chunk, scale_factor=scale_factor)\n            out_list.append(out_chunk)\n        return torch.cat(out_list, dim=1)\n\n\ndef get_conv3d_output_shape(\n    input_shape: torch.Size, out_channels: int, kernel_size: list, stride: list, padding: int, dilation: list\n) -> list:\n    output_shape = [out_channels]\n    if len(input_shape) == 5:\n        output_shape.insert(0, input_shape[0])\n    for i, d in enumerate(input_shape[-3:]):\n        d_out = math.floor((d + 2 * padding[i] - dilation[i] * (kernel_size[i] - 1) - 1) / stride[i] + 1)\n        output_shape.append(d_out)\n    return output_shape\n\n\ndef get_conv3d_n_chunks(numel: int, n_channels: int, numel_limit: int):\n    n_chunks = math.ceil(numel / numel_limit)\n    n_chunks = ceil_to_divisible(n_chunks, n_channels)\n    return n_chunks\n\n\ndef channel_chunk_conv3d(\n    input: torch.Tensor,\n    weight: torch.Tensor,\n    bias: torch.Tensor,\n    stride: list,\n    padding: list,\n    dilation: list,\n    groups: int,\n    numel_limit: int,\n):\n    out_channels, in_channels = weight.shape[:2]\n    kernel_size = weight.shape[2:]\n    output_shape = get_conv3d_output_shape(input.shape, out_channels, kernel_size, stride, padding, dilation)\n    n_in_chunks = get_conv3d_n_chunks(input.numel(), in_channels, numel_limit)\n    n_out_chunks = get_conv3d_n_chunks(\n        np.prod(output_shape),\n        out_channels,\n        numel_limit,\n    )\n    if n_in_chunks == 1 and n_out_chunks == 1:\n        return F.conv3d(input, weight, bias, stride, padding, dilation, groups)\n    # output = torch.empty(output_shape, device=input.device, dtype=input.dtype)\n    # outputs = output.chunk(n_out_chunks, dim=1)\n    input_shards = input.chunk(n_in_chunks, dim=1)\n    weight_chunks = weight.chunk(n_out_chunks)\n    output_list = []\n    if bias is not None:\n        bias_chunks = bias.chunk(n_out_chunks)\n    else:\n        bias_chunks = [None] * n_out_chunks\n    for weight_, bias_ in zip(weight_chunks, bias_chunks):\n        weight_shards = weight_.chunk(n_in_chunks, dim=1)\n        o = None\n        for x, w in zip(input_shards, weight_shards):\n            if o is None:\n                o = F.conv3d(x, w, None, stride, padding, dilation, groups).float()\n            else:\n                o += F.conv3d(x, w, None, stride, padding, dilation, groups).float()\n        o = o.to(input.dtype)\n        if bias_ is not None:\n            o += bias_[None, :, None, None, None]\n        # inplace operation cannot be used during training\n        # output_.copy_(o)\n        output_list.append(o)\n    return torch.cat(output_list, dim=1)\n\n\nclass DiagonalGaussianDistribution(object):\n    def __init__(\n        self,\n        parameters,\n        deterministic=False,\n    ):\n        \"\"\"Stripped version of https://github.com/richzhang/PerceptualSimilarity/tree/master/models\"\"\"\n        self.parameters = parameters\n        self.mean, self.logvar = torch.chunk(parameters, 2, dim=1)\n        self.logvar = torch.clamp(self.logvar, -30.0, 20.0)\n        self.deterministic = deterministic\n        self.std = torch.exp(0.5 * self.logvar)\n        self.var = torch.exp(self.logvar)\n        if self.deterministic:\n            self.var = self.std = torch.zeros_like(self.mean).to(device=self.parameters.device, dtype=self.mean.dtype)\n\n    def sample(self):\n        # torch.randn: standard normal distribution\n        x = self.mean + self.std * torch.randn(self.mean.shape).to(device=self.parameters.device, dtype=self.mean.dtype)\n        return x\n\n    def kl(self, other=None):\n        if self.deterministic:\n            return torch.Tensor([0.0])\n        else:\n            if other is None:  # SCH: assumes other is a standard normal distribution\n                return 0.5 * torch.sum(torch.pow(self.mean, 2) + self.var - 1.0 - self.logvar, dim=[1, 3, 4]).flatten(0)\n            else:\n                return 0.5 * torch.sum(\n                    torch.pow(self.mean - other.mean, 2) / other.var\n                    + self.var / other.var\n                    - 1.0\n                    - self.logvar\n                    + other.logvar,\n                    dim=[1, 3, 4],\n                ).flatten(0)\n\n    def mode(self):\n        return self.mean\n\n\nclass ChannelChunkConv3d(nn.Conv3d):\n    CONV3D_NUMEL_LIMIT = 2**31\n\n    def _get_output_numel(self, input_shape: torch.Size) -> int:\n        numel = self.out_channels\n        if len(input_shape) == 5:\n            numel *= input_shape[0]\n        for i, d in enumerate(input_shape[-3:]):\n            d_out = math.floor(\n                (d + 2 * self.padding[i] - self.dilation[i] * (self.kernel_size[i] - 1) - 1) / self.stride[i] + 1\n            )\n            numel *= d_out\n        return numel\n\n    def _get_n_chunks(self, numel: int, n_channels: int):\n        n_chunks = math.ceil(numel / ChannelChunkConv3d.CONV3D_NUMEL_LIMIT)\n        n_chunks = ceil_to_divisible(n_chunks, n_channels)\n        return n_chunks\n\n    def forward(self, input: Tensor) -> Tensor:\n        if input.numel() // input.size(0) < ChannelChunkConv3d.CONV3D_NUMEL_LIMIT:\n            return super().forward(input)\n        n_in_chunks = self._get_n_chunks(input.numel(), self.in_channels)\n        n_out_chunks = self._get_n_chunks(self._get_output_numel(input.shape), self.out_channels)\n        if n_in_chunks == 1 and n_out_chunks == 1:\n            return super().forward(input)\n        outputs = []\n        input_shards = input.chunk(n_in_chunks, dim=1)\n        for weight, bias in zip(self.weight.chunk(n_out_chunks), self.bias.chunk(n_out_chunks)):\n            weight_shards = weight.chunk(n_in_chunks, dim=1)\n            o = None\n            for x, w in zip(input_shards, weight_shards):\n                if o is None:\n                    o = F.conv3d(x, w, bias, self.stride, self.padding, self.dilation, self.groups)\n                else:\n                    o += F.conv3d(x, w, None, self.stride, self.padding, self.dilation, self.groups)\n            outputs.append(o)\n        return torch.cat(outputs, dim=1)\n\n\n@torch.compile(mode=\"max-autotune-no-cudagraphs\", dynamic=True)\ndef pad_for_conv3d(x: torch.Tensor, width_pad: int, height_pad: int, time_pad: int) -> torch.Tensor:\n    if width_pad > 0 or height_pad > 0:\n        x = F.pad(x, (width_pad, width_pad, height_pad, height_pad), mode=\"constant\", value=0)\n    if time_pad > 0:\n        x = F.pad(x, (0, 0, 0, 0, time_pad, time_pad), mode=\"replicate\")\n    return x\n\n\ndef pad_for_conv3d_kernel_3x3x3(x: torch.Tensor) -> torch.Tensor:\n    n_chunks = math.ceil(x.numel() / NUMEL_LIMIT)\n    if n_chunks == 1:\n        x = F.pad(x, (1, 1, 1, 1), mode=\"constant\", value=0)\n        x = F.pad(x, (0, 0, 0, 0, 1, 1), mode=\"replicate\")\n    else:\n        out_list = []\n        n_chunks += 1\n        for inp_chunk in x.chunk(n_chunks, dim=1):\n            out_chunk = F.pad(inp_chunk, (1, 1, 1, 1), mode=\"constant\", value=0)\n            out_chunk = F.pad(out_chunk, (0, 0, 0, 0, 1, 1), mode=\"replicate\")\n            out_list.append(out_chunk)\n        x = torch.cat(out_list, dim=1)\n    return x\n\n\nclass PadConv3D(nn.Module):\n    \"\"\"\n    pad the first frame in temporal dimension\n    \"\"\"\n\n    def __init__(self, in_channels: int, out_channels: int, kernel_size: int = 3):\n        super().__init__()\n\n        if isinstance(kernel_size, int):\n            kernel_size = (kernel_size,) * 3\n        self.kernel_size = kernel_size\n\n        # == specific padding ==\n        time_kernel_size, height_kernel_size, width_kernel_size = kernel_size\n        assert time_kernel_size == height_kernel_size == width_kernel_size, \"only support cubic kernel size\"\n        if time_kernel_size == 3:\n            self.pad = pad_for_conv3d_kernel_3x3x3\n        else:\n            assert time_kernel_size == 1, f\"only support kernel size 1/3 for now, got {kernel_size}\"\n            self.pad = lambda x: x\n\n        self.conv = nn.Conv3d(\n            in_channels,\n            out_channels,\n            kernel_size=kernel_size,\n            stride=1,\n            padding=0,\n        )\n\n    def forward(self, x: Tensor) -> Tensor:\n        x = self.pad(x)\n        x = self.conv(x)\n        return x\n\n\n@torch.compile(mode=\"max-autotune-no-cudagraphs\", dynamic=True)\nclass ChannelChunkPadConv3D(PadConv3D):\n    def __init__(self, in_channels: int, out_channels: int, kernel_size: int = 3):\n        super().__init__(in_channels, out_channels, kernel_size)\n        self.conv = ChannelChunkConv3d(in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1)\n"
  },
  {
    "path": "opensora/registry.py",
    "content": "from copy import deepcopy\n\nimport torch.nn as nn\nfrom mmengine.registry import Registry\n\n\ndef build_module(module: dict | nn.Module, builder: Registry, **kwargs) -> nn.Module | None:\n    \"\"\"Build module from config or return the module itself.\n\n    Args:\n        module (dict | nn.Module): The module to build.\n        builder (Registry): The registry to build module.\n        *args, **kwargs: Arguments passed to build function.\n\n    Returns:\n        (None | nn.Module): The created model.\n    \"\"\"\n    if module is None:\n        return None\n    if isinstance(module, dict):\n        cfg = deepcopy(module)\n        for k, v in kwargs.items():\n            cfg[k] = v\n        return builder.build(cfg)\n    elif isinstance(module, nn.Module):\n        return module\n    elif module is None:\n        return None\n    else:\n        raise TypeError(f\"Only support dict and nn.Module, but got {type(module)}.\")\n\n\nMODELS = Registry(\n    \"model\",\n    locations=[\"opensora.models\"],\n)\n\nDATASETS = Registry(\n    \"dataset\",\n    locations=[\"opensora.datasets\"],\n)\n"
  },
  {
    "path": "opensora/utils/__init__.py",
    "content": ""
  },
  {
    "path": "opensora/utils/cai.py",
    "content": "import colossalai\nimport torch\nimport torch.distributed as dist\nfrom colossalai.booster import Booster\nfrom colossalai.cluster import DistCoordinator\n\nfrom opensora.acceleration.parallel_states import (\n    get_sequence_parallel_group,\n    get_tensor_parallel_group,\n    set_sequence_parallel_group,\n)\nfrom opensora.models.hunyuan_vae.policy import HunyuanVaePolicy\nfrom opensora.models.mmdit.distributed import MMDiTPolicy\nfrom opensora.utils.logger import is_distributed\nfrom opensora.utils.train import create_colossalai_plugin\n\nfrom .logger import log_message\n\n\ndef set_group_size(plugin_config: dict):\n    \"\"\"\n    Set the group size for tensor parallelism and sequence parallelism.\n\n    Args:\n        plugin_config (dict): Plugin configuration.\n    \"\"\"\n    tp_size = int(plugin_config.get(\"tp_size\", 1))\n    sp_size = int(plugin_config.get(\"sp_size\", 1))\n    if tp_size > 1:\n        assert sp_size == 1\n        plugin_config[\"tp_size\"] = tp_size = min(tp_size, torch.cuda.device_count())\n        log_message(f\"Using TP with size {tp_size}\")\n    if sp_size > 1:\n        assert tp_size == 1\n        plugin_config[\"sp_size\"] = sp_size = min(sp_size, torch.cuda.device_count())\n        log_message(f\"Using SP with size {sp_size}\")\n\n\ndef init_inference_environment():\n    \"\"\"\n    Initialize the inference environment.\n    \"\"\"\n    if is_distributed():\n        colossalai.launch_from_torch({})\n        coordinator = DistCoordinator()\n        enable_sequence_parallelism = coordinator.world_size > 1\n        if enable_sequence_parallelism:\n            set_sequence_parallel_group(dist.group.WORLD)\n\n\ndef get_booster(cfg: dict, ae: bool = False):\n    suffix = \"_ae\" if ae else \"\"\n    policy = HunyuanVaePolicy if ae else MMDiTPolicy\n\n    plugin_type = cfg.get(f\"plugin{suffix}\", \"zero2\")\n    plugin_config = cfg.get(f\"plugin_config{suffix}\", {})\n    plugin_kwargs = {}\n    booster = None\n    if plugin_type == \"hybrid\":\n        set_group_size(plugin_config)\n        plugin_kwargs = dict(custom_policy=policy)\n\n        plugin = create_colossalai_plugin(\n            plugin=plugin_type,\n            dtype=cfg.get(\"dtype\", \"bf16\"),\n            grad_clip=cfg.get(\"grad_clip\", 0),\n            **plugin_config,\n            **plugin_kwargs,\n        )\n        booster = Booster(plugin=plugin)\n    return booster\n\n\ndef get_is_saving_process(cfg: dict):\n    \"\"\"\n    Check if the current process is the one that saves the model.\n\n    Args:\n        plugin_config (dict): Plugin configuration.\n\n    Returns:\n        bool: True if the current process is the one that saves the model.\n    \"\"\"\n    plugin_type = cfg.get(\"plugin\", \"zero2\")\n    plugin_config = cfg.get(\"plugin_config\", {})\n    is_saving_process = (\n        plugin_type != \"hybrid\"\n        or (plugin_config[\"tp_size\"] > 1 and dist.get_rank(get_tensor_parallel_group()) == 0)\n        or (plugin_config[\"sp_size\"] > 1 and dist.get_rank(get_sequence_parallel_group()) == 0)\n    )\n    return is_saving_process\n"
  },
  {
    "path": "opensora/utils/ckpt.py",
    "content": "import functools\nimport json\nimport operator\nimport os\nimport re\nimport shutil\nfrom glob import glob\nfrom typing import Dict, Optional\n\nimport torch\nimport torch.distributed as dist\nimport torch.nn as nn\nfrom colossalai.booster import Booster\nfrom colossalai.checkpoint_io import GeneralCheckpointIO\nfrom colossalai.utils.safetensors import save as async_save\nfrom colossalai.zero.low_level import LowLevelZeroOptimizer\nfrom huggingface_hub import hf_hub_download\nfrom safetensors.torch import load_file\nfrom tensornvme.async_file_io import AsyncFileWriter\nfrom torch.optim import Optimizer\nfrom torch.optim.lr_scheduler import _LRScheduler\n\nfrom opensora.acceleration.parallel_states import get_data_parallel_group\n\nfrom .logger import log_message\n\nhf_endpoint = os.environ.get(\"HF_ENDPOINT\")\nif hf_endpoint is None:\n    hf_endpoint = \"https://huggingface.co\"\nos.environ[\"TENSORNVME_DEBUG\"] = \"1\"\n\n\ndef load_from_hf_hub(repo_path: str, cache_dir: str = None) -> str:\n    \"\"\"\n    Loads a checkpoint from the Hugging Face Hub.\n\n    Args:\n        repo_path (str): The path to the checkpoint on the Hugging Face Hub.\n        cache_dir (str): The directory to cache the downloaded checkpoint.\n\n    Returns:\n        str: The path to the downloaded checkpoint.\n    \"\"\"\n    repo_id = \"/\".join(repo_path.split(\"/\")[:-1])\n    repo_file = repo_path.split(\"/\")[-1]\n    ckpt_path = hf_hub_download(repo_id=repo_id, filename=repo_file, cache_dir=cache_dir)\n    return ckpt_path\n\n\ndef load_from_sharded_state_dict(model: nn.Module, ckpt_path: str, model_name: str = \"model\", strict=False):\n    \"\"\"\n    Loads a model from a sharded checkpoint.\n\n    Args:\n        model (nn.Module): The model to load the checkpoint into.\n        ckpt_path (str): The path to the checkpoint.\n        model_name (str): The name of the model in the checkpoint.\n        strict (bool): Whether to strictly enforce that the keys in the checkpoint match the keys in the model.\n    \"\"\"\n    ckpt_io = GeneralCheckpointIO()\n    ckpt_io.load_model(model, os.path.join(ckpt_path, model_name), strict=strict)\n\n\ndef print_load_warning(missing: list[str], unexpected: list[str]) -> None:\n    \"\"\"\n    Prints a warning if there are missing or unexpected keys when loading a model.\n\n    Args:\n        missing (list[str]): The missing keys.\n        unexpected (list[str]): The unexpected keys.\n    \"\"\"\n    if len(missing) > 0 and len(unexpected) > 0:\n        log_message(f\"Got {len(missing)} missing keys:\\n\\t\" + \"\\n\\t\".join(missing))\n        log_message(\"\\n\" + \"-\" * 79 + \"\\n\")\n        log_message(f\"Got {len(unexpected)} unexpected keys:\\n\\t\" + \"\\n\\t\".join(unexpected))\n    elif len(missing) > 0:\n        log_message(f\"Got {len(missing)} missing keys:\\n\\t\" + \"\\n\\t\".join(missing))\n    elif len(unexpected) > 0:\n        log_message(f\"Got {len(unexpected)} unexpected keys:\\n\\t\" + \"\\n\\t\".join(unexpected))\n    else:\n        log_message(\"Model loaded successfully\")\n\n\ndef load_checkpoint(\n    model: nn.Module,\n    path: str,\n    cache_dir: str = None,\n    device_map: torch.device | str = \"cpu\",\n    cai_model_name: str = \"model\",\n    strict: bool = False,\n    rename_keys: dict = None,  # rename keys in the checkpoint to support fine-tuning with a different model architecture; map old_key_prefix to new_key_prefix\n) -> nn.Module:\n    \"\"\"\n    Loads a checkpoint into model from a path. Support three types of checkpoints:\n        1. huggingface safetensors\n        2. local .pt or .pth\n        3. colossalai sharded checkpoint\n\n    Args:\n        model (nn.Module): The model to load the checkpoint into.\n        path (str): The path to the checkpoint.\n        cache_dir (str): The directory to cache the downloaded checkpoint.\n        device_map (torch.device | str): The device to map the checkpoint to.\n        cai_model_name (str): The name of the model in the checkpoint.\n\n    Returns:\n        nn.Module: The model with the loaded checkpoint.\n    \"\"\"\n    if not os.path.exists(path):\n        log_message(f\"Checkpoint not found at {path}, trying to download from Hugging Face Hub\")\n        path = load_from_hf_hub(path, cache_dir)\n    assert os.path.exists(path), f\"Could not find checkpoint at {path}\"\n\n    log_message(f\"Loading checkpoint from {path}\")\n    if path.endswith(\".safetensors\"):\n        ckpt = load_file(path, device='cpu')\n\n        if rename_keys is not None:\n            # rename keys in the loaded state_dict with old_key_prefix to with new_key_prefix.\n            renamed_ckpt = {}\n            for old_key, v in ckpt.items():\n                new_key = old_key\n                for old_key_prefix, new_key_prefix in rename_keys.items():\n                    if old_key_prefix in old_key:\n                        new_key = old_key.replace(old_key_prefix, new_key_prefix)\n                        print(f\"Renamed {old_key} to {new_key} in the loaded state_dict\")\n                        break\n                renamed_ckpt[new_key] = v\n            ckpt = renamed_ckpt\n\n        missing, unexpected = model.load_state_dict(ckpt, strict=strict)\n        print_load_warning(missing, unexpected)\n    elif path.endswith(\".pt\") or path.endswith(\".pth\"):\n        ckpt = torch.load(path, map_location=device_map)\n        missing, unexpected = model.load_state_dict(ckpt, strict=strict)\n        print_load_warning(missing, unexpected)\n    else:\n        assert os.path.isdir(path), f\"Invalid checkpoint path: {path}\"\n        load_from_sharded_state_dict(model, path, model_name=cai_model_name, strict=strict)\n    return model\n\n\ndef rm_checkpoints(\n    save_dir: str,\n    keep_n_latest: int = 0,\n):\n    \"\"\"\n    Remove old checkpoints.\n\n    Args:\n        save_dir (str): The directory to save the checkpoints.\n        keep_n_latest (int): The number of latest checkpoints to keep.\n    \"\"\"\n    if keep_n_latest <= 0 or dist.get_rank() != 0:\n        return\n    files = glob(os.path.join(save_dir, \"epoch*-global_step*\"))\n    files = sorted(\n        files, key=lambda s: tuple(map(int, re.search(r\"epoch(\\d+)-global_step(\\d+)\", s).groups())), reverse=True\n    )\n    to_remove = files[keep_n_latest:]\n    for f in to_remove:\n        # shutil.rmtree(f)\n        for item in glob(os.path.join(f, \"*\")):\n            if os.path.isdir(item):\n                dir_name = os.path.basename(item)\n                if dir_name != \"eval\":\n                    shutil.rmtree(item)\n            else:\n                os.remove(item)\n\n\ndef model_sharding(model: torch.nn.Module, device: torch.device = None):\n    \"\"\"\n    Sharding the model parameters across multiple GPUs.\n\n    Args:\n        model (torch.nn.Module): The model to shard.\n        device (torch.device): The device to shard the model to.\n    \"\"\"\n    global_rank = dist.get_rank()\n    world_size = dist.get_world_size()\n    for _, param in model.named_parameters():\n        if device is None:\n            device = param.device\n        padding_size = (world_size - param.numel() % world_size) % world_size\n        if padding_size > 0:\n            padding_param = torch.nn.functional.pad(param.data.view(-1), [0, padding_size])\n        else:\n            padding_param = param.data.view(-1)\n        splited_params = padding_param.split(padding_param.numel() // world_size)\n        splited_params = splited_params[global_rank]\n        param.data = splited_params.to(device)\n\n\ndef model_gathering(model: torch.nn.Module, model_shape_dict: dict, pinned_state_dict: dict) -> None:\n    \"\"\"\n    Gather the model parameters from multiple GPUs.\n\n    Args:\n        model (torch.nn.Module): The model to gather.\n        model_shape_dict (dict): The shape of the model parameters.\n        device (torch.device): The device to gather the model to.\n    \"\"\"\n    global_rank = dist.get_rank()\n    global_size = dist.get_world_size()\n    params = set()\n    for name, param in model.named_parameters():\n        params.add(name)\n        all_params = [torch.empty_like(param.data) for _ in range(global_size)]\n        dist.all_gather(all_params, param.data, group=dist.group.WORLD)\n        if int(global_rank) == 0:\n            all_params = torch.cat(all_params)\n            gathered_param = remove_padding(all_params, model_shape_dict[name]).view(model_shape_dict[name])\n            pinned_state_dict[name].copy_(gathered_param)\n    if int(global_rank) == 0:\n        for k, v in model.state_dict(keep_vars=True).items():\n            if k not in params:\n                pinned_state_dict[k].copy_(v)\n\n    dist.barrier()\n\n\ndef remove_padding(tensor: torch.Tensor, original_shape: tuple) -> torch.Tensor:\n    \"\"\"\n    Remove padding from a tensor.\n\n    Args:\n        tensor (torch.Tensor): The tensor to remove padding from.\n        original_shape (tuple): The original shape of the tensor.\n    \"\"\"\n    return tensor[: functools.reduce(operator.mul, original_shape)]\n\n\ndef record_model_param_shape(model: torch.nn.Module) -> dict:\n    \"\"\"\n    Record the shape of the model parameters.\n\n    Args:\n        model (torch.nn.Module): The model to record the parameter shape of.\n\n    Returns:\n        dict: The shape of the model parameters.\n    \"\"\"\n    param_shape = {}\n    for name, param in model.named_parameters():\n        param_shape[name] = param.shape\n    return param_shape\n\n\ndef load_json(file_path: str) -> dict:\n    \"\"\"\n    Load a JSON file.\n\n    Args:\n        file_path (str): The path to the JSON file.\n\n    Returns:\n        dict: The loaded JSON file.\n    \"\"\"\n    with open(file_path, \"r\", encoding=\"utf-8\") as f:\n        return json.load(f)\n\n\ndef save_json(data, file_path: str):\n    \"\"\"\n    Save a dictionary to a JSON file.\n\n    Args:\n        data: The dictionary to save.\n        file_path (str): The path to save the JSON file.\n    \"\"\"\n    with open(file_path, \"w\", encoding=\"utf-8\") as f:\n        json.dump(data, f, indent=4)\n\n\ndef _prepare_ema_pinned_state_dict(model: nn.Module, ema_shape_dict: dict):\n    ema_pinned_state_dict = dict()\n    for name, p in model.named_parameters():\n        ema_pinned_state_dict[name] = torch.empty(ema_shape_dict[name], pin_memory=True, device=\"cpu\", dtype=p.dtype)\n    sd = model.state_dict(keep_vars=True)\n    # handle buffers\n    for k, v in sd.items():\n        if k not in ema_pinned_state_dict:\n            ema_pinned_state_dict[k] = torch.empty(v.shape, pin_memory=True, device=\"cpu\", dtype=v.dtype)\n\n    return ema_pinned_state_dict\n\n\ndef _search_valid_path(path: str) -> str:\n    if os.path.exists(f\"{path}.safetensors\"):\n        return f\"{path}.safetensors\"\n    elif os.path.exists(f\"{path}.pt\"):\n        return f\"{path}.pt\"\n    return path\n\n\ndef master_weights_gathering(model: torch.nn.Module, optimizer: LowLevelZeroOptimizer, pinned_state_dict: dict) -> None:\n    \"\"\"\n    Gather the model parameters from multiple GPUs.\n\n    Args:\n        model (torch.nn.Module): The model to gather.\n        model_shape_dict (dict): The shape of the model parameters.\n        device (torch.device): The device to gather the model to.\n    \"\"\"\n    w2m = optimizer.get_working_to_master_map()\n    for name, param in model.named_parameters():\n        master_p = w2m[id(param)]\n        zero_pg = optimizer.param_to_pg[param]\n        world_size = dist.get_world_size(zero_pg)\n        all_params = [torch.empty_like(master_p) for _ in range(world_size)]\n        dist.all_gather(all_params, master_p, group=zero_pg)\n        if dist.get_rank() == 0:\n            all_params = torch.cat(all_params)\n            gathered_param = remove_padding(all_params, param.shape).view(param.shape)\n            pinned_state_dict[name].copy_(gathered_param)\n\n    dist.barrier()\n\n\ndef load_master_weights(model: torch.nn.Module, optimizer: LowLevelZeroOptimizer, state_dict: dict) -> None:\n    pg = get_data_parallel_group(get_mixed_dp_pg=True)\n    world_size = dist.get_world_size(pg)\n    rank = dist.get_rank(pg)\n    w2m = optimizer.get_working_to_master_map()\n    for name, param in model.named_parameters():\n        master_p = w2m[id(param)]\n        state = state_dict[name].view(-1)\n        padding_size = len(master_p) * world_size - len(state)\n        state = torch.nn.functional.pad(state, [0, padding_size])\n        target_chunk = state.chunk(world_size)[rank].to(master_p.dtype)\n        master_p[: len(target_chunk)].copy_(target_chunk)\n\n\nclass CheckpointIO:\n    def __init__(self, n_write_entries: int = 32):\n        self.n_write_entries = n_write_entries\n        self.writer: Optional[AsyncFileWriter] = None\n        self.pinned_state_dict: Optional[Dict[str, torch.Tensor]] = None\n        self.master_pinned_state_dict: Optional[Dict[str, torch.Tensor]] = None\n        self.master_writer: Optional[AsyncFileWriter] = None\n\n    def _sync_io(self):\n        if self.writer is not None:\n            self.writer.synchronize()\n            self.writer = None\n        if self.master_writer is not None:\n            self.master_writer.synchronize()\n            self.master_writer = None\n\n    def __del__(self):\n        self._sync_io()\n\n    def _prepare_pinned_state_dict(self, ema: nn.Module, ema_shape_dict: dict):\n        if self.pinned_state_dict is None and dist.get_rank() == 0:\n            self.pinned_state_dict = _prepare_ema_pinned_state_dict(ema, ema_shape_dict)\n\n    def _prepare_master_pinned_state_dict(self, model: nn.Module, optimizer: LowLevelZeroOptimizer):\n        if self.master_pinned_state_dict is None and dist.get_rank() == 0:\n            sd = {}\n            w2m = optimizer.get_working_to_master_map()\n            for n, p in model.named_parameters():\n                master_p = w2m[id(p)]\n                sd[n] = torch.empty(p.shape, dtype=master_p.dtype, pin_memory=True, device=\"cpu\")\n            self.master_pinned_state_dict = sd\n\n    def save(\n        self,\n        booster: Booster,\n        save_dir: str,\n        model: nn.Module = None,\n        ema: nn.Module = None,\n        optimizer: Optimizer = None,\n        lr_scheduler: _LRScheduler = None,\n        sampler=None,\n        epoch: int = None,\n        step: int = None,\n        global_step: int = None,\n        batch_size: int = None,\n        lora: bool = False,\n        actual_update_step: int = None,\n        ema_shape_dict: dict = None,\n        async_io: bool = True,\n        include_master_weights: bool = False,\n    ) -> str:\n        \"\"\"\n        Save a checkpoint.\n\n        Args:\n            booster (Booster): The Booster object.\n            save_dir (str): The directory to save the checkpoint to.\n            model (nn.Module): The model to save the checkpoint from.\n            ema (nn.Module): The EMA model to save the checkpoint from.\n            optimizer (Optimizer): The optimizer to save the checkpoint from.\n            lr_scheduler (_LRScheduler): The learning rate scheduler to save the checkpoint from.\n            sampler: The sampler to save the checkpoint from.\n            epoch (int): The epoch of the checkpoint.\n            step (int): The step of the checkpoint.\n            global_step (int): The global step of the checkpoint.\n            batch_size (int): The batch size of the checkpoint.\n            lora (bool): Whether the model is trained with LoRA.\n\n        Returns:\n            str: The path to the saved checkpoint\n        \"\"\"\n        self._sync_io()\n        save_dir = os.path.join(save_dir, f\"epoch{epoch}-global_step{actual_update_step}\")\n        os.environ[\"TENSORNVME_DEBUG_LOG\"] = os.path.join(save_dir, \"async_file_io.log\")\n        if model is not None:\n            if not lora:\n                os.makedirs(os.path.join(save_dir, \"model\"), exist_ok=True)\n                booster.save_model(\n                    model,\n                    os.path.join(save_dir, \"model\"),\n                    shard=True,\n                    use_safetensors=True,\n                    size_per_shard=4096,\n                    use_async=async_io,\n                )\n            else:\n                os.makedirs(os.path.join(save_dir, \"lora\"), exist_ok=True)\n                booster.save_lora_as_pretrained(model, os.path.join(save_dir, \"lora\"))\n        if optimizer is not None:\n            booster.save_optimizer(\n                optimizer, os.path.join(save_dir, \"optimizer\"), shard=True, size_per_shard=4096, use_async=async_io\n            )\n            if include_master_weights:\n                self._prepare_master_pinned_state_dict(model, optimizer)\n                master_weights_gathering(model, optimizer, self.master_pinned_state_dict)\n        if lr_scheduler is not None:\n            booster.save_lr_scheduler(lr_scheduler, os.path.join(save_dir, \"lr_scheduler\"))\n        if ema is not None:\n            self._prepare_pinned_state_dict(ema, ema_shape_dict)\n            model_gathering(ema, ema_shape_dict, self.pinned_state_dict)\n        if dist.get_rank() == 0:\n            running_states = {\n                \"epoch\": epoch,\n                \"step\": step,\n                \"global_step\": global_step,\n                \"batch_size\": batch_size,\n                \"actual_update_step\": actual_update_step,\n            }\n            save_json(running_states, os.path.join(save_dir, \"running_states.json\"))\n\n            if ema is not None:\n                if async_io:\n                    self.writer = async_save(os.path.join(save_dir, \"ema.safetensors\"), self.pinned_state_dict)\n                else:\n                    torch.save(ema.state_dict(), os.path.join(save_dir, \"ema.pt\"))\n\n            if sampler is not None:\n                # only for VariableVideoBatchSampler\n                torch.save(sampler.state_dict(step), os.path.join(save_dir, \"sampler\"))\n\n            if optimizer is not None and include_master_weights:\n                self.master_writer = async_save(\n                    os.path.join(save_dir, \"master.safetensors\"), self.master_pinned_state_dict\n                )\n\n        dist.barrier()\n        return save_dir\n\n    def load(\n        self,\n        booster: Booster,\n        load_dir: str,\n        model: nn.Module = None,\n        ema: nn.Module = None,\n        optimizer: Optimizer = None,\n        lr_scheduler: _LRScheduler = None,\n        sampler=None,\n        strict: bool = False,\n        include_master_weights: bool = False,\n    ) -> tuple[int, int]:\n        \"\"\"\n        Load a checkpoint.\n\n        Args:\n            booster (Booster): The Booster object.\n            load_dir (str): The directory to load the checkpoint from.\n            model (nn.Module): The model to load the checkpoint into.\n            ema (nn.Module): The EMA model to load the checkpoint into.\n            optimizer (Optimizer): The optimizer to load the checkpoint into.\n            lr_scheduler (_LRScheduler): The learning rate scheduler to load the checkpoint into.\n            sampler: The sampler to load the checkpoint into.\n\n        Returns:\n            tuple[int, int]: The epoch and step of the checkpoint.\n        \"\"\"\n        assert os.path.exists(load_dir), f\"Checkpoint directory {load_dir} does not exist\"\n        assert os.path.exists(os.path.join(load_dir, \"running_states.json\")), \"running_states.json does not exist\"\n\n        running_states = load_json(os.path.join(load_dir, \"running_states.json\"))\n        if model is not None:\n            booster.load_model(\n                model,\n                _search_valid_path(os.path.join(load_dir, \"model\")),\n                strict=strict,\n                low_cpu_mem_mode=False,\n                num_threads=32,\n            )\n        if ema is not None:\n            if os.path.exists(os.path.join(load_dir, \"ema.safetensors\")):\n                ema_state_dict = load_file(os.path.join(load_dir, \"ema.safetensors\"))\n            else:\n                ema_state_dict = torch.load(os.path.join(load_dir, \"ema.pt\"), map_location=torch.device(\"cpu\"))\n            # ema is not boosted, so we don't use booster.load_model\n            ema.load_state_dict(ema_state_dict, strict=strict, assign=True)\n\n        if optimizer is not None:\n            booster.load_optimizer(\n                optimizer, os.path.join(load_dir, \"optimizer\"), low_cpu_mem_mode=False, num_threads=32\n            )\n            if include_master_weights:\n                master_state_dict = load_file(os.path.join(load_dir, \"master.safetensors\"))\n                load_master_weights(model, optimizer, master_state_dict)\n        if lr_scheduler is not None:\n            booster.load_lr_scheduler(lr_scheduler, os.path.join(load_dir, \"lr_scheduler\"))\n        if sampler is not None:\n            sampler.load_state_dict(torch.load(os.path.join(load_dir, \"sampler\")))\n\n        dist.barrier()\n\n        return (running_states[\"epoch\"], running_states[\"step\"])\n"
  },
  {
    "path": "opensora/utils/config.py",
    "content": "import argparse\nimport ast\nimport json\nimport os\nfrom datetime import datetime\n\nimport torch\nfrom mmengine.config import Config\n\nfrom .logger import is_distributed, is_main_process\n\n\ndef parse_args() -> tuple[str, argparse.Namespace]:\n    \"\"\"\n    This function parses the command line arguments.\n\n    Returns:\n        tuple[str, argparse.Namespace]: The path to the configuration file and the command line arguments.\n    \"\"\"\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\"config\", type=str, help=\"model config file path\")\n    args, unknown_args = parser.parse_known_args()\n    return args.config, unknown_args\n\n\ndef read_config(config_path: str) -> Config:\n    \"\"\"\n    This function reads the configuration file.\n\n    Args:\n        config_path (str): The path to the configuration file.\n\n    Returns:\n        Config: The configuration object.\n    \"\"\"\n    cfg = Config.fromfile(config_path)\n    return cfg\n\n\ndef parse_configs() -> Config:\n    \"\"\"\n    This function parses the configuration file and command line arguments.\n\n    Returns:\n        Config: The configuration object.\n    \"\"\"\n    config, args = parse_args()\n    cfg = read_config(config)\n    cfg = merge_args(cfg, args)\n    cfg.config_path = config\n\n    # hard-coded for spatial compression\n    if cfg.get(\"ae_spatial_compression\", None) is not None:\n        os.environ[\"AE_SPATIAL_COMPRESSION\"] = str(cfg.ae_spatial_compression)\n    return cfg\n\n\ndef merge_args(cfg: Config, args: argparse.Namespace) -> Config:\n    \"\"\"\n    This function merges the configuration file and command line arguments.\n\n    Args:\n        cfg (Config): The configuration object.\n        args (argparse.Namespace): The command line arguments.\n\n    Returns:\n        Config: The configuration object.\n    \"\"\"\n    for k, v in zip(args[::2], args[1::2]):\n        assert k.startswith(\"--\"), f\"Invalid argument: {k}\"\n        k = k[2:].replace(\"-\", \"_\")\n        k_split = k.split(\".\")\n        target = cfg\n        for key in k_split[:-1]:\n            assert key in cfg, f\"Key {key} not found in config\"\n            target = target[key]\n        if v.lower() == \"none\":\n            v = None\n        elif k in target:\n            v_type = type(target[k])\n            if v_type == bool:\n                v = auto_convert(v)\n            else:\n                v = type(target[k])(v)\n        else:\n            v = auto_convert(v)\n        target[k_split[-1]] = v\n    return cfg\n\n\ndef auto_convert(value: str) -> int | float | bool | list | dict | None:\n    \"\"\"\n    Automatically convert a string to the appropriate Python data type,\n    including int, float, bool, list, dict, etc.\n\n    Args:\n        value (str): The string to convert.\n\n    Returns:\n        int, float, bool, list |  dict: The converted value.\n    \"\"\"\n    # Handle empty string\n    if value == \"\":\n        return value\n\n    # Handle None\n    if value.lower() == \"none\":\n        return None\n\n    # Handle boolean values\n    lower_value = value.lower()\n    if lower_value == \"true\":\n        return True\n    elif lower_value == \"false\":\n        return False\n\n    # Try to convert the string to an integer or float\n    try:\n        # Try converting to an integer\n        return int(value)\n    except ValueError:\n        pass\n\n    try:\n        # Try converting to a float\n        return float(value)\n    except ValueError:\n        pass\n\n    # Try to convert the string to a list, dict, tuple, etc.\n    try:\n        return ast.literal_eval(value)\n    except (ValueError, SyntaxError):\n        pass\n\n    # If all attempts fail, return the original string\n    return value\n\n\ndef sync_string(value: str):\n    \"\"\"\n    This function synchronizes a string across all processes.\n    \"\"\"\n    if not is_distributed():\n        return value\n    bytes_value = value.encode(\"utf-8\")\n    max_len = 256\n    bytes_tensor = torch.zeros(max_len, dtype=torch.uint8).cuda()\n    bytes_tensor[: len(bytes_value)] = torch.tensor(\n        list(bytes_value), dtype=torch.uint8\n    )\n    torch.distributed.broadcast(bytes_tensor, 0)\n    synced_value = bytes_tensor.cpu().numpy().tobytes().decode(\"utf-8\").rstrip(\"\\x00\")\n    return synced_value\n\n\ndef create_experiment_workspace(\n    output_dir: str, model_name: str = None, config: dict = None, exp_name: str = None\n) -> tuple[str, str]:\n    \"\"\"\n    This function creates a folder for experiment tracking.\n\n    Args:\n        output_dir: The path to the output directory.\n        model_name: The name of the model.\n        exp_name: The given name of the experiment, if None will use default.\n\n    Returns:\n        tuple[str, str]: The experiment name and the experiment directory.\n    \"\"\"\n    if exp_name is None:\n        # Make outputs folder (holds all experiment subfolders)\n        experiment_index = datetime.now().strftime(\"%y%m%d_%H%M%S\")\n        experiment_index = sync_string(experiment_index)\n        # Create an experiment folder\n        model_name = (\n            \"-\" + model_name.replace(\"/\", \"-\") if model_name is not None else \"\"\n        )\n        exp_name = f\"{experiment_index}{model_name}\"\n    exp_dir = f\"{output_dir}/{exp_name}\"\n    if is_main_process():\n        os.makedirs(exp_dir, exist_ok=True)\n        # Save the config\n        with open(f\"{exp_dir}/config.txt\", \"w\", encoding=\"utf-8\") as f:\n            json.dump(config, f, indent=4)\n\n    return exp_name, exp_dir\n\n\ndef config_to_name(cfg: Config) -> str:\n    filename = cfg._filename\n    filename = filename.replace(\"configs/\", \"\")\n    filename = filename.replace(\".py\", \"\")\n    filename = filename.replace(\"/\", \"_\")\n    return filename\n\n\ndef parse_alias(cfg: Config) -> Config:\n    if cfg.get(\"resolution\", None) is not None:\n        cfg.sampling_option.resolution = cfg.resolution\n    if cfg.get(\"guidance\", None) is not None:\n        cfg.sampling_option.guidance = float(cfg.guidance)\n    if cfg.get(\"guidance_img\", None) is not None:\n        cfg.sampling_option.guidance_img = float(cfg.guidance_img)\n    if cfg.get(\"num_steps\", None) is not None:\n        cfg.sampling_option.num_steps = int(cfg.num_steps)\n    if cfg.get(\"num_frames\", None) is not None:\n        cfg.sampling_option.num_frames = int(cfg.num_frames)\n    if cfg.get(\"aspect_ratio\", None) is not None:\n        cfg.sampling_option.aspect_ratio = cfg.aspect_ratio\n    if cfg.get(\"ckpt_path\", None) is not None:\n        cfg.model.from_pretrained = cfg.ckpt_path\n    return cfg\n"
  },
  {
    "path": "opensora/utils/inference.py",
    "content": "import copy\nimport os\nimport re\nfrom enum import Enum\n\nimport torch\nfrom torch import nn\n\nfrom opensora.datasets import save_sample\nfrom opensora.datasets.aspect import get_image_size\nfrom opensora.datasets.utils import read_from_path, rescale_image_by_path\nfrom opensora.utils.logger import log_message\nfrom opensora.utils.prompt_refine import refine_prompts\n\n\nclass SamplingMethod(Enum):\n    I2V = \"i2v\"  # for open sora video generation\n    DISTILLED = \"distill\"  # for flux image generation\n\n\ndef create_tmp_csv(save_dir: str, prompt: str, ref: str = None, create=True) -> str:\n    \"\"\"\n    Create a temporary CSV file with the prompt text.\n\n    Args:\n        save_dir (str): The directory where the CSV file will be saved.\n        prompt (str): The prompt text.\n\n    Returns:\n        str: The path to the temporary CSV file.\n    \"\"\"\n    tmp_file = os.path.join(save_dir, \"prompt.csv\")\n    if not create:\n        return tmp_file\n    with open(tmp_file, \"w\", encoding=\"utf-8\") as f:\n        if ref is not None:\n            f.write(f'text,ref\\n\"{prompt}\",\"{ref}\"')\n        else:\n            f.write(f'text\\n\"{prompt}\"')\n    return tmp_file\n\n\ndef modify_option_to_t2i(sampling_option, distilled: bool = False, img_resolution: str = \"1080px\"):\n    \"\"\"\n    Modify the sampling option to be used for text-to-image generation.\n    \"\"\"\n    sampling_option_t2i = copy.copy(sampling_option)\n    if distilled:\n        sampling_option_t2i.method = SamplingMethod.DISTILLED\n    sampling_option_t2i.num_frames = 1\n    sampling_option_t2i.height, sampling_option_t2i.width = get_image_size(img_resolution, sampling_option.aspect_ratio)\n    sampling_option_t2i.guidance = 4.0\n    sampling_option_t2i.resized_resolution = sampling_option.resolution\n\n    return sampling_option_t2i\n\n\ndef get_save_path_name(\n    save_dir,\n    sub_dir,\n    save_prefix=\"\",\n    name=None,\n    fallback_name=None,\n    index=None,\n    num_sample_pos=None,  # idx for prompt as path\n    prompt_as_path=False,  # save sample with same name as prompt\n    prompt=None,\n):\n    \"\"\"\n    Get the save path for the generated samples.\n    \"\"\"\n    if prompt_as_path:  # for vbench\n        cleaned_prompt = prompt.strip(\".\")\n        fname = f\"{cleaned_prompt}-{num_sample_pos}\"\n    else:\n        if name is not None:\n            fname = save_prefix + name\n        else:\n            fname = f\"{save_prefix + fallback_name}_{index:04d}\"\n        if num_sample_pos > 0:\n            fname += f\"_{num_sample_pos}\"\n\n    return os.path.join(save_dir, sub_dir, fname)\n\n\ndef get_names_from_path(path):\n    \"\"\"\n    Get the filename and extension from a path.\n\n    Args:\n        path (str): The path to the file.\n\n    Returns:\n        tuple[str, str]: The filename and the extension.\n    \"\"\"\n    filename = os.path.basename(path)\n    name, _ = os.path.splitext(filename)\n    return name\n\n\ndef process_and_save(\n    x: torch.Tensor,\n    batch: dict,\n    cfg: dict,\n    sub_dir: str,\n    generate_sampling_option,\n    epoch: int,\n    start_index: int,\n    saving: bool = True,\n):\n    \"\"\"\n    Process the generated samples and save them to disk.\n    \"\"\"\n    fallback_name = cfg.dataset.data_path.split(\"/\")[-1].split(\".\")[0]\n    prompt_as_path = cfg.get(\"prompt_as_path\", False)\n    fps_save = cfg.get(\"fps_save\", 16)\n    save_dir = cfg.save_dir\n\n    names = batch[\"name\"] if \"name\" in batch else [None] * len(x)\n    indices = batch[\"index\"] if \"index\" in batch else [None] * len(x)\n    if \"index\" in batch:\n        indices = [idx + start_index for idx in indices]\n    prompts = batch[\"text\"]\n\n    ret_names = []\n    is_image = generate_sampling_option.num_frames == 1\n    for img, name, index, prompt in zip(x, names, indices, prompts):\n        # == get save path ==\n        save_path = get_save_path_name(\n            save_dir,\n            sub_dir,\n            save_prefix=cfg.get(\"save_prefix\", \"\"),\n            name=name,\n            fallback_name=fallback_name,\n            index=index,\n            num_sample_pos=epoch,\n            prompt_as_path=prompt_as_path,\n            prompt=prompt,\n        )\n        ret_name = get_names_from_path(save_path)\n        ret_names.append(ret_name)\n\n        if saving:\n            # == write txt to disk ==\n            with open(save_path + \".txt\", \"w\", encoding=\"utf-8\") as f:\n                f.write(prompt)\n\n            # == save samples ==\n            save_sample(img, save_path=save_path, fps=fps_save)\n\n            # == resize image for t2i2v ==\n            if (\n                cfg.get(\"use_t2i2v\", False)\n                and is_image\n                and generate_sampling_option.resolution != generate_sampling_option.resized_resolution\n            ):\n                log_message(\"Rescaling image to %s...\", generate_sampling_option.resized_resolution)\n                height, width = get_image_size(\n                    generate_sampling_option.resized_resolution, generate_sampling_option.aspect_ratio\n                )\n                rescale_image_by_path(save_path + \".png\", width, height)\n\n    return ret_names\n\n\ndef check_fps_added(sentence):\n    \"\"\"\n    Check if the sentence ends with the FPS information.\n    \"\"\"\n    pattern = r\"\\d+ FPS\\.$\"\n    if re.search(pattern, sentence):\n        return True\n    return False\n\n\ndef ensure_sentence_ends_with_period(sentence: str):\n    \"\"\"\n    Ensure that the sentence ends with a period.\n    \"\"\"\n    sentence = sentence.strip()\n    if not sentence.endswith(\".\"):\n        sentence += \".\"\n    return sentence\n\n\ndef add_fps_info_to_text(text: list[str], fps: int = 16):\n    \"\"\"\n    Add the FPS information to the text.\n    \"\"\"\n    mod_text = []\n    for item in text:\n        item = ensure_sentence_ends_with_period(item)\n        if not check_fps_added(item):\n            item = item + f\" {fps} FPS.\"\n        mod_text.append(item)\n    return mod_text\n\n\ndef add_motion_score_to_text(text, motion_score: int | str):\n    \"\"\"\n    Add the motion score to the text.\n    \"\"\"\n    if motion_score == \"dynamic\":\n        ms = refine_prompts(text, type=\"motion_score\")\n        return [f\"{t} {ms[i]}.\" for i, t in enumerate(text)]\n    else:\n        return [f\"{t} {motion_score} motion score.\" for t in text]\n\n\ndef add_noise_to_ref(masked_ref: torch.Tensor, masks: torch.Tensor, t: float, sigma_min: float = 1e-5):\n    z_1 = torch.randn_like(masked_ref)\n    z_noisy = (1 - (1 - sigma_min) * t) * masked_ref + t * z_1\n    return masks * z_noisy\n\n\ndef collect_references_batch(\n    reference_paths: list[str],\n    cond_type: str,\n    model_ae: nn.Module,\n    image_size: tuple[int, int],\n    is_causal=False,\n):\n    refs_x = []  # refs_x: [batch, ref_num, C, T, H, W]\n    device = next(model_ae.parameters()).device\n    dtype = next(model_ae.parameters()).dtype\n    for reference_path in reference_paths:\n        if reference_path == \"\":\n            refs_x.append(None)\n            continue\n        ref_path = reference_path.split(\";\")\n        ref = []\n\n        if \"v2v\" in cond_type:\n            r = read_from_path(ref_path[0], image_size, transform_name=\"resize_crop\")  # size [C, T, H, W]\n            actual_t = r.size(1)\n            target_t = (\n                64 if (actual_t >= 64 and \"easy\" in cond_type) else 32\n            )  # if reference not long enough, default to shorter ref\n            if is_causal:\n                target_t += 1\n            assert actual_t >= target_t, f\"need at least {target_t} reference frames for v2v generation\"\n            if \"head\" in cond_type:  # v2v head\n                r = r[:, :target_t]\n            elif \"tail\" in cond_type:  # v2v tail\n                r = r[:, -target_t:]\n            else:\n                raise NotImplementedError\n            r_x = model_ae.encode(r.unsqueeze(0).to(device, dtype))\n            r_x = r_x.squeeze(0)  # size [C, T, H, W]\n            ref.append(r_x)\n        elif cond_type == \"i2v_head\":  # take the 1st frame from first ref_path\n            r = read_from_path(ref_path[0], image_size, transform_name=\"resize_crop\")  # size [C, T, H, W]\n            r = r[:, :1]\n            r_x = model_ae.encode(r.unsqueeze(0).to(device, dtype))\n            r_x = r_x.squeeze(0)  # size [C, T, H, W]\n            ref.append(r_x)\n        elif cond_type == \"i2v_tail\":  # take the last frame from last ref_path\n            r = read_from_path(ref_path[-1], image_size, transform_name=\"resize_crop\")  # size [C, T, H, W]\n            r = r[:, -1:]\n            r_x = model_ae.encode(r.unsqueeze(0).to(device, dtype))\n            r_x = r_x.squeeze(0)  # size [C, T, H, W]\n            ref.append(r_x)\n        elif cond_type == \"i2v_loop\":\n            # first frame\n            r_head = read_from_path(ref_path[0], image_size, transform_name=\"resize_crop\")  # size [C, T, H, W]\n            r_head = r_head[:, :1]\n            r_x_head = model_ae.encode(r_head.unsqueeze(0).to(device, dtype))\n            r_x_head = r_x_head.squeeze(0)  # size [C, T, H, W]\n            ref.append(r_x_head)\n            # last frame\n            r_tail = read_from_path(ref_path[-1], image_size, transform_name=\"resize_crop\")  # size [C, T, H, W]\n            r_tail = r_tail[:, -1:]\n            r_x_tail = model_ae.encode(r_tail.unsqueeze(0).to(device, dtype))\n            r_x_tail = r_x_tail.squeeze(0)  # size [C, T, H, W]\n            ref.append(r_x_tail)\n        else:\n            raise NotImplementedError(f\"Unknown condition type {cond_type}\")\n\n        refs_x.append(ref)\n    return refs_x\n\n\ndef prepare_inference_condition(\n    z: torch.Tensor,\n    mask_cond: str,\n    ref_list: list[list[torch.Tensor]] = None,\n    causal: bool = True,\n) -> torch.Tensor:\n    \"\"\"\n    Prepare the visual condition for the model, using causal vae.\n\n    Args:\n        z (torch.Tensor): The latent noise tensor, of shape [B, C, T, H, W]\n        mask_cond (dict): The condition configuration.\n        ref_list: list of lists of media (image/video) for i2v and v2v condition, of shape [C, T', H, W]; len(ref_list)==B; ref_list[i] is the list of media for the generation in batch idx i, we use a list of media for each batch item so that it can have multiple references. For example, ref_list[i] could be [ref_image_1, ref_image_2] for i2v_loop condition.\n\n    Returns:\n        torch.Tensor: The visual condition tensor.\n    \"\"\"\n    # x has shape [b, c, t, h, w], where b is the batch size\n    B, C, T, H, W = z.shape\n\n    masks = torch.zeros(B, 1, T, H, W)\n    masked_z = torch.zeros(B, C, T, H, W)\n\n    if ref_list is None:\n        assert mask_cond == \"t2v\", f\"reference is required for {mask_cond}\"\n\n    for i in range(B):\n        ref = ref_list[i]\n\n        # warning message\n        if ref is None and mask_cond != \"t2v\":\n            print(\"no reference found. will default to cond_type t2v!\")\n\n        if ref is not None and T > 1:  # video\n            # Apply the selected mask condition directly on the masks tensor\n            if mask_cond == \"i2v_head\":  # equivalent to masking the first timestep\n                masks[i, :, 0, :, :] = 1\n                masked_z[i, :, 0, :, :] = ref[0][:, 0, :, :]\n            elif mask_cond == \"i2v_tail\":  # mask the last timestep\n                masks[i, :, -1, :, :] = 1\n                masked_z[i, :, -1, :, :] = ref[-1][:, -1, :, :]\n            elif mask_cond == \"v2v_head\":\n                k = 8 + int(causal)\n                masks[i, :, :k, :, :] = 1\n                masked_z[i, :, :k, :, :] = ref[0][:, :k, :, :]\n            elif mask_cond == \"v2v_tail\":\n                k = 8 + int(causal)\n                masks[i, :, -k:, :, :] = 1\n                masked_z[i, :, -k:, :, :] = ref[0][:, -k:, :, :]\n            elif mask_cond == \"v2v_head_easy\":\n                k = 16 + int(causal)\n                masks[i, :, :k, :, :] = 1\n                masked_z[i, :, :k, :, :] = ref[0][:, :k, :, :]\n            elif mask_cond == \"v2v_tail_easy\":\n                k = 16 + int(causal)\n                masks[i, :, -k:, :, :] = 1\n                masked_z[i, :, -k:, :, :] = ref[0][:, -k:, :, :]\n            elif mask_cond == \"i2v_loop\":  # mask first and last timesteps\n                masks[i, :, 0, :, :] = 1\n                masks[i, :, -1, :, :] = 1\n                masked_z[i, :, 0, :, :] = ref[0][:, 0, :, :]\n                masked_z[i, :, -1, :, :] = ref[-1][:, -1, :, :]  # last frame of last referenced content\n            else:\n                # \"t2v\" is the fallback case where no specific condition is specified\n                assert mask_cond == \"t2v\", f\"Unknown mask condition {mask_cond}\"\n\n    masks = masks.to(z.device, z.dtype)\n    masked_z = masked_z.to(z.device, z.dtype)\n    return masks, masked_z\n"
  },
  {
    "path": "opensora/utils/logger.py",
    "content": "import logging\nimport os\n\nimport torch.distributed as dist\n\n\ndef is_distributed() -> bool:\n    \"\"\"\n    Check if the code is running in a distributed setting.\n\n    Returns:\n        bool: True if running in a distributed setting, False otherwise\n    \"\"\"\n    return os.environ.get(\"WORLD_SIZE\", None) is not None\n\n\ndef is_main_process() -> bool:\n    \"\"\"\n    Check if the current process is the main process.\n\n    Returns:\n        bool: True if the current process is the main process, False otherwise.\n    \"\"\"\n    return not is_distributed() or dist.get_rank() == 0\n\n\ndef get_world_size() -> int:\n    \"\"\"\n    Get the number of processes in the distributed setting.\n\n    Returns:\n        int: The number of processes.\n    \"\"\"\n    if is_distributed():\n        return dist.get_world_size()\n    else:\n        return 1\n\n\ndef create_logger(logging_dir: str = None) -> logging.Logger:\n    \"\"\"\n    Create a logger that writes to a log file and stdout. Only the main process logs.\n\n    Args:\n        logging_dir (str): The directory to save the log file.\n\n    Returns:\n        logging.Logger: The logger.\n    \"\"\"\n    if is_main_process():\n        additional_args = dict()\n        if logging_dir is not None:\n            additional_args[\"handlers\"] = [\n                logging.StreamHandler(),\n                logging.FileHandler(f\"{logging_dir}/log.txt\"),\n            ]\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            **additional_args,\n        )\n        logger = logging.getLogger(__name__)\n        if logging_dir is not None:\n            logger.info(\"Experiment directory created at %s\", logging_dir)\n    else:\n        logger = logging.getLogger(__name__)\n        logger.addHandler(logging.NullHandler())\n    return logger\n\n\ndef log_message(*args, level: str = \"info\"):\n    \"\"\"\n    Log a message to the logger.\n\n    Args:\n        *args: The message to log.\n        level (str): The logging level.\n    \"\"\"\n    logger = logging.getLogger(__name__)\n    if level == \"info\":\n        logger.info(*args)\n    elif level == \"warning\":\n        logger.warning(*args)\n    elif level == \"error\":\n        logger.error(*args)\n    elif level == \"print\":\n        print(*args)\n    else:\n        raise ValueError(f\"Invalid logging level: {level}\")\n"
  },
  {
    "path": "opensora/utils/misc.py",
    "content": "import os\nimport time\nfrom collections import OrderedDict\nfrom collections.abc import Sequence\nfrom contextlib import nullcontext\n\nimport numpy as np\nimport psutil\nimport torch\nimport torch.distributed as dist\nimport torch.nn as nn\nfrom colossalai.cluster.dist_coordinator import DistCoordinator\nfrom torch.utils.tensorboard import SummaryWriter\n\nfrom opensora.acceleration.parallel_states import get_data_parallel_group\n\nfrom .logger import log_message\n\n\ndef create_tensorboard_writer(exp_dir: str) -> SummaryWriter:\n    \"\"\"\n    Create a tensorboard writer.\n\n    Args:\n        exp_dir (str): The directory to save tensorboard logs.\n\n    Returns:\n        SummaryWriter: The tensorboard writer.\n    \"\"\"\n    tensorboard_dir = f\"{exp_dir}/tensorboard\"\n    os.makedirs(tensorboard_dir, exist_ok=True)\n    writer = SummaryWriter(tensorboard_dir)\n    return writer\n\n\n# ======================================================\n# Memory\n# ======================================================\n\nGIGABYTE = 1024**3\n\n\ndef log_cuda_memory(stage: str = None):\n    \"\"\"\n    Log the current CUDA memory usage.\n\n    Args:\n        stage (str): The stage of the training process.\n    \"\"\"\n    text = \"CUDA memory usage\"\n    if stage is not None:\n        text += f\" at {stage}\"\n    log_message(text + \": %.1f GB\", torch.cuda.memory_allocated() / GIGABYTE)\n\n\ndef log_cuda_max_memory(stage: str = None):\n    \"\"\"\n    Log the max CUDA memory usage.\n\n    Args:\n        stage (str): The stage of the training process.\n    \"\"\"\n    torch.cuda.synchronize()\n    max_memory_allocated = torch.cuda.max_memory_allocated()\n    max_memory_reserved = torch.cuda.max_memory_reserved()\n    log_message(\"CUDA max memory max memory allocated at \" + stage + \": %.1f GB\", max_memory_allocated / GIGABYTE)\n    log_message(\"CUDA max memory max memory reserved at \" + stage + \": %.1f GB\", max_memory_reserved / GIGABYTE)\n\n\n# ======================================================\n# Number of parameters\n# ======================================================\n\n\ndef get_model_numel(model: torch.nn.Module) -> tuple[int, int]:\n    \"\"\"\n    Get the number of parameters in a model.\n\n    Args:\n        model (torch.nn.Module): The model.\n\n    Returns:\n        tuple[int, int]: The total number of parameters and the number of trainable parameters.\n    \"\"\"\n    num_params = 0\n    num_params_trainable = 0\n    for p in model.parameters():\n        num_params += p.numel()\n        if p.requires_grad:\n            num_params_trainable += p.numel()\n    return num_params, num_params_trainable\n\n\ndef log_model_params(model: nn.Module):\n    \"\"\"\n    Log the number of parameters in a model.\n\n    Args:\n        model (torch.nn.Module): The model.\n    \"\"\"\n    num_params, num_params_trainable = get_model_numel(model)\n    model_name = model.__class__.__name__\n    log_message(f\"[{model_name}] Number of parameters: {format_numel_str(num_params)}\")\n    log_message(f\"[{model_name}] Number of trainable parameters: {format_numel_str(num_params_trainable)}\")\n\n\n# ======================================================\n# String\n# ======================================================\n\n\ndef format_numel_str(numel: int) -> str:\n    \"\"\"\n    Format a number of elements to a human-readable string.\n\n    Args:\n        numel (int): The number of elements.\n\n    Returns:\n        str: The formatted string.\n    \"\"\"\n    B = 1024**3\n    M = 1024**2\n    K = 1024\n    if numel >= B:\n        return f\"{numel / B:.2f} B\"\n    elif numel >= M:\n        return f\"{numel / M:.2f} M\"\n    elif numel >= K:\n        return f\"{numel / K:.2f} K\"\n    else:\n        return f\"{numel}\"\n\n\ndef format_duration(seconds: int) -> str:\n    days, remainder = divmod(seconds, 86400)  # Extract days\n    hours, remainder = divmod(remainder, 3600)  # Extract hours\n    minutes, seconds = divmod(remainder, 60)  # Extract minutes and seconds\n\n    parts = []\n    if days > 0:\n        parts.append(f\"{days}d\")\n    if hours > 0:\n        parts.append(f\"{hours}h\")\n    if minutes > 0:\n        parts.append(f\"{minutes}m\")\n    if seconds > 0 or not parts:  # Always show seconds if nothing else\n        parts.append(f\"{seconds}s\")\n\n    return \" \".join(parts)\n\n\n# ======================================================\n# PyTorch\n# ======================================================\n\n\ndef all_reduce_mean(tensor: torch.Tensor) -> torch.Tensor:\n    dist.all_reduce(tensor=tensor, group=get_data_parallel_group())\n    tensor.div_(dist.get_world_size(group=get_data_parallel_group()))\n    return tensor\n\n\ndef all_reduce_sum(tensor: torch.Tensor) -> torch.Tensor:\n    dist.all_reduce(tensor=tensor, group=get_data_parallel_group())\n    return tensor\n\n\ndef to_tensor(data: torch.Tensor | np.ndarray | Sequence | int | float) -> torch.Tensor:\n    \"\"\"Convert objects of various python types to :obj:`torch.Tensor`.\n\n    Supported types are: :class:`numpy.ndarray`, :class:`torch.Tensor`,\n    :class:`Sequence`, :class:`int` and :class:`float`.\n\n    Args:\n        data (torch.Tensor | numpy.ndarray | Sequence | int | float): Data to\n            be converted.\n\n    Returns:\n        torch.Tensor: The converted tensor.\n    \"\"\"\n\n    if isinstance(data, torch.Tensor):\n        return data\n    elif isinstance(data, np.ndarray):\n        return torch.from_numpy(data)\n    elif isinstance(data, Sequence) and not isinstance(data, str):\n        return torch.tensor(data)\n    elif isinstance(data, int):\n        return torch.LongTensor([data])\n    elif isinstance(data, float):\n        return torch.FloatTensor([data])\n    else:\n        raise TypeError(f\"type {type(data)} cannot be converted to tensor.\")\n\n\ndef to_ndarray(data: torch.Tensor | np.ndarray | Sequence | int | float) -> np.ndarray:\n    \"\"\"Convert objects of various python types to :obj:`numpy.ndarray`.\n\n    Supported types are: :class:`numpy.ndarray`, :class:`torch.Tensor`,\n    :class:`Sequence`, :class:`int` and :class:`float`.\n\n    Args:\n        data (torch.Tensor | numpy.ndarray | Sequence | int | float): Data to\n            be converted.\n\n    Returns:\n        numpy.ndarray: The converted ndarray.\n    \"\"\"\n    if isinstance(data, torch.Tensor):\n        return data.numpy()\n    elif isinstance(data, np.ndarray):\n        return data\n    elif isinstance(data, Sequence):\n        return np.array(data)\n    elif isinstance(data, int):\n        return np.ndarray([data], dtype=int)\n    elif isinstance(data, float):\n        return np.array([data], dtype=float)\n    else:\n        raise TypeError(f\"type {type(data)} cannot be converted to ndarray.\")\n\n\ndef to_torch_dtype(dtype: str | torch.dtype) -> torch.dtype:\n    \"\"\"\n    Convert a string or a torch.dtype to a torch.dtype.\n\n    Args:\n        dtype (str | torch.dtype): The input dtype.\n\n    Returns:\n        torch.dtype: The converted dtype.\n    \"\"\"\n    if isinstance(dtype, torch.dtype):\n        return dtype\n    elif isinstance(dtype, str):\n        dtype_mapping = {\n            \"float64\": torch.float64,\n            \"float32\": torch.float32,\n            \"float16\": torch.float16,\n            \"fp32\": torch.float32,\n            \"fp16\": torch.float16,\n            \"half\": torch.float16,\n            \"bf16\": torch.bfloat16,\n        }\n        if dtype not in dtype_mapping:\n            raise ValueError(f\"Unsupported dtype {dtype}\")\n        dtype = dtype_mapping[dtype]\n        return dtype\n    else:\n        raise ValueError(f\"Unsupported dtype {dtype}\")\n\n\n# ======================================================\n# Profile\n# ======================================================\n\n\nclass Timer:\n    def __init__(self, name, log=False, barrier=False, coordinator: DistCoordinator | None = None):\n        self.name = name\n        self.start_time = None\n        self.end_time = None\n        self.log = log\n        self.barrier = barrier\n        self.coordinator = coordinator\n\n    @property\n    def elapsed_time(self) -> float:\n        return self.end_time - self.start_time\n\n    def __enter__(self):\n        torch.cuda.synchronize()\n        if self.barrier:\n            dist.barrier()\n        self.start_time = time.time()\n        return self\n\n    def __exit__(self, exc_type, exc_val, exc_tb):\n        if self.coordinator is not None:\n            self.coordinator.block_all()\n        torch.cuda.synchronize()\n        if self.barrier:\n            dist.barrier()\n        self.end_time = time.time()\n        if self.log:\n            print(f\"Elapsed time for {self.name}: {self.elapsed_time:.2f} s\")\n\n\nclass Timers:\n    def __init__(self, record_time: bool, record_barrier: bool = False, coordinator: DistCoordinator | None = None):\n        self.timers = OrderedDict()\n        self.record_time = record_time\n        self.record_barrier = record_barrier\n        self.coordinator = coordinator\n\n    def __getitem__(self, name: str) -> Timer:\n        if name not in self.timers:\n            if self.record_time:\n                self.timers[name] = Timer(name, barrier=self.record_barrier, coordinator=self.coordinator)\n            else:\n                self.timers[name] = nullcontext()\n        return self.timers[name]\n\n    def to_dict(self):\n        return {f\"time_debug/{name}\": timer.elapsed_time for name, timer in self.timers.items()}\n\n    def to_str(self, epoch: int, step: int) -> str:\n        log_str = f\"Rank {dist.get_rank()} | Epoch {epoch} | Step {step} | \"\n        for name, timer in self.timers.items():\n            log_str += f\"{name}: {timer.elapsed_time:.2f} s | \"\n        return log_str\n\n\ndef is_pipeline_enabled(plugin_type: str, plugin_config: dict) -> bool:\n    return plugin_type == \"hybrid\" and plugin_config.get(\"pp_size\", 1) > 1\n\n\ndef is_log_process(plugin_type: str, plugin_config: dict) -> bool:\n    if is_pipeline_enabled(plugin_type, plugin_config):\n        return dist.get_rank() == dist.get_world_size() - 1\n    return dist.get_rank() == 0\n\n\nclass NsysRange:\n    def __init__(self, range_name: str):\n        self.range_name = range_name\n\n    def __enter__(self):\n        torch.cuda.nvtx.range_push(self.range_name)\n        return self\n\n    def __exit__(self, exc_type, exc_val, exc_tb):\n        torch.cuda.nvtx.range_pop()\n\n\nclass NsysProfiler:\n    \"\"\"\n    Use NVIDIA Nsight Systems to profile the code.\n\n    Example (~30MB):\n    ```bash\n    /home/zhengzangwei/nsight-systems-2024.7.1/bin/nsys profile -w true -t cuda,nvtx,osrt,cudnn,cublas --capture-range=cudaProfilerApi --capture-range-end=stop-shutdown  -o cache/nsys/report2 \\\n        torchrun --nproc_per_node 8 scripts/diffusion/train.py configs/diffusion/train/stage2.py --nsys True --dataset.data-path /mnt/ddn/sora/meta/train/all_till_20241115_chunk901+img7.6M.parquet\n    ```\n\n    Example (~130MB + 2G):\n    ```bash\n    /home/zhengzangwei/nsight-systems-2024.7.1/bin/nsys profile -w true -t cuda,nvtx,osrt,cudnn,cublas --capture-range=cudaProfilerApi --capture-range-end=stop-shutdown -s process-tree --cudabacktrace=all --stats=true -o cache/nsys/report5 \\\n        torchrun --nproc_per_node 8 scripts/diffusion/train.py configs/diffusion/train/stage2.py --nsys True --dataset.data-path /mnt/ddn/sora/meta/train/all_till_20241115_chunk901+img7.6M.parquet --record_time True --record_barrier True\n    ```\n\n    To generate summary statistics, use `--stats=true`.\n    To disable stack traces, use use `-s none --cudabacktrace=none`.\n    To use stack traces, use `-s process-tree --cudabacktrace=all`.\n    To enable timer, use `--record_time True --record_barrier True` for `scripts/diffusion/train.py`.\n    \"\"\"\n\n    def __init__(self, warmup_steps: int = 0, num_steps: int = 1, enabled: bool = True):\n        self.warmup_steps = warmup_steps\n        self.num_steps = num_steps\n        self.current_step = 0\n        self.enabled = enabled\n\n    def step(self):\n        if not self.enabled:\n            return\n        self.current_step += 1\n        if self.current_step == self.warmup_steps:\n            torch.cuda.cudart().cudaProfilerStart()\n        elif self.current_step >= self.warmup_steps + self.num_steps:\n            torch.cuda.cudart().cudaProfilerStop()\n\n    def range(self, range_name: str) -> NsysRange:\n        if not self.enabled:\n            return nullcontext()\n        return NsysRange(range_name)\n\n\nclass ProfilerContext:\n    def __init__(\n        self,\n        save_path: str = \"./log\",\n        record_shapes: bool = False,\n        with_stack: bool = True,\n        wait: int = 1,\n        warmup: int = 1,\n        active: int = 1,\n        repeat: int = 1,\n        enable: bool = True,\n        **kwargs,\n    ):\n        self.enable = enable\n        self.prof = None\n        self.step_cnt = 0\n        self.total_steps = (wait + warmup + active) * repeat\n        if enable:\n            self.prof = torch.profiler.profile(\n                activities=[\n                    torch.profiler.ProfilerActivity.CPU,\n                    torch.profiler.ProfilerActivity.CUDA,\n                ],\n                schedule=torch.profiler.schedule(wait=wait, warmup=warmup, active=active, repeat=repeat),\n                record_shapes=record_shapes,\n                with_stack=with_stack,\n                on_trace_ready=torch.profiler.tensorboard_trace_handler(save_path),\n                **kwargs,\n            )\n\n    def step(self):\n        if self.enable:\n            if self.step_cnt == 0:\n                self.prof.__enter__()\n            self.prof.step()\n            self.step_cnt += 1\n            if self.is_profile_end():\n                self.prof.__exit__(None, None, None)\n                exit(0)\n\n    def is_profile_end(self):\n        return self.step_cnt >= self.total_steps\n\n\ndef get_process_mem():\n    process = psutil.Process(os.getpid())\n    return process.memory_info().rss / 1024**3\n\n\ndef get_total_mem():\n    return psutil.virtual_memory().used / 1024**3\n\n\ndef print_mem(prefix: str = \"\"):\n    rank = dist.get_rank()\n    print(\n        f\"[{rank}] {prefix} process memory: {get_process_mem():.2f} GB, total memory: {get_total_mem():.2f} GB\",\n        flush=True,\n    )\n"
  },
  {
    "path": "opensora/utils/optimizer.py",
    "content": "import torch\nfrom colossalai.nn.lr_scheduler import CosineAnnealingWarmupLR\nfrom colossalai.nn.optimizer import HybridAdam\nfrom torch.optim.lr_scheduler import _LRScheduler\n\n\ndef create_optimizer(\n    model: torch.nn.Module,\n    optimizer_config: dict,\n) -> torch.optim.Optimizer:\n    \"\"\"\n    Create an optimizer.\n\n    Args:\n        model (torch.nn.Module): The model to be optimized.\n        optimizer_config (dict): The configuration of the optimizer.\n\n    Returns:\n        torch.optim.Optimizer: The optimizer.\n    \"\"\"\n    optimizer_name = optimizer_config.pop(\"cls\", \"HybridAdam\")\n    if optimizer_name == \"HybridAdam\":\n        optimizer_cls = HybridAdam\n    else:\n        raise ValueError(f\"Unknown optimizer: {optimizer_name}\")\n    optimizer = optimizer_cls(\n        filter(lambda p: p.requires_grad, model.parameters()),\n        **optimizer_config,\n    )\n    return optimizer\n\n\ndef create_lr_scheduler(\n    optimizer: torch.optim.Optimizer,\n    num_steps_per_epoch: int,\n    epochs: int = 1000,\n    warmup_steps: int | None = None,\n    use_cosine_scheduler: bool = False,\n    initial_lr: float = 1e-6,\n) -> _LRScheduler | None:\n    \"\"\"\n    Create a learning rate scheduler.\n\n    Args:\n        optimizer (torch.optim.Optimizer): The optimizer to be used.\n        num_steps_per_epoch (int): The number of steps per epoch.\n        epochs (int): The number of epochs.\n        warmup_steps (int |  None): The number of warmup steps.\n        use_cosine_scheduler (bool): Whether to use cosine scheduler.\n\n    Returns:\n        _LRScheduler |  None: The learning rate scheduler\n    \"\"\"\n    if warmup_steps is None and not use_cosine_scheduler:\n        lr_scheduler = None\n    elif use_cosine_scheduler:\n        lr_scheduler = CosineAnnealingWarmupLR(\n            optimizer,\n            total_steps=num_steps_per_epoch * epochs,\n            warmup_steps=warmup_steps,\n        )\n    else:\n        lr_scheduler = LinearWarmupLR(optimizer, initial_lr=1e-6, warmup_steps=warmup_steps)\n        # lr_scheduler = LinearWarmupLR(optimizer, warmup_steps=warmup_steps)\n\n    return lr_scheduler\n\n\nclass LinearWarmupLR(_LRScheduler):\n    \"\"\"Linearly warmup learning rate and then linearly decay.\n\n    Args:\n        optimizer (:class:`torch.optim.Optimizer`): Wrapped optimizer.\n        warmup_steps (int, optional): Number of warmup steps, defaults to 0\n        last_step (int, optional): The index of last step, defaults to -1. When last_step=-1,\n            the schedule is started from the beginning or When last_step=-1, sets initial lr as lr.\n    \"\"\"\n\n    def __init__(self, optimizer, initial_lr=0, warmup_steps: int = 0, last_epoch: int = -1):\n        self.initial_lr = initial_lr\n        self.warmup_steps = warmup_steps\n        super().__init__(optimizer, last_epoch=last_epoch)\n\n    def get_lr(self):\n        if self.last_epoch < self.warmup_steps:\n            return [\n                self.initial_lr + (self.last_epoch + 1) / (self.warmup_steps + 1) * (lr - self.initial_lr)\n                for lr in self.base_lrs\n            ]\n        else:\n            return self.base_lrs\n"
  },
  {
    "path": "opensora/utils/prompt_refine.py",
    "content": "import base64\nimport os\nfrom mimetypes import guess_type\n\nfrom openai import OpenAI\n\nsys_prompt_t2v = \"\"\"You are part of a team of bots that creates videos. The workflow is that you first create a caption of the video, and then the assistant bot will generate the video based on the caption. You work with an assistant bot that will draw anything you say.\n\nFor example, outputting \"a beautiful morning in the woods with the sun peaking through the trees\" will trigger your partner bot to output an video of a forest morning, as described. You will be prompted by people looking to create detailed, amazing videos. The way to accomplish this is to take their short prompts and make them extremely detailed and descriptive.\n\nThere are a few rules to follow:\n\nYou will only ever output a single video description per user request.\n\nYou should not simply make the description longer.\n\nVideo descriptions must have the same num of words as examples below. Extra words will be ignored.\n\"\"\"\n\nsys_prompt_t2i = \"\"\"You are part of a team of bots that creates videos. The workflow is that you first create an image caption for the first frame of the video, and then the assistant bot will generate the video based on the image caption.\n\nFor example, outputting \"a beautiful morning in the woods with the sun peaking through the trees\" will trigger your partner bot to output an image of a forest morning, as described. You will be prompted by people looking to create detailed, amazing videos. The way to accomplish this is to take their short prompts and make them extremely detailed and descriptive.\n\nThere are a few rules to follow:\n\nYou will only ever output a single image description per user request.\n\nYou should not simply make the description longer.\n\nImage captions must have the same num of words as examples. Extra words will be ignored.\n\nNote: The input image is the first frame of the video, and the output image caption should include dynamic information.\n\nNote: Don't contain camera transitions!!! Don't contain screen switching!!! Don't contain perspective shifts !!!\n\nNote: Use daily language to describe the video, don't use complex words or phrases!!!\n\"\"\"\n\nsys_prompt_i2v = \"\"\"You are part of a team of bots that creates videos. The workflow is that you first create a caption of the video based on the image, and then the assistant bot will generate the video based on the caption. You work with an assistant bot that will draw anything you say.\n\nGive a highly descriptive video caption based on input image and user input. As an expert, delve deep into the image with a discerning eye, leveraging rich creativity, meticulous thought. When describing the details of an video, include appropriate dynamic information to ensure that the video caption contains reasonable actions and plots. If user input is not empty, then the caption should be expanded according to the user's input.\n\nThe input image is the first frame of the video, and the output video caption should describe the motion starting from the current image. User input is optional and can be empty.\n\nAnswers should be comprehensive, conversational, and use complete sentences. The answer should be in English no matter what the user's input is. Provide context where necessary and maintain a certain tone.  Begin directly without introductory phrases like \"The image/video showcases\" \"The photo captures\" and more. For example, say \"A scene of a woman on a beach\", instead of \"A woman is depicted in the image\".\n\nNote: Must include appropriate dynamic information like actions, plots, etc. If the user prompt did not contain any dynamic information, then you must add some proper dynamic information like actions to make the video move!!!\n\nNote: Try begin the sentence with phrases like  \"A scene of\" or \"A view of\" or \"A close-up of\" to make the video more descriptive!!!\n\nNote: Use daily language to describe the video, don't use complex words or phrases!!!\n\"\"\"\n\nsys_prompt_motion_score = \"\"\"\nWe define a video’s motion score as its FFMPEG VMAF motion value. We now have a video generation model that accepts a desired VMAF motion value as input. To reduce user burden, please predict an optimal motion score for generating a high-quality video based on the user’s text prompt. For reference:\n\t•\tFor runway videos featuring models, a motion score of 4 is ideal.\n\t•\tFor static videos, a motion score of 1 is preferred.\n\nOutput format:\n“{} motion score”, where {} is an integer between 1 and 15.\n\nUser input:\n\"\"\"\n\n\ndef image_to_url(image_path):\n    mime_type, _ = guess_type(image_path)\n    if mime_type is None:\n        mime_type = \"application/octet-stream\"\n    with open(image_path, \"rb\") as image_file:\n        base64_encoded_data = base64.b64encode(image_file.read()).decode(\"utf-8\")\n    return f\"data:{mime_type};base64,{base64_encoded_data}\"\n\n\ndef refine_prompt(prompt: str, retry_times: int = 3, type: str = \"t2v\", image_path: str = None):\n    \"\"\"\n    Refine a prompt to a format that can be used by the model for inference\n    \"\"\"\n\n    client = OpenAI(api_key=os.environ.get(\"OPENAI_API_KEY\"))\n\n    text = prompt.strip()\n    response = None\n    for i in range(retry_times):\n        if type == \"t2v\":\n            response = client.chat.completions.create(\n                messages=[\n                    {\"role\": \"system\", \"content\": f\"{sys_prompt_t2v}\"},\n                    {\n                        \"role\": \"user\",\n                        \"content\": 'Create an imaginative video descriptive caption or modify an earlier caption for the user input : \"A street with parked cars on both sides, lined with commercial buildings featuring Korean signs. The overcast sky suggests early morning or late afternoon.\"',\n                    },\n                    {\n                        \"role\": \"assistant\",\n                        \"content\": \"A view of a street lined with parked cars on both sides. the buildings flanking the street have various signs and advertisements, some of which are in korean, indicating that this might be a location in south korea. the sky is overcast, suggesting either early morning or late afternoon light. the architecture of the buildings is typical of urban commercial areas, with storefronts on the ground level and possibly offices or residences above.\",\n                    },\n                    {\n                        \"role\": \"user\",\n                        \"content\": 'Create an imaginative video descriptive caption or modify an earlier caption for the user input : \"Hands with rings and bracelets wash small greenish-brown seeds in a blue basin under running water, likely outdoors.\"',\n                    },\n                    {\n                        \"role\": \"assistant\",\n                        \"content\": \"A close-up shot of a person's hands, adorned with rings and bracelets, washing a pile of small, round, greenish-brown seeds in a blue plastic basin. the water is running from an unseen source, likely a tap, and the person is using their hands to agitate the seeds, presumably to clean them. the background is indistinct but appears to be an outdoor setting with natural light.\",\n                    },\n                    {\n                        \"role\": \"user\",\n                        \"content\": 'Create an imaginative video descriptive caption or modify an earlier caption for the user input : \"Three men stand near an open black car in a parking lot, with parked vehicles and a partly cloudy sky in the background.\"',\n                    },\n                    {\n                        \"role\": \"assistant\",\n                        \"content\": \"A scene showing three men in an outdoor setting, likely a parking lot. the man on the left is wearing a light blue shirt and dark shorts, the man in the middle is dressed in a white shirt with a pattern and dark shorts, and the man on the right is wearing a green shirt and jeans. they are standing near a black car with its door open. in the background, there are parked vehicles, including a white truck and a red trailer. the sky is partly cloudy, suggesting it might be a sunny day.\",\n                    },\n                    {\n                        \"role\": \"user\",\n                        \"content\": f'Create an imaginative video descriptive caption or modify an earlier caption in ENGLISH for the user input: \" {text} \"',\n                    },\n                ],\n                model=\"gpt-4o\",  # glm-4-plus and gpt-4o have be tested\n                temperature=0.01,\n                top_p=0.7,\n                stream=False,\n                max_tokens=250,\n            )\n        elif type == \"t2i\":\n            response = client.chat.completions.create(\n                messages=[\n                    {\"role\": \"system\", \"content\": f\"{sys_prompt_t2i}\"},\n                    {\n                        \"role\": \"user\",\n                        \"content\": 'Create an imaginative image descriptive caption or modify an earlier caption for the user input : \"a girl on the beach\"',\n                    },\n                    {\n                        \"role\": \"assistant\",\n                        \"content\": \"A radiant woman stands on a deserted beach, arms outstretched, wearing a beige trench coat, white blouse, light blue jeans, and chic boots, against a backdrop of soft sky and sea.\",\n                    },\n                    {\n                        \"role\": \"user\",\n                        \"content\": 'Create an imaginative image descriptive caption or modify an earlier caption for the user input : \"A man in a blue shirt\"',\n                    },\n                    {\n                        \"role\": \"assistant\",\n                        \"content\": \"A determined man in athletic attire, including a blue long-sleeve shirt, black shorts, and blue socks, against a backdrop of a snowy field.\",\n                    },\n                    {\n                        \"role\": \"user\",\n                        \"content\": f'Create an imaginative image descriptive caption or modify an earlier caption in ENGLISH for the user input: \" {text} \"',\n                    },\n                ],\n                model=\"gpt-4o\",  # glm-4-plus and gpt-4o have be tested\n                temperature=0.01,\n                top_p=0.7,\n                stream=False,\n                max_tokens=250,\n            )\n        elif type == \"i2v\":\n            response = client.chat.completions.create(\n                model=\"gpt-4o\",\n                messages=[\n                    {\"role\": \"system\", \"content\": f\"{sys_prompt_i2v}\"},\n                    {\n                        \"role\": \"user\",\n                        \"content\": 'Create an imaginative video descriptive caption or modify an earlier caption for the user input : \"A street with parked cars on both sides, lined with commercial buildings featuring Korean signs. The overcast sky suggests early morning or late afternoon.\"',\n                    },\n                    {\n                        \"role\": \"assistant\",\n                        \"content\": \"A view of a street lined with parked cars on both sides. the buildings flanking the street have various signs and advertisements, some of which are in korean, indicating that this might be a location in south korea. the sky is overcast, suggesting either early morning or late afternoon light. the architecture of the buildings is typical of urban commercial areas, with storefronts on the ground level and possibly offices or residences above.\",\n                    },\n                    {\n                        \"role\": \"user\",\n                        \"content\": 'Create an imaginative video descriptive caption or modify an earlier caption for the user input : \"Hands with rings and bracelets wash small greenish-brown seeds in a blue basin under running water, likely outdoors.\"',\n                    },\n                    {\n                        \"role\": \"assistant\",\n                        \"content\": \"A close-up shot of a person's hands, adorned with rings and bracelets, washing a pile of small, round, greenish-brown seeds in a blue plastic basin. the water is running from an unseen source, likely a tap, and the person is using their hands to agitate the seeds, presumably to clean them. the background is indistinct but appears to be an outdoor setting with natural light.\",\n                    },\n                    {\n                        \"role\": \"user\",\n                        \"content\": 'Create an imaginative video descriptive caption or modify an earlier caption for the user input : \"Three men stand near an open black car in a parking lot, with parked vehicles and a partly cloudy sky in the background.\"',\n                    },\n                    {\n                        \"role\": \"assistant\",\n                        \"content\": \"A scene showing three men in an outdoor setting, likely a parking lot. the man on the left is wearing a light blue shirt and dark shorts, the man in the middle is dressed in a white shirt with a pattern and dark shorts, and the man on the right is wearing a green shirt and jeans. they are standing near a black car with its door open. in the background, there are parked vehicles, including a white truck and a red trailer. the sky is partly cloudy, suggesting it might be a sunny day.\",\n                    },\n                    {\n                        \"role\": \"user\",\n                        \"content\": f'Create an imaginative video descriptive caption or modify an earlier caption in ENGLISH for the user input based on the image: \" {text} \"',\n                    },\n                    {\n                        \"role\": \"user\",\n                        \"content\": [\n                            {\n                                \"type\": \"image_url\",\n                                \"image_url\": {\n                                    \"url\": image_to_url(image_path),\n                                },\n                            },\n                        ],\n                    },\n                ],\n                temperature=0.01,\n                top_p=0.7,\n                stream=False,\n                max_tokens=250,\n            )\n        elif type == \"motion_score\":\n            response = client.chat.completions.create(\n                messages=[\n                    {\"role\": \"system\", \"content\": f\"{sys_prompt_motion_score}\"},\n                    {\n                        \"role\": \"user\",\n                        \"content\": f\"{text}\",\n                    },\n                ],\n                model=\"gpt-4o\",  # glm-4-plus and gpt-4o have be tested\n                temperature=0.01,\n                top_p=0.7,\n                stream=False,\n                max_tokens=100,\n            )\n        if response is None:\n            continue\n        if response.choices:\n            return response.choices[0].message.content\n    return prompt\n\n\ndef refine_prompts(prompts: list[str], retry_times: int = 3, type: str = \"t2v\", image_paths: list[str] = None):\n    if image_paths is None:\n        image_paths = [None] * len(prompts)\n    refined_prompts = []\n    for prompt, image_path in zip(prompts, image_paths):\n        refined_prompt = refine_prompt(prompt, retry_times=retry_times, type=type, image_path=image_path)\n        refined_prompts.append(refined_prompt)\n    return refined_prompts\n"
  },
  {
    "path": "opensora/utils/sampling.py",
    "content": "import math\nimport os\nimport random\nfrom abc import ABC, abstractmethod\nfrom dataclasses import dataclass, replace\n\nimport torch\nfrom einops import rearrange, repeat\nfrom mmengine.config import Config\nfrom peft import PeftModel\nfrom torch import Tensor, nn\n\nfrom opensora.datasets.aspect import get_image_size\nfrom opensora.models.mmdit.model import MMDiTModel\nfrom opensora.models.text.conditioner import HFEmbedder\nfrom opensora.registry import MODELS, build_module\nfrom opensora.utils.inference import (\n    SamplingMethod,\n    collect_references_batch,\n    prepare_inference_condition,\n)\n\n# ======================================================\n# Sampling Options\n# ======================================================\n\n\n@dataclass\nclass SamplingOption:\n    # The width of the image/video.\n    width: int | None = None\n\n    # The height of the image/video.\n    height: int | None = None\n\n    # The resolution of the image/video. If provided, it will override the height and width.\n    resolution: str | None = None\n\n    # The aspect ratio of the image/video. If provided, it will override the height and width.\n    aspect_ratio: str | None = None\n\n    # The number of frames.\n    num_frames: int = 1\n\n    # The number of sampling steps.\n    num_steps: int = 50\n\n    # The classifier-free guidance (text).\n    guidance: float = 4.0\n\n    # use oscillation for text guidance\n    text_osci: bool = False\n\n    # The classifier-free guidance (image), or for the guidance on condition for i2v and v2v\n    guidance_img: float | None = None\n\n    # use oscillation for image guidance\n    image_osci: bool = False\n\n    # use temporal scaling for image guidance\n    scale_temporal_osci: bool = False\n\n    # The seed for the random number generator.\n    seed: int | None = None\n\n    # Whether to shift the schedule.\n    shift: bool = True\n\n    # The sampling method.\n    method: str | SamplingMethod = SamplingMethod.I2V\n\n    # Temporal reduction\n    temporal_reduction: int = 1\n\n    # is causal vae\n    is_causal_vae: bool = False\n\n    # flow shift\n    flow_shift: float | None = None\n\n\ndef sanitize_sampling_option(sampling_option: SamplingOption) -> SamplingOption:\n    \"\"\"\n    Sanitize the sampling options.\n\n    Args:\n        sampling_option (SamplingOption): The sampling options.\n\n    Returns:\n        SamplingOption: The sanitized sampling options.\n    \"\"\"\n    if (\n        sampling_option.resolution is not None\n        or sampling_option.aspect_ratio is not None\n    ):\n        assert (\n            sampling_option.resolution is not None\n            and sampling_option.aspect_ratio is not None\n        ), \"Both resolution and aspect ratio must be provided\"\n        resolution = sampling_option.resolution\n        aspect_ratio = sampling_option.aspect_ratio\n        height, width = get_image_size(resolution, aspect_ratio, training=False)\n    else:\n        assert (\n            sampling_option.height is not None and sampling_option.width is not None\n        ), \"Both height and width must be provided\"\n        height, width = sampling_option.height, sampling_option.width\n\n    height = (height // 16 + (1 if height % 16 else 0)) * 16\n    width = (width // 16 + (1 if width % 16 else 0)) * 16\n    replace_dict = dict(height=height, width=width)\n\n    if isinstance(sampling_option.method, str):\n        method = SamplingMethod(sampling_option.method)\n        replace_dict[\"method\"] = method\n\n    return replace(sampling_option, **replace_dict)\n\n\ndef get_oscillation_gs(guidance_scale: float, i: int, force_num=10):\n    \"\"\"\n    get oscillation guidance for cfg.\n\n    Args:\n        guidance_scale: original guidance value\n        i: denoising step\n        force_num: before which don't apply oscillation\n    \"\"\"\n    if i < force_num or (i >= force_num and i % 2 == 0):\n        gs = guidance_scale\n    else:\n        gs = 1.0\n    return gs\n\n\n# ======================================================\n# Denoising\n# ======================================================\n\n\nclass Denoiser(ABC):\n    @abstractmethod\n    def denoise(self, model: MMDiTModel, **kwargs) -> Tensor:\n        \"\"\"Denoise the input.\"\"\"\n\n    @abstractmethod\n    def prepare_guidance(\n        self,\n        text: list[str],\n        optional_models: dict[str, nn.Module],\n        device: torch.device,\n        dtype: torch.dtype,\n        **kwargs,\n    ) -> dict[str, Tensor]:\n        \"\"\"Prepare the guidance for the model. This method will alter text.\"\"\"\n\n\nclass I2VDenoiser(Denoiser):\n    def denoise(self, model: MMDiTModel, **kwargs) -> Tensor:\n        img = kwargs.pop(\"img\")\n        timesteps = kwargs.pop(\"timesteps\")\n        guidance = kwargs.pop(\"guidance\")\n        guidance_img = kwargs.pop(\"guidance_img\")\n\n        # cond ref arguments\n        masks = kwargs.pop(\"masks\")\n        masked_ref = kwargs.pop(\"masked_ref\")\n        kwargs.pop(\"sigma_min\")\n\n        # oscillation guidance\n        text_osci = kwargs.pop(\"text_osci\", False)\n        image_osci = kwargs.pop(\"image_osci\", False)\n        scale_temporal_osci = kwargs.pop(\"scale_temporal_osci\", False)\n\n        # patch size\n        patch_size = kwargs.pop(\"patch_size\", 2)\n\n        guidance_vec = torch.full(\n            (img.shape[0],), guidance, device=img.device, dtype=img.dtype\n        )\n        for i, (t_curr, t_prev) in enumerate(zip(timesteps[:-1], timesteps[1:])):\n            # timesteps\n            t_vec = torch.full(\n                (img.shape[0],), t_curr, dtype=img.dtype, device=img.device\n            )\n            b, c, t, w, h = masked_ref.size()\n            cond = torch.cat((masks, masked_ref), dim=1)\n            cond = pack(cond, patch_size=patch_size)\n            kwargs[\"cond\"] = torch.cat([cond, cond, torch.zeros_like(cond)], dim=0)\n\n            # forward preparation\n            cond_x = img[: len(img) // 3]\n\n            img = torch.cat([cond_x, cond_x, cond_x], dim=0)\n            # forward\n            pred = model(\n                img=img,\n                **kwargs,\n                timesteps=t_vec,\n                guidance=guidance_vec,\n            )\n\n            # prepare guidance\n            text_gs = get_oscillation_gs(guidance, i) if text_osci else guidance\n            image_gs = (\n                get_oscillation_gs(guidance_img, i) if image_osci else guidance_img\n            )\n            cond, uncond, uncond_2 = pred.chunk(3, dim=0)\n            if image_gs > 1.0 and scale_temporal_osci:\n                # image_gs decrease with each denoising step\n                step_upper_image_gs = torch.linspace(image_gs, 1.0, len(timesteps))[i]\n                # image_gs increase along the temporal axis of the latent video\n                image_gs = torch.linspace(1.0, step_upper_image_gs, t)[\n                    None, None, :, None, None\n                ].repeat(b, c, 1, h, w)\n                image_gs = pack(image_gs, patch_size=patch_size).to(cond.device, cond.dtype)\n\n            # update\n            pred = uncond_2 + image_gs * (uncond - uncond_2) + text_gs * (cond - uncond)\n            pred = torch.cat([pred, pred, pred], dim=0)\n\n            img = img + (t_prev - t_curr) * pred\n\n        img = img[: len(img) // 3]\n\n        return img\n\n    def prepare_guidance(\n        self,\n        text: list[str],\n        optional_models: dict[str, nn.Module],\n        device: torch.device,\n        dtype: torch.dtype,\n        **kwargs,\n    ) -> tuple[list[str], dict[str, Tensor]]:\n        ret = {}\n\n        neg = kwargs.get(\"neg\", None)\n        ret[\"guidance_img\"] = kwargs.pop(\"guidance_img\")\n\n        # text\n        if neg is None:\n            neg = [\"\"] * len(text)\n        text = text + neg + neg\n        return text, ret\n\n\nclass DistilledDenoiser(Denoiser):\n    def denoise(self, model: MMDiTModel, **kwargs) -> Tensor:\n        img = kwargs.pop(\"img\")\n        timesteps = kwargs.pop(\"timesteps\")\n        guidance = kwargs.pop(\"guidance\")\n\n        guidance_vec = torch.full(\n            (img.shape[0],), guidance, device=img.device, dtype=img.dtype\n        )\n        for t_curr, t_prev in zip(timesteps[:-1], timesteps[1:]):\n            # timesteps\n            t_vec = torch.full(\n                (img.shape[0],), t_curr, dtype=img.dtype, device=img.device\n            )\n            # forward\n            pred = model(\n                img=img,\n                **kwargs,\n                timesteps=t_vec,\n                guidance=guidance_vec,\n            )\n            # update\n            img = img + (t_prev - t_curr) * pred\n        return img\n\n    def prepare_guidance(\n        self,\n        text: list[str],\n        optional_models: dict[str, nn.Module],\n        device: torch.device,\n        dtype: torch.dtype,\n        **kwargs,\n    ) -> tuple[list[str], dict[str, Tensor]]:\n        return text, {}\n\n\nSamplingMethodDict = {\n    SamplingMethod.I2V: I2VDenoiser(),\n    SamplingMethod.DISTILLED: DistilledDenoiser(),\n}\n\n\n# ======================================================\n# Timesteps\n# ======================================================\n\n\ndef time_shift(alpha: float, t: Tensor) -> Tensor:\n    return alpha * t / (1 + (alpha - 1) * t)\n\n\ndef get_res_lin_function(\n    x1: float = 256, y1: float = 1, x2: float = 4096, y2: float = 3\n) -> callable:\n    m = (y2 - y1) / (x2 - x1)\n    b = y1 - m * x1\n    return lambda x: m * x + b\n\n\ndef get_schedule(\n    num_steps: int,\n    image_seq_len: int,\n    num_frames: int,\n    shift_alpha: float | None = None,\n    base_shift: float = 1,\n    max_shift: float = 3,\n    shift: bool = True,\n) -> list[float]:\n    # extra step for zero\n    timesteps = torch.linspace(1, 0, num_steps + 1)\n\n    # shifting the schedule to favor high timesteps for higher signal images\n    if shift:\n        if shift_alpha is None:\n            # estimate mu based on linear estimation between two points\n            # spatial scale\n            shift_alpha = get_res_lin_function(y1=base_shift, y2=max_shift)(\n                image_seq_len\n            )\n            # temporal scale\n            shift_alpha *= math.sqrt(num_frames)\n        # calculate shifted timesteps\n        timesteps = time_shift(shift_alpha, timesteps)\n\n    return timesteps.tolist()\n\n\ndef get_noise(\n    num_samples: int,\n    height: int,\n    width: int,\n    num_frames: int,\n    device: torch.device,\n    dtype: torch.dtype,\n    seed: int,\n    patch_size: int = 2,\n    channel: int = 16,\n) -> Tensor:\n    \"\"\"\n    Generate a noise tensor.\n\n    Args:\n        num_samples (int): Number of samples.\n        height (int): Height of the noise tensor.\n        width (int): Width of the noise tensor.\n        num_frames (int): Number of frames.\n        device (torch.device): Device to put the noise tensor on.\n        dtype (torch.dtype): Data type of the noise tensor.\n        seed (int): Seed for the random number generator.\n\n    Returns:\n        Tensor: The noise tensor.\n    \"\"\"\n    D = int(os.environ.get(\"AE_SPATIAL_COMPRESSION\", 16))\n    return torch.randn(\n        num_samples,\n        channel,\n        num_frames,\n        # allow for packing\n        patch_size * math.ceil(height / D),\n        patch_size * math.ceil(width / D),\n        device=device,\n        dtype=dtype,\n        generator=torch.Generator(device=device).manual_seed(seed),\n    )\n\n\ndef pack(x: Tensor, patch_size: int = 2) -> Tensor:\n    return rearrange(\n        x, \"b c t (h ph) (w pw) -> b (t h w) (c ph pw)\", ph=patch_size, pw=patch_size\n    )\n\n\ndef unpack(\n    x: Tensor, height: int, width: int, num_frames: int, patch_size: int = 2\n) -> Tensor:\n    D = int(os.environ.get(\"AE_SPATIAL_COMPRESSION\", 16))\n    return rearrange(\n        x,\n        \"b (t h w) (c ph pw) -> b c t (h ph) (w pw)\",\n        h=math.ceil(height / D),\n        w=math.ceil(width / D),\n        t=num_frames,\n        ph=patch_size,\n        pw=patch_size,\n    )\n\n\n# ======================================================\n# Prepare\n# ======================================================\n\n\ndef prepare(\n    t5,\n    clip: HFEmbedder,\n    img: Tensor,\n    prompt: str | list[str],\n    seq_align: int = 1,\n    patch_size: int = 2,\n) -> dict[str, Tensor]:\n    \"\"\"\n    Prepare the input for the model.\n\n    Args:\n        t5 (HFEmbedder): The T5 model.\n        clip (HFEmbedder): The CLIP model.\n        img (Tensor): The image tensor.\n        prompt (str | list[str]): The prompt(s).\n\n    Returns:\n        dict[str, Tensor]: The input dictionary.\n\n        img_ids: used for positional embedding in T,H,W dimensions later\n        text_ids: for positional embedding, but set to 0 for now since our text encoder already encodes positional information\n    \"\"\"\n    bs, c, t, h, w = img.shape\n    device, dtype = img.device, img.dtype\n    if isinstance(prompt, str):\n        prompt = [prompt]\n    if bs != len(prompt):\n        bs = len(prompt)\n\n    img = rearrange(\n        img, \"b c t (h ph) (w pw) -> b (t h w) (c ph pw)\", ph=patch_size, pw=patch_size\n    )\n    if img.shape[0] != bs:\n        img = repeat(img, \"b ... -> (repeat b) ...\", repeat=bs // img.shape[0])\n\n    img_ids = torch.zeros(t, h // patch_size, w // patch_size, 3)\n    img_ids[..., 0] = img_ids[..., 0] + torch.arange(t)[:, None, None]\n    img_ids[..., 1] = img_ids[..., 1] + torch.arange(h // patch_size)[None, :, None]\n    img_ids[..., 2] = img_ids[..., 2] + torch.arange(w // patch_size)[None, None, :]\n    img_ids = repeat(img_ids, \"t h w c -> b (t h w) c\", b=bs)\n\n    # Encode the tokenized prompts\n    txt = t5(prompt, added_tokens=img_ids.shape[1], seq_align=seq_align)\n    if txt.shape[0] == 1 and bs > 1:\n        txt = repeat(txt, \"1 ... -> bs ...\", bs=bs)\n    txt_ids = torch.zeros(bs, txt.shape[1], 3)\n\n    vec = clip(prompt)\n    if vec.shape[0] == 1 and bs > 1:\n        vec = repeat(vec, \"1 ... -> bs ...\", bs=bs)\n\n    return {\n        \"img\": img,\n        \"img_ids\": img_ids.to(device, dtype),\n        \"txt\": txt.to(device, dtype),\n        \"txt_ids\": txt_ids.to(device, dtype),\n        \"y_vec\": vec.to(device, dtype),\n    }\n\n\ndef prepare_ids(\n    img: Tensor,\n    t5_embedding: Tensor,\n    clip_embedding: Tensor,\n) -> dict[str, Tensor]:\n    \"\"\"\n    Prepare the input for the model.\n\n    Args:\n        img (Tensor): The image tensor.\n        t5_embedding (Tensor): The T5 embedding.\n        clip_embedding (Tensor): The CLIP embedding.\n\n    Returns:\n        dict[str, Tensor]: The input dictionary.\n\n        img_ids: used for positional embedding in T,H,W dimensions later\n        text_ids: for positional embedding, but set to 0 for now since our text encoder already encodes positional information\n    \"\"\"\n    bs, c, t, h, w = img.shape\n    device, dtype = img.device, img.dtype\n\n    img = rearrange(img, \"b c t (h ph) (w pw) -> b (t h w) (c ph pw)\", ph=2, pw=2)\n    if img.shape[0] != bs:\n        img = repeat(img, \"b ... -> (repeat b) ...\", repeat=bs // img.shape[0])\n\n    img_ids = torch.zeros(t, h // 2, w // 2, 3)\n    img_ids[..., 0] = img_ids[..., 0] + torch.arange(t)[:, None, None]\n    img_ids[..., 1] = img_ids[..., 1] + torch.arange(h // 2)[None, :, None]\n    img_ids[..., 2] = img_ids[..., 2] + torch.arange(w // 2)[None, None, :]\n    img_ids = repeat(img_ids, \"t h w c -> b (t h w) c\", b=bs)\n\n    # Encode the tokenized prompts\n    if t5_embedding.shape[0] == 1 and bs > 1:\n        t5_embedding = repeat(t5_embedding, \"1 ... -> bs ...\", bs=bs)\n    txt_ids = torch.zeros(bs, t5_embedding.shape[1], 3)\n\n    if clip_embedding.shape[0] == 1 and bs > 1:\n        clip_embedding = repeat(clip_embedding, \"1 ... -> bs ...\", bs=bs)\n\n    return {\n        \"img\": img,\n        \"img_ids\": img_ids.to(device, dtype),\n        \"txt\": t5_embedding.to(device, dtype),\n        \"txt_ids\": txt_ids.to(device, dtype),\n        \"y_vec\": clip_embedding.to(device, dtype),\n    }\n\n\ndef prepare_models(\n    cfg: Config,\n    device: torch.device,\n    dtype: torch.dtype,\n    offload_model: bool = False,\n) -> tuple[nn.Module, nn.Module, nn.Module, nn.Module, dict[str, nn.Module]]:\n    \"\"\"\n    Prepare models for inference.\n\n    Args:\n        cfg (Config): The configuration object.\n        device (torch.device): The device to use.\n        dtype (torch.dtype): The data type to use.\n\n    Returns:\n        tuple[nn.Module, nn.Module, nn.Module, nn.Module, dict[str, nn.Module]]: The models. They are the diffusion model, the autoencoder model, the T5 model, the CLIP model, and the optional models.\n    \"\"\"\n    model_device = (\n        \"cpu\" if offload_model and cfg.get(\"img_flux\", None) is not None else device\n    )\n\n    model = build_module(\n        cfg.model, MODELS, device_map=model_device, torch_dtype=dtype\n    ).eval()\n    model_ae = build_module(\n        cfg.ae, MODELS, device_map=model_device, torch_dtype=dtype\n    ).eval()\n    model_t5 = build_module(cfg.t5, MODELS, device_map=device, torch_dtype=dtype).eval()\n    model_clip = build_module(\n        cfg.clip, MODELS, device_map=device, torch_dtype=dtype\n    ).eval()\n    if cfg.get(\"pretrained_lora_path\", None) is not None:\n        model = PeftModel.from_pretrained(\n            model, cfg.pretrained_lora_path, is_trainable=False\n        )\n\n    # optional models\n    optional_models = {}\n    if cfg.get(\"img_flux\", None) is not None:\n        model_img_flux = build_module(\n            cfg.img_flux, MODELS, device_map=device, torch_dtype=dtype\n        ).eval()\n        model_ae_img_flux = build_module(\n            cfg.img_flux_ae, MODELS, device_map=device, torch_dtype=dtype\n        ).eval()\n        optional_models[\"img_flux\"] = model_img_flux\n        optional_models[\"img_flux_ae\"] = model_ae_img_flux\n\n    return model, model_ae, model_t5, model_clip, optional_models\n\n\ndef prepare_api(\n    model: nn.Module,\n    model_ae: nn.Module,\n    model_t5: nn.Module,\n    model_clip: nn.Module,\n    optional_models: dict[str, nn.Module],\n) -> callable:\n    \"\"\"\n    Prepare the API function for inference.\n\n    Args:\n        model (nn.Module): The diffusion model.\n        model_ae (nn.Module): The autoencoder model.\n        model_t5 (nn.Module): The T5 model.\n        model_clip (nn.Module): The CLIP model.\n\n    Returns:\n        callable: The API function for inference.\n    \"\"\"\n\n    @torch.inference_mode()\n    def api_fn(\n        opt: SamplingOption,\n        cond_type: str = \"t2v\",\n        seed: int = None,\n        sigma_min: float = 1e-5,\n        text: list[str] = None,\n        neg: list[str] = None,\n        patch_size: int = 2,\n        channel: int = 16,\n        **kwargs,\n    ):\n        \"\"\"\n        The API function for inference.\n\n        Args:\n            opt (SamplingOption): The sampling options.\n            text (list[str], optional): The text prompts. Defaults to None.\n            neg (list[str], optional): The negative text prompts. Defaults to None.\n\n        Returns:\n            torch.Tensor: The generated images.\n        \"\"\"\n        device = next(model.parameters()).device\n        dtype = next(model.parameters()).dtype\n\n        # passing seed will overwrite opt seed\n        if seed is None:\n            # random seed if not provided\n            seed = opt.seed if opt.seed is not None else random.randint(0, 2**32 - 1)\n        if opt.is_causal_vae:\n            num_frames = (\n                1\n                if opt.num_frames == 1\n                else (opt.num_frames - 1) // opt.temporal_reduction + 1\n            )\n        else:\n            num_frames = (\n                1 if opt.num_frames == 1 else opt.num_frames // opt.temporal_reduction\n            )\n\n        z = get_noise(\n            len(text),\n            opt.height,\n            opt.width,\n            num_frames,\n            device,\n            dtype,\n            seed,\n            patch_size=patch_size,\n            channel=channel // (patch_size**2),\n        )\n        denoiser = SamplingMethodDict[opt.method]\n\n        # i2v reference conditions\n        references = [None] * len(text)\n        if cond_type != \"t2v\" and \"ref\" in kwargs:\n            reference_path_list = kwargs.pop(\"ref\")\n            references = collect_references_batch(\n                reference_path_list,\n                cond_type,\n                model_ae,\n                (opt.height, opt.width),\n                is_causal=opt.is_causal_vae,\n            )\n        elif cond_type != \"t2v\":\n            print(\n                \"your csv file doesn't have a ref column or is not processed properly. will default to cond_type t2v!\"\n            )\n            cond_type = \"t2v\"\n\n        # timestep editing\n        timesteps = get_schedule(\n            opt.num_steps,\n            (z.shape[-1] * z.shape[-2]) // patch_size**2,\n            num_frames,\n            shift=opt.shift,\n            shift_alpha=opt.flow_shift,\n        )\n\n        # prepare classifier-free guidance data (method specific)\n        text, additional_inp = denoiser.prepare_guidance(\n            text=text,\n            optional_models=optional_models,\n            device=device,\n            dtype=dtype,\n            neg=neg,\n            guidance_img=opt.guidance_img,\n        )\n\n        inp = prepare(model_t5, model_clip, z, prompt=text, patch_size=patch_size)\n        inp.update(additional_inp)\n\n        if opt.method in [SamplingMethod.I2V]:\n            # prepare references\n            masks, masked_ref = prepare_inference_condition(\n                z, cond_type, ref_list=references, causal=opt.is_causal_vae\n            )\n            inp[\"masks\"] = masks\n            inp[\"masked_ref\"] = masked_ref\n            inp[\"sigma_min\"] = sigma_min\n\n        x = denoiser.denoise(\n            model,\n            **inp,\n            timesteps=timesteps,\n            guidance=opt.guidance,\n            text_osci=opt.text_osci,\n            image_osci=opt.image_osci,\n            scale_temporal_osci=(\n                opt.scale_temporal_osci and \"i2v\" in cond_type\n            ),  # don't use temporal osci for v2v or t2v\n            flow_shift=opt.flow_shift,\n            patch_size=patch_size,\n        )\n\n        x = unpack(x, opt.height, opt.width, num_frames, patch_size=patch_size)\n\n        # replace for image condition\n        if cond_type == \"i2v_head\":\n            x[0, :, :1] = references[0][0]\n        elif cond_type == \"i2v_tail\":\n            x[0, :, -1:] = references[0][0]\n        elif cond_type == \"i2v_loop\":\n            x[0, :, :1] = references[0][0]\n            x[0, :, -1:] = references[0][1]\n\n        x = model_ae.decode(x)\n        x = x[:, :, : opt.num_frames]  # image\n\n        # remove the duplicate frames\n        if not opt.is_causal_vae:\n            if cond_type == \"i2v_head\":\n                pad_len = model_ae.compression[0] - 1\n                x = x[:, :, pad_len:]\n            elif cond_type == \"i2v_tail\":\n                pad_len = model_ae.compression[0] - 1\n                x = x[:, :, :-pad_len]\n            elif cond_type == \"i2v_loop\":\n                pad_len = model_ae.compression[0] - 1\n                x = x[:, :, pad_len:-pad_len]\n\n        return x\n\n    return api_fn\n"
  },
  {
    "path": "opensora/utils/train.py",
    "content": "import random\nimport warnings\nfrom collections import OrderedDict\nfrom datetime import timedelta\n\nimport torch\nimport torch.distributed as dist\nimport torch.nn.functional as F\nfrom colossalai.booster.plugin import HybridParallelPlugin, LowLevelZeroPlugin\nfrom colossalai.cluster import DistCoordinator\nfrom colossalai.utils import get_current_device\nfrom einops import rearrange\nfrom torch import nn\nfrom torch.optim.lr_scheduler import _LRScheduler\nfrom tqdm import tqdm\n\nfrom opensora.acceleration.parallel_states import (\n    set_data_parallel_group,\n    set_sequence_parallel_group,\n    set_tensor_parallel_group,\n)\nfrom opensora.utils.optimizer import LinearWarmupLR\n\n\ndef set_lr(\n    optimizer: torch.optim.Optimizer,\n    lr_scheduler: _LRScheduler,\n    lr: float,\n    initial_lr: float = None,\n):\n    for param_group in optimizer.param_groups:\n        param_group[\"lr\"] = lr\n    if isinstance(lr_scheduler, LinearWarmupLR):\n        lr_scheduler.base_lrs = [lr] * len(lr_scheduler.base_lrs)\n        if initial_lr is not None:\n            lr_scheduler.initial_lr = initial_lr\n\n\ndef set_warmup_steps(\n    lr_scheduler: _LRScheduler,\n    warmup_steps: int,\n):\n    if isinstance(lr_scheduler, LinearWarmupLR):\n        lr_scheduler.warmup_steps = warmup_steps\n\n\ndef set_eps(\n    optimizer: torch.optim.Optimizer,\n    eps: float = None,\n):\n    if eps is not None:\n        for param_group in optimizer.param_groups:\n            param_group[\"eps\"] = eps\n\n\ndef setup_device() -> tuple[torch.device, DistCoordinator]:\n    \"\"\"\n    Setup the device and the distributed coordinator.\n\n    Returns:\n        tuple[torch.device, DistCoordinator]: The device and the distributed coordinator.\n    \"\"\"\n    assert torch.cuda.is_available(), \"Training currently requires at least one GPU.\"\n    # NOTE: A very large timeout is set to avoid some processes exit early\n    dist.init_process_group(backend=\"nccl\", timeout=timedelta(hours=24))\n    torch.cuda.set_device(dist.get_rank() % torch.cuda.device_count())\n    coordinator = DistCoordinator()\n    device = get_current_device()\n\n    return device, coordinator\n\n\ndef create_colossalai_plugin(\n    plugin: str,\n    dtype: str,\n    grad_clip: float,\n    **kwargs,\n) -> LowLevelZeroPlugin | HybridParallelPlugin:\n    \"\"\"\n    Create a ColossalAI plugin.\n\n    Args:\n        plugin (str): The plugin name.\n        dtype (str): The data type.\n        grad_clip (float): The gradient clip value.\n\n    Returns:\n        LowLevelZeroPlugin |  HybridParallelPlugin: The plugin.\n    \"\"\"\n    plugin_kwargs = dict(\n        precision=dtype,\n        initial_scale=2**16,\n        max_norm=grad_clip,\n        overlap_allgather=True,\n        cast_inputs=False,\n        reduce_bucket_size_in_m=20,\n    )\n    plugin_kwargs.update(kwargs)\n    sp_size = plugin_kwargs.get(\"sp_size\", 1)\n    if plugin == \"zero1\" or plugin == \"zero2\":\n        assert sp_size == 1, \"Zero plugin does not support sequence parallelism\"\n        stage = 1 if plugin == \"zero1\" else 2\n        plugin = LowLevelZeroPlugin(\n            stage=stage,\n            **plugin_kwargs,\n        )\n        set_data_parallel_group(dist.group.WORLD)\n    elif plugin == \"hybrid\":\n        plugin_kwargs[\"find_unused_parameters\"] = True\n        reduce_bucket_size_in_m = plugin_kwargs.pop(\"reduce_bucket_size_in_m\")\n        if \"zero_bucket_size_in_m\" not in plugin_kwargs:\n            plugin_kwargs[\"zero_bucket_size_in_m\"] = reduce_bucket_size_in_m\n        plugin_kwargs.pop(\"cast_inputs\")\n        plugin_kwargs[\"enable_metadata_cache\"] = False\n\n        custom_policy = plugin_kwargs.pop(\"custom_policy\", None)\n        if custom_policy is not None:\n            custom_policy = custom_policy()\n        plugin = HybridParallelPlugin(\n            custom_policy=custom_policy,\n            **plugin_kwargs,\n        )\n        set_tensor_parallel_group(plugin.tp_group)\n        set_sequence_parallel_group(plugin.sp_group)\n        set_data_parallel_group(plugin.dp_group)\n    else:\n        raise ValueError(f\"Unknown plugin {plugin}\")\n    return plugin\n\n\n@torch.no_grad()\ndef update_ema(\n    ema_model: torch.nn.Module, model: torch.nn.Module, optimizer=None, decay: float = 0.9999, sharded: bool = True\n):\n    \"\"\"\n    Step the EMA model towards the current model.\n\n    Args:\n        ema_model (torch.nn.Module): The EMA model.\n        model (torch.nn.Module): The current model.\n        optimizer (torch.optim.Optimizer): The optimizer.\n        decay (float): The decay rate.\n        sharded (bool): Whether the model is sharded.\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        if name == \"pos_embed\":\n            continue\n        if not param.requires_grad:\n            continue\n        if not sharded:\n            param_data = param.data\n            ema_params[name].mul_(decay).add_(param_data, alpha=1 - decay)\n        else:\n            if param.data.dtype != torch.float32:\n                param_id = id(param)\n                master_param = optimizer.get_working_to_master_map()[param_id]\n                param_data = master_param.data\n            else:\n                param_data = param.data\n            ema_params[name].mul_(decay).add_(param_data, alpha=1 - decay)\n\n\ndef dropout_condition(prob: float, txt: torch.Tensor, null_txt: torch.Tensor) -> torch.Tensor:\n    \"\"\"\n    Apply dropout to the text tensor.\n\n    Args:\n        prob (float): The dropout probability.\n        txt (torch.Tensor): The text tensor.\n        null_txt (torch.Tensor): The null text tensor.\n\n    Returns:\n        torch.Tensor: The text tensor with dropout applied.\n    \"\"\"\n    if prob == 0:\n        warnings.warn(\"Dropout probability is 0, skipping dropout\")\n    drop_ids = torch.rand(txt.shape[0], device=txt.device) < prob\n    drop_ids = drop_ids.view((drop_ids.shape[0],) + (1,) * (txt.ndim - 1))\n    new_txt = torch.where(drop_ids, null_txt, txt)\n    return new_txt\n\n\ndef prepare_visual_condition_uncausal(\n    x: torch.Tensor, condition_config: dict, model_ae: torch.nn.Module, pad: bool = False\n) -> torch.Tensor:\n    \"\"\"\n    Prepare the visual condition for the model.\n\n    Args:\n        x: (torch.Tensor): The input video tensor.\n        condition_config (dict): The condition configuration.\n        model_ae (torch.nn.Module): The video encoder module.\n\n    Returns:\n        torch.Tensor: The visual condition tensor.\n    \"\"\"\n    # x has shape [b, c, t, h, w], where b is the batch size\n    B = x.shape[0]\n    C = model_ae.cfg.latent_channels\n    T, H, W = model_ae.get_latent_size(x.shape[-3:])\n\n    # Initialize masks tensor to match the shape of x, but only the time dimension will be masked\n    masks = torch.zeros(B, 1, T, H, W).to(\n        x.device, x.dtype\n    )  # broadcasting over channel, concat to masked_x with 1 + 16 = 17 channesl\n    # to prevent information leakage, image must be encoded separately and copied to latent\n    latent = torch.zeros(B, C, T, H, W).to(x.device, x.dtype)\n    x_0 = torch.zeros(B, C, T, H, W).to(x.device, x.dtype)\n    if T > 1:  # video\n        # certain v2v conditions not are applicable for short videos\n        if T <= 32 // model_ae.time_compression_ratio:\n            condition_config.pop(\"v2v_head\", None)  # given first 32 frames\n            condition_config.pop(\"v2v_tail\", None)  # given last 32 frames\n            condition_config.pop(\"v2v_head_easy\", None)  # given first 64 frames\n            condition_config.pop(\"v2v_tail_easy\", None)  # given last 64 frames\n        if T <= 64 // model_ae.time_compression_ratio:\n            condition_config.pop(\"v2v_head_easy\", None)  # given first 64 frames\n            condition_config.pop(\"v2v_tail_easy\", None)  # given last 64 frames\n\n        mask_cond_options = list(condition_config.keys())  # list of mask conditions\n        mask_cond_weights = list(condition_config.values())  # corresponding probabilities\n\n        for i in range(B):\n            # Randomly select a mask condition based on the provided probabilities\n            mask_cond = random.choices(mask_cond_options, weights=mask_cond_weights, k=1)[0]\n            # Apply the selected mask condition directly on the masks tensor\n            if mask_cond == \"i2v_head\":  # NOTE: modify video, mask first latent frame\n                # padded video such that the first latent frame correspond to image only\n                masks[i, :, 0, :, :] = 1\n                if pad:\n                    pad_num = model_ae.time_compression_ratio - 1  # 32 --> new video: 7 + (1+31-7)\n                    padded_x = torch.cat([x[i, :, :1]] * pad_num + [x[i, :, :-pad_num]], dim=1).unsqueeze(0)\n                    x_0[i] = model_ae.encode(padded_x)[0]\n                else:\n                    x_0[i] = model_ae.encode(x[i : i + 1])[0]\n                # condition: encode the image only\n                latent[i, :, :1, :, :] = model_ae.encode(\n                    x[i, :, :1, :, :].unsqueeze(0)\n                )  # since the first dimension of right hand side is singleton, torch auto-ignores it\n            elif mask_cond == \"i2v_loop\":  # # NOTE: modify video, mask first and last latent frame\n                # pad video such that first and last latent frame correspond to image only\n                masks[i, :, 0, :, :] = 1\n                masks[i, :, -1, :, :] = 1\n                if pad:\n                    pad_num = model_ae.time_compression_ratio - 1\n                    padded_x = torch.cat(\n                        [x[i, :, :1]] * pad_num\n                        + [x[i, :, : -pad_num * 2]]\n                        + [x[i, :, -pad_num * 2 - 1].unsqueeze(1)] * pad_num,\n                        dim=1,\n                    ).unsqueeze(\n                        0\n                    )  # remove the last pad_num * 2 frames from the end of the video\n                    x_0[i] = model_ae.encode(padded_x)[0]\n                    # condition: encode the image only\n                    latent[i, :, :1, :, :] = model_ae.encode(x[i, :, :1, :, :].unsqueeze(0))\n                    latent[i, :, -1:, :, :] = model_ae.encode(x[i, :, -pad_num * 2 - 1, :, :].unsqueeze(1).unsqueeze(0))\n                else:\n                    x_0[i] = model_ae.encode(x[i : i + 1])[0]\n                    latent[i, :, :1, :, :] = model_ae.encode(x[i, :, :1, :, :].unsqueeze(0))\n                    latent[i, :, -1:, :, :] = model_ae.encode(x[i, :, -1:, :, :].unsqueeze(0))\n            elif mask_cond == \"i2v_tail\":  # mask the last latent frame\n                masks[i, :, -1, :, :] = 1\n                if pad:\n                    pad_num = model_ae.time_compression_ratio - 1\n                    padded_x = torch.cat([x[i, :, pad_num:]] + [x[i, :, -1:]] * pad_num, dim=1).unsqueeze(0)\n                    x_0[i] = model_ae.encode(padded_x)[0]\n                    latent[i, :, -1:, :, :] = model_ae.encode(x[i, :, -pad_num * 2 - 1, :, :].unsqueeze(1).unsqueeze(0))\n                else:\n                    x_0[i] = model_ae.encode(x[i : i + 1])[0]\n                    latent[i, :, -1:, :, :] = model_ae.encode(x[i, :, -1:, :, :].unsqueeze(0))\n            elif mask_cond == \"v2v_head\":  # mask the first 32 video frames\n                assert T > 32 // model_ae.time_compression_ratio\n                conditioned_t = 32 // model_ae.time_compression_ratio\n                masks[i, :, :conditioned_t, :, :] = 1\n                x_0[i] = model_ae.encode(x[i].unsqueeze(0))[0]\n                latent[i, :, :conditioned_t, :, :] = x_0[i, :, :conditioned_t, :, :]\n            elif mask_cond == \"v2v_tail\":  # mask the last 32 video frames\n                assert T > 32 // model_ae.time_compression_ratio\n                conditioned_t = 32 // model_ae.time_compression_ratio\n                masks[i, :, -conditioned_t:, :, :] = 1\n                x_0[i] = model_ae.encode(x[i].unsqueeze(0))[0]\n                latent[i, :, -conditioned_t:, :, :] = x_0[i, :, -conditioned_t:, :, :]\n            elif mask_cond == \"v2v_head_easy\":  # mask the first 64 video frames\n                assert T > 64 // model_ae.time_compression_ratio\n                conditioned_t = 64 // model_ae.time_compression_ratio\n                masks[i, :, :conditioned_t, :, :] = 1\n                x_0[i] = model_ae.encode(x[i].unsqueeze(0))[0]\n                latent[i, :, :conditioned_t, :, :] = x_0[i, :, :conditioned_t, :, :]\n            elif mask_cond == \"v2v_tail_easy\":  # mask the last 64 video frames\n                assert T > 64 // model_ae.time_compression_ratio\n                conditioned_t = 64 // model_ae.time_compression_ratio\n                masks[i, :, -conditioned_t:, :, :] = 1\n                x_0[i] = model_ae.encode(x[i].unsqueeze(0))[0]\n                latent[i, :, -conditioned_t:, :, :] = x_0[i, :, -conditioned_t:, :, :]\n            # elif mask_cond == \"v2v_head\":  # mask from the beginning to a random point\n            #     masks[i, :, : random.randint(1, T - 2), :, :] = 1\n            # elif mask_cond == \"v2v_tail\":  # mask from a random point to the end\n            #     masks[i, :, -random.randint(1, T - 2) :, :, :] = 1\n            else:\n                # \"t2v\" is the fallback case where no specific condition is specified\n                assert mask_cond == \"t2v\", f\"Unknown mask condition {mask_cond}\"\n                x_0[i] = model_ae.encode(x[i].unsqueeze(0))[0]\n    else:  # image\n        x_0 = model_ae.encode(x)  # latent video\n\n    latent = masks * latent  # condition latent\n    # merge the masks and the masked_x into a single tensor\n    cond = torch.cat((masks, latent), dim=1)\n    return x_0, cond\n\n\ndef prepare_visual_condition_causal(x: torch.Tensor, condition_config: dict, model_ae: torch.nn.Module) -> torch.Tensor:\n    \"\"\"\n    Prepare the visual condition for the model.\n\n    Args:\n        x: (torch.Tensor): The input video tensor.\n        condition_config (dict): The condition configuration.\n        model_ae (torch.nn.Module): The video encoder module.\n\n    Returns:\n        torch.Tensor: The visual condition tensor.\n    \"\"\"\n    # x has shape [b, c, t, h, w], where b is the batch size\n    B = x.shape[0]\n    C = model_ae.cfg.latent_channels\n    T, H, W = model_ae.get_latent_size(x.shape[-3:])\n\n    # Initialize masks tensor to match the shape of x, but only the time dimension will be masked\n    masks = torch.zeros(B, 1, T, H, W).to(\n        x.device, x.dtype\n    )  # broadcasting over channel, concat to masked_x with 1 + 16 = 17 channesl\n    # to prevent information leakage, image must be encoded separately and copied to latent\n    latent = torch.zeros(B, C, T, H, W).to(x.device, x.dtype)\n    x_0 = torch.zeros(B, C, T, H, W).to(x.device, x.dtype)\n    if T > 1:  # video\n        # certain v2v conditions not are applicable for short videos\n        if T <= (32 // model_ae.time_compression_ratio) + 1:\n            condition_config.pop(\"v2v_head\", None)  # given first 33 frames\n            condition_config.pop(\"v2v_tail\", None)  # given last 33 frames\n            condition_config.pop(\"v2v_head_easy\", None)  # given first 65 frames\n            condition_config.pop(\"v2v_tail_easy\", None)  # given last 65 frames\n        if T <= (64 // model_ae.time_compression_ratio) + 1:\n            condition_config.pop(\"v2v_head_easy\", None)  # given first 65 frames\n            condition_config.pop(\"v2v_tail_easy\", None)  # given last 65 frames\n\n        mask_cond_options = list(condition_config.keys())  # list of mask conditions\n        mask_cond_weights = list(condition_config.values())  # corresponding probabilities\n\n        for i in range(B):\n            # Randomly select a mask condition based on the provided probabilities\n            mask_cond = random.choices(mask_cond_options, weights=mask_cond_weights, k=1)[0]\n            # Apply the selected mask condition directly on the masks tensor\n\n            if mask_cond == \"i2v_head\":  # NOTE: modify video, mask first latent frame\n                masks[i, :, 0, :, :] = 1\n                x_0[i] = model_ae.encode(x[i].unsqueeze(0))[0]\n                # condition: encode the image only\n                latent[i, :, :1, :, :] = model_ae.encode(x[i, :, :1, :, :].unsqueeze(0))\n\n            elif mask_cond == \"i2v_loop\":  # # NOTE: modify video, mask first and last latent frame\n                # pad video such that first and last latent frame correspond to image only\n                masks[i, :, 0, :, :] = 1\n                masks[i, :, -1, :, :] = 1\n                x_0[i] = model_ae.encode(x[i].unsqueeze(0))[0]\n                # condition: encode the image only\n                latent[i, :, :1, :, :] = model_ae.encode(x[i, :, :1, :, :].unsqueeze(0))\n                latent[i, :, -1:, :, :] = model_ae.encode(x[i, :, -1:, :, :].unsqueeze(0))\n\n            elif mask_cond == \"i2v_tail\":  # mask the last latent frame\n                masks[i, :, -1, :, :] = 1\n                x_0[i] = model_ae.encode(x[i].unsqueeze(0))[0]\n                # condition: encode the last image only\n                latent[i, :, -1:, :, :] = model_ae.encode(x[i, :, -1:, :, :].unsqueeze(0))\n\n            elif \"v2v_head\" in mask_cond:  # mask the first 33 video frames\n                ref_t = 33 if not \"easy\" in mask_cond else 65\n                assert (ref_t - 1) % model_ae.time_compression_ratio == 0\n                conditioned_t = (ref_t - 1) // model_ae.time_compression_ratio + 1\n                masks[i, :, :conditioned_t, :, :] = 1\n                x_0[i] = model_ae.encode(x[i].unsqueeze(0))[0]\n                # encode the first ref_t frame video separately\n                latent[i, :, :conditioned_t, :, :] = model_ae.encode(x[i, :, :ref_t, :, :].unsqueeze(0))\n\n            elif \"v2v_tail\" in mask_cond:  # mask the last 32 video frames\n                ref_t = 33 if not \"easy\" in mask_cond else 65\n                assert (ref_t - 1) % model_ae.time_compression_ratio == 0\n                conditioned_t = (ref_t - 1) // model_ae.time_compression_ratio + 1\n                masks[i, :, -conditioned_t:, :, :] = 1\n                x_0[i] = model_ae.encode(x[i].unsqueeze(0))[0]\n                # encode the first ref_t frame video separately\n                latent[i, :, -conditioned_t:, :, :] = model_ae.encode(x[i, :, -ref_t:, :, :].unsqueeze(0))\n            else:\n                # \"t2v\" is the fallback case where no specific condition is specified\n                assert mask_cond == \"t2v\", f\"Unknown mask condition {mask_cond}\"\n                x_0[i] = model_ae.encode(x[i].unsqueeze(0))[0]\n    else:  # image\n        x_0 = model_ae.encode(x)  # latent video\n\n    latent = masks * latent  # condition latent\n    # merge the masks and the masked_x into a single tensor\n    cond = torch.cat((masks, latent), dim=1)\n    return x_0, cond\n\n\ndef get_batch_loss(model_pred, v_t, masks=None):\n    # for I2V, only include the generated frames in loss calculation\n    if masks is not None:  # shape [B, T, H, W]\n        num_frames, height, width = masks.shape[-3:]\n        masks = masks[:, :, 0, 0]  # only look at [B, T]\n        model_pred = rearrange(\n            model_pred,\n            \"b (t h w) (c ph pw) -> b c t (h ph) (w pw)\",\n            h=height // 2,\n            w=width // 2,\n            t=num_frames,\n            ph=2,\n            pw=2,\n        )\n        v_t = rearrange(\n            v_t,\n            \"b (t h w) (c ph pw) -> b c t (h ph) (w pw)\",\n            h=height // 2,\n            w=width // 2,\n            t=num_frames,\n            ph=2,\n            pw=2,\n        )\n\n        batch_loss = 0\n        for i in range(model_pred.size(0)):\n            pred_val = model_pred[i]\n            target_val = v_t[i]\n            if masks[i][0] == 1 and (not 1 in masks[i][1:-1]):  # have front padding\n                pred_val = pred_val[:, 1:]\n                target_val = target_val[:, 1:]\n            if masks[i][-1] == 1 and (not 1 in masks[i][1:-1]):  # have tail padding\n                pred_val = pred_val[:, :-1]\n                target_val = target_val[:, :-1]\n            batch_loss += F.mse_loss(pred_val.float(), target_val.float(), reduction=\"mean\")\n            # print(f\"mask {masks[i]}, pred_val shape: {pred_val.size()}\")\n        loss = batch_loss / model_pred.size(0)\n    else:\n        # use reduction mean so that each batch will have same level of influence regardless of batch size\n        loss = F.mse_loss(model_pred.float(), v_t.float(), reduction=\"mean\")\n    return loss\n\n\n@torch.no_grad()\ndef warmup_ae(model_ae: nn.Module, shapes: list[tuple[int, ...]], device: torch.device, dtype: torch.dtype):\n    progress_bar = tqdm(shapes, desc=\"Warmup AE\", disable=dist.get_rank() != 0)\n    for x_shape in progress_bar:\n        x = torch.randn(*x_shape, device=device, dtype=dtype)\n        _ = model_ae.encode(x)\n"
  },
  {
    "path": "requirements.txt",
    "content": "torch==2.4.0\ntorchvision==0.19.0\ncolossalai>=0.4.4\nmmengine>=0.10.3\nftfy>=6.2.0 # for t5\naccelerate>=0.29.2 # for t5\nav==13.1.0 # for video loading\nliger-kernel==0.5.2\npandas>=2.0.3\npandarallel>=1.6.5\nopenai>=1.52.2\nwandb>=0.17.0\ntensorboard>=2.14.0\npre-commit>=3.5.0\nomegaconf>=2.3.0\npyarrow\n"
  },
  {
    "path": "scripts/cnv/meta.py",
    "content": "import argparse\n\nimport numpy as np\nimport pandas as pd\nfrom pandarallel import pandarallel\nfrom torchvision.io.video import read_video\nfrom tqdm import tqdm\n\n\ndef set_parallel(num_workers: int = None) -> callable:\n    if num_workers == 0:\n        return lambda x, *args, **kwargs: x.progress_apply(*args, **kwargs)\n    else:\n        if num_workers is not None:\n            pandarallel.initialize(progress_bar=True, nb_workers=num_workers)\n        else:\n            pandarallel.initialize(progress_bar=True)\n        return lambda x, *args, **kwargs: x.parallel_apply(*args, **kwargs)\n\n\ndef get_video_info(path: str) -> pd.Series:\n    vframes, _, vinfo = read_video(path, pts_unit=\"sec\", output_format=\"TCHW\")\n    num_frames, C, height, width = vframes.shape\n    fps = round(vinfo[\"video_fps\"], 3)\n    aspect_ratio = height / width if width > 0 else np.nan\n    resolution = height * width\n\n    ret = pd.Series(\n        [height, width, fps, num_frames, aspect_ratio, resolution],\n        index=[\n            \"height\",\n            \"width\",\n            \"fps\",\n            \"num_frames\",\n            \"aspect_ratio\",\n            \"resolution\",\n        ],\n        dtype=object,\n    )\n    return ret\n\n\ndef parse_args():\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\"--input\", type=str, required=True, help=\"Input file path\")\n    parser.add_argument(\"--output\", type=str, required=True, help=\"Output file path\")\n    parser.add_argument(\n        \"--num_workers\", type=int, default=None, help=\"Number of workers\"\n    )\n    return parser.parse_args()\n\n\ndef main():\n    args = parse_args()\n    input_path = args.input\n    output_path = args.output\n    num_workers = args.num_workers\n\n    df = pd.read_csv(input_path)\n    tqdm.pandas()\n    apply = set_parallel(num_workers)\n\n    result = apply(df[\"path\"], get_video_info)\n    for col in result.columns:\n        df[col] = result[col]\n    df.to_csv(output_path, index=False)\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "scripts/cnv/shard.py",
    "content": "import os\n\nimport pandas as pd\nfrom tqdm import tqdm\n\ntry:\n    import dask.dataframe as dd\n\n    SUPPORT_DASK = True\nexcept:\n    SUPPORT_DASK = False\n\n\ndef shard_parquet(input_path, k):\n    # 检查输入路径是否存在\n    if not os.path.exists(input_path):\n        raise FileNotFoundError(f\"Input file {input_path} does not exist.\")\n\n    # 读取 Parquet 文件为 Pandas DataFrame\n    if SUPPORT_DASK:\n        df = dd.read_parquet(input_path).compute()\n    else:\n        df = pd.read_parquet(input_path)\n\n    # 去除指定的列\n    columns_to_remove = [\n        \"num_frames\",\n        \"height\",\n        \"width\",\n        \"aspect_ratio\",\n        \"fps\",\n        \"resolution\",\n    ]\n    df = df.drop(columns=[col for col in columns_to_remove if col in df.columns])\n\n    # 计算每个分片的大小\n    total_rows = len(df)\n    rows_per_shard = (total_rows + k - 1) // k  # 向上取整\n\n    # 创建与原始文件同名的文件夹\n    base_dir = os.path.dirname(input_path)\n    base_name = os.path.splitext(os.path.basename(input_path))[0]\n    output_dir = os.path.join(base_dir, base_name)\n    os.makedirs(output_dir, exist_ok=True)\n\n    # 创建分片并保存到文件夹\n    for i in tqdm(range(k)):\n        start_idx = i * rows_per_shard\n        end_idx = min(start_idx + rows_per_shard, total_rows)\n\n        shard_df = df.iloc[start_idx:end_idx]\n        if shard_df.empty:\n            continue\n\n        shard_file_name = f\"{i + 1:05d}.parquet\"\n        shard_path = os.path.join(output_dir, shard_file_name)\n\n        shard_df.to_parquet(shard_path, index=False)\n\n        # print(f\"Shard saved to {shard_path}, rows: {len(shard_df)}\")\n\n\nif __name__ == \"__main__\":\n    import argparse\n\n    parser = argparse.ArgumentParser(description=\"Shard a Parquet file.\")\n    parser.add_argument(\"input_path\", type=str, help=\"Path to the input Parquet file.\")\n    parser.add_argument(\n        \"k\", type=int, help=\"Number of shards to create.\", default=10000\n    )\n\n    args = parser.parse_args()\n\n    shard_parquet(args.input_path, args.k)\n"
  },
  {
    "path": "scripts/diffusion/inference.py",
    "content": "import os\nimport time\nimport warnings\nfrom pprint import pformat\n\nwarnings.filterwarnings(\"ignore\", category=FutureWarning)\nwarnings.filterwarnings(\"ignore\", category=UserWarning)\n\nimport torch\nimport torch.distributed as dist\nfrom colossalai.utils import set_seed\nfrom tqdm import tqdm\n\nfrom opensora.acceleration.parallel_states import get_data_parallel_group\nfrom opensora.datasets.dataloader import prepare_dataloader\nfrom opensora.registry import DATASETS, build_module\nfrom opensora.utils.cai import (\n    get_booster,\n    get_is_saving_process,\n    init_inference_environment,\n)\nfrom opensora.utils.config import parse_alias, parse_configs\nfrom opensora.utils.inference import (\n    add_fps_info_to_text,\n    add_motion_score_to_text,\n    create_tmp_csv,\n    modify_option_to_t2i,\n    process_and_save,\n)\nfrom opensora.utils.logger import create_logger, is_main_process\nfrom opensora.utils.misc import log_cuda_max_memory, to_torch_dtype\nfrom opensora.utils.prompt_refine import refine_prompts\nfrom opensora.utils.sampling import (\n    SamplingOption,\n    prepare_api,\n    prepare_models,\n    sanitize_sampling_option,\n)\n\n\n@torch.inference_mode()\ndef main():\n    # ======================================================\n    # 1. configs & runtime variables\n    # ======================================================\n    torch.set_grad_enabled(False)\n\n    # == parse configs ==\n    cfg = parse_configs()\n    cfg = parse_alias(cfg)\n\n    # == device and dtype ==\n    device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n    dtype = to_torch_dtype(cfg.get(\"dtype\", \"bf16\"))\n    seed = cfg.get(\"seed\", 1024)\n    if seed is not None:\n        set_seed(seed)\n\n    # == init distributed env ==\n    init_inference_environment()\n    logger = create_logger()\n    logger.info(\"Inference configuration:\\n %s\", pformat(cfg.to_dict()))\n    is_saving_process = get_is_saving_process(cfg)\n    booster = get_booster(cfg)\n    booster_ae = get_booster(cfg, ae=True)\n\n    # ======================================================\n    # 2. build dataset and dataloader\n    # ======================================================\n    logger.info(\"Building dataset...\")\n\n    # save directory\n    save_dir = cfg.save_dir\n    os.makedirs(save_dir, exist_ok=True)\n\n    # == build dataset ==\n    if cfg.get(\"prompt\"):\n        cfg.dataset.data_path = create_tmp_csv(save_dir, cfg.prompt, cfg.get(\"ref\", None), create=is_main_process())\n    dist.barrier()\n    dataset = build_module(cfg.dataset, DATASETS)\n\n    # range selection\n    start_index = cfg.get(\"start_index\", 0)\n    end_index = cfg.get(\"end_index\", None)\n    if end_index is None:\n        end_index = start_index + cfg.get(\"num_samples\", len(dataset.data) + 1)\n    dataset.data = dataset.data[start_index:end_index]\n    logger.info(\"Dataset contains %s samples.\", len(dataset))\n\n    # == build dataloader ==\n    dataloader_args = dict(\n        dataset=dataset,\n        batch_size=cfg.get(\"batch_size\", 1),\n        num_workers=cfg.get(\"num_workers\", 4),\n        seed=cfg.get(\"seed\", 1024),\n        shuffle=False,\n        drop_last=False,\n        pin_memory=True,\n        process_group=get_data_parallel_group(),\n        prefetch_factor=cfg.get(\"prefetch_factor\", None),\n    )\n    dataloader, _ = prepare_dataloader(**dataloader_args)\n\n    # == prepare default params ==\n    sampling_option = SamplingOption(**cfg.sampling_option)\n    sampling_option = sanitize_sampling_option(sampling_option)\n\n    cond_type = cfg.get(\"cond_type\", \"t2v\")\n    prompt_refine = cfg.get(\"prompt_refine\", False)\n    fps_save = cfg.get(\"fps_save\", 16)\n    num_sample = cfg.get(\"num_sample\", 1)\n\n    type_name = \"image\" if cfg.sampling_option.num_frames == 1 else \"video\"\n    sub_dir = f\"{type_name}_{cfg.sampling_option.resolution}\"\n    os.makedirs(os.path.join(save_dir, sub_dir), exist_ok=True)\n    use_t2i2v = cfg.get(\"use_t2i2v\", False)\n    img_sub_dir = os.path.join(sub_dir, \"generated_condition\")\n    if use_t2i2v:\n        os.makedirs(os.path.join(save_dir, sub_dir, \"generated_condition\"), exist_ok=True)\n\n    # ======================================================\n    # 3. build model\n    # ======================================================\n    logger.info(\"Building models...\")\n\n    # == build flux model ==\n    model, model_ae, model_t5, model_clip, optional_models = prepare_models(\n        cfg, device, dtype, offload_model=cfg.get(\"offload_model\", False)\n    )\n    log_cuda_max_memory(\"build model\")\n\n    if booster:\n        model, _, _, _, _ = booster.boost(model=model)\n        model = model.unwrap()\n    if booster_ae:\n        model_ae, _, _, _, _ = booster_ae.boost(model=model_ae)\n        model_ae = model_ae.unwrap()\n\n    api_fn = prepare_api(model, model_ae, model_t5, model_clip, optional_models)\n\n    # prepare image flux model if t2i2v\n    if use_t2i2v:\n        api_fn_img = prepare_api(\n            optional_models[\"img_flux\"], optional_models[\"img_flux_ae\"], model_t5, model_clip, optional_models\n        )\n\n    # ======================================================\n    # 4. inference\n    # ======================================================\n    for epoch in range(num_sample):  # generate multiple samples with different seeds\n        dataloader_iter = iter(dataloader)\n        with tqdm(\n            enumerate(dataloader_iter, start=0),\n            desc=\"Inference progress\",\n            disable=not is_main_process(),\n            initial=0,\n            total=len(dataloader),\n        ) as pbar:\n            for _, batch in pbar:\n                original_text = batch.pop(\"text\")\n                if use_t2i2v:\n                    batch[\"text\"] = original_text if not prompt_refine else refine_prompts(original_text, type=\"t2i\")\n                    sampling_option_t2i = modify_option_to_t2i(\n                        sampling_option,\n                        distilled=True,\n                        img_resolution=cfg.get(\"img_resolution\", \"768px\"),\n                    )\n                    if cfg.get(\"offload_model\", False):\n                        model_move_start = time.time()\n                        model = model.to(\"cpu\", dtype)\n                        model_ae = model_ae.to(\"cpu\", dtype)\n                        optional_models[\"img_flux\"].to(device, dtype)\n                        optional_models[\"img_flux_ae\"].to(device, dtype)\n                        logger.info(\n                            \"offload video diffusion model to cpu, load image flux model to gpu: %s s\",\n                            time.time() - model_move_start,\n                        )\n\n                    logger.info(\"Generating image condition by flux...\")\n                    x_cond = api_fn_img(\n                        sampling_option_t2i,\n                        \"t2v\",\n                        seed=sampling_option.seed + epoch if sampling_option.seed else None,\n                        channel=cfg[\"img_flux\"][\"in_channels\"],\n                        **batch,\n                    ).cpu()\n\n                    # save image to disk\n                    batch[\"name\"] = process_and_save(\n                        x_cond,\n                        batch,\n                        cfg,\n                        img_sub_dir,\n                        sampling_option_t2i,\n                        epoch,\n                        start_index,\n                        saving=is_saving_process,\n                    )\n                    dist.barrier()\n\n                    if cfg.get(\"offload_model\", False):\n                        model_move_start = time.time()\n                        model = model.to(device, dtype)\n                        model_ae = model_ae.to(device, dtype)\n                        optional_models[\"img_flux\"].to(\"cpu\", dtype)\n                        optional_models[\"img_flux_ae\"].to(\"cpu\", dtype)\n                        logger.info(\n                            \"load video diffusion model to gpu, offload image flux model to cpu: %s s\",\n                            time.time() - model_move_start,\n                        )\n\n                    ref_dir = os.path.join(save_dir, os.path.join(sub_dir, \"generated_condition\"))\n                    batch[\"ref\"] = [os.path.join(ref_dir, f\"{x}.png\") for x in batch[\"name\"]]\n                    cond_type = \"i2v_head\"\n\n                batch[\"text\"] = original_text\n                if prompt_refine:\n                    batch[\"text\"] = refine_prompts(\n                        original_text, type=\"t2v\" if cond_type == \"t2v\" else \"t2i\", image_paths=batch.get(\"ref\", None)\n                    )\n                batch[\"text\"] = add_fps_info_to_text(batch.pop(\"text\"), fps=fps_save)\n                if \"motion_score\" in cfg:\n                    batch[\"text\"] = add_motion_score_to_text(batch.pop(\"text\"), cfg.get(\"motion_score\", 5))\n\n                logger.info(\"Generating video...\")\n                x = api_fn(\n                    sampling_option,\n                    cond_type,\n                    seed=sampling_option.seed + epoch if sampling_option.seed else None,\n                    patch_size=cfg.get(\"patch_size\", 2),\n                    save_prefix=cfg.get(\"save_prefix\", \"\"),\n                    channel=cfg[\"model\"][\"in_channels\"],\n                    **batch,\n                ).cpu()\n\n                if is_saving_process:\n                    process_and_save(x, batch, cfg, sub_dir, sampling_option, epoch, start_index)\n                dist.barrier()\n\n    logger.info(\"Inference finished.\")\n    log_cuda_max_memory(\"inference\")\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "scripts/diffusion/train.py",
    "content": "import gc\nimport math\nimport os\nimport subprocess\nimport warnings\nfrom contextlib import nullcontext\nfrom copy import deepcopy\nfrom pprint import pformat\n\nwarnings.filterwarnings(\"ignore\", category=FutureWarning)\nwarnings.filterwarnings(\"ignore\", category=UserWarning)\ngc.disable()\n\n\nimport torch\nimport torch.distributed as dist\nimport torch.nn.functional as F\nimport wandb\nfrom colossalai.booster import Booster\nfrom colossalai.utils import set_seed\nfrom peft import LoraConfig\nfrom tqdm import tqdm\n\nfrom opensora.acceleration.checkpoint import (\n    GLOBAL_ACTIVATION_MANAGER,\n    set_grad_checkpoint,\n)\nfrom opensora.acceleration.parallel_states import get_data_parallel_group\nfrom opensora.datasets.aspect import bucket_to_shapes\nfrom opensora.datasets.dataloader import prepare_dataloader\nfrom opensora.datasets.pin_memory_cache import PinMemoryCache\nfrom opensora.models.mmdit.distributed import MMDiTPolicy\nfrom opensora.registry import DATASETS, MODELS, build_module\nfrom opensora.utils.ckpt import (\n    CheckpointIO,\n    model_sharding,\n    record_model_param_shape,\n    rm_checkpoints,\n)\nfrom opensora.utils.config import (\n    config_to_name,\n    create_experiment_workspace,\n    parse_configs,\n)\nfrom opensora.utils.logger import create_logger\nfrom opensora.utils.misc import (\n    NsysProfiler,\n    Timers,\n    all_reduce_mean,\n    create_tensorboard_writer,\n    is_log_process,\n    is_pipeline_enabled,\n    log_cuda_max_memory,\n    log_cuda_memory,\n    log_model_params,\n    print_mem,\n    to_torch_dtype,\n)\nfrom opensora.utils.optimizer import create_lr_scheduler, create_optimizer\nfrom opensora.utils.sampling import (\n    get_res_lin_function,\n    pack,\n    prepare,\n    prepare_ids,\n    time_shift,\n)\nfrom opensora.utils.train import (\n    create_colossalai_plugin,\n    dropout_condition,\n    get_batch_loss,\n    prepare_visual_condition_causal,\n    prepare_visual_condition_uncausal,\n    set_eps,\n    set_lr,\n    setup_device,\n    update_ema,\n    warmup_ae,\n)\n\ntorch.backends.cudnn.benchmark = False  # True leads to slow down in conv3d\n\n\ndef main():\n    # ======================================================\n    # 1. configs & runtime variables\n    # ======================================================\n    # == parse configs ==\n    cfg = parse_configs()\n\n    # == get dtype & device ==\n    dtype = to_torch_dtype(cfg.get(\"dtype\", \"bf16\"))\n    device, coordinator = setup_device()\n    grad_ckpt_buffer_size = cfg.get(\"grad_ckpt_buffer_size\", 0)\n    if grad_ckpt_buffer_size > 0:\n        GLOBAL_ACTIVATION_MANAGER.setup_buffer(grad_ckpt_buffer_size, dtype)\n    checkpoint_io = CheckpointIO()\n    set_seed(cfg.get(\"seed\", 1024))\n    PinMemoryCache.force_dtype = dtype\n    pin_memory_cache_pre_alloc_numels = cfg.get(\"pin_memory_cache_pre_alloc_numels\", None)\n    PinMemoryCache.pre_alloc_numels = pin_memory_cache_pre_alloc_numels\n\n    # == init ColossalAI booster ==\n    plugin_type = cfg.get(\"plugin\", \"zero2\")\n    plugin_config = cfg.get(\"plugin_config\", {})\n    plugin_kwargs = {}\n    if plugin_type == \"hybrid\":\n        plugin_kwargs[\"custom_policy\"] = MMDiTPolicy\n    plugin = create_colossalai_plugin(\n        plugin=plugin_type,\n        dtype=cfg.get(\"dtype\", \"bf16\"),\n        grad_clip=cfg.get(\"grad_clip\", 0),\n        **plugin_config,\n        **plugin_kwargs,\n    )\n    booster = Booster(plugin=plugin)\n\n    seq_align = plugin_config.get(\"sp_size\", 1)\n\n    # == init exp_dir ==\n    exp_name, exp_dir = create_experiment_workspace(\n        cfg.get(\"outputs\", \"./outputs\"),\n        model_name=config_to_name(cfg),\n        config=cfg.to_dict(),\n        exp_name=cfg.get(\"exp_name\", None),  # useful for automatic restart to specify the exp_name\n    )\n\n    if is_log_process(plugin_type, plugin_config):\n        print(f\"changing {exp_dir} to share\")\n        os.system(f\"chgrp -R share {exp_dir}\")\n\n    # == init logger, tensorboard & wandb ==\n    logger = create_logger(exp_dir)\n    logger.info(\"Training configuration:\\n %s\", pformat(cfg.to_dict()))\n    tb_writer = None\n    if coordinator.is_master():\n        tb_writer = create_tensorboard_writer(exp_dir)\n        if cfg.get(\"wandb\", False):\n            wandb.init(\n                project=cfg.get(\"wandb_project\", \"Open-Sora\"),\n                name=exp_name,\n                config=cfg.to_dict(),\n                dir=exp_dir,\n            )\n    num_gpus = dist.get_world_size() if dist.is_initialized() else 1\n    tp_size = cfg[\"plugin_config\"].get(\"tp_size\", 1)\n    sp_size = cfg[\"plugin_config\"].get(\"sp_size\", 1)\n    pp_size = cfg[\"plugin_config\"].get(\"pp_size\", 1)\n    num_groups = num_gpus // (tp_size * sp_size * pp_size)\n    logger.info(\"Number of GPUs: %s\", num_gpus)\n    logger.info(\"Number of groups: %s\", num_groups)\n\n    # ======================================================\n    # 2. build dataset and dataloader\n    # ======================================================\n    logger.info(\"Building dataset...\")\n    # == build dataset ==\n    dataset = build_module(cfg.dataset, DATASETS)\n    logger.info(\"Dataset contains %s samples.\", len(dataset))\n\n    # == build dataloader ==\n    cache_pin_memory = pin_memory_cache_pre_alloc_numels is not None\n    dataloader_args = dict(\n        dataset=dataset,\n        batch_size=cfg.get(\"batch_size\", None),\n        num_workers=cfg.get(\"num_workers\", 4),\n        seed=cfg.get(\"seed\", 1024),\n        shuffle=True,\n        drop_last=True,\n        pin_memory=True,\n        process_group=get_data_parallel_group(),\n        prefetch_factor=cfg.get(\"prefetch_factor\", None),\n        cache_pin_memory=cache_pin_memory,\n        num_groups=num_groups,\n    )\n    print_mem(\"before prepare_dataloader\")\n    dataloader, sampler = prepare_dataloader(\n        bucket_config=cfg.get(\"bucket_config\", None),\n        num_bucket_build_workers=cfg.get(\"num_bucket_build_workers\", 1),\n        **dataloader_args,\n    )\n    print_mem(\"after prepare_dataloader\")\n    num_steps_per_epoch = len(dataloader)\n    dataset.to_efficient()\n\n    # ======================================================\n    # 3. build model\n    # ======================================================\n    logger.info(\"Building models...\")\n\n    # == build model model ==\n    model = build_module(cfg.model, MODELS, device_map=device, torch_dtype=dtype).train()\n    if cfg.get(\"grad_checkpoint\", True):\n        set_grad_checkpoint(model)\n    log_cuda_memory(\"diffusion\")\n    log_model_params(model)\n\n    # == build EMA model ==\n    use_lora = cfg.get(\"lora_config\", None) is not None\n    if cfg.get(\"ema_decay\", None) is not None and not use_lora:\n        ema = deepcopy(model).cpu().eval().requires_grad_(False)\n        ema_shape_dict = record_model_param_shape(ema)\n        logger.info(\"EMA model created.\")\n    else:\n        ema = ema_shape_dict = None\n        logger.info(\"No EMA model created.\")\n    log_cuda_memory(\"EMA\")\n\n    # == enable LoRA ==\n    if use_lora:\n        lora_config = LoraConfig(**cfg.get(\"lora_config\", None))\n        model = booster.enable_lora(\n            model=model,\n            lora_config=lora_config,\n            pretrained_dir=cfg.get(\"lora_checkpoint\", None),\n        )\n        log_cuda_memory(\"lora\")\n        log_model_params(model)\n\n    if not cfg.get(\"cached_video\", False):\n        # == buildn autoencoder ==\n        model_ae = build_module(cfg.ae, MODELS, device_map=device, torch_dtype=dtype).eval().requires_grad_(False)\n        del model_ae.decoder\n        log_cuda_memory(\"autoencoder\")\n        log_model_params(model_ae)\n        model_ae.encode = torch.compile(model_ae.encoder, dynamic=True)\n\n    if not cfg.get(\"cached_text\", False):\n        # == build text encoder (t5) ==\n        model_t5 = build_module(cfg.t5, MODELS, device_map=device, torch_dtype=dtype).eval().requires_grad_(False)\n        log_cuda_memory(\"t5\")\n        log_model_params(model_t5)\n\n        # == build text encoder (clip) ==\n        model_clip = build_module(cfg.clip, MODELS, device_map=device, torch_dtype=dtype).eval().requires_grad_(False)\n        log_cuda_memory(\"clip\")\n        log_model_params(model_clip)\n\n    # == setup optimizer ==\n    optimizer = create_optimizer(model, cfg.optim)\n\n    # == setup lr scheduler ==\n    lr_scheduler = create_lr_scheduler(\n        optimizer=optimizer,\n        num_steps_per_epoch=num_steps_per_epoch,\n        epochs=cfg.get(\"epochs\", 1000),\n        warmup_steps=cfg.get(\"warmup_steps\", None),\n        use_cosine_scheduler=cfg.get(\"use_cosine_scheduler\", False),\n    )\n    log_cuda_memory(\"optimizer\")\n\n    # == prepare null vectors for dropout ==\n    if cfg.get(\"cached_text\", False):\n        null_txt = torch.load(\"/mnt/ddn/sora/tmp_load/null_t5.pt\", map_location=device)\n        null_vec = torch.load(\"/mnt/ddn/sora/tmp_load/null_clip.pt\", map_location=device)\n    else:\n        null_txt = model_t5(\"\")\n        null_vec = model_clip(\"\")\n\n    # =======================================================\n    # 4. distributed training preparation with colossalai\n    # =======================================================\n    logger.info(\"Preparing for distributed training...\")\n    # == boosting ==\n    torch.set_default_dtype(dtype)\n    model, optimizer, _, dataloader, lr_scheduler = booster.boost(\n        model=model,\n        optimizer=optimizer,\n        lr_scheduler=lr_scheduler,\n        dataloader=dataloader,\n    )\n    torch.set_default_dtype(torch.float)\n    logger.info(\"Boosted model for distributed training\")\n    log_cuda_memory(\"boost\")\n\n    # == global variables ==\n    cfg_epochs = cfg.get(\"epochs\", 1000)\n    log_step = acc_step = 0\n    running_loss = 0.0\n    timers = Timers(record_time=cfg.get(\"record_time\", False), record_barrier=cfg.get(\"record_barrier\", False))\n    nsys = NsysProfiler(\n        warmup_steps=cfg.get(\"nsys_warmup_steps\", 2),\n        num_steps=cfg.get(\"nsys_num_steps\", 2),\n        enabled=cfg.get(\"nsys\", False),\n    )\n    logger.info(\"Training for %s epochs with %s steps per epoch\", cfg_epochs, num_steps_per_epoch)\n\n    # == resume ==\n    load_master_weights = cfg.get(\"load_master_weights\", False)\n    save_master_weights = cfg.get(\"save_master_weights\", False)\n    start_epoch = cfg.get(\"start_epoch\", None)\n    start_step = cfg.get(\"start_step\", None)\n    if cfg.get(\"load\", None) is not None:\n        logger.info(\"Loading checkpoint from %s\", cfg.load)\n\n        lr_scheduler_to_load = lr_scheduler\n        if cfg.get(\"update_warmup_steps\", False):\n            lr_scheduler_to_load = None\n        ret = checkpoint_io.load(\n            booster,\n            cfg.load,\n            model=model,\n            ema=ema,\n            optimizer=optimizer,\n            lr_scheduler=lr_scheduler_to_load,\n            sampler=(\n                None if start_step is not None else sampler\n            ),  # if specify start step, set last_micro_batch_access_index of a new sampler instead\n            include_master_weights=load_master_weights,\n        )\n        start_epoch = start_epoch if start_epoch is not None else ret[0]\n        start_step = start_step if start_step is not None else ret[1]\n        logger.info(\"Loaded checkpoint %s at epoch %s step %s\", cfg.load, ret[0], ret[1])\n\n        # load optimizer and scheduler will overwrite some of the hyperparameters, so we need to reset them\n        set_lr(optimizer, lr_scheduler, cfg.optim.lr, cfg.get(\"initial_lr\", None))\n        set_eps(optimizer, cfg.optim.eps)\n\n        if cfg.get(\"update_warmup_steps\", False):\n            assert (\n                cfg.get(\"warmup_steps\", None) is not None\n            ), \"you need to set warmup_steps in order to pass --update-warmup-steps True\"\n            # set_warmup_steps(lr_scheduler, cfg.warmup_steps)\n            lr_scheduler.step(start_epoch * num_steps_per_epoch + start_step)\n            logger.info(\"The learning rate starts from %s\", optimizer.param_groups[0][\"lr\"])\n    if start_step is not None:\n        # if start step exceeds data length, go to next epoch\n        if start_step > num_steps_per_epoch:\n            start_epoch = (\n                start_epoch + start_step // num_steps_per_epoch\n                if start_epoch is not None\n                else start_step // num_steps_per_epoch\n            )\n            start_step = start_step % num_steps_per_epoch\n    else:\n        start_step = 0\n    sampler.set_step(start_step)\n    start_epoch = start_epoch if start_epoch is not None else 0\n    logger.info(\"Starting from epoch %s step %s\", start_epoch, start_step)\n\n    # == sharding EMA model ==\n    if ema is not None:\n        model_sharding(ema)\n        ema = ema.to(device)\n        log_cuda_memory(\"sharding EMA\")\n\n    # == warmup autoencoder ==\n    if cfg.get(\"warmup_ae\", False):\n        shapes = bucket_to_shapes(cfg.get(\"bucket_config\", None), batch_size=cfg.ae.batch_size)\n        warmup_ae(model_ae, shapes, device, dtype)\n\n    # =======================================================\n    # 5. training iter\n    # =======================================================\n    sigma_min = cfg.get(\"sigma_min\", 1e-5)\n    accumulation_steps = cfg.get(\"accumulation_steps\", 1)\n    ckpt_every = cfg.get(\"ckpt_every\", 0)\n\n    if cfg.get(\"is_causal_vae\", False):\n        prepare_visual_condition = prepare_visual_condition_causal\n    else:\n        prepare_visual_condition = prepare_visual_condition_uncausal\n\n    @torch.no_grad()\n    def prepare_inputs(batch):\n        inp = dict()\n        x = batch.pop(\"video\")\n        y = batch.pop(\"text\")\n        bs = x.shape[0]\n\n        # == encode video ==\n        with nsys.range(\"encode_video\"), timers[\"encode_video\"]:\n            # == prepare condition ==\n            if cfg.get(\"condition_config\", None) is not None:\n                # condition for i2v & v2v\n                x_0, cond = prepare_visual_condition(x, cfg.condition_config, model_ae)\n                cond = pack(cond, patch_size=cfg.get(\"patch_size\", 2))\n                inp[\"cond\"] = cond\n            else:\n                if cfg.get(\"cached_video\", False):\n                    x_0 = batch.pop(\"video_latents\").to(device=device, dtype=dtype)\n                else:\n                    x_0 = model_ae.encode(x)\n\n        # == prepare timestep ==\n        # follow SD3 time shift, shift_alpha = 1 for 256px and shift_alpha = 3 for 1024px\n        shift_alpha = get_res_lin_function()((x_0.shape[-1] * x_0.shape[-2]) // 4)\n        # add temporal influence\n        shift_alpha *= math.sqrt(x_0.shape[-3])  # for image, T=1 so no effect\n        t = torch.sigmoid(torch.randn((bs), device=device))\n        t = time_shift(shift_alpha, t).to(dtype)\n\n        if cfg.get(\"cached_text\", False):\n            # == encode text ==\n            t5_embedding = batch.pop(\"text_t5\").to(device=device, dtype=dtype)\n            clip_embedding = batch.pop(\"text_clip\").to(device=device, dtype=dtype)\n            with nsys.range(\"encode_text\"), timers[\"encode_text\"]:\n                inp_ = prepare_ids(x_0, t5_embedding, clip_embedding)\n                inp.update(inp_)\n                x_0 = pack(x_0, patch_size=cfg.get(\"patch_size\", 2))\n        else:\n            # == encode text ==\n            with nsys.range(\"encode_text\"), timers[\"encode_text\"]:\n                inp_ = prepare(\n                    model_t5,\n                    model_clip,\n                    x_0,\n                    prompt=y,\n                    seq_align=seq_align,\n                    patch_size=cfg.get(\"patch_size\", 2),\n                )\n                inp.update(inp_)\n                x_0 = pack(x_0, patch_size=cfg.get(\"patch_size\", 2))\n\n        # == dropout ==\n        if cfg.get(\"dropout_ratio\", None) is not None:\n            cur_null_txt = null_txt\n            num_pad_null_txt = inp[\"txt\"].shape[1] - cur_null_txt.shape[1]\n            if num_pad_null_txt > 0:\n                cur_null_txt = torch.cat([cur_null_txt] + [cur_null_txt[:, -1:]] * num_pad_null_txt, dim=1)\n            inp[\"txt\"] = dropout_condition(\n                cfg.dropout_ratio.get(\"t5\", 0.0),\n                inp[\"txt\"],\n                cur_null_txt,\n            )\n            inp[\"y_vec\"] = dropout_condition(\n                cfg.dropout_ratio.get(\"clip\", 0.0),\n                inp[\"y_vec\"],\n                null_vec,\n            )\n\n        # == prepare noise vector ==\n        x_1 = torch.randn_like(x_0, dtype=torch.float32).to(device, dtype)\n        t_rev = 1 - t\n        x_t = t_rev[:, None, None] * x_0 + (1 - (1 - sigma_min) * t_rev[:, None, None]) * x_1\n        inp[\"img\"] = x_t\n        inp[\"timesteps\"] = t.to(dtype)\n        inp[\"guidance\"] = torch.full((x_t.shape[0],), cfg.get(\"guidance\", 4), device=x_t.device, dtype=x_t.dtype)\n\n        return inp, x_0, x_1\n\n    def run_iter(inp, x_0, x_1):\n        if is_pipeline_enabled(plugin_type, plugin_config):\n            inp[\"target\"] = (1 - sigma_min) * x_1 - x_0  # follow MovieGen, modify V_t accordingly\n            with nsys.range(\"forward-backward\"), timers[\"forward-backward\"]:\n                data_iter = iter([inp])\n                if cfg.get(\"no_i2v_ref_loss\", False):\n                    loss_fn = (\n                        lambda out, input_: get_batch_loss(out, input_[\"target\"], input_.pop(\"masks\", None))\n                        / accumulation_steps\n                    )\n                else:\n                    loss_fn = (\n                        lambda out, input_: F.mse_loss(out.float(), input_[\"target\"].float(), reduction=\"mean\")\n                        / accumulation_steps\n                    )\n                loss = booster.execute_pipeline(data_iter, model, loss_fn, optimizer)[\"loss\"]\n                loss = loss * accumulation_steps if loss is not None else loss\n                loss_item = all_reduce_mean(loss.data.clone().detach())\n        else:\n            with nsys.range(\"forward\"), timers[\"forward\"]:\n                model_pred = model(**inp)  # B, T, L\n                v_t = (1 - sigma_min) * x_1 - x_0\n                if cfg.get(\"no_i2v_ref_loss\", False):\n                    loss = get_batch_loss(model_pred, v_t, inp.pop(\"masks\", None))\n                else:\n                    loss = F.mse_loss(model_pred.float(), v_t.float(), reduction=\"mean\")\n\n            loss_item = all_reduce_mean(loss.data.clone().detach()).item()\n\n            # == backward & update ==\n            dist.barrier()\n            with nsys.range(\"backward\"), timers[\"backward\"]:\n                ctx = (\n                    booster.no_sync(model, optimizer)\n                    if cfg.get(\"plugin\", \"zero2\") in (\"zero1\", \"zero1-seq\") and (step + 1) % accumulation_steps != 0\n                    else nullcontext()\n                )\n                with ctx:\n                    booster.backward(loss=(loss / accumulation_steps), optimizer=optimizer)\n\n        with nsys.range(\"optim\"), timers[\"optim\"]:\n            if (step + 1) % accumulation_steps == 0:\n                booster.checkpoint_io.synchronize()\n                optimizer.step()\n                optimizer.zero_grad()\n            if lr_scheduler is not None:\n                lr_scheduler.step()\n\n        # == update EMA ==\n        if ema is not None:\n            with nsys.range(\"update_ema\"), timers[\"update_ema\"]:\n                update_ema(\n                    ema,\n                    model.unwrap(),\n                    optimizer=optimizer,\n                    decay=cfg.get(\"ema_decay\", 0.9999),\n                )\n\n        return loss_item\n\n    # =======================================================\n    # 6. training loop\n    # =======================================================\n    dist.barrier()\n    for epoch in range(start_epoch, cfg_epochs):\n        # == set dataloader to new epoch ==\n        sampler.set_epoch(epoch)\n        dataloader_iter = iter(dataloader)\n        logger.info(\"Beginning epoch %s...\", epoch)\n\n        # == training loop in an epoch ==\n        with tqdm(\n            enumerate(dataloader_iter, start=start_step),\n            desc=f\"Epoch {epoch}\",\n            disable=not is_log_process(plugin_type, plugin_config),\n            initial=start_step,\n            total=num_steps_per_epoch,\n        ) as pbar:\n            pbar_iter = iter(pbar)\n\n            # prefetch one for non-blocking data loading\n            def fetch_data():\n                step, batch = next(pbar_iter)\n                # print(f\"==debug== rank{dist.get_rank()} {dataloader_iter.get_cache_info()}\")\n                pinned_video = batch[\"video\"]\n                batch[\"video\"] = pinned_video.to(device, dtype, non_blocking=True)\n                return batch, step, pinned_video\n\n            batch_, step_, pinned_video_ = fetch_data()\n\n            for _ in range(start_step, num_steps_per_epoch):\n                nsys.step()\n                # == load data ===\n                with nsys.range(\"load_data\"), timers[\"load_data\"]:\n                    batch, step, pinned_video = batch_, step_, pinned_video_\n\n                    if step + 1 < num_steps_per_epoch:\n                        # only fetch new data if not last step\n                        batch_, step_, pinned_video_ = fetch_data()\n\n                # == run iter ==\n                with nsys.range(\"iter\"), timers[\"iter\"]:\n                    inp, x_0, x_1 = prepare_inputs(batch)\n                    if cache_pin_memory:\n                        dataloader_iter.remove_cache(pinned_video)\n                    loss = run_iter(inp, x_0, x_1)\n\n                # == update log info ==\n                if loss is not None:\n                    running_loss += loss\n\n                # == log config ==\n                global_step = epoch * num_steps_per_epoch + step\n                actual_update_step = (global_step + 1) // accumulation_steps\n                log_step += 1\n                acc_step += 1\n\n                # == logging ==\n                if (global_step + 1) % accumulation_steps == 0:\n                    if actual_update_step % cfg.get(\"log_every\", 1) == 0:\n                        if is_log_process(plugin_type, plugin_config):\n                            avg_loss = running_loss / log_step\n                            # progress bar\n                            pbar.set_postfix(\n                                {\n                                    \"loss\": avg_loss,\n                                    \"global_grad_norm\": optimizer.get_grad_norm(),\n                                    \"step\": step,\n                                    \"global_step\": global_step,\n                                    # \"actual_update_step\": actual_update_step,\n                                    \"lr\": optimizer.param_groups[0][\"lr\"],\n                                }\n                            )\n                            # tensorboard\n                            if tb_writer is not None:\n                                tb_writer.add_scalar(\"loss\", loss, actual_update_step)\n                            # wandb\n                            if cfg.get(\"wandb\", False):\n                                wandb_dict = {\n                                    \"iter\": global_step,\n                                    \"acc_step\": acc_step,\n                                    \"epoch\": epoch,\n                                    \"loss\": loss,\n                                    \"avg_loss\": avg_loss,\n                                    \"lr\": optimizer.param_groups[0][\"lr\"],\n                                    \"eps\": optimizer.param_groups[0][\"eps\"],\n                                    \"global_grad_norm\": optimizer.get_grad_norm(),  # test grad norm\n                                }\n                                if cfg.get(\"record_time\", False):\n                                    wandb_dict.update(timers.to_dict())\n                                wandb.log(wandb_dict, step=actual_update_step)\n\n                        running_loss = 0.0\n                        log_step = 0\n\n                # == checkpoint saving ==\n                # uncomment below 3 lines to forcely clean cache\n                with nsys.range(\"clean_cache\"), timers[\"clean_cache\"]:\n                    if ckpt_every > 0 and actual_update_step % ckpt_every == 0 and coordinator.is_master():\n                        subprocess.run(\"sudo drop_cache\", shell=True)\n\n                with nsys.range(\"checkpoint\"), timers[\"checkpoint\"]:\n                    if ckpt_every > 0 and actual_update_step % ckpt_every == 0:\n                        # mannual garbage collection\n                        gc.collect()\n\n                        save_dir = checkpoint_io.save(\n                            booster,\n                            exp_dir,\n                            model=model,\n                            ema=ema,\n                            optimizer=optimizer,\n                            lr_scheduler=lr_scheduler,\n                            sampler=sampler,\n                            epoch=epoch,\n                            step=step + 1,\n                            global_step=global_step + 1,\n                            batch_size=cfg.get(\"batch_size\", None),\n                            lora=use_lora,\n                            actual_update_step=actual_update_step,\n                            ema_shape_dict=ema_shape_dict,\n                            async_io=cfg.get(\"async_io\", False),\n                            include_master_weights=save_master_weights,\n                        )\n\n                        if is_log_process(plugin_type, plugin_config):\n                            os.system(f\"chgrp -R share {save_dir}\")\n\n                        logger.info(\n                            \"Saved checkpoint at epoch %s, step %s, global_step %s to %s\",\n                            epoch,\n                            step + 1,\n                            actual_update_step,\n                            save_dir,\n                        )\n\n                        # remove old checkpoints\n                        rm_checkpoints(exp_dir, keep_n_latest=cfg.get(\"keep_n_latest\", -1))\n                        logger.info(\"Removed old checkpoints and kept %s latest ones.\", cfg.get(\"keep_n_latest\", -1))\n                # uncomment below 3 lines to benchmark checkpoint\n                # if ckpt_every > 0 and actual_update_step % ckpt_every == 0:\n                #     booster.checkpoint_io._sync_io()\n                #     checkpoint_io._sync_io()\n                # == terminal timer ==\n                if cfg.get(\"record_time\", False):\n                    print(timers.to_str(epoch, step))\n\n        sampler.reset()\n        start_step = 0\n    log_cuda_max_memory(\"final\")\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "scripts/vae/inference.py",
    "content": "import os\nfrom pprint import pformat\n\nimport colossalai\nimport torch\nfrom colossalai.utils import get_current_device, set_seed\nfrom tqdm import tqdm\n\nfrom opensora.acceleration.parallel_states import get_data_parallel_group\nfrom opensora.datasets import save_sample\nfrom opensora.datasets.dataloader import prepare_dataloader\nfrom opensora.registry import DATASETS, MODELS, build_module\nfrom opensora.utils.config import parse_configs\nfrom opensora.utils.logger import create_logger, is_distributed, is_main_process\nfrom opensora.utils.misc import log_cuda_max_memory, log_model_params, to_torch_dtype\n\n\n@torch.inference_mode()\ndef main():\n    torch.set_grad_enabled(False)\n    # ======================================================\n    # configs & runtime variables\n    # ======================================================\n    # == parse configs ==\n    cfg = parse_configs()\n\n    # == get dtype & device ==\n    dtype = to_torch_dtype(cfg.get(\"dtype\", \"fp32\"))\n    device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n    if is_distributed():\n        colossalai.launch_from_torch({})\n        device = get_current_device()\n    set_seed(cfg.get(\"seed\", 1024))\n\n    # == init logger ==\n    logger = create_logger()\n    logger.info(\"Inference configuration:\\n %s\", pformat(cfg.to_dict()))\n    verbose = cfg.get(\"verbose\", 1)\n\n    # ======================================================\n    # build model & loss\n    # ======================================================\n    if cfg.get(\"ckpt_path\", None) is not None:\n        cfg.model.from_pretrained = cfg.ckpt_path\n    logger.info(\"Building models...\")\n    model = build_module(cfg.model, MODELS, device_map=device, torch_dtype=dtype).eval()\n    log_model_params(model)\n\n    # ======================================================\n    # build dataset and dataloader\n    # ======================================================\n    logger.info(\"Building dataset...\")\n    # == build dataset ==\n    dataset = build_module(cfg.dataset, DATASETS)\n    logger.info(\"Dataset contains %s samples.\", len(dataset))\n    # == build dataloader ==\n    dataloader_args = dict(\n        dataset=dataset,\n        batch_size=cfg.get(\"batch_size\", None),\n        num_workers=cfg.get(\"num_workers\", 4),\n        seed=cfg.get(\"seed\", 1024),\n        shuffle=False,\n        drop_last=False,\n        pin_memory=True,\n        process_group=get_data_parallel_group(),\n        prefetch_factor=cfg.get(\"prefetch_factor\", None),\n    )\n\n    if cfg.get(\"eval_setting\", None) is not None:\n        # e.g. 32x256, 1x1024\n        num_frames = int(cfg.eval_setting.split(\"x\")[0])\n        resolution = str(cfg.eval_setting.split(\"x\")[-1])\n        bucket_config = {\n            resolution + \"px\" + \"_ar1:1\": {num_frames: (1.0, 1)},\n        }\n        print(\"eval setting:\\n\", bucket_config)\n    else:\n        bucket_config = cfg.get(\"bucket_config\", None)\n\n    dataloader, sampler = prepare_dataloader(\n        bucket_config=bucket_config,\n        num_bucket_build_workers=cfg.get(\"num_bucket_build_workers\", 1),\n        **dataloader_args,\n    )\n    dataiter = iter(dataloader)\n    num_steps_per_epoch = len(dataloader)\n\n    # ======================================================\n    # inference\n    # ======================================================\n    # prepare arguments\n    save_fps = cfg.get(\"fps\", 16) // cfg.get(\"frame_interval\", 1)\n    save_dir = cfg.get(\"save_dir\", None)\n    save_dir_orig = os.path.join(save_dir, \"orig\")\n    save_dir_recn = os.path.join(save_dir, \"recn\")\n    os.makedirs(save_dir_orig, exist_ok=True)\n    os.makedirs(save_dir_recn, exist_ok=True)\n\n    running_sum = running_var = 0.0\n    num_samples = 0\n\n    # Iter over the dataset\n    with tqdm(\n        enumerate(dataiter),\n        disable=not is_main_process() or verbose < 1,\n        total=num_steps_per_epoch,\n        initial=0,\n    ) as pbar:\n        for _, batch in pbar:\n            # == load data ==\n            x = batch[\"video\"].to(device, dtype)  # [B, C, T, H, W]\n            path = batch[\"path\"]\n\n            # == vae encoding & decoding ===\n            x_rec, posterior, z = model(x)\n\n            num_samples += 1\n            running_sum += z.mean()\n            running_var += (z - running_sum / num_samples).pow(2).mean()\n            if num_samples % 10 == 0:\n                logger.info(\n                    \"VAE feature per channel stats: mean %s, var %s\",\n                    (running_sum / num_samples).item(),\n                    (running_var / num_samples).sqrt().item(),\n                )\n\n            # == save samples ==\n            if is_main_process() and save_dir is not None:\n                for idx, x_orig in enumerate(x):\n                    fname = os.path.splitext(os.path.basename(path[idx]))[0]\n                    save_path_orig = os.path.join(save_dir_orig, f\"{fname}_orig\")\n                    save_sample(x_orig, save_path=save_path_orig, fps=save_fps)\n\n                    save_path_rec = os.path.join(save_dir_recn, f\"{fname}_recn\")\n                    save_sample(x_rec[idx], save_path=save_path_rec, fps=save_fps)\n\n    logger.info(\"Inference finished.\")\n    log_cuda_max_memory(\"inference\")\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "scripts/vae/stats.py",
    "content": "from pprint import pformat\n\nimport colossalai\nimport torch\nfrom colossalai.utils import get_current_device, set_seed\nfrom tqdm import tqdm\n\nfrom opensora.acceleration.parallel_states import get_data_parallel_group\nfrom opensora.datasets.dataloader import prepare_dataloader\nfrom opensora.registry import DATASETS, MODELS, build_module\nfrom opensora.utils.config import parse_configs\nfrom opensora.utils.logger import create_logger, is_distributed, is_main_process\nfrom opensora.utils.misc import log_cuda_max_memory, log_model_params, to_torch_dtype\n\n\n@torch.inference_mode()\ndef main():\n    torch.set_grad_enabled(False)\n    # ======================================================\n    # configs & runtime variables\n    # ======================================================\n    # == parse configs ==\n    cfg = parse_configs()\n\n    # == get dtype & device ==\n    dtype = to_torch_dtype(cfg.get(\"dtype\", \"bf16\"))\n    device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n    if is_distributed():\n        colossalai.launch_from_torch({})\n        device = get_current_device()\n    set_seed(cfg.get(\"seed\", 1024))\n\n    # == init logger ==\n    logger = create_logger()\n    logger.info(\"Inference configuration:\\n %s\", pformat(cfg.to_dict()))\n    verbose = cfg.get(\"verbose\", 1)\n\n    # ======================================================\n    # build model & loss\n    # ======================================================\n    if cfg.get(\"ckpt_path\", None) is not None:\n        cfg.model.from_pretrained = cfg.ckpt_path\n    logger.info(\"Building models...\")\n    model = build_module(cfg.model, MODELS, device_map=device, torch_dtype=dtype).eval()\n    log_model_params(model)\n\n    # ======================================================\n    # build dataset and dataloader\n    # ======================================================\n    logger.info(\"Building dataset...\")\n    # == build dataset ==\n    dataset = build_module(cfg.dataset, DATASETS)\n    logger.info(\"Dataset contains %s samples.\", len(dataset))\n    # == build dataloader ==\n    dataloader_args = dict(\n        dataset=dataset,\n        batch_size=cfg.get(\"batch_size\", None),\n        num_workers=cfg.get(\"num_workers\", 4),\n        seed=cfg.get(\"seed\", 1024),\n        shuffle=False,\n        drop_last=False,\n        pin_memory=True,\n        process_group=get_data_parallel_group(),\n        prefetch_factor=cfg.get(\"prefetch_factor\", None),\n    )\n\n    if cfg.get(\"eval_setting\", None) is not None:\n        # e.g. 32x256x256, 1x1024x1024\n        num_frames = int(cfg.eval_setting.split(\"x\")[0])\n        resolution = str(cfg.eval_setting.split(\"x\")[-1])\n        bucket_config = {\n            resolution + \"px_ar1:1\": {num_frames: (1.0, 1)},\n        }\n        print(\"eval setting:\\n\", bucket_config)\n    else:\n        bucket_config = cfg.get(\"bucket_config\", None)\n\n    dataloader, _ = prepare_dataloader(\n        bucket_config=bucket_config,\n        num_bucket_build_workers=cfg.get(\"num_bucket_build_workers\", 1),\n        **dataloader_args,\n    )\n    dataiter = iter(dataloader)\n    num_steps_per_epoch = len(dataloader)\n\n    # ======================================================\n    # inference\n    # ======================================================\n    num_samples = 0\n    running_sum = running_var = 0.0\n\n    # Iter over the dataset\n    with tqdm(\n        enumerate(dataiter),\n        disable=not is_main_process() or verbose < 1,\n        total=num_steps_per_epoch,\n        initial=0,\n    ) as pbar:\n        for _, batch in pbar:\n            # == load data ==\n            x = batch[\"video\"].to(device, dtype)  # [B, C, T, H, W]\n\n            # == vae encoding & decoding ===\n            z = model.encode(x)\n\n            num_samples += 1\n            running_sum += z.mean().item()\n            running_var += (z - running_sum / num_samples).pow(2).mean().item()\n            shift = running_sum / num_samples\n            scale = (running_var / num_samples) ** 0.5\n            pbar.set_postfix({\"mean\": shift, \"std\": scale})\n\n    logger.info(\"Mean: %.4f, std: %.4f\", shift, scale)\n    log_cuda_max_memory(\"inference\")\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "scripts/vae/train.py",
    "content": "import gc\nimport os\nimport random\nimport subprocess\nimport warnings\nfrom contextlib import nullcontext\nfrom copy import deepcopy\nfrom pprint import pformat\n\nwarnings.filterwarnings(\"ignore\", category=FutureWarning)\nwarnings.filterwarnings(\"ignore\", category=UserWarning)\ngc.disable()\n\n\nimport torch\nimport torch.distributed as dist\nfrom colossalai.booster import Booster\nfrom colossalai.utils import set_seed\nfrom torch.profiler import ProfilerActivity, profile, schedule\nfrom tqdm import tqdm\n\nimport wandb\nfrom opensora.acceleration.checkpoint import set_grad_checkpoint\nfrom opensora.acceleration.parallel_states import get_data_parallel_group\nfrom opensora.datasets.dataloader import prepare_dataloader\nfrom opensora.datasets.pin_memory_cache import PinMemoryCache\nfrom opensora.models.vae.losses import DiscriminatorLoss, GeneratorLoss, VAELoss\nfrom opensora.registry import DATASETS, MODELS, build_module\nfrom opensora.utils.ckpt import CheckpointIO, model_sharding, record_model_param_shape, rm_checkpoints\nfrom opensora.utils.config import config_to_name, create_experiment_workspace, parse_configs\nfrom opensora.utils.logger import create_logger\nfrom opensora.utils.misc import (\n    Timer,\n    all_reduce_sum,\n    create_tensorboard_writer,\n    is_log_process,\n    log_model_params,\n    to_torch_dtype,\n)\nfrom opensora.utils.optimizer import create_lr_scheduler, create_optimizer\nfrom opensora.utils.train import create_colossalai_plugin, set_lr, set_warmup_steps, setup_device, update_ema\n\ntorch.backends.cudnn.benchmark = True\n\nWAIT = 1\nWARMUP = 10\nACTIVE = 20\n\nmy_schedule = schedule(\n    wait=WAIT,  # number of warmup steps\n    warmup=WARMUP,  # number of warmup steps with profiling\n    active=ACTIVE,  # number of active steps with profiling\n)\n\n\ndef main():\n    # ======================================================\n    # 1. configs & runtime variables\n    # ======================================================\n    # == parse configs ==\n    cfg = parse_configs()\n\n    # == get dtype & device ==\n    dtype = to_torch_dtype(cfg.get(\"dtype\", \"bf16\"))\n    device, coordinator = setup_device()\n    checkpoint_io = CheckpointIO()\n    set_seed(cfg.get(\"seed\", 1024))\n    PinMemoryCache.force_dtype = dtype\n    pin_memory_cache_pre_alloc_numels = cfg.get(\"pin_memory_cache_pre_alloc_numels\", None)\n    PinMemoryCache.pre_alloc_numels = pin_memory_cache_pre_alloc_numels\n\n    # == init ColossalAI booster ==\n    plugin_type = cfg.get(\"plugin\", \"zero2\")\n    plugin_config = cfg.get(\"plugin_config\", {})\n    plugin = (\n        create_colossalai_plugin(\n            plugin=plugin_type,\n            dtype=cfg.get(\"dtype\", \"bf16\"),\n            grad_clip=cfg.get(\"grad_clip\", 0),\n            **plugin_config,\n        )\n        if plugin_type != \"none\"\n        else None\n    )\n    booster = Booster(plugin=plugin)\n\n    # == init exp_dir ==\n    exp_name, exp_dir = create_experiment_workspace(\n        cfg.get(\"outputs\", \"./outputs\"),\n        model_name=config_to_name(cfg),\n        config=cfg.to_dict(),\n    )\n    if is_log_process(plugin_type, plugin_config):\n        print(f\"changing {exp_dir} to share\")\n        os.system(f\"chgrp -R share {exp_dir}\")\n\n    # == init logger, tensorboard & wandb ==\n    logger = create_logger(exp_dir)\n    logger.info(\"Training configuration:\\n %s\", pformat(cfg.to_dict()))\n    tb_writer = None\n    if coordinator.is_master():\n        tb_writer = create_tensorboard_writer(exp_dir)\n        if cfg.get(\"wandb\", False):\n            wandb.init(\n                project=cfg.get(\"wandb_project\", \"Open-Sora\"),\n                name=cfg.get(\"wandb_expr_name\", exp_name),\n                config=cfg.to_dict(),\n                dir=exp_dir,\n            )\n\n    # ======================================================\n    # 2. build dataset and dataloader\n    # ======================================================\n    logger.info(\"Building dataset...\")\n    # == build dataset ==\n    dataset = build_module(cfg.dataset, DATASETS)\n    logger.info(\"Dataset contains %s samples.\", len(dataset))\n\n    # == build dataloader ==\n    cache_pin_memory = pin_memory_cache_pre_alloc_numels is not None\n    dataloader_args = dict(\n        dataset=dataset,\n        batch_size=cfg.get(\"batch_size\", None),\n        num_workers=cfg.get(\"num_workers\", 4),\n        seed=cfg.get(\"seed\", 1024),\n        shuffle=True,\n        drop_last=True,\n        pin_memory=True,\n        process_group=get_data_parallel_group(),\n        prefetch_factor=cfg.get(\"prefetch_factor\", None),\n        cache_pin_memory=cache_pin_memory,\n    )\n    dataloader, sampler = prepare_dataloader(\n        bucket_config=cfg.get(\"bucket_config\", None),\n        num_bucket_build_workers=cfg.get(\"num_bucket_build_workers\", 1),\n        **dataloader_args,\n    )\n    num_steps_per_epoch = len(dataloader)\n\n    # ======================================================\n    # 3. build model\n    # ======================================================\n    logger.info(\"Building models...\")\n\n    # == build vae model ==\n    model = build_module(cfg.model, MODELS, device_map=device, torch_dtype=dtype).train()\n    log_model_params(model)\n\n    if cfg.get(\"grad_checkpoint\", False):\n        set_grad_checkpoint(model)\n    vae_loss_fn = VAELoss(**cfg.vae_loss_config, device=device, dtype=dtype)\n\n    # == build EMA model ==\n    if cfg.get(\"ema_decay\", None) is not None:\n        ema = deepcopy(model).cpu().eval().requires_grad_(False)\n        ema_shape_dict = record_model_param_shape(ema)\n        logger.info(\"EMA model created.\")\n    else:\n        ema = ema_shape_dict = None\n        logger.info(\"No EMA model created.\")\n\n    # == build discriminator model ==\n    use_discriminator = cfg.get(\"discriminator\", None) is not None\n    if use_discriminator:\n        discriminator = build_module(cfg.discriminator, MODELS).to(device, dtype).train()\n        log_model_params(discriminator)\n        generator_loss_fn = GeneratorLoss(**cfg.gen_loss_config)\n        discriminator_loss_fn = DiscriminatorLoss(**cfg.disc_loss_config)\n\n    # == setup optimizer ==\n    optimizer = create_optimizer(model, cfg.optim)\n\n    # == setup lr scheduler ==\n    lr_scheduler = create_lr_scheduler(\n        optimizer=optimizer, num_steps_per_epoch=num_steps_per_epoch, epochs=cfg.get(\"epochs\", 1000), **cfg.lr_scheduler\n    )\n\n    # == setup discriminator optimizer ==\n    if use_discriminator:\n        disc_optimizer = create_optimizer(discriminator, cfg.optim_discriminator)\n        disc_lr_scheduler = create_lr_scheduler(\n            optimizer=disc_optimizer,\n            num_steps_per_epoch=num_steps_per_epoch,\n            epochs=cfg.get(\"epochs\", 1000),\n            **cfg.disc_lr_scheduler,\n        )\n\n    # =======================================================\n    # 4. distributed training preparation with colossalai\n    # =======================================================\n    logger.info(\"Preparing for distributed training...\")\n    # == boosting ==\n    torch.set_default_dtype(dtype)\n    model, optimizer, _, dataloader, lr_scheduler = booster.boost(\n        model=model,\n        optimizer=optimizer,\n        lr_scheduler=lr_scheduler,\n        dataloader=dataloader,\n    )\n\n    if use_discriminator:\n        discriminator, disc_optimizer, _, _, disc_lr_scheduler = booster.boost(\n            model=discriminator,\n            optimizer=disc_optimizer,\n            lr_scheduler=disc_lr_scheduler,\n        )\n    torch.set_default_dtype(torch.float)\n    logger.info(\"Boosted model for distributed training\")\n\n    # == global variables ==\n    cfg_epochs = cfg.get(\"epochs\", 1000)\n    mixed_strategy = cfg.get(\"mixed_strategy\", None)\n    mixed_image_ratio = cfg.get(\"mixed_image_ratio\", 0.0)\n    # modulate mixed image ratio since we force rank 0 to be video\n    num_ranks = dist.get_world_size()\n    modulated_mixed_image_ratio = (\n        num_ranks * mixed_image_ratio / (num_ranks - 1) if num_ranks > 1 else mixed_image_ratio\n    )\n    if is_log_process(plugin_type, plugin_config):\n        print(\"modulated mixed image ratio:\", modulated_mixed_image_ratio)\n\n    start_epoch = start_step = log_step = acc_step = 0\n    running_loss = dict(  # loss accumulated over config.log_every steps\n        all=0.0,\n        nll=0.0,\n        nll_rec=0.0,\n        nll_per=0.0,\n        kl=0.0,\n        gen=0.0,\n        gen_w=0.0,\n        disc=0.0,\n        debug=0.0,\n    )\n\n    def log_loss(name, loss, loss_dict, use_video):\n        # only calculate loss for video\n        if use_video == 0:\n            loss.data = torch.tensor(0.0, device=device, dtype=dtype)\n        all_reduce_sum(loss.data)\n        num_video = torch.tensor(use_video, device=device, dtype=dtype)\n        all_reduce_sum(num_video)\n        loss_item = loss.item() / num_video.item()\n        loss_dict[name] = loss_item\n        running_loss[name] += loss_item\n\n    logger.info(\"Training for %s epochs with %s steps per epoch\", cfg_epochs, num_steps_per_epoch)\n\n    # == resume ==\n    if cfg.get(\"load\", None) is not None:\n        logger.info(\"Loading checkpoint from %s\", cfg.load)\n        start_epoch = cfg.get(\"start_epoch\", None)\n        start_step = cfg.get(\"start_step\", None)\n        ret = checkpoint_io.load(\n            booster,\n            cfg.load,\n            model=model,\n            ema=ema,\n            optimizer=optimizer,\n            lr_scheduler=lr_scheduler,\n            sampler=(\n                None if start_step is not None else sampler\n            ),  # if specify start step, set last_micro_batch_access_index of a new sampler instead\n        )\n        if start_step is not None:\n            # if start step exceeds data length, go to next epoch\n            if start_step > num_steps_per_epoch:\n                start_epoch = (\n                    start_epoch + start_step // num_steps_per_epoch\n                    if start_epoch is not None\n                    else start_step // num_steps_per_epoch\n                )\n                start_step = start_step % num_steps_per_epoch\n            sampler.set_step(start_step)\n\n        start_epoch = start_epoch if start_epoch is not None else ret[0]\n        start_step = start_step if start_step is not None else ret[1]\n\n        if (\n            use_discriminator\n            and os.path.exists(os.path.join(cfg.load, \"discriminator\"))\n            and not cfg.get(\"restart_disc\", False)\n        ):\n            booster.load_model(discriminator, os.path.join(cfg.load, \"discriminator\"))\n            if cfg.get(\"load_optimizer\", True):\n                booster.load_optimizer(disc_optimizer, os.path.join(cfg.load, \"disc_optimizer\"))\n                if disc_lr_scheduler is not None:\n                    booster.load_lr_scheduler(disc_lr_scheduler, os.path.join(cfg.load, \"disc_lr_scheduler\"))\n                if cfg.get(\"disc_lr\", None) is not None:\n                    set_lr(disc_optimizer, disc_lr_scheduler, cfg.disc_lr)\n\n        logger.info(\"Loaded checkpoint %s at epoch %s step %s\", cfg.load, start_epoch, start_step)\n\n        if cfg.get(\"lr\", None) is not None:\n            set_lr(optimizer, lr_scheduler, cfg.lr, cfg.get(\"initial_lr\", None))\n\n        if cfg.get(\"update_warmup_steps\", False):\n            assert (\n                cfg.lr_scheduler.get(\"warmup_steps\", None) is not None\n            ), \"you need to set lr_scheduler.warmup_steps in order to pass --update-warmup-steps True\"\n            set_warmup_steps(lr_scheduler, cfg.lr_scheduler.warmup_steps)\n            if use_discriminator:\n                assert (\n                    cfg.disc_lr_scheduler.get(\"warmup_steps\", None) is not None\n                ), \"you need to set disc_lr_scheduler.warmup_steps in order to pass --update-warmup-steps True\"\n                set_warmup_steps(disc_lr_scheduler, cfg.disc_lr_scheduler.warmup_steps)\n\n    # == sharding EMA model ==\n    if ema is not None:\n        model_sharding(ema)\n        ema = ema.to(device)\n\n    if cfg.get(\"freeze_layers\", None) == \"all\":\n        for param in model.module.parameters():\n            param.requires_grad = False\n        print(\"all layers frozen\")\n\n    # model.module.requires_grad_(False)\n    # =======================================================\n    # 5. training loop\n    # =======================================================\n    dist.barrier()\n    accumulation_steps = int(cfg.get(\"accumulation_steps\", 1))\n    for epoch in range(start_epoch, cfg_epochs):\n        # == set dataloader to new epoch ==\n        sampler.set_epoch(epoch)\n        dataiter = iter(dataloader)\n        logger.info(\"Beginning epoch %s...\", epoch)\n        random.seed(1024 + dist.get_rank())  # load vid/img for each rank\n\n        # == training loop in an epoch ==\n        with tqdm(\n            enumerate(dataiter, start=start_step),\n            desc=f\"Epoch {epoch}\",\n            disable=not coordinator.is_master(),\n            total=num_steps_per_epoch,\n            initial=start_step,\n        ) as pbar:\n            pbar_iter = iter(pbar)\n\n            def fetch_data():\n                step, batch = next(pbar_iter)\n                pinned_video = batch[\"video\"]\n                batch[\"video\"] = pinned_video.to(device, dtype, non_blocking=True)\n                return batch, step, pinned_video\n\n            batch_, step_, pinned_video_ = fetch_data()\n\n            profiler_ctxt = (\n                profile(\n                    activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA],\n                    schedule=my_schedule,\n                    on_trace_ready=torch.profiler.tensorboard_trace_handler(\"./log/profile\"),\n                    record_shapes=True,\n                    profile_memory=True,\n                    with_stack=True,\n                )\n                if cfg.get(\"profile\", False)\n                else nullcontext()\n            )\n\n            with profiler_ctxt:\n                for _ in range(start_step, num_steps_per_epoch):\n                    if cfg.get(\"profile\", False) and _ == WARMUP + ACTIVE + WAIT + 3:\n                        break\n\n                    # == load data ===\n                    batch, step, pinned_video = batch_, step_, pinned_video_\n                    if step + 1 < num_steps_per_epoch:\n                        batch_, step_, pinned_video_ = fetch_data()\n\n                    # == log config ==\n                    global_step = epoch * num_steps_per_epoch + step\n                    actual_update_step = (global_step + 1) // accumulation_steps\n                    log_step += 1\n                    acc_step += 1\n\n                    # == mixed strategy ==\n                    x = batch[\"video\"]\n                    t_length = x.size(2)\n                    use_video = 1\n                    if mixed_strategy == \"mixed_video_image\":\n                        if random.random() < modulated_mixed_image_ratio and dist.get_rank() != 0:\n                            # NOTE: enable the first rank to use video\n                            t_length = 1\n                            use_video = 0\n                    elif mixed_strategy == \"mixed_video_random\":\n                        t_length = random.randint(1, x.size(2))\n                    x = x[:, :, :t_length, :, :]\n\n                    with Timer(\"model\", log=True) if cfg.get(\"profile\", False) else nullcontext():\n                        # == forward pass ==\n                        x_rec, posterior, z = model(x)\n\n                        if cfg.get(\"profile\", False):\n                            profiler_ctxt.step()\n\n                        if cache_pin_memory:\n                            dataiter.remove_cache(pinned_video)\n\n                        # == loss initialization ==\n                        vae_loss = torch.tensor(0.0, device=device, dtype=dtype)\n                        loss_dict = {}  # loss at every step\n\n                        # == reconstruction loss ==\n                        ret = vae_loss_fn(x, x_rec, posterior)\n                        nll_loss = ret[\"nll_loss\"]\n                        kl_loss = ret[\"kl_loss\"]\n                        recon_loss = ret[\"recon_loss\"]\n                        perceptual_loss = ret[\"perceptual_loss\"]\n                        vae_loss += nll_loss + kl_loss\n\n                        # == generator loss ==\n                        if use_discriminator:\n                            # turn off grad update for disc\n                            discriminator.requires_grad_(False)\n                            fake_logits = discriminator(x_rec.contiguous())\n\n                            generator_loss, g_loss = generator_loss_fn(\n                                fake_logits,\n                                nll_loss,\n                                model.module.get_last_layer(),\n                                actual_update_step,\n                                is_training=model.training,\n                            )\n                            # print(f\"generator_loss: {generator_loss}, recon_loss: {recon_loss}, perceptual_loss: {perceptual_loss}\")\n\n                            vae_loss += generator_loss\n                            # turn on disc training\n                            discriminator.requires_grad_(True)\n\n                        # == generator backward & update ==\n                        ctx = (\n                            booster.no_sync(model, optimizer)\n                            if cfg.get(\"plugin\", \"zero2\") in (\"zero1\", \"zero1-seq\")\n                            and (step + 1) % accumulation_steps != 0\n                            else nullcontext()\n                        )\n                        with Timer(\"backward\", log=True) if cfg.get(\"profile\", False) else nullcontext():\n                            with ctx:\n                                booster.backward(loss=vae_loss / accumulation_steps, optimizer=optimizer)\n\n                        with Timer(\"optimizer\", log=True) if cfg.get(\"profile\", False) else nullcontext():\n                            if (step + 1) % accumulation_steps == 0:\n                                optimizer.step()\n                                optimizer.zero_grad()\n                                if lr_scheduler is not None:\n                                    lr_scheduler.step(\n                                        actual_update_step,\n                                    )\n                                # == update EMA ==\n                                if ema is not None:\n                                    update_ema(\n                                        ema,\n                                        model.unwrap(),\n                                        optimizer=optimizer,\n                                        decay=cfg.get(\"ema_decay\", 0.9999),\n                                    )\n\n                    # == logging ==\n                    log_loss(\"all\", vae_loss, loss_dict, use_video)\n                    log_loss(\"nll\", nll_loss, loss_dict, use_video)\n                    log_loss(\"nll_rec\", recon_loss, loss_dict, use_video)\n                    log_loss(\"nll_per\", perceptual_loss, loss_dict, use_video)\n                    log_loss(\"kl\", kl_loss, loss_dict, use_video)\n                    if use_discriminator:\n                        log_loss(\"gen_w\", generator_loss, loss_dict, use_video)\n                        log_loss(\"gen\", g_loss, loss_dict, use_video)\n\n                    # == loss: discriminator adversarial ==\n                    if use_discriminator:\n                        real_logits = discriminator(x.detach().contiguous())\n                        fake_logits = discriminator(x_rec.detach().contiguous())\n                        disc_loss = discriminator_loss_fn(\n                            real_logits,\n                            fake_logits,\n                            actual_update_step,\n                        )\n\n                        # == discriminator backward & update ==\n                        ctx = (\n                            booster.no_sync(discriminator, disc_optimizer)\n                            if cfg.get(\"plugin\", \"zero2\") in (\"zero1\", \"zero1-seq\")\n                            and (step + 1) % accumulation_steps != 0\n                            else nullcontext()\n                        )\n                        with ctx:\n                            booster.backward(loss=disc_loss / accumulation_steps, optimizer=disc_optimizer)\n                        if (step + 1) % accumulation_steps == 0:\n                            disc_optimizer.step()\n                            disc_optimizer.zero_grad()\n                            if disc_lr_scheduler is not None:\n                                disc_lr_scheduler.step(actual_update_step)\n\n                        # log\n                        log_loss(\"disc\", disc_loss, loss_dict, use_video)\n\n                    # == logging ==\n                    if (global_step + 1) % accumulation_steps == 0:\n                        if coordinator.is_master() and actual_update_step % cfg.get(\"log_every\", 1) == 0:\n                            avg_loss = {k: v / log_step for k, v in running_loss.items()}\n                            # progress bar\n                            pbar.set_postfix(\n                                {\n                                    # \"step\": step,\n                                    # \"global_step\": global_step,\n                                    # \"actual_update_step\": actual_update_step,\n                                    # \"lr\": optimizer.param_groups[0][\"lr\"],\n                                    **{k: f\"{v:.2f}\" for k, v in avg_loss.items()},\n                                }\n                            )\n                            # tensorboard\n                            tb_writer.add_scalar(\"loss\", vae_loss.item(), actual_update_step)\n                            # wandb\n                            if cfg.get(\"wandb\", False):\n                                wandb.log(\n                                    {\n                                        \"iter\": global_step,\n                                        \"epoch\": epoch,\n                                        \"lr\": optimizer.param_groups[0][\"lr\"],\n                                        \"avg_loss_\": avg_loss,\n                                        \"avg_loss\": avg_loss[\"all\"],\n                                        \"loss_\": loss_dict,\n                                        \"loss\": vae_loss.item(),\n                                        \"global_grad_norm\": optimizer.get_grad_norm(),\n                                    },\n                                    step=actual_update_step,\n                                )\n\n                            running_loss = {k: 0.0 for k in running_loss}\n                            log_step = 0\n\n                        # == checkpoint saving ==\n                        ckpt_every = cfg.get(\"ckpt_every\", 0)\n                        if ckpt_every > 0 and actual_update_step % ckpt_every == 0 and coordinator.is_master():\n                            subprocess.run(\"sudo drop_cache\", shell=True)\n\n                        if ckpt_every > 0 and actual_update_step % ckpt_every == 0:\n                            # mannually garbage collection\n                            gc.collect()\n\n                            save_dir = checkpoint_io.save(\n                                booster,\n                                exp_dir,\n                                model=model,\n                                ema=ema,\n                                optimizer=optimizer,\n                                lr_scheduler=lr_scheduler,\n                                sampler=sampler,\n                                epoch=epoch,\n                                step=step + 1,\n                                global_step=global_step + 1,\n                                batch_size=cfg.get(\"batch_size\", None),\n                                actual_update_step=actual_update_step,\n                                ema_shape_dict=ema_shape_dict,\n                                async_io=True,\n                            )\n\n                            if is_log_process(plugin_type, plugin_config):\n                                os.system(f\"chgrp -R share {save_dir}\")\n\n                            if use_discriminator:\n                                booster.save_model(discriminator, os.path.join(save_dir, \"discriminator\"), shard=True)\n                                booster.save_optimizer(\n                                    disc_optimizer,\n                                    os.path.join(save_dir, \"disc_optimizer\"),\n                                    shard=True,\n                                    size_per_shard=4096,\n                                )\n                                if disc_lr_scheduler is not None:\n                                    booster.save_lr_scheduler(\n                                        disc_lr_scheduler, os.path.join(save_dir, \"disc_lr_scheduler\")\n                                    )\n                            dist.barrier()\n\n                            logger.info(\n                                \"Saved checkpoint at epoch %s, step %s, global_step %s to %s\",\n                                epoch,\n                                step + 1,\n                                actual_update_step,\n                                save_dir,\n                            )\n\n                            # remove old checkpoints\n                            rm_checkpoints(exp_dir, keep_n_latest=cfg.get(\"keep_n_latest\", -1))\n                            logger.info(\n                                \"Removed old checkpoints and kept %s latest ones.\", cfg.get(\"keep_n_latest\", -1)\n                            )\n\n            if cfg.get(\"profile\", False):\n                profiler_ctxt.export_chrome_trace(\"./log/profile/trace.json\")\n\n        sampler.reset()\n        start_step = 0\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "setup.py",
    "content": "from typing import List\n\nfrom setuptools import find_packages, setup\n\n\ndef fetch_requirements(paths) -> List[str]:\n    \"\"\"\n    This function reads the requirements file.\n\n    Args:\n        path (str): the path to the requirements file.\n\n    Returns:\n        The lines in the requirements file.\n    \"\"\"\n    if not isinstance(paths, list):\n        paths = [paths]\n    requirements = []\n    for path in paths:\n        with open(path, \"r\") as fd:\n            requirements += [r.strip() for r in fd.readlines()]\n    return requirements\n\n\ndef fetch_readme() -> str:\n    \"\"\"\n    This function reads the README.md file in the current directory.\n\n    Returns:\n        The lines in the README file.\n    \"\"\"\n    with open(\"README.md\", encoding=\"utf-8\") as f:\n        return f.read()\n\n\nsetup(\n    name=\"opensora\",\n    version=\"2.0.0\",\n    packages=find_packages(\n        exclude=(\n            \"assets\",\n            \"configs\",\n            \"docs\",\n            \"eval\",\n            \"evaluation_results\",\n            \"gradio\",\n            \"logs\",\n            \"notebooks\",\n            \"outputs\",\n            \"pretrained_models\",\n            \"samples\",\n            \"scripts\",\n            \"*.egg-info\",\n        )\n    ),\n    description=\"Democratizing Efficient Video Production for All\",\n    long_description=fetch_readme(),\n    long_description_content_type=\"text/markdown\",\n    license=\"Apache Software License 2.0\",\n    url=\"https://github.com/hpcaitech/Open-Sora\",\n    project_urls={\n        \"Bug Tracker\": \"https://github.com/hpcaitech/Open-Sora/issues\",\n        \"Examples\": \"https://hpcaitech.github.io/Open-Sora/\",\n        \"Documentation\": \"https://github.com/hpcaitech/Open-Sora?tab=readme-ov-file\",\n        \"Github\": \"https://github.com/hpcaitech/Open-Sora\",\n    },\n    install_requires=fetch_requirements(\"requirements.txt\"),\n    python_requires=\">=3.6\",\n    classifiers=[\n        \"Programming Language :: Python :: 3\",\n        \"License :: OSI Approved :: Apache Software License\",\n        \"Environment :: GPU :: NVIDIA CUDA\",\n        \"Topic :: Scientific/Engineering :: Artificial Intelligence\",\n        \"Topic :: System :: Distributed Computing\",\n    ],\n)\n"
  }
]