Repository: hpcaitech/Open-Sora Branch: main Commit: d0cd5ac50da7 Files: 107 Total size: 725.4 KB Directory structure: gitextract_lugswvy_/ ├── .github/ │ └── workflows/ │ ├── close_issue.yaml │ └── github_page.yaml ├── .gitignore ├── .pre-commit-config.yaml ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── assets/ │ └── texts/ │ ├── example.csv │ ├── i2v.csv │ └── sora.csv ├── configs/ │ ├── diffusion/ │ │ ├── inference/ │ │ │ ├── 256px.py │ │ │ ├── 256px_tp.py │ │ │ ├── 768px.py │ │ │ ├── high_compression.py │ │ │ ├── plugins/ │ │ │ │ ├── sp.py │ │ │ │ ├── t2i2v.py │ │ │ │ └── tp.py │ │ │ ├── t2i2v_256px.py │ │ │ └── t2i2v_768px.py │ │ └── train/ │ │ ├── demo.py │ │ ├── high_compression.py │ │ ├── image.py │ │ ├── stage1.py │ │ ├── stage1_i2v.py │ │ ├── stage2.py │ │ └── stage2_i2v.py │ └── vae/ │ ├── inference/ │ │ ├── hunyuanvideo_vae.py │ │ └── video_dc_ae.py │ └── train/ │ ├── video_dc_ae.py │ └── video_dc_ae_disc.py ├── docs/ │ ├── ae.md │ ├── hcae.md │ ├── report_01.md │ ├── report_02.md │ ├── report_03.md │ ├── report_04.md │ ├── train.md │ └── zh_CN/ │ ├── report_v1.md │ ├── report_v2.md │ ├── report_v3.md │ └── report_v4.md ├── gradio/ │ └── app.py ├── opensora/ │ ├── __init__.py │ ├── acceleration/ │ │ ├── __init__.py │ │ ├── checkpoint.py │ │ ├── communications.py │ │ ├── parallel_states.py │ │ └── shardformer/ │ │ ├── __init__.py │ │ ├── modeling/ │ │ │ ├── __init__.py │ │ │ └── t5.py │ │ └── policy/ │ │ ├── __init__.py │ │ └── t5_encoder.py │ ├── models/ │ │ ├── __init__.py │ │ ├── dc_ae/ │ │ │ ├── __init__.py │ │ │ ├── ae_model_zoo.py │ │ │ ├── models/ │ │ │ │ ├── __init__.py │ │ │ │ ├── dc_ae.py │ │ │ │ └── nn/ │ │ │ │ ├── __init__.py │ │ │ │ ├── act.py │ │ │ │ ├── norm.py │ │ │ │ ├── ops.py │ │ │ │ └── vo_ops.py │ │ │ └── utils/ │ │ │ ├── __init__.py │ │ │ ├── init.py │ │ │ └── list.py │ │ ├── hunyuan_vae/ │ │ │ ├── __init__.py │ │ │ ├── autoencoder_kl_causal_3d.py │ │ │ ├── distributed.py │ │ │ ├── policy.py │ │ │ ├── unet_causal_3d_blocks.py │ │ │ └── vae.py │ │ ├── mmdit/ │ │ │ ├── __init__.py │ │ │ ├── distributed.py │ │ │ ├── layers.py │ │ │ ├── math.py │ │ │ ├── model.py │ │ │ └── policy.py │ │ ├── text/ │ │ │ ├── __init__.py │ │ │ └── conditioner.py │ │ └── vae/ │ │ ├── __init__.py │ │ ├── autoencoder_2d.py │ │ ├── discriminator.py │ │ ├── losses.py │ │ ├── lpips.py │ │ ├── tensor_parallel.py │ │ └── utils.py │ ├── registry.py │ └── utils/ │ ├── __init__.py │ ├── cai.py │ ├── ckpt.py │ ├── config.py │ ├── inference.py │ ├── logger.py │ ├── misc.py │ ├── optimizer.py │ ├── prompt_refine.py │ ├── sampling.py │ └── train.py ├── requirements.txt ├── scripts/ │ ├── cnv/ │ │ ├── meta.py │ │ └── shard.py │ ├── diffusion/ │ │ ├── inference.py │ │ └── train.py │ └── vae/ │ ├── inference.py │ ├── stats.py │ └── train.py └── setup.py ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/workflows/close_issue.yaml ================================================ name: Close inactive issues on: schedule: - cron: "30 1 * * *" jobs: close-issues: runs-on: ubuntu-latest permissions: issues: write pull-requests: write steps: - uses: actions/stale@v9 with: days-before-issue-stale: 7 days-before-issue-close: 7 stale-issue-label: "stale" stale-issue-message: "This issue is stale because it has been open for 7 days with no activity." close-issue-message: "This issue was closed because it has been inactive for 7 days since being marked as stale." days-before-pr-stale: -1 days-before-pr-close: -1 repo-token: ${{ secrets.GITHUB_TOKEN }} ================================================ FILE: .github/workflows/github_page.yaml ================================================ name: GitHub Pages on: workflow_dispatch: jobs: deploy: runs-on: ubuntu-22.04 permissions: contents: write concurrency: group: ${{ github.workflow }}-${{ github.ref }} steps: - uses: actions/checkout@v3 with: ref: gallery - name: Setup Node uses: actions/setup-node@v4 with: node-version: 20 - run: npm install - run: npm run build - name: Deploy uses: peaceiris/actions-gh-pages@v3 with: github_token: ${{ secrets.GITHUB_TOKEN }} publish_dir: ./build ================================================ FILE: .gitignore ================================================ __pycache__/ *.py[cod] *$py.class # C extensions *.so # Distribution / packaging .Python build/ develop-eggs/ dist/ downloads/ eggs/ .eggs/ lib/ lib64/ parts/ sdist/ var/ wheels/ share/python-wheels/ *.egg-info/ .installed.cfg *.egg MANIFEST # PyInstaller # Usually these files are written by a python script from a template # before PyInstaller builds the exe, so as to inject date/other infos into it. *.manifest *.spec # Installer logs pip-log.txt pip-delete-this-directory.txt # Unit test / coverage reports htmlcov/ .tox/ .nox/ .coverage .coverage.* .cache nosetests.xml coverage.xml *.cover *.py,cover .hypothesis/ .pytest_cache/ cover/ # Translations *.mo *.pot # Django stuff: *.log local_settings.py db.sqlite3 db.sqlite3-journal # Flask stuff: instance/ .webassets-cache # Scrapy stuff: .scrapy # Sphinx documentation docs/_build/ # PyBuilder .pybuilder/ target/ # Jupyter Notebook .ipynb_checkpoints # IPython profile_default/ ipython_config.py # pyenv # For a library or package, you might want to ignore these files since the code is # intended to run in multiple environments; otherwise, check them in: # .python-version # pipenv # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. # However, in case of collaboration, if having platform-specific dependencies or dependencies # having no cross-platform support, pipenv may install dependencies that don't work, or not # install all needed dependencies. #Pipfile.lock # poetry # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. # This is especially recommended for binary packages to ensure reproducibility, and is more # commonly ignored for libraries. # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control #poetry.lock # pdm # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. #pdm.lock # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it # in version control. # https://pdm.fming.dev/#use-with-ide .pdm.toml # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm __pypackages__/ # Celery stuff celerybeat-schedule celerybeat.pid # SageMath parsed files *.sage.py # Environments .env .venv env/ venv/ ENV/ env.bak/ venv.bak/ # Spyder project settings .spyderproject .spyproject # Rope project settings .ropeproject # mkdocs documentation /site # mypy .mypy_cache/ .dmypy.json dmypy.json # Pyre type checker .pyre/ # pytype static type analyzer .pytype/ # Cython debug symbols cython_debug/ # PyCharm # JetBrains specific template is maintained in a separate JetBrains.gitignore that can # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore # and can be added to the global gitignore or merged into this file. For a more nuclear # option (not recommended) you can uncomment the following to ignore the entire idea folder. .idea/ .vscode/ # macos *.DS_Store # misc files data/ dataset/ runs/ checkpoints/ outputs/ outputs samples/ samples logs/ pretrained_models/ pretrained_models evaluation_results/ cache/ *.swp debug/ # Secret files hostfiles/ hostfile* run.sh gradio_cached_examples/ wandb/ # npm node_modules/ package-lock.json package.json exps ckpts flash-attention datasets ================================================ FILE: .pre-commit-config.yaml ================================================ repos: - repo: https://github.com/PyCQA/autoflake rev: v2.2.1 hooks: - id: autoflake name: autoflake (python) args: ['--in-place'] - repo: https://github.com/pycqa/isort rev: 5.12.0 hooks: - id: isort name: sort all imports (python) - repo: https://github.com/psf/black-pre-commit-mirror rev: 23.9.1 hooks: - id: black name: black formatter - repo: https://github.com/pre-commit/pre-commit-hooks rev: v4.3.0 hooks: - id: check-yaml - id: check-merge-conflict - id: check-case-conflict - id: trailing-whitespace - id: end-of-file-fixer - id: mixed-line-ending args: ['--fix=lf'] ================================================ FILE: CONTRIBUTING.md ================================================ # Contributing The 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. ## Development Environment Setup To 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. You can refer to the [Installation Section](./README.md#installation) and replace `pip install -v .` with `pip install -v -e .`. ### Code Style We 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. ```shell # these commands are executed under the Open-Sora directory pip install pre-commit pre-commit install ``` Code format checking will be automatically executed when you commit your changes. ## Contribution Guide You 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). ### 1. Fork the Official Repository Firstly, 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`. Now, you can clone your own forked repository into your local environment. ```shell git clone https://github.com//Open-Sora.git ``` ### 2. Configure Git You 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). Then add the original repository as upstream ```shell cd Open-Sora git remote add upstream https://github.com/hpcaitech/Open-Sora.git ``` you can use the following command to verify that the remote is set. You should see both `origin` and `upstream` in the output. ```shell git remote -v ``` ### 3. Synchronize with Official Repository Before 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. ```shell git fetch upstream git checkout main git merge upstream/main git push origin main ``` ### 5. Create a New Branch You 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. ```shell git checkout -b ``` ### 6. Implementation and Code Commit Now 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. You can commit and push the changes to your local repository. The changes should be kept logical, modular and atomic. ```shell git add -A git commit -m "" git push -u origin ``` ### 7. Open a Pull Request You can now create a pull request on the GitHub webpage of your repository. The source branch is `` 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). The Open-Sora team will review your code change and merge your code if applicable. ## FQA 1. `pylint` cannot recognize some members: Add this into your `settings.json` in VSCode: ```json "pylint.args": [ "--generated-members=numpy.* ,torch.*,cv2.*", ], ``` ================================================ FILE: LICENSE ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2024 HPC-AI Technology Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ========================================================================= This project is inspired by the listed projects and is subject to the following licenses: 10. [T5: Text-To-Text Transfer Transformer](https://github.com/google-research/text-to-text-transfer-transformer) Copyright 2019 Google Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. 11. [CLIP](https://github.com/openai/CLIP/tree/main) MIT License Copyright (c) 2021 OpenAI Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 12. [FLUX](https://github.com/black-forest-labs/flux) Copyright 2024 Black Forest Labs Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. 13. [EfficientViT](https://github.com/mit-han-lab/efficientvit) Copyright [2023] [Han Cai] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. 14. [HunyuanVideo](https://github.com/Tencent/HunyuanVideo/tree/main) TENCENT HUNYUAN COMMUNITY LICENSE AGREEMENT Tencent HunyuanVideo Release Date: December 3, 2024 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. 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. 1. DEFINITIONS. a. “Acceptable Use Policy” shall mean the policy made available by Tencent as set forth in the Exhibit A. 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. c. “Documentation” shall mean the specifications, manuals and documentation for Tencent Hunyuan made publicly available by Tencent. d. “Hosted Service” shall mean a hosted service offered via an application programming interface (API), web access, or any other electronic or remote means. 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. f. “Materials” shall mean, collectively, Tencent’s proprietary Tencent Hunyuan and Documentation (and any portion thereof) as made available by Tencent under this Agreement. 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. 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. i. “Tencent,” “We” or “Us” shall mean THL A29 Limited. 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]. k. “Tencent Hunyuan Works” shall mean: (i) the Materials; (ii) Model Derivatives; and (iii) all derivative works thereof. l. “Territory” shall mean the worldwide territory, excluding the territory of the European Union, United Kingdom and South Korea. m. “Third Party” or “Third Parties” shall mean individuals or legal entities that are not under common control with Us or You. n. “including” shall mean including but not limited to. 2. GRANT OF RIGHTS. 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. 3. DISTRIBUTION. 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: 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; b. You must cause any modified files to carry prominent notices stating that You changed the files; 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 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.” 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. 4. ADDITIONAL COMMERCIAL TERMS. 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. 5. RULES OF USE. 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). 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). 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. 6. INTELLECTUAL PROPERTY. 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. 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. 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. d. Tencent claims no rights in Outputs You generate. You and Your users are solely responsible for Outputs and their subsequent uses. 7. DISCLAIMERS OF WARRANTY AND LIMITATIONS OF LIABILITY. 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. 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. 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. 8. SURVIVAL AND TERMINATION. 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. 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. 9. GOVERNING LAW AND JURISDICTION. 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. 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. EXHIBIT A ACCEPTABLE USE POLICY Tencent reserves the right to update this Acceptable Use Policy from time to time. Last modified: November 5, 2024 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: 1. Outside the Territory; 2. In any way that violates any applicable national, federal, state, local, international or any other law or regulation; 3. To harm Yourself or others; 4. To repurpose or distribute output from Tencent Hunyuan or any Model Derivatives to harm Yourself or others; 5. To override or circumvent the safety guardrails and safeguards We have put in place; 6. For the purpose of exploiting, harming or attempting to exploit or harm minors in any way; 7. To generate or disseminate verifiably false information and/or content with the purpose of harming others or influencing elections; 8. To generate or facilitate false online engagement, including fake reviews and other means of fake online engagement; 9. To intentionally defame, disparage or otherwise harass others; 10. To generate and/or disseminate malware (including ransomware) or any other content to be used for the purpose of harming electronic systems; 11. To generate or disseminate personal identifiable information with the purpose of harming others; 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; 13. To impersonate another individual without consent, authorization, or legal right; 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); 15. In a manner that violates or disrespects the social ethics and moral standards of other countries or regions; 16. To perform, facilitate, threaten, incite, plan, promote or encourage violent extremism or terrorism; 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; 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; 19. For military purposes; 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. ================================================ FILE: README.md ================================================

## Open-Sora: Democratizing Efficient Video Production for All We design and implement **Open-Sora**, an initiative dedicated to **efficiently** producing high-quality video. We hope to make the model, tools and all details accessible to all. By embracing **open-source** principles, Open-Sora not only democratizes access to advanced video generation techniques, but also offers a streamlined and user-friendly platform that simplifies the complexities of video generation. With Open-Sora, our goal is to foster innovation, creativity, and inclusivity within the field of content creation. 🎬 For a professional AI video-generation product, try [Video Ocean](https://video-ocean.com/) — powered by a superior model. ## 📰 News - **[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) - **[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) - **[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/) - **[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) - **[2024.04.25]** 🤗 We released the [Gradio demo for Open-Sora](https://huggingface.co/spaces/hpcai-tech/open-sora) on Hugging Face Spaces. - **[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) - **[2024.03.18]** We released **Open-Sora 1.0**, a fully open-source project for video generation. Open-Sora 1.0 supports a full pipeline of video data preprocessing, training with acceleration, inference, and more. Our model can produce 2s 512x512 videos with only 3 days training. [[checkpoints]](#open-sora-10-model-weights) [[blog]](https://hpc-ai.com/blog/open-sora-v1.0) [[report]](/docs/report_01.md) - **[2024.03.04]** Open-Sora provides training with 46% cost reduction. [[blog]](https://hpc-ai.com/blog/open-sora) 📍 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). ## 🎥 Latest Demo Demos 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/). | **5s 1024×576** | **5s 576×1024** | **5s 576×1024** | | -------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | | [](https://streamable.com/e/8g9y9h?autoplay=1) | [](https://streamable.com/e/k50mnv?autoplay=1) | [](https://streamable.com/e/bzrn9n?autoplay=1) | | [](https://streamable.com/e/dsv8da?autoplay=1) | [](https://streamable.com/e/3wif07?autoplay=1) | [](https://streamable.com/e/us2w7h?autoplay=1) | | [](https://streamable.com/e/yfwk8i?autoplay=1) | [](https://streamable.com/e/jgjil0?autoplay=1) | [](https://streamable.com/e/lsoai1?autoplay=1) |
OpenSora 1.3 Demo | **5s 720×1280** | **5s 720×1280** | **5s 720×1280** | | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | [](https://streamable.com/e/r0imrp?quality=highest&autoplay=1) | [](https://streamable.com/e/hfvjkh?quality=highest&autoplay=1) | [](https://streamable.com/e/kutmma?quality=highest&autoplay=1) | | [](https://streamable.com/e/osn1la?quality=highest&autoplay=1) | [](https://streamable.com/e/l1pzws?quality=highest&autoplay=1) | [](https://streamable.com/e/2vqari?quality=highest&autoplay=1) | | [](https://streamable.com/e/1in7d6?quality=highest&autoplay=1) | [](https://streamable.com/e/e9bi4o?quality=highest&autoplay=1) | [](https://streamable.com/e/09z7xi?quality=highest&autoplay=1) | | [](https://streamable.com/e/16c3hk?quality=highest&autoplay=1) | [](https://streamable.com/e/wi250w?quality=highest&autoplay=1) | [](https://streamable.com/e/vw5b64?quality=highest&autoplay=1) |
OpenSora 1.2 Demo | **4s 720×1280** | **4s 720×1280** | **4s 720×1280** | | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | [](https://github.com/hpcaitech/Open-Sora/assets/99191637/7895aab6-ed23-488c-8486-091480c26327) | [](https://github.com/hpcaitech/Open-Sora/assets/99191637/20f07c7b-182b-4562-bbee-f1df74c86c9a) | [](https://github.com/hpcaitech/Open-Sora/assets/99191637/3d897e0d-dc21-453a-b911-b3bda838acc2) | | [](https://github.com/hpcaitech/Open-Sora/assets/99191637/644bf938-96ce-44aa-b797-b3c0b513d64c) | [](https://github.com/hpcaitech/Open-Sora/assets/99191637/272d88ac-4b4a-484d-a665-8d07431671d0) | [](https://github.com/hpcaitech/Open-Sora/assets/99191637/ebbac621-c34e-4bb4-9543-1c34f8989764) | | [](https://github.com/hpcaitech/Open-Sora/assets/99191637/a1e3a1a3-4abd-45f5-8df2-6cced69da4ca) | [](https://github.com/hpcaitech/Open-Sora/assets/99191637/d6ce9c13-28e1-4dff-9644-cc01f5f11926) | [](https://github.com/hpcaitech/Open-Sora/assets/99191637/561978f8-f1b0-4f4d-ae7b-45bec9001b4a) |
OpenSora 1.1 Demo | **2s 240×426** | **2s 240×426** | | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | [](https://github.com/hpcaitech/Open-Sora-dev/assets/99191637/c31ebc52-de39-4a4e-9b1e-9211d45e05b2) | [](https://github.com/hpcaitech/Open-Sora-dev/assets/99191637/c31ebc52-de39-4a4e-9b1e-9211d45e05b2) | | [](https://github.com/hpcaitech/Open-Sora-dev/assets/99191637/f7ce4aaa-528f-40a8-be7a-72e61eaacbbd) | [](https://github.com/hpcaitech/Open-Sora-dev/assets/99191637/5d58d71e-1fda-4d90-9ad3-5f2f7b75c6a9) | | **2s 426×240** | **4s 480×854** | | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | [](https://github.com/hpcaitech/Open-Sora-dev/assets/99191637/34ecb4a0-4eef-4286-ad4c-8e3a87e5a9fd) | [](https://github.com/hpcaitech/Open-Sora-dev/assets/99191637/c1619333-25d7-42ba-a91c-18dbc1870b18) | | **16s 320×320** | **16s 224×448** | **2s 426×240** | | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | [](https://github.com/hpcaitech/Open-Sora/assets/99191637/3cab536e-9b43-4b33-8da8-a0f9cf842ff2) | [](https://github.com/hpcaitech/Open-Sora/assets/99191637/9fb0b9e0-c6f4-4935-b29e-4cac10b373c4) | [](https://github.com/hpcaitech/Open-Sora-dev/assets/99191637/3e892ad2-9543-4049-b005-643a4c1bf3bf) |
OpenSora 1.0 Demo | **2s 512×512** | **2s 512×512** | **2s 512×512** | | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | [](https://github.com/hpcaitech/Open-Sora/assets/99191637/de1963d3-b43b-4e68-a670-bb821ebb6f80) | [](https://github.com/hpcaitech/Open-Sora/assets/99191637/13f8338f-3d42-4b71-8142-d234fbd746cc) | [](https://github.com/hpcaitech/Open-Sora/assets/99191637/fa6a65a6-e32a-4d64-9a9e-eabb0ebb8c16) | | 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. | | [](https://github.com/hpcaitech/Open-Sora/assets/99191637/64232f84-1b36-4750-a6c0-3e610fa9aa94) | [](https://github.com/hpcaitech/Open-Sora/assets/99191637/983a1965-a374-41a7-a76b-c07941a6c1e9) | [](https://github.com/hpcaitech/Open-Sora/assets/99191637/ec10c879-9767-4c31-865f-2e8d6cf11e65) | | 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 [...] | Videos are downsampled to `.gif` for display. Click for original videos. Prompts are trimmed for display, see [here](/assets/texts/t2v_samples.txt) for full prompts.
## 🔆 Reports - **[Tech Report of Open-Sora 2.0](https://arxiv.org/abs/2503.09642v1)** - **[Step by step to train or finetune your own model](docs/train.md)** - **[Step by step to train and evaluate an video autoencoder](docs/ae.md)** - **[Visit the high compression video autoencoder](docs/hcae.md)** - Reports of previous version (better see in according branch): - [Open-Sora 1.3](docs/report_04.md): shift-window attention, unified spatial-temporal VAE, etc. - [Open-Sora 1.2](docs/report_03.md), [Tech Report](https://arxiv.org/abs/2412.20404): rectified flow, 3d-VAE, score condition, evaluation, etc. - [Open-Sora 1.1](docs/report_02.md): multi-resolution/length/aspect-ratio, image/video conditioning/editing, data preprocessing, etc. - [Open-Sora 1.0](docs/report_01.md): architecture, captioning, etc. 📍 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). ## Quickstart ### Installation ```bash # create a virtual env and activate (conda as an example) conda create -n opensora python=3.10 conda activate opensora # download the repo git clone https://github.com/hpcaitech/Open-Sora cd Open-Sora # Ensure torch >= 2.4.0 pip install -v . # for development mode, `pip install -v -e .` pip install xformers==0.0.27.post2 --index-url https://download.pytorch.org/whl/cu121 # install xformers according to your cuda version pip install flash-attn --no-build-isolation ``` Optionally, you can install flash attention 3 for faster speed. ```bash git clone https://github.com/Dao-AILab/flash-attention # 4f0640d5 cd flash-attention/hopper python setup.py install ``` ### Model Download Our 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). Download from huggingface: ```bash pip install "huggingface_hub[cli]" huggingface-cli download hpcai-tech/Open-Sora-v2 --local-dir ./ckpts ``` Download from ModelScope: ```bash pip install modelscope modelscope download hpcai-tech/Open-Sora-v2 --local_dir ./ckpts ``` ### Text-to-Video Generation Our 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: ```bash # Generate one given prompt torchrun --nproc_per_node 1 --standalone scripts/diffusion/inference.py configs/diffusion/inference/t2i2v_256px.py --save-dir samples --prompt "raining, sea" # Save memory with offloading torchrun --nproc_per_node 1 --standalone scripts/diffusion/inference.py configs/diffusion/inference/t2i2v_256px.py --save-dir samples --prompt "raining, sea" --offload True # Generation with csv torchrun --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 ``` For 768x768 resolution: ```bash # One GPU torchrun --nproc_per_node 1 --standalone scripts/diffusion/inference.py configs/diffusion/inference/t2i2v_768px.py --save-dir samples --prompt "raining, sea" # Multi-GPU with colossalai sp torchrun --nproc_per_node 8 --standalone scripts/diffusion/inference.py configs/diffusion/inference/t2i2v_768px.py --save-dir samples --prompt "raining, sea" ``` You 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. You can also run direct text-to-video by: ```bash # One GPU for 256px torchrun --nproc_per_node 1 --standalone scripts/diffusion/inference.py configs/diffusion/inference/256px.py --prompt "raining, sea" # Multi-GPU for 768px torchrun --nproc_per_node 8 --standalone scripts/diffusion/inference.py configs/diffusion/inference/768px.py --prompt "raining, sea" ``` ### Image-to-Video Generation Given a prompt and a reference image, you can generate a video with the following command: ```bash # 256px torchrun --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 # 256px with csv torchrun --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 # Multi-GPU 768px torchrun --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 ``` ## Advanced Usage ### Motion Score During 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): ```bash torchrun --nproc_per_node 1 --standalone scripts/diffusion/inference.py configs/diffusion/inference/t2i2v_256px.py --save-dir samples --prompt "raining, sea" --motion-score 4 ``` We 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: ```bash torchrun --nproc_per_node 1 --standalone scripts/diffusion/inference.py configs/diffusion/inference/t2i2v_256px.py --save-dir samples --prompt "raining, sea" --motion-score dynamic ``` | Score | 1 | 4 | 7 | | ----- | ------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- | | | | | | ### Prompt Refine We 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. ```bash export OPENAI_API_KEY=sk-xxxx torchrun --nproc_per_node 1 --standalone scripts/diffusion/inference.py configs/diffusion/inference/t2i2v_256px.py --save-dir samples --prompt "raining, sea" --refine-prompt True ``` ### Reproductivity To make the results reproducible, you can set the random seed by: ```bash torchrun --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 ``` Use `--num-sample k` to generate `k` samples for each prompt. ## Computational Efficiency We 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)}}$ | Resolution | 1x GPU | 2x GPUs | 4x GPUs | 8x GPUs | | ---------- | -------------------------------------- | ------------------------------------- | ------------------------------------- | ------------------------------------- | | 256x256 | $\color{blue}{60}/\color{red}{52.5}$ | $\color{blue}{40}/\color{red}{44.3}$ | $\color{blue}{34}/\color{red}{44.3}$ | | | 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}$ | ## Evaluation On [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. ![VBench](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/v2_vbench.png) Human preference results show our model is on par with HunyuanVideo 11B and Step-Video 30B. ![Win Rate](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/v2_winrate.png) With strong performance, Open-Sora 2.0 is cost-effective. ![Cost](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/v2_cost.png) ## Contribution Thanks goes to these wonderful contributors: If you wish to contribute to this project, please refer to the [Contribution Guideline](./CONTRIBUTING.md). ## Acknowledgement Here we only list a few of the projects. For other works and datasets, please refer to our report. - [ColossalAI](https://github.com/hpcaitech/ColossalAI): A powerful large model parallel acceleration and optimization system. - [DiT](https://github.com/facebookresearch/DiT): Scalable Diffusion Models with Transformers. - [OpenDiT](https://github.com/NUS-HPC-AI-Lab/OpenDiT): An acceleration for DiT training. We adopt valuable acceleration strategies for training progress from OpenDiT. - [PixArt](https://github.com/PixArt-alpha/PixArt-alpha): An open-source DiT-based text-to-image model. - [Flux](https://github.com/black-forest-labs/flux): A powerful text-to-image generation model. - [Latte](https://github.com/Vchitect/Latte): An attempt to efficiently train DiT for video. - [HunyuanVideo](https://github.com/Tencent/HunyuanVideo/tree/main?tab=readme-ov-file): Open-Source text-to-video model. - [StabilityAI VAE](https://huggingface.co/stabilityai/sd-vae-ft-mse-original): A powerful image VAE model. - [DC-AE](https://github.com/mit-han-lab/efficientvit): Deep Compression AutoEncoder for image compression. - [CLIP](https://github.com/openai/CLIP): A powerful text-image embedding model. - [T5](https://github.com/google-research/text-to-text-transfer-transformer): A powerful text encoder. - [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). - [PLLaVA](https://github.com/magic-research/PLLaVA): A powerful video captioning model. - [MiraData](https://github.com/mira-space/MiraData): A large-scale video dataset with long durations and structured caption. ## Citation ```bibtex @article{opensora, title={Open-sora: Democratizing efficient video production for all}, 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}, journal={arXiv preprint arXiv:2412.20404}, year={2024} } @article{opensora2, title={Open-Sora 2.0: Training a Commercial-Level Video Generation Model in $200k}, 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}, year={2025}, journal={arXiv preprint arXiv:2503.09642}, } ``` ## Star History [![Star History Chart](https://api.star-history.com/svg?repos=hpcaitech/Open-Sora&type=Date)](https://star-history.com/#hpcaitech/Open-Sora&Date) ================================================ FILE: assets/texts/example.csv ================================================ text "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." "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." "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." "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." "A wave of glowing steam crashes into a stone wall, the vapor hissing and swirling as it dissipates." "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." "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." "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." ================================================ FILE: assets/texts/i2v.csv ================================================ text,ref "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 ================================================ FILE: assets/texts/sora.csv ================================================ text "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." "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." "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." "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." "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." "A gorgeously rendered papercraft world of a coral reef, rife with colorful fish and sea creatures." "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." Photorealistic closeup video of two pirate ships battling each other as they sail inside a cup of coffee. "A young man at his 20s is sitting on a piece of cloud in the sky, reading a book." Historical footage of California during the gold rush. A 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. "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" A cartoon kangaroo disco dances. "A beautiful homemade video showing the people of Lagos, Nigeria in the year 2056. Shot with a mobile phone camera." A petri dish with a bamboo forest growing within it that has tiny red pandas running around. "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." "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." "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." Reflections in the window of a train traveling through the Tokyo suburbs. "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." "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." "A flock of paper airplanes flutters through a dense jungle, weaving around trees as if they were migrating birds." "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." Borneo wildlife on the Kinabatangan River A Chinese Lunar New Year celebration video with Chinese Dragon. Tour of an art gallery with many beautiful works of art in different styles. "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." A stop motion animation of a flower growing out of the windowsill of a suburban house. The story of a robot's life in a cyberpunk setting. "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." "A beautiful silhouette animation shows a wolf howling at the moon, feeling lonely, until it finds its pack." "New York City submerged like Atlantis. Fish, whales, sea turtles and sharks swim through the streets of New York." "A litter of golden retriever puppies playing in the snow. Their heads pop out of the snow, covered in." "Step-printing scene of a person running, cinematic film shot in 35mm." "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." Basketball through hoop then explodes. "Archeologists discover a generic plastic chair in the desert, excavating and dusting it with great care." "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." The 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. "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." "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." A corgi vlogging itself in tropical Maui. "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." "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." "Tiltshift of a construction site filled with workers, equipment, and heavy machinery." "A giant, towering cloud in the shape of a man looms over the earth. The cloud man shoots lighting bolts down to the earth." A 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. "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." ================================================ FILE: configs/diffusion/inference/256px.py ================================================ save_dir = "samples" # save directory seed = 42 # random seed (except seed for z) batch_size = 1 dtype = "bf16" cond_type = "t2v" # conditional inference options: # t2v: text-to-video # i2v_head: image-to-video (head) # i2v_tail: image-to-video (tail) # i2v_loop: connect images # v2v_head_half: video extension with first half # v2v_tail_half: video extension with second half dataset = dict(type="text") sampling_option = dict( resolution="256px", # 256px or 768px aspect_ratio="16:9", # 9:16 or 16:9 or 1:1 num_frames=129, # number of frames num_steps=50, # number of steps shift=True, temporal_reduction=4, is_causal_vae=True, guidance=7.5, # guidance for text-to-video guidance_img=3.0, # guidance for image-to-video text_osci=True, # enable text guidance oscillation image_osci=True, # enable image guidance oscillation scale_temporal_osci=True, method="i2v", # hard-coded for now seed=None, # random seed for z ) motion_score = "4" # motion score for video generation fps_save = 24 # fps for video generation and saving # Define model components model = dict( type="flux", from_pretrained="./ckpts/Open_Sora_v2.safetensors", guidance_embed=False, fused_qkv=False, use_liger_rope=True, # model architecture in_channels=64, vec_in_dim=768, context_in_dim=4096, hidden_size=3072, mlp_ratio=4.0, num_heads=24, depth=19, depth_single_blocks=38, axes_dim=[16, 56, 56], theta=10_000, qkv_bias=True, cond_embed=True, ) ae = dict( type="hunyuan_vae", from_pretrained="./ckpts/hunyuan_vae.safetensors", in_channels=3, out_channels=3, layers_per_block=2, latent_channels=16, use_spatial_tiling=True, use_temporal_tiling=False, ) t5 = dict( type="text_embedder", from_pretrained="./ckpts/google/t5-v1_1-xxl", max_length=512, shardformer=True, ) clip = dict( type="text_embedder", from_pretrained="./ckpts/openai/clip-vit-large-patch14", max_length=77, ) ================================================ FILE: configs/diffusion/inference/256px_tp.py ================================================ _base_ = [ # inherit grammer from mmengine "256px.py", "plugins/tp.py", # use tensor parallel ] ================================================ FILE: configs/diffusion/inference/768px.py ================================================ _base_ = [ # inherit grammer from mmengine "256px.py", "plugins/sp.py", # use sequence parallel ] sampling_option = dict( resolution="768px", ) ================================================ FILE: configs/diffusion/inference/high_compression.py ================================================ _base_ = ["t2i2v_768px.py"] # no need for parallelism plugin = None plugin_config = None plugin_ae = None plugin_config_ae = None # model settings patch_size = 1 model = dict( from_pretrained="./ckpts/Open_Sora_v2_Video_DC_AE.safetensors", in_channels=128, cond_embed=True, patch_size=1, ) # AE settings ae = dict( _delete_=True, type="dc_ae", from_scratch=True, model_name="dc-ae-f32t4c128", from_pretrained="./ckpts/F32T4C128_AE.safetensors", use_spatial_tiling=True, use_temporal_tiling=True, spatial_tile_size=256, temporal_tile_size=32, tile_overlap_factor=0.25, ) ae_spatial_compression = 32 sampling_option = dict( num_frames=128, ) ================================================ FILE: configs/diffusion/inference/plugins/sp.py ================================================ plugin = "hybrid" plugin_config = dict( tp_size=1, pp_size=1, sp_size=8, sequence_parallelism_mode="ring_attn", enable_sequence_parallelism=True, static_graph=True, zero_stage=2, overlap_allgather=False, ) plugin_ae = "hybrid" plugin_config_ae = dict( tp_size=8, pp_size=1, sp_size=1, zero_stage=2, overlap_allgather=False, ) ================================================ FILE: configs/diffusion/inference/plugins/t2i2v.py ================================================ use_t2i2v = True # flux configurations img_flux = dict( type="flux", from_pretrained="./ckpts/flux1-dev.safetensors", guidance_embed=True, # model architecture in_channels=64, vec_in_dim=768, context_in_dim=4096, hidden_size=3072, mlp_ratio=4.0, num_heads=24, depth=19, depth_single_blocks=38, axes_dim=[16, 56, 56], theta=10_000, qkv_bias=True, cond_embed=False, # pass i2v & v2v info, for t2v need this layer too but with x_cond and mask all set to 0 ) img_flux_ae = dict( type="autoencoder_2d", from_pretrained="./ckpts/flux1-dev-ae.safetensors", resolution=256, in_channels=3, ch=128, out_ch=3, ch_mult=[1, 2, 4, 4], num_res_blocks=2, z_channels=16, scale_factor=0.3611, shift_factor=0.1159, ) img_resolution = "768px" ================================================ FILE: configs/diffusion/inference/plugins/tp.py ================================================ plugin = "hybrid" plugin_config = dict( tp_size=8, pp_size=1, sp_size=1, zero_stage=2, overlap_allgather=False, ) plugin_ae = "hybrid" plugin_config_ae = dict( tp_size=8, pp_size=1, sp_size=1, zero_stage=2, overlap_allgather=False, ) ================================================ FILE: configs/diffusion/inference/t2i2v_256px.py ================================================ _base_ = [ # inherit grammer from mmengine "256px.py", "plugins/t2i2v.py", ] ================================================ FILE: configs/diffusion/inference/t2i2v_768px.py ================================================ _base_ = [ # inherit grammer from mmengine "768px.py", "plugins/t2i2v.py", ] ================================================ FILE: configs/diffusion/train/demo.py ================================================ _base_ = ["stage1.py"] bucket_config = { "_delete_": True, "256px": { 1: (1.0, 1), 33: (1.0, 1), 97: (1.0, 1), 129: (1.0, 1), }, } ================================================ FILE: configs/diffusion/train/high_compression.py ================================================ _base_ = ["image.py"] bucket_config = { "_delete_": True, "768px": { 1: (1.0, 20), 16: (1.0, 8), 20: (1.0, 8), 24: (1.0, 8), 28: (1.0, 8), 32: (1.0, 8), 36: (1.0, 4), 40: (1.0, 4), 44: (1.0, 4), 48: (1.0, 4), 52: (1.0, 4), 56: (1.0, 4), 60: (1.0, 4), 64: (1.0, 4), 68: (1.0, 3), 72: (1.0, 3), 76: (1.0, 3), 80: (1.0, 3), 84: (1.0, 3), 88: (1.0, 3), 92: (1.0, 3), 96: (1.0, 3), 100: (1.0, 2), 104: (1.0, 2), 108: (1.0, 2), 112: (1.0, 2), 116: (1.0, 2), 120: (1.0, 2), 124: (1.0, 2), 128: (1.0, 2), # 30s }, } condition_config = dict( t2v=1, i2v_head=7, ) grad_ckpt_settings = (100, 100) patch_size = 1 model = dict( from_pretrained=None, grad_ckpt_settings=grad_ckpt_settings, in_channels=128, cond_embed=True, patch_size=patch_size, ) ae = dict( _delete_=True, type="dc_ae", model_name="dc-ae-f32t4c128", from_pretrained="./ckpts/F32T4C128_AE.safetensors", from_scratch=True, scaling_factor=0.493, use_spatial_tiling=True, use_temporal_tiling=True, spatial_tile_size=256, temporal_tile_size=32, tile_overlap_factor=0.25, ) is_causal_vae = False ae_spatial_compression = 32 ckpt_every = 250 lr = 3e-5 optim = dict(lr=lr) ================================================ FILE: configs/diffusion/train/image.py ================================================ # Dataset settings dataset = dict( type="video_text", transform_name="resize_crop", fps_max=24, # the desired fps for training vmaf=True, # load vmaf scores into text ) grad_ckpt_settings = (8, 100) # set the grad checkpoint settings bucket_config = { "256px": {1: (1.0, 50)}, "768px": {1: (0.5, 11)}, "1024px": {1: (0.5, 7)}, } # Define model components model = dict( type="flux", from_pretrained=None, strict_load=False, guidance_embed=False, fused_qkv=False, use_liger_rope=True, grad_ckpt_settings=grad_ckpt_settings, # model architecture in_channels=64, vec_in_dim=768, context_in_dim=4096, hidden_size=3072, mlp_ratio=4.0, num_heads=24, depth=19, depth_single_blocks=38, axes_dim=[16, 56, 56], theta=10_000, qkv_bias=True, ) dropout_ratio = { # probability for dropout text embedding "t5": 0.31622777, "clip": 0.31622777, } ae = dict( type="hunyuan_vae", from_pretrained="./ckpts/hunyuan_vae.safetensors", in_channels=3, out_channels=3, layers_per_block=2, latent_channels=16, use_spatial_tiling=True, use_temporal_tiling=False, ) is_causal_vae = True t5 = dict( type="text_embedder", from_pretrained="google/t5-v1_1-xxl", cache_dir="/mnt/ddn/sora/tmp_load/huggingface/hub/", max_length=512, shardformer=True, ) clip = dict( type="text_embedder", from_pretrained="openai/clip-vit-large-patch14", cache_dir="/mnt/ddn/sora/tmp_load/huggingface/hub/", max_length=77, ) # Optimization settings lr = 1e-5 eps = 1e-15 optim = dict( cls="HybridAdam", lr=lr, eps=eps, weight_decay=0.0, adamw_mode=True, ) warmup_steps = 0 update_warmup_steps = True grad_clip = 1.0 accumulation_steps = 1 ema_decay = None # Acceleration settings prefetch_factor = 2 num_workers = 12 num_bucket_build_workers = 64 dtype = "bf16" plugin = "zero2" grad_checkpoint = True plugin_config = dict( reduce_bucket_size_in_m=128, overlap_allgather=False, ) pin_memory_cache_pre_alloc_numels = [(260 + 20) * 1024 * 1024] * 24 + [ (34 + 20) * 1024 * 1024 ] * 4 async_io = False # Other settings seed = 42 outputs = "outputs" epochs = 1000 log_every = 10 ckpt_every = 100 keep_n_latest = 20 wandb_project = "mmdit" save_master_weights = True load_master_weights = True # For debugging # record_time = True # record_barrier = True ================================================ FILE: configs/diffusion/train/stage1.py ================================================ _base_ = ["image.py"] dataset = dict(memory_efficient=False) # new config grad_ckpt_settings = (8, 100) bucket_config = { "_delete_": True, "256px": { 1: (1.0, 45), 5: (1.0, 12), 9: (1.0, 12), 13: (1.0, 12), 17: (1.0, 12), 21: (1.0, 12), 25: (1.0, 12), 29: (1.0, 12), 33: (1.0, 12), 37: (1.0, 6), 41: (1.0, 6), 45: (1.0, 6), 49: (1.0, 6), 53: (1.0, 6), 57: (1.0, 6), 61: (1.0, 6), 65: (1.0, 6), 69: (1.0, 4), 73: (1.0, 4), 77: (1.0, 4), 81: (1.0, 4), 85: (1.0, 4), 89: (1.0, 4), 93: (1.0, 4), 97: (1.0, 4), 101: (1.0, 3), 105: (1.0, 3), 109: (1.0, 3), 113: (1.0, 3), 117: (1.0, 3), 121: (1.0, 3), 125: (1.0, 3), 129: (1.0, 3), }, "768px": { 1: (0.5, 13), }, "1024px": { 1: (0.5, 7), }, } model = dict(grad_ckpt_settings=grad_ckpt_settings) lr = 5e-5 optim = dict(lr=lr) ckpt_every = 2000 keep_n_latest = 20 ================================================ FILE: configs/diffusion/train/stage1_i2v.py ================================================ _base_ = ["stage1.py"] # Define model components model = dict(cond_embed=True) condition_config = dict( t2v=1, i2v_head=5, # train i2v (image as first frame) with weight 5 i2v_loop=1, # train image connection with weight 1 i2v_tail=1, # train i2v (image as last frame) with weight 1 ) lr = 1e-5 optim = dict(lr=lr) ================================================ FILE: configs/diffusion/train/stage2.py ================================================ _base_ = ["image.py"] # new config grad_ckpt_settings = (100, 100) plugin = "hybrid" plugin_config = dict( tp_size=1, pp_size=1, sp_size=4, sequence_parallelism_mode="ring_attn", enable_sequence_parallelism=True, static_graph=True, zero_stage=2, ) bucket_config = { "_delete_": True, "256px": { 1: (1.0, 130), 5: (1.0, 14), 9: (1.0, 14), 13: (1.0, 14), 17: (1.0, 14), 21: (1.0, 14), 25: (1.0, 14), 29: (1.0, 14), 33: (1.0, 14), 37: (1.0, 10), 41: (1.0, 10), 45: (1.0, 10), 49: (1.0, 10), 53: (1.0, 10), 57: (1.0, 10), 61: (1.0, 10), 65: (1.0, 10), 73: (1.0, 7), 77: (1.0, 7), 81: (1.0, 7), 85: (1.0, 7), 89: (1.0, 7), 93: (1.0, 7), 97: (1.0, 7), 101: (1.0, 6), 105: (1.0, 6), 109: (1.0, 6), 113: (1.0, 6), 117: (1.0, 6), 121: (1.0, 6), 125: (1.0, 6), 129: (1.0, 6), }, "768px": { 1: (1.0, 38), 5: (1.0, 6), 9: (1.0, 6), 13: (1.0, 6), 17: (1.0, 6), 21: (1.0, 6), 25: (1.0, 6), 29: (1.0, 6), 33: (1.0, 6), 37: (1.0, 4), 41: (1.0, 4), 45: (1.0, 4), 49: (1.0, 4), 53: (1.0, 4), 57: (1.0, 4), 61: (1.0, 4), 65: (1.0, 4), 69: (1.0, 3), 73: (1.0, 3), 77: (1.0, 3), 81: (1.0, 3), 85: (1.0, 3), 89: (1.0, 3), 93: (1.0, 3), 97: (1.0, 3), 101: (1.0, 2), 105: (1.0, 2), 109: (1.0, 2), 113: (1.0, 2), 117: (1.0, 2), 121: (1.0, 2), 125: (1.0, 2), 129: (1.0, 2), }, } model = dict(grad_ckpt_settings=grad_ckpt_settings) lr = 5e-5 optim = dict(lr=lr) ckpt_every = 200 keep_n_latest = 20 ================================================ FILE: configs/diffusion/train/stage2_i2v.py ================================================ _base_ = ["stage2.py"] # Define model components model = dict(cond_embed=True) grad_ckpt_buffer_size = 25 * 1024**3 condition_config = dict( t2v=1, i2v_head=5, i2v_loop=1, i2v_tail=1, ) is_causal_vae = True bucket_config = { "_delete_": True, "256px": { 1: (1.0, 195), 5: (1.0, 80), 9: (1.0, 80), 13: (1.0, 80), 17: (1.0, 80), 21: (1.0, 80), 25: (1.0, 80), 29: (1.0, 80), 33: (1.0, 80), 37: (1.0, 40), 41: (1.0, 40), 45: (1.0, 40), 49: (1.0, 40), 53: (1.0, 40), 57: (1.0, 40), 61: (1.0, 40), 65: (1.0, 40), 69: (1.0, 28), 73: (1.0, 28), 77: (1.0, 28), 81: (1.0, 28), 85: (1.0, 28), 89: (1.0, 28), 93: (1.0, 28), 97: (1.0, 28), 101: (1.0, 23), 105: (1.0, 23), 109: (1.0, 23), 113: (1.0, 23), 117: (1.0, 23), 121: (1.0, 23), 125: (1.0, 23), 129: (1.0, 23), }, "768px": { 1: (0.5, 38), 5: (0.5, 10), 9: (0.5, 10), 13: (0.5, 10), 17: (0.5, 10), 21: (0.5, 10), 25: (0.5, 10), 29: (0.5, 10), 33: (0.5, 10), 37: (0.5, 5), 41: (0.5, 5), 45: (0.5, 5), 49: (0.5, 5), 53: (0.5, 5), 57: (0.5, 5), 61: (0.5, 5), 65: (0.5, 5), 69: (0.5, 3), 73: (0.5, 3), 77: (0.5, 3), 81: (0.5, 3), 85: (0.5, 3), 89: (0.5, 3), 93: (0.5, 3), 97: (0.5, 3), 101: (0.5, 2), 105: (0.5, 2), 109: (0.5, 2), 113: (0.5, 2), 117: (0.5, 2), 121: (0.5, 2), 125: (0.5, 2), 129: (0.5, 2), }, } ================================================ FILE: configs/vae/inference/hunyuanvideo_vae.py ================================================ dtype = "bf16" batch_size = 1 seed = 42 save_dir = "samples/hunyuanvideo_vae" plugin = "zero2" dataset = dict( type="video_text", transform_name="resize_crop", fps_max=16, data_path="datasets/pexels_45k_necessary.csv", ) bucket_config = { "512px_ar1:1": {97: (1.0, 1)}, } num_workers = 24 num_bucket_build_workers = 16 prefetch_factor = 4 model = dict( type="hunyuan_vae", from_pretrained="./ckpts/hunyuan_vae.safetensors", in_channels=3, out_channels=3, layers_per_block=2, latent_channels=16, scale_factor=0.476986, shift_factor=0, use_spatial_tiling=True, use_temporal_tiling=True, time_compression_ratio=4, ) ================================================ FILE: configs/vae/inference/video_dc_ae.py ================================================ dtype = "bf16" batch_size = 1 seed = 42 dataset = dict( type="video_text", transform_name="resize_crop", fps_max=16, data_path="datasets/pexels_45k_necessary.csv", ) bucket_config = { "512px_ar1:1": {96: (1.0, 1)}, } model = dict( type="dc_ae", model_name="dc-ae-f32t4c128", from_pretrained="./ckpts/F32T4C128_AE.safetensors", from_scratch=True, use_spatial_tiling=True, use_temporal_tiling=True, spatial_tile_size=256, temporal_tile_size=32, tile_overlap_factor=0.25, ) save_dir = "samples/video_dc_ae" num_workers = 24 num_bucket_build_workers = 16 prefetch_factor = 4 ================================================ FILE: configs/vae/train/video_dc_ae.py ================================================ # ============ # model config # ============ model = dict( type="dc_ae", model_name="dc-ae-f32t4c128", from_scratch=True, from_pretrained=None, ) # ============ # data config # ============ dataset = dict( type="video_text", transform_name="resize_crop", data_path="datasets/pexels_45k_necessary.csv", fps_max=24, ) bucket_config = { "256px_ar1:1": {32: (1.0, 1)}, } num_bucket_build_workers = 64 num_workers = 12 prefetch_factor = 2 # ============ # train config # ============ optim = dict( cls="HybridAdam", lr=5e-5, eps=1e-8, weight_decay=0.0, adamw_mode=True, betas=(0.9, 0.98), ) lr_scheduler = dict(warmup_steps=0) mixed_strategy = "mixed_video_image" mixed_image_ratio = 0.2 # 1:4 dtype = "bf16" plugin = "zero2" plugin_config = dict( reduce_bucket_size_in_m=128, overlap_allgather=False, ) grad_clip = 1.0 grad_checkpoint = False pin_memory_cache_pre_alloc_numels = [50 * 1024 * 1024] * num_workers * prefetch_factor seed = 42 outputs = "outputs" epochs = 100 log_every = 10 ckpt_every = 3000 keep_n_latest = 50 ema_decay = 0.99 wandb_project = "dcae" update_warmup_steps = True # ============ # loss config # ============ vae_loss_config = dict( perceptual_loss_weight=0.5, kl_loss_weight=0, ) ================================================ FILE: configs/vae/train/video_dc_ae_disc.py ================================================ _base_ = ["video_dc_ae.py"] discriminator = dict( type="N_Layer_discriminator_3D", from_pretrained=None, input_nc=3, n_layers=5, conv_cls="conv3d" ) disc_lr_scheduler = dict(warmup_steps=0) gen_loss_config = dict( gen_start=0, disc_weight=0.05, ) disc_loss_config = dict( disc_start=0, disc_loss_type="hinge", ) optim_discriminator = dict( cls="HybridAdam", lr=1e-4, eps=1e-8, weight_decay=0.0, adamw_mode=True, betas=(0.9, 0.98), ) grad_checkpoint = True model = dict( disc_off_grad_ckpt = True, # set to true if your `grad_checkpoint` is True ) ================================================ FILE: docs/ae.md ================================================ # Step by step to train and evaluate an video autoencoder (AE) Inspired 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. Thus, 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. ## Data Preparation Follow this [guide](./train.md#prepare-dataset) to prepare the __DATASET__ for training and inference. You may use our provided dataset or custom ones. To use custom dataset, pass the argument `--dataset.data_path ` to the following training or inference command. ## Training We train our __Video DC-AE__ from scratch on 8xGPUs for 3 weeks. We first train with the following command: ```bash torchrun --nproc_per_node 8 scripts/vae/train.py configs/vae/train/video_dc_ae.py ``` When the model is almost converged, we add a discriminator and continue to train the model with the checkpoint `model_ckpt` using the following command: ```bash torchrun --nproc_per_node 8 scripts/vae/train.py configs/vae/train/video_dc_ae_disc.py --model.from_pretrained ``` You may pass the flag `--wandb True` if you have a [wandb](https://wandb.ai/home) account and wish to track the training progress online. ## Inference Download 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 `. ### Video DC-AE Use the following code to reconstruct the videos using our trained `Video DC-AE`: ```bash torchrun --nproc_per_node 1 --standalone scripts/vae/inference.py configs/vae/inference/video_dc_ae.py --save-dir samples/dcae ``` ### Hunyuan Video Alternatively, we have incorporated [HunyuanVideo vae](https://github.com/Tencent/HunyuanVideo) into our code, you may run inference with the following command: ```bash torchrun --nproc_per_node 1 --standalone scripts/vae/inference.py configs/vae/inference/hunyuanvideo_vae.py --save-dir samples/hunyuanvideo_vae ``` ## Config Interpretation All AE configs are located in `configs/vae/`, divided into configs for training (`configs/vae/train`) and for inference (`configs/vae/inference`). ### Training Config For training, the same config rules as [those](./train.md#config) for the diffusion model are applied.
Loss Config Our __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*. Experimentally, we found that setting a ratio of 0.5 for the perceptual loss is effective. ```python vae_loss_config = dict( perceptual_loss_weight=0.5, # weigh the perceptual loss by 0.5 kl_loss_weight=0, # no KL loss ) ``` In 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: ```python gen_loss_config = dict( gen_start=0, # include generator loss from step 0 onwards disc_weight=0.05, # weigh the loss by 0.05 ) ``` The discriminator we use is trained from scratch, and it's loss is simply the hinged loss: ```python disc_loss_config = dict( disc_start=0, # update the discriminator from step 0 onwards disc_loss_type="hinge", # the discriminator loss type ) ```
Data Bucket Config For the data bucket, we used 32 frames of 256px videos to train our AE. ```python bucket_config = { "256px_ar1:1": {32: (1.0, 1)}, } ```
Train with more frames or higher resolutions If 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). You may increase the video frames to 96 (although multiples of 4 works, we generally recommend to use frame numbers of multiples of 32): ```python bucket_config = { "256px_ar1:1": {96: (1.0, 1)}, } grad_checkpoint = True ``` or train for higher resolution such as 512px: ```python bucket_config = { "512px_ar1:1": {32: (1.0, 1)}, } grad_checkpoint = True ``` Note that gradient checkpoint needs to be turned on in order to avoid prevent OOM error. Moreover, 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: ```python grad_checkpoint = True model = dict( disc_off_grad_ckpt = True, # set to true if your `grad_checkpoint` is True ) ``` This is to make sure the discriminator loss will have a gradient at the laster later during adaptive loss calculation.
### Inference Config For AE inference, we have replicated the tiling mechanism in hunyuan to our Video DC-AE, which can be turned on with the following: ```python model = dict( ..., use_spatial_tiling=True, use_temporal_tiling=True, spatial_tile_size=256, temporal_tile_size=32, tile_overlap_factor=0.25, ..., ) ``` By default, both spatial tiling and temporal tiling are turned on for the best performance. Since 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. If you train your own Video DC-AE with other resolutions and length, you may adjust the values accordingly. You can specify the directory to store output samples with `--save_dir ` or setting it in config, for instance: ```python save_dir = "./samples" ``` ================================================ FILE: docs/hcae.md ================================================ # 10× inference speedup with high-compression autoencoder The high computational cost of training video generation models arises from the large number of tokens and the dominance of attention computation. To further reduce training expenses, we 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__: ![opensorav2_speed](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/hcae_opensorav2_speed.png) Nevertheless, 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 relationships. We release this model to the research community for further exploration. Checkout more details in our [report](https://arxiv.org/abs/2503.09642v1). ## Model Download Download from 🤗 [Huggingface](https://huggingface.co/hpcai-tech/Open-Sora-v2-Video-DC-AE): ```bash pip install "huggingface_hub[cli]" huggingface-cli download hpcai-tech/Open-Sora-v2-Video-DC-AE --local-dir ./ckpts ``` ## Inference To inference on our fast video generation model: ```bash torchrun --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." ``` ## Training Follow this [guide](./train.md#prepare-dataset) to parepare the __DATASET__ for training. Then, you may train your own fast generation model with the following command: ```bash torchrun --nproc_per_node 8 scripts/diffusion/train.py configs/diffusion/train/high_compression.py --dataset.data-path datasets/pexels_45k_necessary.csv ``` ================================================ FILE: docs/report_01.md ================================================ # Open-Sora 1.0 Report OpenAI'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. ## Efficiency in choosing the architecture To 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. The 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). As 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). ![Architecture Comparison](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/report_arch_comp.png) To 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. ![Architecture](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/report_arch.jpg) Drawing 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. We 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. ## Data is the key to high quality We 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. ![Caption](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/report_caption.png) As 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. ## Training Details With 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. ## Loss curves 16x256x256 Pretraining Loss Curve ![16x256x256 Pretraining Loss Curve](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/report_loss_curve_1.png) 16x256x256 HQ Training Loss Curve ![16x256x256 HQ Training Loss Curve](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/report_loss_curve_2.png) 16x512x512 HQ Training Loss Curve ![16x512x512 HQ Training Loss Curve](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/report_loss_curve_3.png) > Core Contributor: Zangwei Zheng*, Xiangyu Peng*, Shenggui Li, Hongxing Liu, Yang You ================================================ FILE: docs/report_02.md ================================================ # Open-Sora 1.1 Report - [Model Architecture Modification](#model-architecture-modification) - [Support for Multi-time/resolution/aspect ratio/fps Training](#support-for-multi-timeresolutionaspect-ratiofps-training) - [Masked DiT as Image/Video-to-Video Model](#masked-dit-as-imagevideo-to-video-model) - [Data Collection \& Pipeline](#data-collection--pipeline) - [Training Details](#training-details) - [Limitation and Future Work](#limitation-and-future-work) In 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): - Variable durations, resolutions, aspect ratios (Sampling flexibility, Improved framing and composition) - Prompting with images and videos (Animating images, Extending generated videos, Video-to-video editing, Connecting videos) - Image generation capabilities To 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. ## Model Architecture Modification We made the following modifications to the original ST-DiT for better training stability and performance (ST-DiT-2): - **[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. - **AdaIN and Layernorm for temporal attention**: we wrap the temporal attention with AdaIN and layernorm as the spatial attention to stabilize the training. - **[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. - **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. - **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. ## Support for Multi-time/resolution/aspect ratio/fps Training As 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: - [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. - 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. - 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. For 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.
View the concerns - 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. - 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. - 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. - 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.
![bucket](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/report_bucket.png) As 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. Considering 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. A detailed explanation of the bucket usage in training is available in [docs/config.md](/docs/config.md#training-bucket-configs). ## Masked DiT as Image/Video-to-Video Model Transformers 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. ![mask strategy](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/report_mask.png) Typically, 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. Inspired 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. An 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). ![mask strategy config](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/report_mask_config.png) A detailed explanation of the mask strategy usage is available in [docs/config.md](/docs/config.md#advanced-inference-config). ## Data Collection & Pipeline As 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). ![pipeline](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/report_data_pipeline.png) We 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). Image text tokens (by T5 tokenizer): ![image text tokens](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/report_image_textlen.png) Video 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. ![video text tokens](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/report_video_textlen.png) Video duration: ![video duration](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/report_video_duration.png) ## Training Details With 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. 1. 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. 2. **[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%. 3. **[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. 4. **[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**. 5. **[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. 6. **[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. To summarize, the training of Open-Sora 1.1 requires approximately **9 days** on 64 H800 GPUs. ## Limitation and Future Work As 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. - **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. - **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. - **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. - **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. - **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. - **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. > - **Algorithm & Acceleration**: Zangwei Zheng, Xiangyu Peng, Shenggui Li, Hongxing Liu, Yukun Zhou, Tianyi Li > - **Data Collection & Pipeline**: Xiangyu Peng, Zangwei Zheng, Chenhui Shen, Tom Young, Junjie Wang, Chenfeng Yu ================================================ FILE: docs/report_03.md ================================================ # Open-Sora 1.2 Report - [Video compression network](#video-compression-network) - [Rectified flow and model adaptation](#rectified-flow-and-model-adaptation) - [More data and better multi-stage training](#more-data-and-better-multi-stage-training) - [Easy and effective model conditioning](#easy-and-effective-model-conditioning) - [Evaluation](#evaluation) - [Sequence parallelism](#sequence-parallelism) In 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. | | image | 2s | 4s | 8s | 16s | | ---- | ----- | --- | --- | --- | --- | | 240p | ✅ | ✅ | ✅ | ✅ | ✅ | | 360p | ✅ | ✅ | ✅ | ✅ | ✅ | | 480p | ✅ | ✅ | ✅ | ✅ | 🆗 | | 720p | ✅ | ✅ | ✅ | 🆗 | 🆗 | Here ✅ 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. Besides features introduced in Open-Sora 1.1, Open-Sora 1.2 highlights: - Video compression network - Rectifie-flow training - More data and better multi-stage training - Easy and effective model conditioning - Better evaluation metrics All 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. ## Video compression network For 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. Considering 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: ![video_compression_network](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/report_3d_vae.png) We 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. Our training involves three stages: 1. 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. 2. For the next 260k steps, We remove the identity loss and just learn the 3D VAE. 3. 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. For 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. When 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). | Model | SSIM↑ | PSNR↑ | | ------------------ | ----- | ------ | | Open-Sora-Plan 1.1 | 0.882 | 29.890 | | Open-Sora 1.2 | 0.880 | 30.590 | ## Rectified flow and model adaptation Lastest 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: - Basic rectified flow training ([original rectified flow paper](https://arxiv.org/abs/2209.03003)) - 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) - 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) For 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. Open-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): 1. Multi-resolution image generation ability: we train the model to generate different resolution ranging from 144p to 2K for 20k steps. 2. QK-norm: we add the QK-norm to the model and train for 18k steps. 3. Rectified flow: we transform from discrete-time DDPM to continuous-time rectified flow and train for 10k steps. 4. Rectified flow with logit-norm sampling and resolution-aware timestep sampling: we train for 33k steps. 5. Smaller AdamW epsilon: following SD3, with QK-norm, we can use a smaller epsilon (1e-15) for AdamW, we train for 8k steps. 6. 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. 7. Temporal attention blocks: we add temporal attention blocks with zero initialized projection layers. We train on images for 3k steps. 8. Temporal blocks only for video with mask strategy: we train the temporal attention blocks only on videos for 38k steps. After 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: - 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. - With qk-norm, the training is more stablized and an aggressive optimizer can be used. - With new VAE, the temporal dimension is compressed by 4 times, which makes the training more efficient. - With multi-resolution image generation ability, the model can generate videos with different resolutions. ## More data and better multi-stage training Due 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. ### First stage We 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). ### Second stage Then 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). The 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. ### Third stage In this stage, we collect ~2M video clips with a total length of 5K hours from all kinds of sources, including: - Free-license videos, sourced from Pexels, Pixabay, Mixkit, etc. - [MiraData](https://github.com/mira-space/MiraData): a high-quality dataset with long videos, mainly from games and city/scenic exploration. - [Vript](https://github.com/mutonix/Vript/tree/main): a densely annotated dataset. - And some other datasets. While 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. Some 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. We also extract tags for objects and actions from video captions and count their frequencies. ![stats](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/report-03_video_stats.png) ![object_count](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/report-03_objects_count.png) ![object_count](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/report-03_actions_count.png) We 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. ## Easy and effective model conditioning For 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. For example, a video with aesthetic score 5.5, motion score 10, and a detected camera motion pan left, the caption will be: ```plaintext [Original Caption] aesthetic score: 5.5, motion score: 10, camera motion: pan left. ``` During 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. ## Evaluation Previously, 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. We 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. ![Evaluation Loss](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/report_val_loss.png) ![Video Evaluation Loss](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/report_vid_val_loss.png) In 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. ![VBench](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/report_vbench_score.png) All the evaluation code is released in `eval` folder. Check the [README](/eval/README.md) for more details. | Model | Total Score | Quality Score | Semantic Score | | -------------- | ----------- | ------------- | -------------- | | Open-Sora V1.0 | 75.91% | 78.81% | 64.28% | | Open-Sora V1.2 | 79.23% | 80.71% | 73.30% | ## Sequence parallelism We 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. ![SP](..https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/sequence_parallelism.jpeg) Currently, 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 | Resolution | Seconds | Number of GPUs | Enable SP | Time taken/s | Speedup per GPU | | ---------- | ------- | -------------- | --------- | ------------ | --------------- | | 720p | 16s | 1 | No | 547.97 | - | | 720p | 16s | 2 | Yes | 244.38 | 12% | ================================================ FILE: docs/report_04.md ================================================ # Open-Sora 1.3 Report - [Video compression network](#video-compression-network) - [Upgraded STDiT with shifted-window attention](#upgraded-stdit-with-shifted-window-attention) - [Easy and effective model conditioning](#easy-and-effective-model-conditioning) - [Evaluation](#evaluation) In 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. | | image | 49 frames | 65 frames | 81 frames | 97 frames | 113 frames | | ---- | ----- | ---------- | ---------- | ---------- | --------- | ---------- | | 360p | ✅ | ✅ | ✅ | ✅ | ✅ |✅ | | 720p | ✅ | ✅ | ✅ | ✅ | ✅ |✅ | Here ✅ means that the data is seen during training. Besides features introduced in Open-Sora 1.2, Open-Sora 1.3 highlights: - Video compression network - Upgraded STDiT with shifted-window attention - More data and better multi-stage training - Easy and effective model conditioning - Better evaluation metrics All 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. ## Video compression network In 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. Open-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: **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. **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. **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. **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. #### Summary of Improvements | Feature | Open-Sora 1.2 | Open-Sora 1.3 | |------------------------|-----------------------------------------|-----------------------------------------| | **Architecture** | Separate spatial and temporal VAEs | Unified spatial-temporal VAE | | **Tiled Processing** | Not supported | Supported (Tiled 3D Convolutions) | | **Frame Length Support**| Fixed (17 frames) | Dynamic frame support with overlap | | **Normalization** | Fixed parameters | Tunable scaling and shifting | ## Upgraded STDiT with shifted-window attention Following 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. Latest 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: 1. Basic rectified flow training, which enables continuous-time diffusion 2. Logit-norm sampling for training acceleration (following SD3 paper Section 3.1), preferentially sampling timesteps at middle noise levels 3. Resolution and video length aware timestep sampling (following SD3 paper Section 5.3.2), using more noise for larger resolutions and longer videos For OpenSora 1.3, we further enhance the model with significant improvements in architecture, capabilities, and performance: #### 1. Shift-Window Attention Mechanism - Introduced kernel-based local attention with configurable kernel_size for efficient computation - Implemented shift-window partitioning strategy similar to Swin Transformer - Added padding mask handling for window boundaries with extra_pad_on_dims support - Extended position encoding with 3D relative positions within local windows (temporal, height, width) #### 2. Enhanced Position Encoding - Improved RoPE implementation with reduced rotation_dim (1/3 of original) for 3D scenarios - Added separate rotary embeddings for temporal, height, and width dimensions - Implemented resolution-adaptive scaling for position encodings - Optional spatial RoPE for better spatial relationship modeling #### 3. Flexible Generation - Added I2V and V2V capabilities with dedicated conditioning mechanisms - Introduced conditional embedding modules (x_embedder_cond and x_embedder_cond_mask) - Zero-initialized condition embeddings for stable training - Flexible temporal modeling with skip_temporal option #### 4. Performance Optimization - Refined Flash Attention triggering conditions (N > 128) for better efficiency - Added support for torch.scaled_dot_product_attention (SDPA) as an alternative backend - Optimized memory usage through improved padding and window partitioning - Enhanced sequence parallelism with adaptive height padding The adaptation process from [PixArt-Σ 2K](https://github.com/PixArt-alpha/PixArt-sigma) remains similar but with additional steps: 1-7. [Same as v1.2: multi-resolution training, QK-norm, rectified flow, logit-norm sampling, smaller AdamW epsilon, new VAE, and basic temporal attention] #### 8. Enhanced temporal blocks - Added kernel-based local attention with shift-window support - Implemented 3D relative position encoding with resolution-adaptive scaling - Zero-initialized projection layers with improved initialization strategy Compared 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 These 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. ## Easy and effective model conditioning We 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. For example, a video with aesthetic score 5.5, motion score 10, and a detected camera motion pan left, the caption will be: ```plaintext [Original Caption] The aesthetic score is good, the motion strength is high, camera motion: pan left. ``` During 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. ## Evaluation Previously, 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. We 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. In 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. All the evaluation code is released in `eval` folder. Check the [README](/eval/README.md) for more details. ================================================ FILE: docs/train.md ================================================ # Step by step to train or finetune your own model ## Installation Besides from the installation in the main page, you need to install the following packages: ```bash pip install git+https://github.com/hpcaitech/TensorNVMe.git # requires cmake, for checkpoint saving pip install pandarallel # for parallel processing ``` ## Prepare dataset The 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/). First, download the dataset to your local machine: ```bash mkdir datasets cd datasets # For Chinese users, export HF_ENDPOINT=https://hf-mirror.com to speed up the download huggingface-cli download --repo-type dataset hpcai-tech/open-sora-pexels-45k --local-dir open-sora-pexels-45k # 250GB cd open-sora-pexels-45k cat tar/pexels_45k.tar.* > pexels_45k.tar tar -xvf pexels_45k.tar mv pexels_45k .. # make sure the path is Open-Sora/datasets/pexels_45k ``` There are three `csv` files provided: - `pexels_45k.csv`: contains only path and text, which needs to be processed for training. - `pexels_45k_necessary.csv`: contains necessary information for training. - `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. If you want to use custom dataset, at least the following columns are required: ```csv path,text,num_frames,height,width,aspect_ratio,resolution,fps ``` We provide a script to process the `pexels_45k.csv` to `pexels_45k_necessary.csv`: ```bash # single process python scripts/cnv/meta.py --input datasets/pexels_45k.csv --output datasets/pexels_45k_nec.csv --num_workers 0 # parallel process python scripts/cnv/meta.py --input datasets/pexels_45k.csv --output datasets/pexels_45k_nec.csv --num_workers 64 ``` > 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. ## Training The command format to launch training is as follows: ```bash torchrun --nproc_per_node 8 scripts/diffusion/train.py [path/to/config] --dataset.data-path [path/to/dataset] [override options] ``` For example, to train a model with stage 1 config from scratch using pexels dataset: ```bash torchrun --nproc_per_node 8 scripts/diffusion/train.py configs/diffusion/train/stage1.py --dataset.data-path datasets/pexels_45k_necessary.csv ``` ### Config All configs are located in `configs/diffusion/train/`. The following rules are applied: - `_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. - 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`. The `bucket_config` is used to control different training stages. It is a dictionary of dictionaries. The tuple means (sampling probability, batch size). For example: ```python bucket_config = { "256px": { 1: (1.0, 45), # for 256px images, use 100% of the data with batch size 45 33: (1.0, 12), # for 256px videos with no less than 33 frames, use 100% of the data with batch size 12 65: (1.0, 6), # for 256px videos with no less than 65 frames, use 100% of the data with batch size 6 97: (1.0, 4), # for 256px videos with no less than 97 frames, use 100% of the data with batch size 4 129: (1.0, 3), # for 256px videos with no less than 129 frames, use 100% of the data with batch size 3 }, "768px": { 1: (0.5, 13), # for 768px images, use 50% of the data with batch size 13 }, "1024px": { 1: (0.5, 7), # for 1024px images, use 50% of the data with batch size 7 }, } ``` We provide the following configs, the batch size is searched on H200 GPUs with 140GB memory: - `image.py`: train on images only. - `stage1.py`: train on videos with 256px resolution. - `stage2.py`: train on videos with 768px resolution with sequence parallelism (default 4). - `stage1_i2v.py`: train t2v and i2v with 256px resolution. - `stage2_i2v.py`: train t2v and i2v with 768px resolution. We also provide a demo config `demo.py` with small batch size for debugging. ### Fine-tuning To finetune from Open-Sora v2, run: ```bash torchrun --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 ``` To 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: ```bash torchrun --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 ``` ### Multi-GPU To train on multiple GPUs, use `colossalai run`: ```bash colossalai 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 ``` `hostfiles` is a file that contains the IP addresses of the nodes. For example: ```bash xxx.xxx.xxx.xxx yyy.yyy.yyy.yyy zzz.zzz.zzz.zzz ``` use `--wandb True` to log the training process to [wandb](https://wandb.ai/). ### Resume training To resume training, use `--load`. It will load the optimizer state and dataloader state. ```bash torchrun --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* ``` If you want to load optimzer state but not dataloader state, use: ```bash torchrun --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 ``` > Note if dataset, batch size, and number of GPUs are changed, the dataloader state will not be meaningful. ## Inference The inference is the same as described in the main page. The command format is as follows: ```bash torchrun --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* ``` ## Advanced Usage More details are provided in the tech report. If explanation for some techiques is needed, feel free to open an issue. - Tensor parallelism and sequence parallelism - Zero 2 - Pin memory organization - Garbage collection organization - Data prefetching - Communication bucket optimization - Shardformer for T5 ### Gradient Checkpointing We 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. ```python grad_ckpt_setting = (100, 100) model = dict( grad_ckpt_setting=grad_ckpt_setting, ) ``` To further save memory, you can offload gradient checkpointing to CPU by: ```python grad_ckpt_buffer_size = 25 * 1024**3 # 25GB ``` ### Asynchronous Checkpoint Saving With `--async-io True`, the checkpoint will be saved asynchronously with the support of ColossalAI. This will save time for checkpoint saving. ### Dataset With 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: ```bash python scripts/cnv/shard.py /path/to/dataset.parquet ``` Then a folder with shards will be created. You can use the `--dataset.memory_efficient True` to load the dataset shard by shard. ================================================ FILE: docs/zh_CN/report_v1.md ================================================ # Open-Sora v1 技术报告 OpenAI的Sora在生成一分钟高质量视频方面非常出色。然而,它几乎没有透露任何关于其细节的信息。为了使人工智能更加“开放”,我们致力于构建一个开源版本的Sora。这份报告描述了我们第一次尝试训练一个基于Transformer的视频扩散模型。 ## 选择高效的架构 为了降低计算成本,我们希望利用现有的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))。 视频训练涉及大量的token。考虑到24fps的1分钟视频,我们有1440帧。通过VAE下采样4倍和patch大小下采样2倍,我们得到了1440x1024≈150万个token。在150万个token上进行全注意力计算将带来巨大的计算成本。因此,我们使用时空注意力来降低成本,这是遵循[Latte](https://github.com/Vchitect/Latte)的方法。 如图中所示,在STDiT(ST代表时空)中,我们在每个空间注意力之后立即插入一个时间注意力。这类似于Latte论文中的变种3。然而,我们并没有控制这些变体的相似数量的参数。虽然Latte的论文声称他们的变体比变种3更好,但我们在16x256x256视频上的实验表明,相同数量的迭代次数下,性能排名为:DiT(完整)> STDiT(顺序)> STDiT(并行)≈ Latte。因此,我们出于效率考虑选择了STDiT(顺序)。[这里](/docs/acceleration.md#efficient-stdit)提供了速度基准测试。 ![Architecture Comparison](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/report_arch_comp.png) 为了专注于视频生成,我们希望基于一个强大的图像生成模型来训练我们的模型。PixArt-α是一个经过高效训练的高质量图像生成模型,具有T5条件化的DiT结构。我们使用[PixArt-α](https://github.com/PixArt-alpha/PixArt-alpha)初始化我们的模型,并将插入的时间注意力的投影层初始化为零。这种初始化在开始时保留了模型的图像生成能力,而Latte的架构则不能。插入的注意力将参数数量从5.8亿增加到7.24亿。 ![Architecture](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/report_arch.jpg) 借鉴PixArt-α和Stable Video Diffusion的成功,我们还采用了渐进式训练策略:在366K预训练数据集上进行16x256x256的训练,然后在20K数据集上进行16x256x256、16x512x512和64x512x512的训练。通过扩展位置嵌入,这一策略极大地降低了计算成本。 我们还尝试在DiT中使用3D patch嵌入器。然而,在时间维度上2倍下采样后,生成的视频质量较低。因此,我们将在下一版本中将下采样留给时间VAE。目前,我们在每3帧采样一次进行16帧训练,以及在每2帧采样一次进行64帧训练。 ## 数据是训练高质量模型的核心 我们发现数据的数量和质量对生成视频的质量有很大的影响,甚至比模型架构和训练策略的影响还要大。目前,我们只从[HD-VG-130M](https://github.com/daooshee/HD-VG-130M)准备了第一批分割(366K个视频片段)。这些视频的质量参差不齐,而且字幕也不够准确。因此,我们进一步从提供免费许可视频的[Pexels](https://www.pexels.com/)收集了20k相对高质量的视频。我们使用LLaVA,一个图像字幕模型,通过三个帧和一个设计好的提示来标记视频。有了设计好的提示,LLaVA能够生成高质量的字幕。 ![Caption](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/report_caption.png) 由于我们更加注重数据质量,我们准备收集更多数据,并在下一版本中构建一个视频预处理流程。 ## 训练细节 在有限的训练预算下,我们只进行了一些探索。我们发现学习率1e-4过大,因此将其降低到2e-5。在进行大批量训练时,我们发现`fp16`比`bf16`不太稳定,可能会导致生成失败。因此,我们在64x512x512的训练中切换到`bf16`。对于其他超参数,我们遵循了之前的研究工作。 ## 损失曲线 16x256x256 预训练损失曲线 ![16x256x256 Pretraining Loss Curve](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/report_loss_curve_1.png) 16x256x256 高质量训练损失曲线 ![16x256x256 HQ Training Loss Curve](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/report_loss_curve_2.png) 16x512x512 高质量训练损失曲线 ![16x512x512 HQ Training Loss Curve](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/report_loss_curve_3.png) ================================================ FILE: docs/zh_CN/report_v2.md ================================================ # Open-Sora 1.1 技术报告 - [模型架构修改](#模型架构修改) - [支持不同视频长度/分辨率/宽高比/帧率(fps)训练](#支持不同视频长度分辨率宽高比帧率fps训练) - [使用Masked DiT作为图生视频/视频生视频模型](#使用masked-dit作为图生视频视频生视频模型) - [数据收集和流程](#数据收集和流程) - [训练详情](#训练详情) - [结果和评价](#结果和评价) - [不足和下一步计划](#不足和下一步计划) 在Open-Sora1.1版本中,我们使用了10M数据来训练经过结构调优后的STDiT的700M模型(Open-Sora1.0版本仅用400K数据)。我们实现了[Sora报告](https://openai.com/research/video-generation-models-as-world-simulators)中提到的以下功能: - 可变的视频时长、分辨率、宽高比(包括采样灵活性、改进的取景范围和构图) - 提示词增加图片和视频选项(使图像动起来、生成式增长视频、视频到视频编辑、连接不同视频) - 图像生成功能 为了实现这一目标,我们在预训练阶段使用了多任务学习。对于扩散模型来说,用不同的采样时间步长进行训练已经是一种多任务学习。我们将这一思想在图像和视频的条件生成模型上,进一步扩展到多分辨率、宽高比、帧长、fps以及不同的掩码策略。我们在**0~15s、144p到720p、各种宽高比的视频**上训练模型。虽然由于训练FLOPs不足的限制,生成的视频在时间一致性上的表现没有那么高,但我们仍然可以看到这个模型的巨大潜力。 ## 模型架构修改 我们对原始ST-DiT模型进行了以下修改,以获得更好的训练稳定性和模型性能(ST-DiT-2): - **在时间注意力模块中添加[旋转位置编码](https://arxiv.org/abs/2104.09864)**:遵循目前LLM的最佳实践,我们将时间注意力模块中的正弦位置编码更改为旋转位置编码,因为它也算一项序列预测任务。 - **在时间注意力模块中添加AdaIN和Layernormal**:我们将时间注意力与AdaIN和Layer范数作为空间注意力包裹起来,以稳定训练。 - **[QK归一化](https://arxiv.org/abs/2302.05442)与[RMSNorm](https://arxiv.org/abs/1910.07467)**:和[SD3](https://arxiv.org/pdf/2403.03206.pdf)类似地,我们应用QK归一化来提高半精度训练的稳定性。 - **支持动态输入大小和视频条件限定**:为了支持多分辨率、宽高比和fps训练,我们ST-DiT-2来接受任何输入大小。延申[PixArt-alpha](https://github.com/PixArt-alpha/PixArt-alpha)的想法,我们支持限定视频的高度、宽度、宽高比、帧长和fps。 - **将T5token数量从120扩展到200**:我们使用的视频描述通常少于200个token,我们发现模型也可以很好地处理更长的文本。 ## 支持不同视频长度/分辨率/宽高比/帧率(fps)训练 正如[Sora报告](https://openai.com/research/video-generation-models-as-world-simulators)中提到的,使用原始无损视频的分辨率、宽高比和视频长度进行训练可以增加采样灵活性,改善取景和构图。我们找到了三种实现这一目标的方法: - [NaViT](https://arxiv.org/abs/2307.06304):通过不同掩码策略支持在同一训练批次内使用不同大小的数据,并且训练效率下降很少。然而,该系统实现起来有点复杂,并且可能无法兼容kernal优化技术(如flashattention)。 - 填充([FiT](https://arxiv.org/abs/2402.12376),[Open-Sora-Plan](https://github.com/PKU-YuanGroup/Open-Sora-Plan)):通过填充支持同一批次内的不同大小的数据。然而,将不同的分辨率填充到相同的大小会导致效率降低。 - 分桶训练([SDXL](https://arxiv.org/abs/2307.01952)、[PixArt](https://arxiv.org/abs/2310.00426)):支持通过分桶的方式在不同批次中动态调整大小,但在同一批次内数据大小必须相同,只能应用固定数量的数据大小。在一个批次中,我们不需要实现复杂的掩码或填充。 为了更便捷的实现,我们选择分桶训练的方式。我们预先定义了一些固定的分辨率,并将不同的样本分配到不同的桶中。下面列出了分桶方案中值得注意的点。但我们可以看到,这些在我们的实验中并不是一个大问题。
查看注意事项 - 桶大小被限制为固定数量:首先,在实际应用中,通常只使用少数宽高比(9:16、3:4)和分辨率(240p、1080p)。其次,我们发现经过训练的模型可以很好地推广到未见过的解决方案。 - 每批的大小相同,打破了独立同分布(i.i.d.)假设:由于我们使用多个 GPU,因此不同 GPU 上的本地批次具有不同的大小。我们没有发现此问题导致性能显着下降。 - 可能没有足够的样本来填充每个桶,并且分布可能有偏差:首先,当本地批量大小不太大时,我们的数据集足够大以填充每个桶。其次,我们应该分析数据大小的分布并相应地定义桶大小。第三,分配不平衡并没有显着影响训练过程。 - 不同的分辨率和帧长可能有不同的处理速度:与PixArt只处理相似分辨率(相似token数)的宽高比不同,我们需要考虑不同分辨率和帧长的处理速度。我们可以使用“bucket_config”来定义每个桶的批量大小,以确保处理速度相似。
![bucket](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/report_bucket.png) 如图所示,桶是(分辨率,帧数量,宽高比)的三元组。我们为不同的分辨率提供预定义的宽高比,涵盖了大多数常见的视频宽高比。在每个epoch之前,我们打乱数据集并将样本分配到不同的桶中,如图所示。我们将样本放入最大分辨率和帧长度小于视频的桶中。 考虑到我们的计算资源有限,我们进一步为每个(分辨率,num_frame)二元组引入keep_prob和batch_size两个属性,以降低计算成本并实现多阶段训练。具体来说,高清视频将以概率1-keep_prob下采样到较低分辨率的桶中,并且每个桶的样本数量是由batch_size属性决定的。这样,我们可以控制不同桶中的样本数量,并通过为每个桶搜索合适的数据量来平衡GPU负载。 有关训练中桶使用的详细说明,请参阅[配置文件](/docs/config.md#training-bucket-configs). ## 使用Masked DiT作为图生视频/视频生视频模型 Transformer可以很容易地扩展到支持图生图和视频生视频的任务。我们提出了一种蒙版策略来支持图像和视频的调节。蒙版策略如下图所示。 ![mask strategy](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/report_mask.png) 在将图像或视频转换成另一个视频的过程中,我们通常会选择出需要作为条件的帧并取消其掩码(unmask)。在使用ST-DiT模型进行前向传播时,被选择取消掩码(unmask)的帧将被赋予时间步长0,而其他帧则保持它们原有的时间步长t。我们发现,如果直接将这种策略应用到训练好的模型上,会得到较差的结果,因为扩散模型在训练过程中并未学会如何处理一个样本中具有不同时间步长的帧。 受[UL2](https://arxiv.org/abs/2205.05131)的启发,我们在训练期间引入了随机掩码策略。具体来说,我们在训练期间随机取消掩码帧,包括取消掩码第一帧,前k帧,最后k帧,最后k帧,第一和最后k帧,随机帧等。基于Open-Sora 1.0模型,以50%的概率应用掩码策略,我们发现模型能够在10,000步的训练中学会处理图像条件(而30%的概率会导致处理能力变差),同时文本到视频的性能略有下降。因此,在Open-Sora 1.1版本中,我们从头开始预训练模型,并采用了掩码策略。 下图给出了用于推理的掩码策略配置的说明。五数字元组在定义掩码策略方面提供了极大的灵活性。 ![mask strategy config](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/report_mask_config.png) 掩码策略用法的详细说明可在[配置文件](/docs/config.md#advanced-inference-config)中查看. ## 数据收集和流程 正如我们在Sora1.0版本中看见的那样,数据数量和质量对于训练一个好的模型至关重要,因此,我们努力扩展数据集。首先,我们创建了一个遵循[SVD](https://arxiv.org/abs/2311.15127)的自动流水线,包括场景切割、字幕、各种评分和过滤以及数据集管理脚本和通用惯例。 ![pipeline](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/report_data_pipeline.png) 我们计划使用[panda-70M](https://snap-research.github.io/Panda-70M/)和其他数据来训练模型,大约包含3000万条数据。然而,我们发现磁盘输入输出(disk IO)在同时进行训练和数据处理时成为了一个瓶颈。因此,我们只能准备一个包含1000万条数据的数据集,并且没有完成我们构建的所有处理流程。最终,我们使用了包含970万视频和260万图像的数据集进行预训练,以及560,000视频和160万图像的数据集进行微调。预训练数据集的统计信息如下所示。 图像文本标记 (使用T5分词器): ![image text tokens](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/report_image_textlen.png) 视频文本标记 (使用T5分词器)。我们直接使用Panda的短视频描述进行训练,并自己给其他数据集加视频描述。生成的字幕通常少于200个token。 ![video text tokens](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/report_video_textlen.png) 视频时长: ![video duration](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/report_video_duration.png) ## 训练详情 由于计算资源有限,我们必须仔细监控训练过程,并在推测模型学习不佳时更改训练策略,因为没有消融研究的计算。因此,Open-Sora1.1版本的训练包括多个更改,所以,指数移动平均(EMA)未被应用。 1. 首先,我们从`Pixart-alpha-1024`的模型checkpoint开始,使用不同分辨率的图像进行了6000步的微调。我们发现模型能够很容易地适应并生成不同分辨率的图像。为了加快扩散过程的训练,我们使用了[SpeeDiT](https://github.com/1zeryu/SpeeDiT)(iddpm-speed)技术。 2. **[阶段一]** 然后,我们使用梯度检查点(gradient-checkpointing)技术对模型进行了**24,000**步的预训练,这个过程在64个H800 GPU上运行了**4天**。尽管模型看到的数据样本数量相同,我们发现与使用较小批量大小相比,模型的学习速度较慢。我们推测,在训练的早期阶段,步数的数量对于训练更为重要。大多数视频的分辨率是**240p**,预训练时使用的配置与[stage2.py](/configs/opensora-v1-1/train/stage2.py)相似。 3. **[阶段一]** 为了增加训练步数,我们改用了更小的批量大小,并且没有使用梯度检查点技术。在这个阶段,我们还引入了帧率(fps)条件。模型训练了**40,000**步,持续了**2天**。训练中使用的视频大多数是**144p**分辨率,使用的配置文件是[stage1.py](/configs/opensora-v1-1/train/stage1.py)。我们使用较低的分辨率,因为我们在Open-Sora 1.0版本中发现模型可以以相对较低的分辨率学习时间知识。 4. **[阶段一]** 我们发现模型不能很好地学习长视频,并在Open-Sora1.0训练中发现了一个噪声生成结果,推测是半精度问题。因此,我们采用QK-归一化来稳定训练。我们还将iddpm-speed切换成iddpm。我们训练了**17k**步**14小时**。大多数视频的分辨率是144p,预训练时使用的配置是[stage1.py](/configs/opensora-v1-1/train/stage1.py)。阶段1训练持续约一周,总步长**81k**。 5. **[阶段二]** 我们切换到更高的分辨率,其中大多数视频是**240p和480p**分辨率([stage2.py](/configs/opensora-v1-1/train/stage2.py))。我们在所有预训练数据上训练了**22000**步,持续**一天**。 6. **[阶段三]** 我们切换到更高的分辨率,大多数视频的分辨率是**480p和720p**([stage3.py](/configs/opensora-v1-1/train/stage3.py))。我们在高质量数据上训了**4000**步,用时**一天**。 ## 结果和评价 ## 不足和下一步计划 随着我们离Sora的复现又近了一步,我们发现当前模型存在许多不足,这些不足将在我们下阶段工作中得到改善。 - **噪音的生成和影响**:我们发现生成的模型,特别是长视频中,有时很多噪点,不流畅。我们认为问题在于没有使用时间VAE。由于[Pixart-Sigma](https://arxiv.org/abs/2403.04692)发现适应新VAE很容易,我们计划在下一个版本中为模型开发时间VAE。 - **缺乏时间一致性**:我们发现模型无法生成具有高时间一致性的视频,我们认为问题是由于缺乏训练FLOPs,我们计划收集更多数据并继续训练模型以提高时间一致性。 - **人像生成质量低**:我们发现模型无法生成高质量的人类视频,我们认为问题是由于缺乏人类数据,我们计划收集更多的人类数据,并继续训练模型以提高人类生成。 - **美学得分低**:我们发现模型的美学得分不高。问题在于缺少美学得分过滤,由于IO瓶颈没我们没有进行这一步骤。我们计划通过美学得分和微调模型来过滤数据,以提高美学得分。 - **长视频生成质量低**:我们发现,使用同样的提示词,视频越长,质量越差。这意味着图像质量不能同等地被不同长度的序列所适应。 > - **算法与加速实现**:Zangwei Zheng, Xiangyu Peng, Shenggui Li, Hongxing Liu, Yukun Zhou > - **数据收集与处理**:Xiangyu Peng, Zangwei Zheng, Chenhui Shen, Tom Young, Junjie Wang, Chenfeng Yu ================================================ FILE: docs/zh_CN/report_v3.md ================================================ # Open-Sora 1.2 报告 - [视频压缩网络](#视频压缩网络) - [整流流和模型适应](#整流流和模型适应) - [更多数据和更好的多阶段训练](#更多数据和更好的多阶段训练) - [简单有效的模型调节](#简单有效的模型调节) - [评估](#评估) 在 Open-Sora 1.2 版本中,我们在 >30M 数据上训练了 一个1.1B 的模型,支持 0s~16s、144p 到 720p、各种宽高比的视频生成。我们的配置如下所列。继 1.1 版本之后,Open-Sora 1.2 还可以进行图像到视频的生成和视频扩展。 | | 图像 | 2秒 | 4秒 | 8秒 | 16秒 | | ---- | ----- | --- | --- | --- | --- | | 240p | ✅ | ✅ | ✅ | ✅ | ✅ | | 360p | ✅ | ✅ | ✅ | ✅ | ✅ | | 480p | ✅ | ✅ | ✅ | ✅ | 🆗 | | 720p | ✅ | ✅ | ✅ | 🆗 | 🆗 | 这里✅表示在训练期间可以看到数据,🆗表示虽然没有经过训练,但模型可以在该配置下进行推理。🆗的推理需要多个80G内存的GPU和序列并行。 除了 Open-Sora 1.1 中引入的功能外,Open-Sora 1.2 还有以下重磅更新: - 视频压缩网络 - 整流流训练 - 更多数据和更好的多阶段训练 - 简单有效的模型调节 - 更好的评估指标 上述改进的所有实现(包括训练和推理)均可在 Open-Sora 1.2 版本中使用。以下部分将介绍改进的细节。我们还改进了代码库和文档,使其更易于使用。 ## 视频压缩网络 对于 Open-Sora 1.0 & 1.1,我们使用了 stable-ai 的 83M 2D VAE,它仅在空间维度上压缩,将视频压缩 8x8 倍。为了减少时间维度,我们每三帧提取一帧。然而,这种方法导致生成的视频流畅度较低,因为牺牲了生成的帧率(fps)。因此,在这个版本中,我们引入了像 OpenAI 的 Sora 一样的视频压缩网络。该网络在时域上将视频大小压缩至四分之一,因此,我们不必再额外抽帧,而可以使用原有帧率生成模型。 考虑到训练 3D VAE 的计算成本很高,我们希望重新利用在 2D VAE 中学到的知识。我们注意到,经过 2D VAE 压缩后,时间维度上相邻的特征仍然高度相关。因此,我们提出了一个简单的视频压缩网络,首先将视频在空间维度上压缩 8x8 倍,然后将视频在时间维度上压缩 4 倍。网络如下所示: ![video_compression_network](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/report_3d_vae.png) 我们用[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使图像重建更加准确。 我们的训练包括三个阶段: 1. 对于前 380k 步,我们冻结 2D VAE并在 8 个 GPU 上进行训练。训练目标包括重建 2D VAE 的压缩特征(图中粉红色),并添加损失以使 3D VAE 的特征与 2D VAE 的特征相似(粉红色和绿色,称为identity loss)。我们发现后者的损失可以快速使整个 VAE 在图像上取得良好的性能,并在下一阶段更快地收敛。 2. 对于接下来的 260k 步,我们消除identity loss并仅学习 3D VAE。 3. 对于最后 540k 步,由于我们发现仅重建 2D VAE 的特征无法带来进一步的改进,因此我们移除了loss并训练整个 VAE 来重建原始视频。此阶段在 24 个 GPU 上进行训练。 对于训练的前半部分,我们采用 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 版本中找到。 当使用 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 性能相当。 | 模型 | 结构相似性↑ | 峰值信噪比↑ | | ------------------ | ----- | ------ | | Open-Sora-Plan 1.1 | 0.882 | 29.890 | | Open-Sora 1.2 | 0.880 | 30.590 | ## 整流流和模型适应 最新的扩散模型 Stable Diffusion 3 为了获得更好的性能,采用了[rectified flow](https://github.com/gnobitab/RectifiedFlow)替代了 DDPM。可惜 SD3 的 rectified flow 训练代码没有开源。不过 Open-Sora 1.2 提供了遵循 SD3 论文的训练代码,包括: - 基本整流流训练 - 用于训练加速的 Logit-norm 采样 - 分辨率和视频长度感知时间步长采样 对于分辨率感知的时间步长采样,我们应该对分辨率较大的图像使用更多的噪声。我们将这个想法扩展到视频生成,对长度较长的视频使用更多的噪声。 Open-Sora 1.2 从[PixArt-Σ 2K](https://github.com/PixArt-alpha/PixArt-sigma) 模型checkpoint开始。请注意,此模型使用 DDPM 和 SDXL VAE 进行训练,分辨率也高得多。我们发现在小数据集上进行微调可以轻松地使模型适应我们的视频生成设置。适应过程如下,所有训练都在 8 个 GPU 上完成: 1. 多分辨率图像生成能力:我们训练模型以 20k 步生成从 144p 到 2K 的不同分辨率。 2. QK-norm:我们将 QK-norm 添加到模型中并训练 18k 步。 3. 整流流:我们从离散时间 DDPM 转变为连续时间整流流并训练 10k 步。 4. 使用 logit-norm 采样和分辨率感知时间步采样的整流流:我们训练 33k 步。 5. 较小的 AdamW epsilon:按照 SD3,使用 QK-norm,我们可以对 AdamW 使用较小的 epsilon(1e-15),我们训练 8k 步。 6. 新的 VAE 和 fps 调节:我们用自己的 VAE 替换原来的 VAE,并将 fps 调节添加到时间步调节中,我们训练 25k 步。请注意,对每个通道进行规范化对于整流流训练非常重要。 7. 时间注意力模块:我们添加时间注意力模块,其中没有初始化投影层。我们在图像上进行 3k 步训练。 8. 仅针对具有掩码策略的视频的时间块:我们仅在视频上训练时间注意力块,步长为 38k。 经过上述调整后,我们就可以开始在视频上训练模型了。上述调整保留了原始模型生成高质量图像的能力,并未后续的视频生成提供了许多助力: - 通过整流,我们可以加速训练,将视频的采样步数从100步减少到30步,大大减少了推理的等待时间。 - 使用 qk-norm,训练更加稳定,并且可以使用积极的优化器。 - 采用新的VAE,时间维度压缩了4倍,使得训练更加高效。 - 该模型具有多分辨率图像生成能力,可以生成不同分辨率的视频。 ## 更多数据和更好的多阶段训练 由于计算预算有限,我们精心安排了训练数据的质量从低到高,并将训练分为三个阶段。我们的训练涉及 12x8 GPU,总训练时间约为 2 周, 约70k步。 ### 第一阶段 我们首先在 Webvid-10M 数据集(40k 小时)上训练模型,共 30k 步(2 个 epoch)。由于视频分辨率均低于 360p 且包含水印,因此我们首先在此数据集上进行训练。训练主要在 240p 和 360p 上进行,视频长度为 2s~16s。我们使用数据集中的原始字幕进行训练。训练配置位于[stage1.py](/configs/opensora-v1-2/train/stage1.py)中。 ### 第二阶段 然后我们在 Panda-70M 数据集上训练模型。这个数据集很大,但质量参差不齐。我们使用官方的 30M 子集,其中的片段更加多样化,并过滤掉美学评分低于 4.5 的视频。这产生了一个 20M 子集,包含 41k 小时。数据集中的字幕直接用于我们的训练。训练配置位于[stage2.py](/configs/opensora-v1-2/train/stage2.py)中。 训练主要在 360p 和 480p 上进行。我们训练模型 23k 步,即 0.5 个 epoch。训练尚未完成,因为我们希望我们的新模型能早日与大家见面。 ### 第三阶段 在此阶段,我们从各种来源收集了 200 万个视频片段,总时长 5000 小时,其中包括: - 来自 Pexels、Pixabay、Mixkit 等的免费授权视频。 - [MiraData](https://github.com/mira-space/MiraData):一个包含长视频的高质量数据集,主要来自游戏和城市/风景探索。 - [Vript](https://github.com/mutonix/Vript/tree/main):一个密集注释的数据集。 - 还有一些其他数据集。 MiraData 和 Vript 有来自 GPT 的字幕,而我们使用[PLLaVA](https://github.com/magic-research/PLLaVA)为其余字幕添加字幕。与只能进行单帧/图像字幕的 LLaVA 相比,PLLaVA 是专门为视频字幕设计和训练的。[加速版PLLaVA](/tools/caption/README.md#pllava-captioning)已在我们的`tools/`中发布。在实践中,我们使用预训练的 PLLaVA 13B 模型,并从每个视频中选择 4 帧生成字幕,空间池化形状为 2*2。 下面显示了此阶段使用的视频数据的一些统计数据。我们提供了持续时间和分辨率的基本统计数据,以及美学分数和光流分数分布。我们还从视频字幕中提取了对象和动作的标签并计算了它们的频率。 ![stats](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/report-03_video_stats.png) ![object_count](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/report-03_objects_count.png) ![object_count](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/report-03_actions_count.png) 此阶段我们主要在 720p 和 1080p 上进行训练,以提高模型在高清视频上的表现力。在训练中,我们使用的掩码率为25%。训练配置位于[stage3.py](/configs/opensora-v1-2/train/stage3.py)中。我们对模型进行 15k 步训练,大约为 2 个 epoch。 ## 简单有效的模型调节 对于第 3 阶段,我们计算每个视频片段的美学分数和运动分数。但是,由于视频片段数量较少,我们不愿意过滤掉得分较低的片段,这会导致数据集较小。相反,我们将分数附加到字幕中并将其用作条件。我们发现这种方法可以让模型了解分数并遵循分数来生成质量更好的视频。 例如,一段美学评分为 5.5、运动评分为 10 且检测到摄像头运动向左平移的视频,其字幕将为: ```plaintext [Original Caption] aesthetic score: 5.5, motion score: 10, camera motion: pan left. ``` 在推理过程中,我们还可以使用分数来调节模型。对于摄像机运动,我们仅标记了 13k 个具有高置信度的剪辑,并且摄像机运动检测模块已在我们的工具中发布。 ## 评估 之前,我们仅通过人工评估来监控训练过程,因为 DDPM 训练损失与生成的视频质量没有很好的相关性。但是,对于校正流,如 SD3 中所述,我们发现训练损失与生成的视频质量有很好的相关性。因此,我们跟踪了 100 张图像和 1k 个视频的校正流评估损失。 我们从 pixabay 中抽样了 1k 个视频作为验证数据集。我们计算了不同分辨率(144p、240p、360p、480p、720p)下图像和不同长度的视频(2s、4s、8s、16s)的评估损失。对于每个设置,我们等距采样 10 个时间步长。然后对所有损失取平均值。 ![Evaluation Loss](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/report_val_loss.png) ![Video Evaluation Loss](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/report_vid_val_loss.png) 此外,我们还会在训练过程中跟踪[VBench](https://vchitect.github.io/VBench-project/)得分。VBench 是用于短视频生成的自动视频评估基准。我们用 240p 2s 视频计算 vbench 得分。这两个指标验证了我们的模型在训练过程中持续改进。 ![VBench](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/report_vbench_score.png) 所有评估代码均发布在`eval`文件夹中。查看[评估指南](/eval/README.md)了解更多详细信息。 |模型 | 总得分 | 质量得分 | 语义分数 | | -------------- | ----------- | ------------- | -------------- | | Open-Sora V1.0 | 75.91% | 78.81% | 64.28% | | Open-Sora V1.2 | 79.23% | 80.71% | 73.30% | ## 序列并行 我们使用序列并行来支持长序列训练和推理。我们的实现基于Ulysses,工作流程如下所示。启用序列并行后,我们只需要将 `all-to-all` 通信应用于STDiT中的空间模块(spatial block),因为在序列维度上,只有对空间信息的计算是相互依赖的。 ![SP](https://github.com/hpcaitech/Open-Sora-Demo/blob/main/readme/sequence_parallelism.jpeg) 目前,由于训练数据分辨率较小,我们尚未使用序列并行进行训练,我们计划在下一个版本中使用。至于推理,我们可以使用序列并行,以防您的 GPU 内存不足。下表显示,序列并行可以实现加速: | 分辨率 | 时长 | GPU数量 | 是否启用序列并行 |用时(秒) | 加速效果/GPU | | ---------- | ------- | -------------- | --------- | ------------ | --------------- | | 720p | 16秒 | 1 | 否 | 547.97 | - | | 720p | 16s秒 | 2 | 是 | 244.38 | 12% | ================================================ FILE: docs/zh_CN/report_v4.md ================================================ # Open-Sora 1.3 报告 - [视频压缩网络](#视频压缩网络) - [升级版带位移窗口注意力的STDiT](#升级版带位移窗口注意力的STDiT) - [简单有效的模型条件控制](#简单有效的模型条件控制) - [评估方法](#评估方法) 在Open-Sora 1.3版本中,我们在超过60M(约85k小时)的数据上训练了一个1.1B参数的模型,训练耗时35k H100 GPU小时,支持0~113帧、360p和720p分辨率以及多种宽高比的视频生成。我们的配置如下。延续1.2版本的特性,Open-Sora 1.3同样支持图像到视频的生成和视频延展。 | | image | 49 frames | 65 frames | 81 frames | 97 frames | 113 frames | | ---- | ----- | ---------- | ---------- | ---------- | --------- | ---------- | | 360p | ✅ | ✅ | ✅ | ✅ | ✅ |✅ | | 720p | ✅ | ✅ | ✅ | ✅ | ✅ |✅ | 这里✅表示在训练过程中已经见过的数据。 除了Open-Sora 1.2中引入的特性外,Open-Sora 1.3的亮点包括: - 视频压缩网络 - 升级版带位移窗口注意力的STDiT - 更多数据和更好的多阶段训练 - 简单有效的模型条件控制 - 更好的评估指标 以上所有改进的实现(包括训练和推理)都在Open-Sora 1.3版本中提供。以下部分将详细介绍这些改进。我们还优化了代码库和文档以使其更易于使用和开发,并添加了LLM优化器来[优化输入提示词](/README.md#gpt-4o-prompt-refinement)并支持更多语言。 ## 视频压缩网络 在Open-Sora 1.2中,视频压缩架构采用了模块化方法,分别处理空间和时间维度。基于Stability AI的SDXL VAE的空间VAE压缩单个帧的空间维度。时间VAE则处理来自空间VAE的潜在表示以实现时间压缩。这种两阶段设计实现了有效的空间和时间压缩,但也带来了一些限制。这些限制包括由于固定长度输入帧而导致的长视频处理效率低下、空间和时间特征之间缺乏无缝集成,以及在训练和推理过程中更高的内存需求。 Open-Sora 1.3引入了统一的视频压缩方法。通过将空间和时间处理结合到单一框架中,并利用诸如分块3D卷积和动态帧支持等高级特性,Open-Sora 1.3实现了更好的效率、可扩展性和重建质量。以下是Open-Sora 1.3 VAE的主要改进: **1. 统一的时空处理:** 不同于使用独立的VAE进行空间和时间压缩,Open-Sora 1.3采用单一的编码器-解码器结构同时处理这两个维度。这种方法消除了中间表示和空间-时间模块之间的冗余数据传输的需求。 **2. 分块3D卷积:** Open-Sora 1.3在时间维度上引入了分块3D卷积支持。通过将视频分解成更小的时间块,该特性实现了对更长视频序列的高效编码和解码,而不会增加内存开销。这一改进解决了Open-Sora 1.2在处理大量帧时的限制,确保了更高的时间压缩灵活性。 **3. 动态微批次和微帧处理:** Open-Sora 1.3引入了新的微批次和微帧处理机制。这实现了:(1) 自适应时间重叠:时间编码和解码过程中的重叠帧帮助减少块边界的不连续性。(2) 动态帧大小支持:不再局限于固定长度序列(如Open-Sora 1.2中的17帧),Open-Sora 1.3支持动态序列长度,使其能够适应不同的视频长度。 **4. 统一的归一化机制:** Open-Sora 1.3中的归一化过程通过可调的缩放(scale)和平移(shift)参数得到了改进,确保了不同数据集间潜在空间分布的一致性。与Open-Sora 1.2特定于固定数据集的归一化不同,这个版本引入了更通用的参数并支持特定于帧的归一化策略。 #### 改进总结 | 特性 | Open-Sora 1.2 | Open-Sora 1.3 | |---------------|---------------------------------|----------------------------------| | **架构** | 独立的空间和时间VAE | 统一的时空VAE | | **分块处理** | 不支持 | 支持(分块3D卷积) | | **帧长度支持** | 固定(17帧) | 支持动态帧长度和重叠 | | **归一化** | 固定参数 | 可调的缩放和平移参数 | ## 包含滑动窗口注意力的STDiT 在Open-Sora 1.2取得成功的基础上,1.3版本引入了多项架构改进和新功能,以提升视频生成的质量和灵活性。本节概述了这两个版本之间的主要改进和差异。 最新的扩散模型(如Stable Diffusion 3)采用[rectified flow](https://github.com/gnobitab/RectifiedFlow)代替DDPM以获得更好的性能。虽然SD3的rectified flow训练代码未开源,但OpenSora按照SD3论文提供了训练代码实现。OpenSora 1.2从SD3引入了几个关键策略: 1. 基础的rectified flow训练,实现连续时间扩散 2. Logit-norm采样用于加速训练(遵循SD3论文第3.1节),优先在中等噪声水平采样时间步 3. 分辨率和视频长度感知的时间步采样(遵循SD3论文第5.3.2节),对更大分辨率和更长视频使用更多噪声 在OpenSora 1.3中,我们在架构、功能和性能方面进行了显著改进: #### 1. 位移窗口注意力机制 - 引入可配置kernel_size的基于核的局部注意力,提高计算效率 - 实现类似Swin Transformer的位移窗口分区策略 - 增加带extra_pad_on_dims支持的窗口边界填充掩码处理 - 在局部窗口(时间、高度、宽度)内扩展3D相对位置编码 #### 2. 增强的位置编码 - 改进RoPE实现,将rotation_dim降至原来的1/3以适应3D场景 - 为时间、高度和宽度维度添加独立的旋转嵌入 - 实现分辨率自适应的位置编码缩放 - 可选的空间RoPE以更好地建模空间关系 #### 3. 灵活的生成能力 - 添加I2V和V2V功能,配备专门的条件控制机制 - 引入条件嵌入模块(x_embedder_cond和x_embedder_cond_mask) - 零初始化条件嵌入以实现稳定训练 - 通过skip_temporal选项实现灵活的时序建模 #### 4. 性能优化 - 改进Flash Attention触发条件(N > 128)以提高效率 - 添加torch.scaled_dot_product_attention (SDPA)作为替代后端 - 通过改进的填充和窗口分区优化内存使用 - 通过自适应高度填充增强序列并行性 从[PixArt-Σ 2K](https://github.com/PixArt-alpha/PixArt-sigma)的适应过程保持相似,但增加了额外步骤: [第1-7点与v1.2相同:多分辨率训练、QK-norm、rectified flow、logit-norm采样、更小的AdamW epsilon、新VAE和基础时序注意力] #### 8. 增强的时序模块 - 添加带位移窗口支持的基于核的局部注意力 - 实现带分辨率自适应缩放的3D相对位置编码 - 采用改进的初始化策略进行投影层零初始化 相比专注于基础视频生成的v1.2,v1.3在三个关键领域带来了实质性改进:**1. 质量**:通过位移窗口注意力和3D位置编码增强时空建模。**2. 灵活性**:支持I2V/V2V任务和可配置的时序建模。**3. 效率**:优化注意力计算和内存使用 这些改进在保持v1.2核心功能的同时,扩展了模型在实际应用中的能力。模型保留了使用rectified flow生成高质量图像和视频的能力,同时在条件生成和长序列建模方面获得了新的优势。 ## 简单有效的模型条件控制 我们对每个视频片段计算美学分数和运动分数,并过滤掉得分较低的片段,从而得到一个视频质量更好的数据集。此外,我们将这些分数附加到标题中并用作条件控制。具体来说,我们基于预定义的范围将数值分数转换为描述性语言。美学分数转换函数基于预定义范围将数值美学分数转换为描述标签:低于4分标记为"terrible",依次通过"very poor"、"poor"、"fair"、"good"和"very good",6.5分或更高标记为"excellent"。同样,运动分数转换函数将运动强度分数映射为描述符:低于0.5分标记为"very low",依次通过"low"、"fair"、"high"和"very high",20分或更高标记为"extremely high"。我们发现这种方法可以使模型意识到这些分数并遵循分数来生成更高质量的视频。 例如,对于一个美学分数为5.5,运动分数为10,检测到的相机运动为向左平移的视频,其标题将是: ```plaintext [Original Caption] The aesthetic score is good, the motion strength is high, camera motion: pan left. ``` 在推理过程中,我们也可以使用这些分数来控制模型。对于相机运动,我们只标记了13k个高置信度的片段,相机运动检测模块已在我们的工具中发布。 ## 评估方法 此前,我们仅通过人工评估来监控训练过程,因为DDPM训练损失与生成视频的质量相关性不高。然而,对于rectified flow,我们发现正如SD3所述,训练损失与生成视频的质量有很好的相关性。因此,我们持续跟踪100张图像和1k个视频的rectified flow评估损失。 我们从pixabay采样了1k个视频作为验证数据集。我们计算了不同分辨率(360p,720p)下图像和不同长度视频(49帧、65帧、81帧、97帧、113帧)的评估损失。对于每种设置,我们等距采样10个时间步。然后对所有损失取平均值。 此外,我们还在训练期间跟踪[VBench](https://vchitect.github.io/VBench-project/)分数。VBench是一个用于短视频生成的自动视频评估基准。我们使用360p 49帧视频计算vbench分数。这两个指标验证了我们的模型在训练过程中持续改进。 所有评估代码都在`eval`文件夹中发布。查看[README](/eval/README.md)获取更多详细信息。 ================================================ FILE: gradio/app.py ================================================ #!/usr/bin/env python """ This script runs a Gradio App for the Open-Sora model. Usage: python demo.py """ import argparse import datetime import importlib import os import subprocess import sys from tempfile import NamedTemporaryFile import spaces import torch import gradio as gr MODEL_TYPES = ["v1.3"] WATERMARK_PATH = "./assets/images/watermark/watermark.png" CONFIG_MAP = { "v1.3": "configs/opensora-v1-3/inference/t2v.py", "v1.3_i2v": "configs/opensora-v1-3/inference/v2v.py", } HF_STDIT_MAP = { "t2v": { "360p": "hpcaitech/OpenSora-STDiT-v4-360p", "720p": "hpcaitech/OpenSora-STDiT-v4", }, "i2v": "hpcaitech/OpenSora-STDiT-v4-i2v", } # ============================ # Prepare Runtime Environment # ============================ def install_dependencies(enable_optimization=False): """ Install the required dependencies for the demo if they are not already installed. """ def _is_package_available(name) -> bool: try: importlib.import_module(name) return True except (ImportError, ModuleNotFoundError): return False if enable_optimization: # install flash attention if not _is_package_available("flash_attn"): subprocess.run( f"{sys.executable} -m pip install flash-attn --no-build-isolation", env={"FLASH_ATTENTION_SKIP_CUDA_BUILD": "TRUE"}, shell=True, ) # install apex for fused layernorm if not _is_package_available("apex"): subprocess.run( 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', shell=True, ) # install ninja if not _is_package_available("ninja"): subprocess.run(f"{sys.executable} -m pip install ninja", shell=True) # install xformers if not _is_package_available("xformers"): subprocess.run( f"{sys.executable} -m pip install -v -U git+https://github.com/facebookresearch/xformers.git@main#egg=xformers", shell=True, ) # ============================ # Model-related # ============================ def read_config(config_path): """ Read the configuration file. """ from mmengine.config import Config return Config.fromfile(config_path) def build_models(mode, resolution, enable_optimization=False): """ Build the models for the given mode, resolution, and configuration. """ # build vae from opensora.registry import MODELS, build_module if mode == "i2v": config = read_config(CONFIG_MAP["v1.3_i2v"]) else: config = read_config(CONFIG_MAP["v1.3"]) vae = build_module(config.vae, MODELS).cuda() # build text encoder text_encoder = build_module(config.text_encoder, MODELS) # T5 must be fp32 text_encoder.t5.model = text_encoder.t5.model.cuda() # Determine model weights based on mode and resolution if mode == "i2v": weight_path = HF_STDIT_MAP["i2v"] else: # t2v weight_path = HF_STDIT_MAP["t2v"].get(resolution, None) if not weight_path: raise ValueError(f"Unsupported resolution {resolution} for mode {mode}") # build stdit from opensora.models.stdit.stdit3 import STDiT3 model_kwargs = {k: v for k, v in config.model.items() if k not in ("type", "from_pretrained", "force_huggingface")} print("Load STDIT3 from ", weight_path) stdit = STDiT3.from_pretrained(weight_path, **model_kwargs).cuda() # build scheduler from opensora.registry import SCHEDULERS scheduler = build_module(config.scheduler, SCHEDULERS) # hack for classifier-free guidance text_encoder.y_embedder = stdit.y_embedder # move models to device vae = vae.to(torch.bfloat16).eval() text_encoder.t5.model = text_encoder.t5.model.eval() # t5 must be in fp32 stdit = stdit.to(torch.bfloat16).eval() # clear cuda torch.cuda.empty_cache() return vae, text_encoder, stdit, scheduler, config def parse_args(): parser = argparse.ArgumentParser() parser.add_argument( "--model-type", default="v1.3", choices=MODEL_TYPES, help=f"The type of model to run for the Gradio App, can only be {MODEL_TYPES}", ) parser.add_argument("--output", default="./outputs", type=str, help="The path to the output folder") parser.add_argument("--port", default=None, type=int, help="The port to run the Gradio App on.") parser.add_argument("--host", default="0.0.0.0", type=str, help="The host to run the Gradio App on.") parser.add_argument("--share", action="store_true", help="Whether to share this gradio demo.") parser.add_argument( "--enable-optimization", action="store_true", help="Whether to enable optimization such as flash attention and fused layernorm", ) return parser.parse_args() # ============================ # Main Gradio Script # ============================ # as `run_inference` needs to be wrapped by `spaces.GPU` and the input can only be the prompt text # so we can't pass the models to `run_inference` as arguments. # instead, we need to define them globally so that we can access these models inside `run_inference` # read config args = parse_args() config = read_config(CONFIG_MAP[args.model_type]) torch.backends.cuda.matmul.allow_tf32 = True torch.backends.cudnn.allow_tf32 = True # make outputs dir os.makedirs(args.output, exist_ok=True) # disable torch jit as it can cause failure in gradio SDK # gradio sdk uses torch with cuda 11.3 torch.jit._state.disable() # set up install_dependencies(enable_optimization=args.enable_optimization) # import after installation from opensora.datasets import IMG_FPS, save_sample from opensora.datasets.aspect import get_image_size, get_num_frames from opensora.models.text_encoder.t5 import text_preprocessing from opensora.utils.inference_utils import ( add_watermark, append_generated, append_score_to_prompts, apply_mask_strategy, collect_references_batch, dframe_to_frame, extract_json_from_prompts, extract_prompts_loop, get_random_prompt_by_openai, has_openai_key, merge_prompt, prepare_multi_resolution_info, refine_prompts_by_openai, split_prompt, prep_ref_and_update_mask_in_loop, prep_ref_and_mask ) from opensora.utils.misc import to_torch_dtype # some global variables dtype = to_torch_dtype(config.dtype) device = torch.device("cuda") # build model def initialize_models(mode, resolution): return build_models(mode, resolution, enable_optimization=args.enable_optimization) def run_inference( mode, prompt_text, resolution, aspect_ratio, length, motion_strength, aesthetic_score, use_motion_strength, use_aesthetic_score, camera_motion, reference_image, refine_prompt, fps, num_loop, seed, sampling_steps, cfg_scale, ): if prompt_text is None or prompt_text == "": gr.Warning("Your prompt is empty, please enter a valid prompt") return None # Dynamically choose mode based on reference image if reference_image is not None and mode != "Text2Image": mode = "i2v" # Initialize models vae, text_encoder, stdit, scheduler, config = initialize_models(mode, resolution) torch.manual_seed(seed) with torch.inference_mode(): # ====================== # 1. Preparation arguments # ====================== # parse the inputs # frame_interval must be 1 so we ignore it here image_size = get_image_size(resolution, aspect_ratio) use_sdedit = config.get("use_sdedit", False) use_oscillation_guidance_for_text = config.get("use_oscillation_guidance_for_text", None) use_oscillation_guidance_for_image = config.get("use_oscillation_guidance_for_image", None) cond_type = config.get("cond_type", None) cond_type = None if cond_type == "none" else cond_type mask_index = None ref = None image_cfg_scale = None # compute generation parameters if mode == "Text2Image": num_frames = 1 fps = IMG_FPS else: num_frames = config.num_frames num_frames = get_num_frames(length) condition_frame_length = config.get("condition_frame_length", 5) condition_frame_edit = config.get("condition_frame_edit", 0.0) input_size = (num_frames, *image_size) latent_size = vae.get_latent_size(input_size) multi_resolution = "OpenSora" align = 5 # == prepare mask strategy == if mode == "Text2Image": mask_strategy = [None] mask_index = [] elif mode == "Text2Video": if reference_image is not None: mask_strategy = ["0"] mask_index = [0] else: mask_strategy = [None] mask_index = [] elif mode == "i2v": mask_strategy = ["0"] mask_index = [0] else: raise ValueError(f"Invalid mode: {mode}") # == prepare reference == if mode == "Text2Image": refs = [""] elif mode == "Text2Video": if reference_image is not None: # save image to disk from PIL import Image im = Image.fromarray(reference_image) temp_file = NamedTemporaryFile(suffix=".png") im.save(temp_file.name) refs = [temp_file.name] else: refs = [""] elif mode == "i2v": if reference_image is not None: # save image to disk from PIL import Image im = Image.fromarray(reference_image) temp_file = NamedTemporaryFile(suffix=".png") im.save(temp_file.name) refs = [temp_file.name] else: refs = [""] else: raise ValueError(f"Invalid mode: {mode}") # == get json from prompts == batch_prompts = [prompt_text] batch_prompts, refs, mask_strategy = extract_json_from_prompts(batch_prompts, refs, mask_strategy) # == get reference for condition == refs = collect_references_batch(refs, vae, image_size) target_shape = [len(batch_prompts), vae.out_channels, *latent_size] if mode == "i2v": image_cfg_scale = config.get("image_cfg_scale", 7.5) ref, mask_index = prep_ref_and_mask( cond_type, condition_frame_length, refs, target_shape, num_loop, device, dtype ) # == multi-resolution info == model_args = prepare_multi_resolution_info( multi_resolution, len(batch_prompts), image_size, num_frames, fps, device, dtype ) # == process prompts step by step == # 0. split prompt # each element in the list is [prompt_segment_list, loop_idx_list] batched_prompt_segment_list = [] batched_loop_idx_list = [] for prompt in batch_prompts: prompt_segment_list, loop_idx_list = split_prompt(prompt) batched_prompt_segment_list.append(prompt_segment_list) batched_loop_idx_list.append(loop_idx_list) # 1. refine prompt by openai if refine_prompt: # check if openai key is provided if not has_openai_key(): gr.Warning("OpenAI API key is not provided, the prompt will not be enhanced.") else: for idx, prompt_segment_list in enumerate(batched_prompt_segment_list): batched_prompt_segment_list[idx] = refine_prompts_by_openai(prompt_segment_list) # process scores aesthetic_score = aesthetic_score if use_aesthetic_score else None motion_strength = motion_strength if use_motion_strength and mode != "Text2Image" else None camera_motion = None if camera_motion == "none" or mode == "Text2Image" else camera_motion # 2. append score for idx, prompt_segment_list in enumerate(batched_prompt_segment_list): batched_prompt_segment_list[idx] = append_score_to_prompts( prompt_segment_list, aes=aesthetic_score, flow=motion_strength, camera_motion=camera_motion, ) # 3. clean prompt with T5 for idx, prompt_segment_list in enumerate(batched_prompt_segment_list): batched_prompt_segment_list[idx] = [text_preprocessing(prompt) for prompt in prompt_segment_list] # 4. merge to obtain the final prompt batch_prompts = [] for prompt_segment_list, loop_idx_list in zip(batched_prompt_segment_list, batched_loop_idx_list): batch_prompts.append(merge_prompt(prompt_segment_list, loop_idx_list)) # ========================= # Generate image/video # ========================= video_clips = [] for loop_i in range(num_loop): # 4.4 sample in hidden space batch_prompts_loop = extract_prompts_loop(batch_prompts, loop_i) # == loop == # if loop_i > 0: # refs, mask_strategy = append_generated( # vae, video_clips[-1], refs, mask_strategy, loop_i, condition_frame_length, condition_frame_edit # ) # == sampling == z = torch.randn(len(batch_prompts), vae.out_channels, *latent_size, device=device, dtype=dtype) masks = apply_mask_strategy(z, refs, mask_strategy, loop_i, align=align) if mask_index is None else None 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 if x_cond_mask is not None and mask_index is not None: x_cond_mask[:, :, mask_index, :, :] = 1.0 # 4.6. diffusion sampling # hack to update num_sampling_steps and cfg_scale scheduler_kwargs = config.scheduler.copy() scheduler_kwargs.pop("type") scheduler_kwargs["num_sampling_steps"] = sampling_steps scheduler_kwargs["cfg_scale"] = cfg_scale scheduler.__init__(**scheduler_kwargs) samples = scheduler.sample( stdit, text_encoder, z=z, z_cond=ref, z_cond_mask=x_cond_mask, prompts=batch_prompts_loop, device=device, additional_args=model_args, progress=True, mask=masks, mask_index=mask_index, image_cfg_scale=image_cfg_scale, use_sdedit=use_sdedit, use_oscillation_guidance_for_text=use_oscillation_guidance_for_text, use_oscillation_guidance_for_image=use_oscillation_guidance_for_image, ) if loop_i > 1: # process conditions for subsequent loop if cond_type is not None: # i2v or v2v is_last_loop = loop_i == loop_i - 1 ref, mask_index = prep_ref_and_update_mask_in_loop( cond_type, condition_frame_length, samples, refs, target_shape, is_last_loop, device, dtype, ) else: refs, mask_strategy = append_generated( vae, samples, refs, mask_strategy, loop_i, condition_frame_length, condition_frame_edit, is_latent=True, ) # samples = vae.decode(samples.to(dtype), num_frames=num_frames) video_clips.append(samples) # ========================= # Save output # ========================= video_clips = [val[0] for val in video_clips] for i in range(1, num_loop): video_clips[i] = video_clips[i][:, condition_frame_length:] video = torch.cat(video_clips, dim=1) t_cut = max(video.size(1) // 5 * 5, 1) if t_cut < video.size(1): video = video[:, :t_cut] video = vae.decode(video.to(dtype), num_frames=t_cut * 17 // 5).squeeze(0) current_datetime = datetime.datetime.now() timestamp = current_datetime.timestamp() save_path = os.path.join(args.output, f"output_{timestamp}") saved_path = save_sample(video, save_path=save_path, fps=24) torch.cuda.empty_cache() # add watermark if mode != "Text2Image" and os.path.exists(WATERMARK_PATH): watermarked_path = saved_path.replace(".mp4", "_watermarked.mp4") success = add_watermark(saved_path, WATERMARK_PATH, watermarked_path) if success: return watermarked_path else: return saved_path else: return saved_path @spaces.GPU(duration=200) def run_image_inference( prompt_text, resolution, aspect_ratio, length, motion_strength, aesthetic_score, use_motion_strength, use_aesthetic_score, camera_motion, reference_image, refine_prompt, fps, num_loop, seed, sampling_steps, cfg_scale, ): return run_inference( "Text2Image", prompt_text, resolution, aspect_ratio, length, motion_strength, aesthetic_score, use_motion_strength, use_aesthetic_score, camera_motion, reference_image, refine_prompt, fps, num_loop, seed, sampling_steps, cfg_scale, ) @spaces.GPU(duration=200) def run_video_inference( prompt_text, resolution, aspect_ratio, length, motion_strength, aesthetic_score, use_motion_strength, use_aesthetic_score, camera_motion, reference_image, refine_prompt, fps, num_loop, seed, sampling_steps, cfg_scale, ): # if (resolution == "480p" and length == "16s") or \ # (resolution == "720p" and length in ["8s", "16s"]): # gr.Warning("Generation is interrupted as the combination of 480p and 16s will lead to CUDA out of memory") # else: return run_inference( "Text2Video", prompt_text, resolution, aspect_ratio, length, motion_strength, aesthetic_score, use_motion_strength, use_aesthetic_score, camera_motion, reference_image, refine_prompt, fps, num_loop, seed, sampling_steps, cfg_scale, ) def generate_random_prompt(): if "OPENAI_API_KEY" not in os.environ: gr.Warning("Your prompt is empty and the OpenAI API key is not provided, please enter a valid prompt") return None else: prompt_text = get_random_prompt_by_openai() return prompt_text def main(): # create demo with gr.Blocks() as demo: with gr.Row(): with gr.Column(): gr.HTML( """

Open-Sora: Democratizing Efficient Video Production for All

""" ) with gr.Row(): with gr.Column(): prompt_text = gr.Textbox(label="Prompt", placeholder="Describe your video here", lines=4) refine_prompt = gr.Checkbox( value=has_openai_key(), label="Refine prompt with GPT4o", interactive=has_openai_key() ) random_prompt_btn = gr.Button("Random Prompt By GPT4o", interactive=has_openai_key()) gr.Markdown("## Basic Settings") resolution = gr.Radio( choices=["360p", "720p"], value="720p", label="Resolution", ) aspect_ratio = gr.Radio( choices=["9:16", "16:9", "3:4", "4:3", "1:1"], value="9:16", label="Aspect Ratio (H:W)", ) length = gr.Radio( choices=[1, 49, 65, 81, 97, 113], value=97, label="Video Length (Number of Frames)", info="Setting the number of frames to 1 indicates image generation instead of video generation.", ) with gr.Row(): seed = gr.Slider(value=1024, minimum=1, maximum=2048, step=1, label="Seed") sampling_steps = gr.Slider(value=30, minimum=1, maximum=200, step=1, label="Sampling steps") cfg_scale = gr.Slider(value=7.0, minimum=0.0, maximum=10.0, step=0.1, label="CFG Scale") with gr.Row(): with gr.Column(): motion_strength = gr.Radio( choices=["very low", "low", "fair", "high", "very high", "extremely high"], value="fair", label="Motion Strength", info="Only effective for video generation", ) use_motion_strength = gr.Checkbox(value=True, label="Enable") with gr.Column(): aesthetic_score = gr.Radio( choices=["terrible", "very poor", "poor", "fair", "good", "very good", "excellent"], value="excellent", label="Aesthetic", info="Effective for text & video generation", ) use_aesthetic_score = gr.Checkbox(value=True, label="Enable") camera_motion = gr.Radio( value="none", label="Camera Motion", choices=["none", "pan right", "pan left", "tilt up", "tilt down", "zoom in", "zoom out", "static"], interactive=True, ) gr.Markdown("## Advanced Settings") with gr.Row(): fps = gr.Slider( value=24, minimum=1, maximum=60, step=1, label="FPS", info="This is the frames per seconds for video generation, keep it to 24 if you are not sure", ) num_loop = gr.Slider( value=1, minimum=1, maximum=20, step=1, label="Number of Loops", info="This will change the length of the generated video, keep it to 1 if you are not sure", ) gr.Markdown("## Reference Image") reference_image = gr.Image(label="Image (optional)", show_download_button=True) with gr.Column(): output_video = gr.Video(label="Output Video", height="100%") with gr.Row(): image_gen_button = gr.Button("Generate image") video_gen_button = gr.Button("Generate video") image_gen_button.click( fn=run_image_inference, inputs=[ prompt_text, resolution, aspect_ratio, length, motion_strength, aesthetic_score, use_motion_strength, use_aesthetic_score, camera_motion, reference_image, refine_prompt, fps, num_loop, seed, sampling_steps, cfg_scale, ], outputs=reference_image, ) video_gen_button.click( fn=run_video_inference, inputs=[ prompt_text, resolution, aspect_ratio, length, motion_strength, aesthetic_score, use_motion_strength, use_aesthetic_score, camera_motion, reference_image, refine_prompt, fps, num_loop, seed, sampling_steps, cfg_scale, ], outputs=output_video, ) random_prompt_btn.click(fn=generate_random_prompt, outputs=prompt_text) # launch demo.queue(max_size=5, default_concurrency_limit=1) demo.launch(server_port=args.port, server_name=args.host, share=args.share, max_threads=1) if __name__ == "__main__": main() ================================================ FILE: opensora/__init__.py ================================================ ================================================ FILE: opensora/acceleration/__init__.py ================================================ ================================================ FILE: opensora/acceleration/checkpoint.py ================================================ import warnings from collections.abc import Iterable from typing import Callable, ContextManager, Optional, Tuple import torch import torch.nn as nn from colossalai.utils import get_current_device from torch.utils.checkpoint import ( _DEFAULT_DETERMINISM_MODE, CheckpointFunction, _checkpoint_without_reentrant_generator, checkpoint_sequential, noop_context_fn, ) class ActivationManager: def __init__(self): self.enable = False self.buffer = None self.total_size = 0 self.avail_offset = 0 self.tensor_id_queue = [] self.ignore_tensor_id_set = set() def setup_buffer(self, numel: int, dtype: torch.dtype): self.buffer = torch.empty(numel, dtype=dtype, pin_memory=True) self.total_size = numel self.enable = True def offload(self, x: torch.Tensor) -> None: if not self.enable or id(x) in self.ignore_tensor_id_set: return size = x.numel() if self.avail_offset + size > self.total_size: raise RuntimeError("Activation buffer is full") assert x.dtype == self.buffer.dtype, f"Wrong dtype of offload tensor" cpu_x = self.buffer[self.avail_offset : self.avail_offset + size].view_as(x) cpu_x.copy_(x) x.data = cpu_x self.avail_offset += size self.tensor_id_queue.append(id(x)) def onload(self, x: torch.Tensor) -> None: if not self.enable or id(x) in self.ignore_tensor_id_set: return assert self.tensor_id_queue[-1] == id(x), f"Wrong order of offload/onload" # current x is pinned memory assert x.data.is_pinned() x.data = x.data.to(get_current_device(), non_blocking=True) self.tensor_id_queue.pop() self.avail_offset -= x.numel() if len(self.tensor_id_queue) == 0: self.ignore_tensor_id_set.clear() def add_ignore_tensor(self, x: torch.Tensor) -> None: self.ignore_tensor_id_set.add(id(x)) def is_top_tensor(self, x: torch.Tensor) -> bool: return len(self.tensor_id_queue) > 0 and self.tensor_id_queue[-1] == id(x) GLOBAL_ACTIVATION_MANAGER = ActivationManager() class CheckpointFunctionWithOffload(torch.autograd.Function): @staticmethod def forward(ctx, run_function, preserve_rng_state, *args): for x in args[::-1]: # handle those tensors are used in multiple checkpoints if GLOBAL_ACTIVATION_MANAGER.is_top_tensor(x): GLOBAL_ACTIVATION_MANAGER.onload(x) GLOBAL_ACTIVATION_MANAGER.add_ignore_tensor(x) out = CheckpointFunction.forward(ctx, run_function, preserve_rng_state, *args) for x in args: if torch.is_tensor(x): GLOBAL_ACTIVATION_MANAGER.offload(x) return out @staticmethod def backward(ctx, *args): # with stack-fashion, the last tensor is the first to be loaded for tensor in ctx.saved_tensors[::-1]: GLOBAL_ACTIVATION_MANAGER.onload(tensor) return CheckpointFunction.backward(ctx, *args) # TorchDynamo does not step inside utils.checkpoint function. The flow # looks likes this # 1) TorchDynamo tries to wrap utils.checkpoint in a HigherOrderOp by # speculatively checking if the forward function is safe to trace. # 2) If yes, then Dynamo-generated Fx graph has the wrapped higher # order op. As a result, TorchDynamo does not look inside utils.checkpoint. # 3) If not, then TorchDynamo falls back to eager by performing a graph # break. And here, the following disable wrapper ensures that # TorchDynamo does not trigger again on the frames created by # utils.checkpoint innards. @torch._disable_dynamo def checkpoint( function, *args, use_reentrant: Optional[bool] = None, context_fn: Callable[[], Tuple[ContextManager, ContextManager]] = noop_context_fn, determinism_check: str = _DEFAULT_DETERMINISM_MODE, debug: bool = False, **kwargs, ): r"""Checkpoint a model or part of the model. Activation checkpointing is a technique that trades compute for memory. Instead of keeping tensors needed for backward alive until they are used in gradient computation during backward, forward computation in checkpointed regions omits saving tensors for backward and recomputes them during the backward pass. Activation checkpointing can be applied to any part of a model. There are currently two checkpointing implementations available, determined by the :attr:`use_reentrant` parameter. It is recommended that you use ``use_reentrant=False``. Please refer the note below for a discussion of their differences. .. warning:: If the :attr:`function` invocation during the backward pass differs from the forward pass, e.g., due to a global variable, the checkpointed version may not be equivalent, potentially causing an error being raised or leading to silently incorrect gradients. .. warning:: The ``use_reentrant`` parameter should be passed explicitly. In version 2.4 we will raise an exception if ``use_reentrant`` is not passed. If you are using the ``use_reentrant=True`` variant, please refer to the note below for important considerations and potential limitations. .. note:: The reentrant variant of checkpoint (``use_reentrant=True``) and the non-reentrant variant of checkpoint (``use_reentrant=False``) differ in the following ways: * Non-reentrant checkpoint stops recomputation as soon as all needed intermediate activations have been recomputed. This feature is enabled by default, but can be disabled with :func:`set_checkpoint_early_stop`. Reentrant checkpoint always recomputes :attr:`function` in its entirety during the backward pass. * The reentrant variant does not record the autograd graph during the forward pass, as it runs with the forward pass under :func:`torch.no_grad`. The non-reentrant version does record the autograd graph, allowing one to perform backward on the graph within checkpointed regions. * The reentrant checkpoint only supports the :func:`torch.autograd.backward` API for the backward pass without its `inputs` argument, while the non-reentrant version supports all ways of performing the backward pass. * At least one input and output must have ``requires_grad=True`` for the reentrant variant. If this condition is unmet, the checkpointed part of the model will not have gradients. The non-reentrant version does not have this requirement. * The reentrant version does not consider tensors in nested structures (e.g., custom objects, lists, dicts, etc) as participating in autograd, while the non-reentrant version does. * The reentrant checkpoint does not support checkpointed regions with detached tensors from the computational graph, whereas the non-reentrant version does. For the reentrant variant, if the checkpointed segment contains tensors detached using ``detach()`` or with :func:`torch.no_grad`, the backward pass will raise an error. This is because ``checkpoint`` makes all the outputs require gradients and this causes issues when a tensor is defined to have no gradient in the model. To avoid this, detach the tensors outside of the ``checkpoint`` function. Args: function: describes what to run in the forward pass of the model or part of the model. It should also know how to handle the inputs passed as the tuple. For example, in LSTM, if user passes ``(activation, hidden)``, :attr:`function` should correctly use the first input as ``activation`` and the second input as ``hidden`` preserve_rng_state(bool, optional): Omit stashing and restoring the RNG state during each checkpoint. Note that under torch.compile, this flag doesn't take effect and we always preserve RNG state. Default: ``True`` use_reentrant(bool): specify whether to use the activation checkpoint variant that requires reentrant autograd. This parameter should be passed explicitly. In version 2.4 we will raise an exception if ``use_reentrant`` is not passed. If ``use_reentrant=False``, ``checkpoint`` will use an implementation that does not require reentrant autograd. This allows ``checkpoint`` to support additional functionality, such as working as expected with ``torch.autograd.grad`` and support for keyword arguments input into the checkpointed function. context_fn(Callable, optional): A callable returning a tuple of two context managers. The function and its recomputation will be run under the first and second context managers respectively. This argument is only supported if ``use_reentrant=False``. determinism_check(str, optional): A string specifying the determinism check to perform. By default it is set to ``"default"`` which compares the shapes, dtypes, and devices of the recomputed tensors against those the saved tensors. To turn off this check, specify ``"none"``. Currently these are the only two supported values. Please open an issue if you would like to see more determinism checks. This argument is only supported if ``use_reentrant=False``, if ``use_reentrant=True``, the determinism check is always disabled. debug(bool, optional): If ``True``, error messages will also include a trace of the operators ran during the original forward computation as well as the recomputation. This argument is only supported if ``use_reentrant=False``. args: tuple containing inputs to the :attr:`function` Returns: Output of running :attr:`function` on :attr:`*args` """ if use_reentrant is None: warnings.warn( "torch.utils.checkpoint: the use_reentrant parameter should be " "passed explicitly. In version 2.4 we will raise an exception " "if use_reentrant is not passed. use_reentrant=False is " "recommended, but if you need to preserve the current default " "behavior, you can pass use_reentrant=True. Refer to docs for more " "details on the differences between the two variants.", stacklevel=2, ) use_reentrant = True # Hack to mix *args with **kwargs in a python 2.7-compliant way preserve = kwargs.pop("preserve_rng_state", True) if kwargs and use_reentrant: raise ValueError("Unexpected keyword arguments: " + ",".join(arg for arg in kwargs)) if use_reentrant: if context_fn is not noop_context_fn or debug is not False: raise ValueError("Passing `context_fn` or `debug` is only supported when " "use_reentrant=False.") return CheckpointFunctionWithOffload.apply(function, preserve, *args) else: gen = _checkpoint_without_reentrant_generator( function, preserve, context_fn, determinism_check, debug, *args, **kwargs ) # Runs pre-forward logic next(gen) ret = function(*args, **kwargs) # Runs post-forward logic try: next(gen) except StopIteration: return ret def set_grad_checkpoint(model, use_fp32_attention=False, gc_step=1): assert isinstance(model, nn.Module) def set_attr(module): module.grad_checkpointing = True module.fp32_attention = use_fp32_attention module.grad_checkpointing_step = gc_step model.apply(set_attr) def auto_grad_checkpoint(module, *args, **kwargs): if getattr(module, "grad_checkpointing", False): if not isinstance(module, Iterable): return checkpoint(module, *args, use_reentrant=True, **kwargs) gc_step = module[0].grad_checkpointing_step return checkpoint_sequential(module, gc_step, *args, use_reentrant=False, **kwargs) return module(*args, **kwargs) ================================================ FILE: opensora/acceleration/communications.py ================================================ import torch import torch.distributed as dist # ==================== # All-To-All # ==================== def _all_to_all( input_: torch.Tensor, world_size: int, group: dist.ProcessGroup, scatter_dim: int, gather_dim: int, ): input_list = [t.contiguous() for t in torch.tensor_split(input_, world_size, scatter_dim)] output_list = [torch.empty_like(input_list[0]) for _ in range(world_size)] dist.all_to_all(output_list, input_list, group=group) return torch.cat(output_list, dim=gather_dim).contiguous() class _AllToAll(torch.autograd.Function): """All-to-all communication. Args: input_: input matrix process_group: communication group scatter_dim: scatter dimension gather_dim: gather dimension """ @staticmethod def forward(ctx, input_, process_group, scatter_dim, gather_dim): ctx.process_group = process_group ctx.scatter_dim = scatter_dim ctx.gather_dim = gather_dim ctx.world_size = dist.get_world_size(process_group) output = _all_to_all(input_, ctx.world_size, process_group, scatter_dim, gather_dim) return output @staticmethod def backward(ctx, grad_output): grad_output = _all_to_all( grad_output, ctx.world_size, ctx.process_group, ctx.gather_dim, ctx.scatter_dim, ) return ( grad_output, None, None, None, ) def all_to_all( input_: torch.Tensor, process_group: dist.ProcessGroup, scatter_dim: int = 2, gather_dim: int = 1, ): return _AllToAll.apply(input_, process_group, scatter_dim, gather_dim) def _gather( input_: torch.Tensor, world_size: int, group: dist.ProcessGroup, gather_dim: int, ): if gather_list is None: gather_list = [torch.empty_like(input_) for _ in range(world_size)] dist.gather(input_, gather_list, group=group, gather_dim=gather_dim) return gather_list # ==================== # Gather-Split # ==================== def _split(input_, pg: dist.ProcessGroup, dim=-1): # skip if only one rank involved world_size = dist.get_world_size(pg) rank = dist.get_rank(pg) if world_size == 1: return input_ # Split along last dimension. dim_size = input_.size(dim) assert dim_size % world_size == 0, ( f"The dimension to split ({dim_size}) is not a multiple of world size ({world_size}), " f"cannot split tensor evenly" ) tensor_list = torch.split(input_, dim_size // world_size, dim=dim) output = tensor_list[rank].contiguous() return output def _gather(input_, pg: dist.ProcessGroup, dim=-1): # skip if only one rank involved input_ = input_.contiguous() world_size = dist.get_world_size(pg) dist.get_rank(pg) if world_size == 1: return input_ # all gather tensor_list = [torch.empty_like(input_) for _ in range(world_size)] assert input_.device.type == "cuda" torch.distributed.all_gather(tensor_list, input_, group=pg) # concat output = torch.cat(tensor_list, dim=dim).contiguous() return output class _GatherForwardSplitBackward(torch.autograd.Function): """Gather the input from model parallel region and concatenate. Args: input_: input matrix. process_group: parallel mode. dim: dimension """ @staticmethod def symbolic(graph, input_): return _gather(input_) @staticmethod def forward(ctx, input_, process_group, dim, grad_scale): ctx.mode = process_group ctx.dim = dim ctx.grad_scale = grad_scale return _gather(input_, process_group, dim) @staticmethod def backward(ctx, grad_output): if ctx.grad_scale == "up": grad_output = grad_output * dist.get_world_size(ctx.mode) elif ctx.grad_scale == "down": grad_output = grad_output / dist.get_world_size(ctx.mode) return _split(grad_output, ctx.mode, ctx.dim), None, None, None class _SplitForwardGatherBackward(torch.autograd.Function): """ Split the input and keep only the corresponding chuck to the rank. Args: input_: input matrix. process_group: parallel mode. dim: dimension """ @staticmethod def symbolic(graph, input_): return _split(input_) @staticmethod def forward(ctx, input_, process_group, dim, grad_scale): ctx.mode = process_group ctx.dim = dim ctx.grad_scale = grad_scale return _split(input_, process_group, dim) @staticmethod def backward(ctx, grad_output): if ctx.grad_scale == "up": grad_output = grad_output * dist.get_world_size(ctx.mode) elif ctx.grad_scale == "down": grad_output = grad_output / dist.get_world_size(ctx.mode) return _gather(grad_output, ctx.mode, ctx.dim), None, None, None def split_forward_gather_backward(input_, process_group, dim, grad_scale=1.0): return _SplitForwardGatherBackward.apply(input_, process_group, dim, grad_scale) def gather_forward_split_backward(input_, process_group, dim, grad_scale=None): return _GatherForwardSplitBackward.apply(input_, process_group, dim, grad_scale) ================================================ FILE: opensora/acceleration/parallel_states.py ================================================ import torch.distributed as dist _GLOBAL_PARALLEL_GROUPS = dict() def set_data_parallel_group(group: dist.ProcessGroup): _GLOBAL_PARALLEL_GROUPS["data"] = group def get_data_parallel_group(get_mixed_dp_pg : bool = False): if get_mixed_dp_pg and "mixed_dp_group" in _GLOBAL_PARALLEL_GROUPS: return _GLOBAL_PARALLEL_GROUPS["mixed_dp_group"] return _GLOBAL_PARALLEL_GROUPS.get("data", dist.group.WORLD) def set_sequence_parallel_group(group: dist.ProcessGroup): _GLOBAL_PARALLEL_GROUPS["sequence"] = group def get_sequence_parallel_group(): return _GLOBAL_PARALLEL_GROUPS.get("sequence", None) def set_tensor_parallel_group(group: dist.ProcessGroup): _GLOBAL_PARALLEL_GROUPS["tensor"] = group def get_tensor_parallel_group(): return _GLOBAL_PARALLEL_GROUPS.get("tensor", None) ================================================ FILE: opensora/acceleration/shardformer/__init__.py ================================================ ================================================ FILE: opensora/acceleration/shardformer/modeling/__init__.py ================================================ ================================================ FILE: opensora/acceleration/shardformer/modeling/t5.py ================================================ import torch import torch.nn as nn class T5LayerNorm(nn.Module): def __init__(self, hidden_size, eps=1e-6): """ Construct a layernorm module in the T5 style. No bias and no subtraction of mean. """ super().__init__() self.weight = nn.Parameter(torch.ones(hidden_size)) self.variance_epsilon = eps def forward(self, hidden_states): # T5 uses a layer_norm which only scales and doesn't shift, which is also known as Root Mean # Square Layer Normalization https://arxiv.org/abs/1910.07467 thus varience is calculated # w/o mean and there is no bias. Additionally we want to make sure that the accumulation for # half-precision inputs is done in fp32 variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True) hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon) # convert into half-precision if necessary if self.weight.dtype in [torch.float16, torch.bfloat16]: hidden_states = hidden_states.to(self.weight.dtype) return self.weight * hidden_states @staticmethod def from_native_module(module, *args, **kwargs): assert module.__class__.__name__ == "FusedRMSNorm", ( "Recovering T5LayerNorm requires the original layer to be apex's Fused RMS Norm." "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" ) layer_norm = T5LayerNorm(module.normalized_shape, eps=module.eps) layer_norm.weight.data.copy_(module.weight.data) layer_norm = layer_norm.to(module.weight.device) return layer_norm ================================================ FILE: opensora/acceleration/shardformer/policy/__init__.py ================================================ ================================================ FILE: opensora/acceleration/shardformer/policy/t5_encoder.py ================================================ from colossalai.shardformer.modeling.jit import get_jit_fused_dropout_add_func from colossalai.shardformer.modeling.t5 import get_jit_fused_T5_layer_ff_forward, get_T5_layer_self_attention_forward from colossalai.shardformer.policies.base_policy import Policy, SubModuleReplacementDescription class T5EncoderPolicy(Policy): def config_sanity_check(self): assert not self.shard_config.enable_tensor_parallelism assert not self.shard_config.enable_flash_attention def preprocess(self): return self.model def module_policy(self): from transformers.models.t5.modeling_t5 import T5LayerFF, T5LayerSelfAttention, T5Stack policy = {} # use jit operator if self.shard_config.enable_jit_fused: self.append_or_create_method_replacement( description={ "forward": get_jit_fused_T5_layer_ff_forward(), "dropout_add": get_jit_fused_dropout_add_func(), }, policy=policy, target_key=T5LayerFF, ) self.append_or_create_method_replacement( description={ "forward": get_T5_layer_self_attention_forward(), "dropout_add": get_jit_fused_dropout_add_func(), }, policy=policy, target_key=T5LayerSelfAttention, ) return policy def postprocess(self): return self.model ================================================ FILE: opensora/models/__init__.py ================================================ from .dc_ae import * from .hunyuan_vae import * from .mmdit import * from .text import * from .vae import * ================================================ FILE: opensora/models/dc_ae/__init__.py ================================================ from .ae_model_zoo import DC_AE ================================================ FILE: opensora/models/dc_ae/ae_model_zoo.py ================================================ # Copyright 2024 MIT Han Lab # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # SPDX-License-Identifier: Apache-2.0 from typing import Callable, Optional import diffusers import torch from huggingface_hub import PyTorchModelHubMixin from torch import nn from opensora.registry import MODELS from opensora.utils.ckpt import load_checkpoint from .models.dc_ae import DCAE, DCAEConfig, dc_ae_f32 __all__ = ["create_dc_ae_model_cfg", "DCAE_HF", "DC_AE"] REGISTERED_DCAE_MODEL: dict[str, tuple[Callable, Optional[str]]] = { "dc-ae-f32t4c128": (dc_ae_f32, None), } def create_dc_ae_model_cfg(name: str, pretrained_path: Optional[str] = None) -> DCAEConfig: assert name in REGISTERED_DCAE_MODEL, f"{name} is not supported" dc_ae_cls, default_pt_path = REGISTERED_DCAE_MODEL[name] pretrained_path = default_pt_path if pretrained_path is None else pretrained_path model_cfg = dc_ae_cls(name, pretrained_path) return model_cfg class DCAE_HF(DCAE, PyTorchModelHubMixin): def __init__(self, model_name: str): cfg = create_dc_ae_model_cfg(model_name) DCAE.__init__(self, cfg) @MODELS.register_module("dc_ae") def DC_AE( model_name: str, device_map: str | torch.device = "cuda", torch_dtype: torch.dtype = torch.bfloat16, from_scratch: bool = False, from_pretrained: str | None = None, is_training: bool = False, use_spatial_tiling: bool = False, use_temporal_tiling: bool = False, spatial_tile_size: int = 256, temporal_tile_size: int = 32, tile_overlap_factor: float = 0.25, scaling_factor: float = None, disc_off_grad_ckpt: bool = False, ) -> DCAE_HF: if not from_scratch: model = DCAE_HF.from_pretrained(model_name).to(device_map, torch_dtype) else: model = DCAE_HF(model_name).to(device_map, torch_dtype) if from_pretrained is not None: model = load_checkpoint(model, from_pretrained, device_map=device_map) print(f"loaded dc_ae from ckpt path: {from_pretrained}") model.cfg.is_training = is_training model.use_spatial_tiling = use_spatial_tiling model.use_temporal_tiling = use_temporal_tiling model.spatial_tile_size = spatial_tile_size model.temporal_tile_size = temporal_tile_size model.tile_overlap_factor = tile_overlap_factor if scaling_factor is not None: model.scaling_factor = scaling_factor model.decoder.disc_off_grad_ckpt = disc_off_grad_ckpt return model ================================================ FILE: opensora/models/dc_ae/models/__init__.py ================================================ from .dc_ae import * ================================================ FILE: opensora/models/dc_ae/models/dc_ae.py ================================================ # Copyright 2024 MIT Han Lab # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # SPDX-License-Identifier: Apache-2.0 from dataclasses import dataclass, field from typing import Any, Optional import torch import torch.nn as nn from omegaconf import MISSING, OmegaConf from torch import Tensor from opensora.acceleration.checkpoint import auto_grad_checkpoint from ..utils import init_modules from .nn.act import build_act from .nn.norm import build_norm from .nn.ops import ( ChannelDuplicatingPixelShuffleUpSampleLayer, ConvLayer, ConvPixelShuffleUpSampleLayer, ConvPixelUnshuffleDownSampleLayer, EfficientViTBlock, IdentityLayer, InterpolateConvUpSampleLayer, OpSequential, PixelUnshuffleChannelAveragingDownSampleLayer, ResBlock, ResidualBlock, ) __all__ = ["DCAE", "dc_ae_f32"] @dataclass class EncoderConfig: in_channels: int = MISSING latent_channels: int = MISSING width_list: tuple[int, ...] = (128, 256, 512, 512, 1024, 1024) depth_list: tuple[int, ...] = (2, 2, 2, 2, 2, 2) block_type: Any = "ResBlock" norm: str = "rms2d" act: str = "silu" downsample_block_type: str = "ConvPixelUnshuffle" downsample_match_channel: bool = True downsample_shortcut: Optional[str] = "averaging" out_norm: Optional[str] = None out_act: Optional[str] = None out_shortcut: Optional[str] = "averaging" double_latent: bool = False is_video: bool = False temporal_downsample: tuple[bool, ...] = () @dataclass class DecoderConfig: in_channels: int = MISSING latent_channels: int = MISSING in_shortcut: Optional[str] = "duplicating" width_list: tuple[int, ...] = (128, 256, 512, 512, 1024, 1024) depth_list: tuple[int, ...] = (2, 2, 2, 2, 2, 2) block_type: Any = "ResBlock" norm: Any = "rms2d" act: Any = "silu" upsample_block_type: str = "ConvPixelShuffle" upsample_match_channel: bool = True upsample_shortcut: str = "duplicating" out_norm: str = "rms2d" out_act: str = "relu" is_video: bool = False temporal_upsample: tuple[bool, ...] = () @dataclass class DCAEConfig: in_channels: int = 3 latent_channels: int = 32 time_compression_ratio: int = 1 spatial_compression_ratio: int = 32 encoder: EncoderConfig = field( default_factory=lambda: EncoderConfig(in_channels="${..in_channels}", latent_channels="${..latent_channels}") ) decoder: DecoderConfig = field( default_factory=lambda: DecoderConfig(in_channels="${..in_channels}", latent_channels="${..latent_channels}") ) use_quant_conv: bool = False pretrained_path: Optional[str] = None pretrained_source: str = "dc-ae" scaling_factor: Optional[float] = None is_image_model: bool = False is_training: bool = False # NOTE: set to True in vae train config use_spatial_tiling: bool = False use_temporal_tiling: bool = False spatial_tile_size: int = 256 temporal_tile_size: int = 32 tile_overlap_factor: float = 0.25 def build_block( block_type: str, in_channels: int, out_channels: int, norm: Optional[str], act: Optional[str], is_video: bool ) -> nn.Module: if block_type == "ResBlock": assert in_channels == out_channels main_block = ResBlock( in_channels=in_channels, out_channels=out_channels, kernel_size=3, stride=1, use_bias=(True, False), norm=(None, norm), act_func=(act, None), is_video=is_video, ) block = ResidualBlock(main_block, IdentityLayer()) elif block_type == "EViT_GLU": assert in_channels == out_channels block = EfficientViTBlock( in_channels, norm=norm, act_func=act, local_module="GLUMBConv", scales=(), is_video=is_video ) elif block_type == "EViTS5_GLU": assert in_channels == out_channels block = EfficientViTBlock( in_channels, norm=norm, act_func=act, local_module="GLUMBConv", scales=(5,), is_video=is_video ) else: raise ValueError(f"block_type {block_type} is not supported") return block def build_stage_main( width: int, depth: int, block_type: str | list[str], norm: str, act: str, input_width: int, is_video: bool ) -> list[nn.Module]: assert isinstance(block_type, str) or (isinstance(block_type, list) and depth == len(block_type)) stage = [] for d in range(depth): current_block_type = block_type[d] if isinstance(block_type, list) else block_type block = build_block( block_type=current_block_type, in_channels=width if d > 0 else input_width, out_channels=width, norm=norm, act=act, is_video=is_video, ) stage.append(block) return stage def build_downsample_block( block_type: str, in_channels: int, out_channels: int, shortcut: Optional[str], is_video: bool, temporal_downsample: bool = False, ) -> nn.Module: """ Spatial downsample is always performed. Temporal downsample is optional. """ if block_type == "Conv": if is_video: if temporal_downsample: stride = (2, 2, 2) else: stride = (1, 2, 2) else: stride = 2 block = ConvLayer( in_channels=in_channels, out_channels=out_channels, kernel_size=3, stride=stride, use_bias=True, norm=None, act_func=None, is_video=is_video, ) elif block_type == "ConvPixelUnshuffle": if is_video: raise NotImplementedError("ConvPixelUnshuffle downsample is not supported for video") block = ConvPixelUnshuffleDownSampleLayer( in_channels=in_channels, out_channels=out_channels, kernel_size=3, factor=2 ) else: raise ValueError(f"block_type {block_type} is not supported for downsampling") if shortcut is None: pass elif shortcut == "averaging": shortcut_block = PixelUnshuffleChannelAveragingDownSampleLayer( in_channels=in_channels, out_channels=out_channels, factor=2, temporal_downsample=temporal_downsample ) block = ResidualBlock(block, shortcut_block) else: raise ValueError(f"shortcut {shortcut} is not supported for downsample") return block def build_upsample_block( block_type: str, in_channels: int, out_channels: int, shortcut: Optional[str], is_video: bool, temporal_upsample: bool = False, ) -> nn.Module: if block_type == "ConvPixelShuffle": if is_video: raise NotImplementedError("ConvPixelShuffle upsample is not supported for video") block = ConvPixelShuffleUpSampleLayer( in_channels=in_channels, out_channels=out_channels, kernel_size=3, factor=2 ) elif block_type == "InterpolateConv": block = InterpolateConvUpSampleLayer( in_channels=in_channels, out_channels=out_channels, kernel_size=3, factor=2, is_video=is_video, temporal_upsample=temporal_upsample, ) else: raise ValueError(f"block_type {block_type} is not supported for upsampling") if shortcut is None: pass elif shortcut == "duplicating": shortcut_block = ChannelDuplicatingPixelShuffleUpSampleLayer( in_channels=in_channels, out_channels=out_channels, factor=2, temporal_upsample=temporal_upsample ) block = ResidualBlock(block, shortcut_block) else: raise ValueError(f"shortcut {shortcut} is not supported for upsample") return block def build_encoder_project_in_block( in_channels: int, out_channels: int, factor: int, downsample_block_type: str, is_video: bool ): if factor == 1: block = ConvLayer( in_channels=in_channels, out_channels=out_channels, kernel_size=3, stride=1, use_bias=True, norm=None, act_func=None, is_video=is_video, ) elif factor == 2: if is_video: raise NotImplementedError("Downsample during project_in is not supported for video") block = build_downsample_block( block_type=downsample_block_type, in_channels=in_channels, out_channels=out_channels, shortcut=None ) else: raise ValueError(f"downsample factor {factor} is not supported for encoder project in") return block def build_encoder_project_out_block( in_channels: int, out_channels: int, norm: Optional[str], act: Optional[str], shortcut: Optional[str], is_video: bool, ): block = OpSequential( [ build_norm(norm), build_act(act), ConvLayer( in_channels=in_channels, out_channels=out_channels, kernel_size=3, stride=1, use_bias=True, norm=None, act_func=None, is_video=is_video, ), ] ) if shortcut is None: pass elif shortcut == "averaging": shortcut_block = PixelUnshuffleChannelAveragingDownSampleLayer( in_channels=in_channels, out_channels=out_channels, factor=1 ) block = ResidualBlock(block, shortcut_block) else: raise ValueError(f"shortcut {shortcut} is not supported for encoder project out") return block def build_decoder_project_in_block(in_channels: int, out_channels: int, shortcut: Optional[str], is_video: bool): block = ConvLayer( in_channels=in_channels, out_channels=out_channels, kernel_size=3, stride=1, use_bias=True, norm=None, act_func=None, is_video=is_video, ) if shortcut is None: pass elif shortcut == "duplicating": shortcut_block = ChannelDuplicatingPixelShuffleUpSampleLayer( in_channels=in_channels, out_channels=out_channels, factor=1 ) block = ResidualBlock(block, shortcut_block) else: raise ValueError(f"shortcut {shortcut} is not supported for decoder project in") return block def build_decoder_project_out_block( in_channels: int, out_channels: int, factor: int, upsample_block_type: str, norm: Optional[str], act: Optional[str], is_video: bool, ): layers: list[nn.Module] = [ build_norm(norm, in_channels), build_act(act), ] if factor == 1: layers.append( ConvLayer( in_channels=in_channels, out_channels=out_channels, kernel_size=3, stride=1, use_bias=True, norm=None, act_func=None, is_video=is_video, ) ) elif factor == 2: if is_video: raise NotImplementedError("Upsample during project_out is not supported for video") layers.append( build_upsample_block( block_type=upsample_block_type, in_channels=in_channels, out_channels=out_channels, shortcut=None ) ) else: raise ValueError(f"upsample factor {factor} is not supported for decoder project out") return OpSequential(layers) class Encoder(nn.Module): def __init__(self, cfg: EncoderConfig): super().__init__() self.cfg = cfg num_stages = len(cfg.width_list) self.num_stages = num_stages assert len(cfg.depth_list) == num_stages assert len(cfg.width_list) == num_stages assert isinstance(cfg.block_type, str) or ( isinstance(cfg.block_type, list) and len(cfg.block_type) == num_stages ) self.project_in = build_encoder_project_in_block( in_channels=cfg.in_channels, out_channels=cfg.width_list[0] if cfg.depth_list[0] > 0 else cfg.width_list[1], factor=1 if cfg.depth_list[0] > 0 else 2, downsample_block_type=cfg.downsample_block_type, is_video=cfg.is_video, ) self.stages: list[OpSequential] = [] for stage_id, (width, depth) in enumerate(zip(cfg.width_list, cfg.depth_list)): block_type = cfg.block_type[stage_id] if isinstance(cfg.block_type, list) else cfg.block_type stage = build_stage_main( width=width, depth=depth, block_type=block_type, norm=cfg.norm, act=cfg.act, input_width=width, is_video=cfg.is_video, ) if stage_id < num_stages - 1 and depth > 0: downsample_block = build_downsample_block( block_type=cfg.downsample_block_type, in_channels=width, out_channels=cfg.width_list[stage_id + 1] if cfg.downsample_match_channel else width, shortcut=cfg.downsample_shortcut, is_video=cfg.is_video, temporal_downsample=cfg.temporal_downsample[stage_id] if cfg.temporal_downsample != [] else False, ) stage.append(downsample_block) self.stages.append(OpSequential(stage)) self.stages = nn.ModuleList(self.stages) self.project_out = build_encoder_project_out_block( in_channels=cfg.width_list[-1], out_channels=2 * cfg.latent_channels if cfg.double_latent else cfg.latent_channels, norm=cfg.out_norm, act=cfg.out_act, shortcut=cfg.out_shortcut, is_video=cfg.is_video, ) def forward(self, x: torch.Tensor) -> torch.Tensor: x = self.project_in(x) # x = auto_grad_checkpoint(self.project_in, x) for stage in self.stages: if len(stage.op_list) == 0: continue x = auto_grad_checkpoint(stage, x) # x = self.project_out(x) x = auto_grad_checkpoint(self.project_out, x) return x class Decoder(nn.Module): def __init__(self, cfg: DecoderConfig): super().__init__() self.cfg = cfg num_stages = len(cfg.width_list) self.num_stages = num_stages assert len(cfg.depth_list) == num_stages assert len(cfg.width_list) == num_stages assert isinstance(cfg.block_type, str) or ( isinstance(cfg.block_type, list) and len(cfg.block_type) == num_stages ) assert isinstance(cfg.norm, str) or (isinstance(cfg.norm, list) and len(cfg.norm) == num_stages) assert isinstance(cfg.act, str) or (isinstance(cfg.act, list) and len(cfg.act) == num_stages) self.project_in = build_decoder_project_in_block( in_channels=cfg.latent_channels, out_channels=cfg.width_list[-1], shortcut=cfg.in_shortcut, is_video=cfg.is_video, ) self.stages: list[OpSequential] = [] for stage_id, (width, depth) in reversed(list(enumerate(zip(cfg.width_list, cfg.depth_list)))): stage = [] if stage_id < num_stages - 1 and depth > 0: upsample_block = build_upsample_block( block_type=cfg.upsample_block_type, in_channels=cfg.width_list[stage_id + 1], out_channels=width if cfg.upsample_match_channel else cfg.width_list[stage_id + 1], shortcut=cfg.upsample_shortcut, is_video=cfg.is_video, temporal_upsample=cfg.temporal_upsample[stage_id] if cfg.temporal_upsample != [] else False, ) stage.append(upsample_block) block_type = cfg.block_type[stage_id] if isinstance(cfg.block_type, list) else cfg.block_type norm = cfg.norm[stage_id] if isinstance(cfg.norm, list) else cfg.norm act = cfg.act[stage_id] if isinstance(cfg.act, list) else cfg.act stage.extend( build_stage_main( width=width, depth=depth, block_type=block_type, norm=norm, act=act, input_width=( width if cfg.upsample_match_channel else cfg.width_list[min(stage_id + 1, num_stages - 1)] ), is_video=cfg.is_video, ) ) self.stages.insert(0, OpSequential(stage)) self.stages = nn.ModuleList(self.stages) self.project_out = build_decoder_project_out_block( in_channels=cfg.width_list[0] if cfg.depth_list[0] > 0 else cfg.width_list[1], out_channels=cfg.in_channels, factor=1 if cfg.depth_list[0] > 0 else 2, upsample_block_type=cfg.upsample_block_type, norm=cfg.out_norm, act=cfg.out_act, is_video=cfg.is_video, ) def forward(self, x: torch.Tensor) -> torch.Tensor: x = auto_grad_checkpoint(self.project_in, x) for stage in reversed(self.stages): if len(stage.op_list) == 0: continue # x = stage(x) x = auto_grad_checkpoint(stage, x) if self.disc_off_grad_ckpt: x = self.project_out(x) else: x = auto_grad_checkpoint(self.project_out, x) return x class DCAE(nn.Module): def __init__(self, cfg: DCAEConfig): super().__init__() self.cfg = cfg self.encoder = Encoder(cfg.encoder) self.decoder = Decoder(cfg.decoder) self.scaling_factor = cfg.scaling_factor self.time_compression_ratio = cfg.time_compression_ratio self.spatial_compression_ratio = cfg.spatial_compression_ratio self.use_spatial_tiling = cfg.use_spatial_tiling self.use_temporal_tiling = cfg.use_temporal_tiling self.spatial_tile_size = cfg.spatial_tile_size self.temporal_tile_size = cfg.temporal_tile_size assert ( cfg.spatial_tile_size // cfg.spatial_compression_ratio ), f"spatial tile size {cfg.spatial_tile_size} must be divisible by spatial compression of {cfg.spatial_compression_ratio}" self.spatial_tile_latent_size = cfg.spatial_tile_size // cfg.spatial_compression_ratio assert ( cfg.temporal_tile_size // cfg.time_compression_ratio ), f"temporal tile size {cfg.temporal_tile_size} must be divisible by temporal compression of {cfg.time_compression_ratio}" self.temporal_tile_latent_size = cfg.temporal_tile_size // cfg.time_compression_ratio self.tile_overlap_factor = cfg.tile_overlap_factor if self.cfg.pretrained_path is not None: self.load_model() self.to(torch.float32) init_modules(self, init_type="trunc_normal") def load_model(self): if self.cfg.pretrained_source == "dc-ae": state_dict = torch.load(self.cfg.pretrained_path, map_location="cpu", weights_only=True)["state_dict"] self.load_state_dict(state_dict) else: raise NotImplementedError def get_last_layer(self): return self.decoder.project_out.op_list[2].conv.weight # @property # def spatial_compression_ratio(self) -> int: # return 2 ** (self.decoder.num_stages - 1) def encode_single(self, x: torch.Tensor, is_video_encoder: bool = False) -> torch.Tensor: assert x.shape[0] == 1 is_video = x.dim() == 5 if is_video and not is_video_encoder: b, c, f, h, w = x.shape x = x.permute(0, 2, 1, 3, 4).reshape(-1, c, h, w) z = self.encoder(x) if is_video and not is_video_encoder: z = z.unsqueeze(dim=0).permute(0, 2, 1, 3, 4) if self.scaling_factor is not None: z = z / self.scaling_factor return z def _encode(self, x: torch.Tensor) -> torch.Tensor: if self.cfg.is_training: return self.encoder(x) is_video_encoder = self.encoder.cfg.is_video if self.encoder.cfg.is_video is not None else False x_ret = [] for i in range(x.shape[0]): x_ret.append(self.encode_single(x[i : i + 1], is_video_encoder)) return torch.cat(x_ret, dim=0) def blend_v(self, a: torch.Tensor, b: torch.Tensor, blend_extent: int) -> torch.Tensor: blend_extent = min(a.shape[-2], b.shape[-2], blend_extent) for y in range(blend_extent): b[:, :, :, y, :] = a[:, :, :, -blend_extent + y, :] * (1 - y / blend_extent) + b[:, :, :, y, :] * ( y / blend_extent ) return b def blend_h(self, a: torch.Tensor, b: torch.Tensor, blend_extent: int) -> torch.Tensor: blend_extent = min(a.shape[-1], b.shape[-1], blend_extent) for x in range(blend_extent): b[:, :, :, :, x] = a[:, :, :, :, -blend_extent + x] * (1 - x / blend_extent) + b[:, :, :, :, x] * ( x / blend_extent ) return b def blend_t(self, a: torch.Tensor, b: torch.Tensor, blend_extent: int) -> torch.Tensor: blend_extent = min(a.shape[-3], b.shape[-3], blend_extent) for x in range(blend_extent): b[:, :, x, :, :] = a[:, :, -blend_extent + x, :, :] * (1 - x / blend_extent) + b[:, :, x, :, :] * ( x / blend_extent ) return b def spatial_tiled_encode(self, x: torch.Tensor) -> torch.Tensor: net_size = int(self.spatial_tile_size * (1 - self.tile_overlap_factor)) blend_extent = int(self.spatial_tile_latent_size * self.tile_overlap_factor) row_limit = self.spatial_tile_latent_size - blend_extent # Split video into tiles and encode them separately. rows = [] for i in range(0, x.shape[-2], net_size): row = [] for j in range(0, x.shape[-1], net_size): tile = x[:, :, :, i : i + self.spatial_tile_size, j : j + self.spatial_tile_size] tile = self._encode(tile) row.append(tile) rows.append(row) result_rows = [] for i, row in enumerate(rows): result_row = [] for j, tile in enumerate(row): # blend the above tile and the left tile # to the current tile and add the current tile to the result row if i > 0: tile = self.blend_v(rows[i - 1][j], tile, blend_extent) if j > 0: tile = self.blend_h(row[j - 1], tile, blend_extent) result_row.append(tile[:, :, :, :row_limit, :row_limit]) result_rows.append(torch.cat(result_row, dim=-1)) return torch.cat(result_rows, dim=-2) def temporal_tiled_encode(self, x: torch.Tensor) -> torch.Tensor: overlap_size = int(self.temporal_tile_size * (1 - self.tile_overlap_factor)) blend_extent = int(self.temporal_tile_latent_size * self.tile_overlap_factor) t_limit = self.temporal_tile_latent_size - blend_extent # Split the video into tiles and encode them separately. row = [] for i in range(0, x.shape[2], overlap_size): tile = x[:, :, i : i + self.temporal_tile_size, :, :] if self.use_spatial_tiling and ( tile.shape[-1] > self.spatial_tile_size or tile.shape[-2] > self.spatial_tile_size ): tile = self.spatial_tiled_encode(tile) else: tile = self._encode(tile) row.append(tile) result_row = [] for i, tile in enumerate(row): if i > 0: tile = self.blend_t(row[i - 1], tile, blend_extent) result_row.append(tile[:, :, :t_limit, :, :]) return torch.cat(result_row, dim=2) def encode(self, x: torch.Tensor) -> torch.Tensor: if self.use_temporal_tiling and x.shape[2] > self.temporal_tile_size: return self.temporal_tiled_encode(x) elif self.use_spatial_tiling and (x.shape[-1] > self.spatial_tile_size or x.shape[-2] > self.spatial_tile_size): return self.spatial_tiled_encode(x) else: return self._encode(x) def spatial_tiled_decode(self, z: torch.FloatTensor) -> torch.Tensor: net_size = int(self.spatial_tile_latent_size * (1 - self.tile_overlap_factor)) blend_extent = int(self.spatial_tile_size * self.tile_overlap_factor) row_limit = self.spatial_tile_size - blend_extent # Split z into overlapping tiles and decode them separately. # The tiles have an overlap to avoid seams between tiles. rows = [] for i in range(0, z.shape[-2], net_size): row = [] for j in range(0, z.shape[-1], net_size): tile = z[:, :, :, i : i + self.spatial_tile_latent_size, j : j + self.spatial_tile_latent_size] decoded = self._decode(tile) row.append(decoded) rows.append(row) result_rows = [] for i, row in enumerate(rows): result_row = [] for j, tile in enumerate(row): # blend the above tile and the left tile # to the current tile and add the current tile to the result row if i > 0: tile = self.blend_v(rows[i - 1][j], tile, blend_extent) if j > 0: tile = self.blend_h(row[j - 1], tile, blend_extent) result_row.append(tile[:, :, :, :row_limit, :row_limit]) result_rows.append(torch.cat(result_row, dim=-1)) return torch.cat(result_rows, dim=-2) def temporal_tiled_decode(self, z: torch.Tensor) -> torch.Tensor: overlap_size = int(self.temporal_tile_latent_size * (1 - self.tile_overlap_factor)) blend_extent = int(self.temporal_tile_size * self.tile_overlap_factor) t_limit = self.temporal_tile_size - blend_extent row = [] for i in range(0, z.shape[2], overlap_size): tile = z[:, :, i : i + self.temporal_tile_latent_size, :, :] if self.use_spatial_tiling and ( tile.shape[-1] > self.spatial_tile_latent_size or tile.shape[-2] > self.spatial_tile_latent_size ): decoded = self.spatial_tiled_decode(tile) else: decoded = self._decode(tile) row.append(decoded) result_row = [] for i, tile in enumerate(row): if i > 0: tile = self.blend_t(row[i - 1], tile, blend_extent) result_row.append(tile[:, :, :t_limit, :, :]) return torch.cat(result_row, dim=2) def decode_single(self, z: torch.Tensor, is_video_decoder: bool = False) -> torch.Tensor: assert z.shape[0] == 1 is_video = z.dim() == 5 if is_video and not is_video_decoder: b, c, f, h, w = z.shape z = z.permute(0, 2, 1, 3, 4).reshape(-1, c, h, w) if self.scaling_factor is not None: z = z * self.scaling_factor x = self.decoder(z) if is_video and not is_video_decoder: x = x.unsqueeze(dim=0).permute(0, 2, 1, 3, 4) return x def _decode(self, z: torch.Tensor) -> torch.Tensor: if self.cfg.is_training: return self.decoder(z) is_video_decoder = self.decoder.cfg.is_video if self.decoder.cfg.is_video is not None else False x_ret = [] for i in range(z.shape[0]): x_ret.append(self.decode_single(z[i : i + 1], is_video_decoder)) return torch.cat(x_ret, dim=0) def decode(self, z: torch.Tensor) -> torch.Tensor: if self.use_temporal_tiling and z.shape[2] > self.temporal_tile_latent_size: return self.temporal_tiled_decode(z) elif self.use_spatial_tiling and ( z.shape[-1] > self.spatial_tile_latent_size or z.shape[-2] > self.spatial_tile_latent_size ): return self.spatial_tiled_decode(z) else: return self._decode(z) def forward(self, x: torch.Tensor) -> tuple[Any, Tensor, dict[Any, Any]]: x_type = x.dtype is_image_model = self.cfg.__dict__.get("is_image_model", False) x = x.to(self.encoder.project_in.conv.weight.dtype) if is_image_model: b, c, _, h, w = x.shape x = x.permute(0, 2, 1, 3, 4).reshape(-1, c, h, w) z = self.encode(x) dec = self.decode(z) if is_image_model: dec = dec.reshape(b, 1, c, h, w).permute(0, 2, 1, 3, 4) z = z.unsqueeze(dim=0).permute(0, 2, 1, 3, 4) dec = dec.to(x_type) return dec, None, z def get_latent_size(self, input_size: list[int]) -> list[int]: latent_size = [] # T latent_size.append((input_size[0] - 1) // self.time_compression_ratio + 1) # H, w for i in range(1, 3): latent_size.append((input_size[i] - 1) // self.spatial_compression_ratio + 1) return latent_size def dc_ae_f32(name: str, pretrained_path: str) -> DCAEConfig: if name in ["dc-ae-f32t4c128"]: cfg_str = ( "time_compression_ratio=4 " "spatial_compression_ratio=32 " "encoder.block_type=[ResBlock,ResBlock,ResBlock,EViTS5_GLU,EViTS5_GLU,EViTS5_GLU] " "encoder.width_list=[128,256,512,512,1024,1024] encoder.depth_list=[2,2,2,3,3,3] " "encoder.downsample_block_type=Conv " "encoder.norm=rms3d " "encoder.is_video=True " "decoder.block_type=[ResBlock,ResBlock,ResBlock,EViTS5_GLU,EViTS5_GLU,EViTS5_GLU] " "decoder.width_list=[128,256,512,512,1024,1024] decoder.depth_list=[3,3,3,3,3,3] " "decoder.upsample_block_type=InterpolateConv " "decoder.norm=rms3d decoder.act=silu decoder.out_norm=rms3d " "decoder.is_video=True " "encoder.temporal_downsample=[False,False,False,True,True,False] " "decoder.temporal_upsample=[False,False,False,True,True,False] " "latent_channels=128" ) # make sure there is no trailing blankspace in the last line else: raise NotImplementedError cfg = OmegaConf.from_dotlist(cfg_str.split(" ")) cfg: DCAEConfig = OmegaConf.to_object(OmegaConf.merge(OmegaConf.structured(DCAEConfig), cfg)) cfg.pretrained_path = pretrained_path return cfg ================================================ FILE: opensora/models/dc_ae/models/nn/__init__.py ================================================ from .act import * from .norm import * from .ops import * ================================================ FILE: opensora/models/dc_ae/models/nn/act.py ================================================ # Copyright 2024 MIT Han Lab # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # SPDX-License-Identifier: Apache-2.0 from functools import partial from typing import Optional import torch.nn as nn from ..nn.vo_ops import build_kwargs_from_config __all__ = ["build_act"] # register activation function here REGISTERED_ACT_DICT: dict[str, type] = { "relu": nn.ReLU, "relu6": nn.ReLU6, "hswish": nn.Hardswish, "silu": nn.SiLU, "gelu": partial(nn.GELU, approximate="tanh"), } def build_act(name: str, **kwargs) -> Optional[nn.Module]: if name in REGISTERED_ACT_DICT: act_cls = REGISTERED_ACT_DICT[name] args = build_kwargs_from_config(kwargs, act_cls) return act_cls(**args) else: return None ================================================ FILE: opensora/models/dc_ae/models/nn/norm.py ================================================ # Copyright 2024 MIT Han Lab # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # SPDX-License-Identifier: Apache-2.0 from typing import Optional import torch import torch.nn as nn from torch.nn.modules.batchnorm import _BatchNorm from ..nn.vo_ops import build_kwargs_from_config __all__ = ["LayerNorm2d", "build_norm", "set_norm_eps"] class LayerNorm2d(nn.LayerNorm): def forward(self, x: torch.Tensor) -> torch.Tensor: out = x - torch.mean(x, dim=1, keepdim=True) out = out / torch.sqrt(torch.square(out).mean(dim=1, keepdim=True) + self.eps) if self.elementwise_affine: out = out * self.weight.view(1, -1, 1, 1) + self.bias.view(1, -1, 1, 1) return out class RMSNorm2d(nn.Module): def __init__( self, num_features: int, eps: float = 1e-5, elementwise_affine: bool = True, bias: bool = True ) -> None: super().__init__() self.num_features = num_features self.eps = eps self.elementwise_affine = elementwise_affine if self.elementwise_affine: self.weight = torch.nn.parameter.Parameter(torch.empty(self.num_features)) if bias: self.bias = torch.nn.parameter.Parameter(torch.empty(self.num_features)) else: self.register_parameter("bias", None) else: self.register_parameter("weight", None) self.register_parameter("bias", None) def forward(self, x: torch.Tensor) -> torch.Tensor: x = (x / torch.sqrt(torch.square(x.float()).mean(dim=1, keepdim=True) + self.eps)).to(x.dtype) if self.elementwise_affine: x = x * self.weight.view(1, -1, 1, 1) + self.bias.view(1, -1, 1, 1) return x class RMSNorm3d(RMSNorm2d): def forward(self, x: torch.Tensor) -> torch.Tensor: x = (x / torch.sqrt(torch.square(x.float()).mean(dim=1, keepdim=True) + self.eps)).to(x.dtype) if self.elementwise_affine: x = x * self.weight.view(1, -1, 1, 1, 1) + self.bias.view(1, -1, 1, 1, 1) return x # register normalization function here REGISTERED_NORM_DICT: dict[str, type] = { "bn2d": nn.BatchNorm2d, "ln": nn.LayerNorm, "ln2d": LayerNorm2d, "rms2d": RMSNorm2d, "rms3d": RMSNorm3d, } def build_norm(name="bn2d", num_features=None, **kwargs) -> Optional[nn.Module]: if name in ["ln", "ln2d"]: kwargs["normalized_shape"] = num_features else: kwargs["num_features"] = num_features if name in REGISTERED_NORM_DICT: norm_cls = REGISTERED_NORM_DICT[name] args = build_kwargs_from_config(kwargs, norm_cls) return norm_cls(**args) else: return None def set_norm_eps(model: nn.Module, eps: Optional[float] = None) -> None: for m in model.modules(): if isinstance(m, (nn.GroupNorm, nn.LayerNorm, _BatchNorm)): if eps is not None: m.eps = eps ================================================ FILE: opensora/models/dc_ae/models/nn/ops.py ================================================ # Copyright 2024 MIT Han Lab # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # SPDX-License-Identifier: Apache-2.0 # upsample on the temporal dimension as well from typing import Optional import torch import torch.nn as nn import torch.nn.functional as F from opensora.models.vae.utils import ChannelChunkConv3d from ...models.nn.act import build_act from ...models.nn.norm import build_norm from ...models.nn.vo_ops import chunked_interpolate, get_same_padding, pixel_shuffle_3d, pixel_unshuffle_3d, resize from ...utils import list_sum, val2list, val2tuple __all__ = [ "ConvLayer", "UpSampleLayer", "ConvPixelUnshuffleDownSampleLayer", "PixelUnshuffleChannelAveragingDownSampleLayer", "ConvPixelShuffleUpSampleLayer", "ChannelDuplicatingPixelShuffleUpSampleLayer", "LinearLayer", "IdentityLayer", "DSConv", "MBConv", "FusedMBConv", "ResBlock", "LiteMLA", "EfficientViTBlock", "ResidualBlock", "DAGBlock", "OpSequential", ] ################################################################################# # Basic Layers # ################################################################################# class ConvLayer(nn.Module): def __init__( self, in_channels: int, out_channels: int, kernel_size=3, stride=1, dilation=1, groups=1, use_bias=False, dropout=0, norm="bn2d", act_func="relu", is_video=False, pad_mode_3d="constant", ): super().__init__() self.is_video = is_video if self.is_video: assert dilation == 1, "only support dilation=1 for 3d conv" assert kernel_size % 2 == 1, "only support odd kernel size for 3d conv" self.pad_mode_3d = pad_mode_3d # 3d padding follows CausalConv3d by Hunyuan # padding = ( # kernel_size // 2, # kernel_size // 2, # kernel_size // 2, # kernel_size // 2, # kernel_size - 1, # 0, # ) # W, H, T # non-causal padding padding = ( kernel_size // 2, kernel_size // 2, kernel_size // 2, kernel_size // 2, kernel_size // 2, kernel_size // 2, ) self.padding = padding self.dropout = nn.Dropout3d(dropout, inplace=False) if dropout > 0 else None assert isinstance(stride, (int, tuple)), "stride must be an integer or 3-tuple for 3d conv" self.conv = ChannelChunkConv3d( # padding is handled by F.pad() in forward() in_channels, out_channels, kernel_size=(kernel_size, kernel_size, kernel_size), stride=(stride, stride, stride) if isinstance(stride, int) else stride, groups=groups, bias=use_bias, ) else: padding = get_same_padding(kernel_size) padding *= dilation self.dropout = nn.Dropout2d(dropout, inplace=False) if dropout > 0 else None self.conv = nn.Conv2d( in_channels, out_channels, kernel_size=(kernel_size, kernel_size), stride=(stride, stride), padding=padding, dilation=(dilation, dilation), groups=groups, bias=use_bias, ) self.norm = build_norm(norm, num_features=out_channels) self.act = build_act(act_func) self.pad = F.pad def forward(self, x: torch.Tensor) -> torch.Tensor: if self.dropout is not None: x = self.dropout(x) if self.is_video: # custom padding for 3d conv x = self.pad(x, self.padding, mode=self.pad_mode_3d) # "constant" padding defaults to 0 x = self.conv(x) if self.norm: x = self.norm(x) if self.act: x = self.act(x) return x class UpSampleLayer(nn.Module): def __init__( self, mode="bicubic", size: Optional[int | tuple[int, int] | list[int]] = None, factor=2, align_corners=False, ): super().__init__() self.mode = mode self.size = val2list(size, 2) if size is not None else None self.factor = None if self.size is not None else factor self.align_corners = align_corners @torch.autocast(device_type="cuda", enabled=False) def forward(self, x: torch.Tensor) -> torch.Tensor: if (self.size is not None and tuple(x.shape[-2:]) == self.size) or self.factor == 1: return x if x.dtype in [torch.float16, torch.bfloat16]: x = x.float() return resize(x, self.size, self.factor, self.mode, self.align_corners) class ConvPixelUnshuffleDownSampleLayer(nn.Module): def __init__( self, in_channels: int, out_channels: int, kernel_size: int, factor: int, ): super().__init__() self.factor = factor out_ratio = factor**2 assert out_channels % out_ratio == 0 self.conv = ConvLayer( in_channels=in_channels, out_channels=out_channels // out_ratio, kernel_size=kernel_size, use_bias=True, norm=None, act_func=None, ) def forward(self, x: torch.Tensor) -> torch.Tensor: x = self.conv(x) x = F.pixel_unshuffle(x, self.factor) return x class PixelUnshuffleChannelAveragingDownSampleLayer(nn.Module): def __init__( self, in_channels: int, out_channels: int, factor: int, temporal_downsample: bool = False, # temporal downsample for 5d input tensor ): super().__init__() self.in_channels = in_channels self.out_channels = out_channels self.factor = factor self.temporal_downsample = temporal_downsample def forward(self, x: torch.Tensor) -> torch.Tensor: if x.dim() == 4: assert self.in_channels * self.factor**2 % self.out_channels == 0 group_size = self.in_channels * self.factor**2 // self.out_channels x = F.pixel_unshuffle(x, self.factor) B, C, H, W = x.shape x = x.view(B, self.out_channels, group_size, H, W) x = x.mean(dim=2) elif x.dim() == 5: # [B, C, T, H, W] _, _, T, _, _ = x.shape if self.temporal_downsample and T != 1: # 3d pixel unshuffle x = pixel_unshuffle_3d(x, self.factor) assert self.in_channels * self.factor**3 % self.out_channels == 0 group_size = self.in_channels * self.factor**3 // self.out_channels else: # 2d pixel unshuffle x = x.permute(0, 2, 1, 3, 4) # [B, T, C, H, W] x = F.pixel_unshuffle(x, self.factor) x = x.permute(0, 2, 1, 3, 4) # [B, C, T, H, W] assert self.in_channels * self.factor**2 % self.out_channels == 0 group_size = self.in_channels * self.factor**2 // self.out_channels B, C, T, H, W = x.shape x = x.view(B, self.out_channels, group_size, T, H, W) x = x.mean(dim=2) else: raise ValueError(f"Unsupported input dimension: {x.dim()}") return x def __repr__(self): return f"PixelUnshuffleChannelAveragingDownSampleLayer(in_channels={self.in_channels}, out_channels={self.out_channels}, factor={self.factor}), temporal_downsample={self.temporal_downsample}" class ConvPixelShuffleUpSampleLayer(nn.Module): def __init__( self, in_channels: int, out_channels: int, kernel_size: int, factor: int, ): super().__init__() self.factor = factor out_ratio = factor**2 self.conv = ConvLayer( in_channels=in_channels, out_channels=out_channels * out_ratio, kernel_size=kernel_size, use_bias=True, norm=None, act_func=None, ) def forward(self, x: torch.Tensor) -> torch.Tensor: x = self.conv(x) x = F.pixel_shuffle(x, self.factor) return x class InterpolateConvUpSampleLayer(nn.Module): def __init__( self, in_channels: int, out_channels: int, kernel_size: int, factor: int, mode: str = "nearest", is_video: bool = False, temporal_upsample: bool = False, ) -> None: super().__init__() self.factor = factor self.mode = mode self.temporal_upsample = temporal_upsample self.conv = ConvLayer( in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, use_bias=True, norm=None, act_func=None, is_video=is_video, ) def forward(self, x: torch.Tensor) -> torch.Tensor: if x.dim() == 4: x = F.interpolate(x, scale_factor=self.factor, mode=self.mode) elif x.dim() == 5: # [B, C, T, H, W] -> [B, C, T*factor, H*factor, W*factor] if self.temporal_upsample and x.size(2) != 1: # temporal upsample for video input x = chunked_interpolate(x, scale_factor=[self.factor, self.factor, self.factor], mode=self.mode) else: x = chunked_interpolate(x, scale_factor=[1, self.factor, self.factor], mode=self.mode) x = self.conv(x) return x def __repr__(self): return f"InterpolateConvUpSampleLayer(factor={self.factor}, mode={self.mode}, temporal_upsample={self.temporal_upsample})" class ChannelDuplicatingPixelShuffleUpSampleLayer(nn.Module): def __init__( self, in_channels: int, out_channels: int, factor: int, temporal_upsample: bool = False, # upsample on the temporal dimension as well ): super().__init__() self.in_channels = in_channels self.out_channels = out_channels self.factor = factor assert out_channels * factor**2 % in_channels == 0 self.temporal_upsample = temporal_upsample def forward(self, x: torch.Tensor) -> torch.Tensor: if x.dim() == 5: B, C, T, H, W = x.shape assert C == self.in_channels if self.temporal_upsample and T != 1: # video input repeats = self.out_channels * self.factor**3 // self.in_channels else: repeats = self.out_channels * self.factor**2 // self.in_channels x = x.repeat_interleave(repeats, dim=1) if x.dim() == 4: # original image-only training x = F.pixel_shuffle(x, self.factor) elif x.dim() == 5: # [B, C, T, H, W] if self.temporal_upsample and T != 1: # video input x = pixel_shuffle_3d(x, self.factor) else: x = x.permute(0, 2, 1, 3, 4) # [B, T, C, H, W] x = F.pixel_shuffle(x, self.factor) # on H and W only x = x.permute(0, 2, 1, 3, 4) # [B, C, T, H, W] return x def __repr__(self): return f"ChannelDuplicatingPixelShuffleUpSampleLayer(in_channels={self.in_channels}, out_channels={self.out_channels}, factor={self.factor}, temporal_upsample={self.temporal_upsample})" class LinearLayer(nn.Module): def __init__( self, in_features: int, out_features: int, use_bias=True, dropout=0, norm=None, act_func=None, ): super().__init__() self.dropout = nn.Dropout(dropout, inplace=False) if dropout > 0 else None self.linear = nn.Linear(in_features, out_features, use_bias) self.norm = build_norm(norm, num_features=out_features) self.act = build_act(act_func) def _try_squeeze(self, x: torch.Tensor) -> torch.Tensor: if x.dim() > 2: x = torch.flatten(x, start_dim=1) return x def forward(self, x: torch.Tensor) -> torch.Tensor: x = self._try_squeeze(x) if self.dropout: x = self.dropout(x) x = self.linear(x) if self.norm: x = self.norm(x) if self.act: x = self.act(x) return x class IdentityLayer(nn.Module): def forward(self, x: torch.Tensor) -> torch.Tensor: return x ################################################################################# # Basic Blocks # ################################################################################# class DSConv(nn.Module): def __init__( self, in_channels: int, out_channels: int, kernel_size=3, stride=1, use_bias=False, norm=("bn2d", "bn2d"), act_func=("relu6", None), ): super().__init__() use_bias = val2tuple(use_bias, 2) norm = val2tuple(norm, 2) act_func = val2tuple(act_func, 2) self.depth_conv = ConvLayer( in_channels, in_channels, kernel_size, stride, groups=in_channels, norm=norm[0], act_func=act_func[0], use_bias=use_bias[0], ) self.point_conv = ConvLayer( in_channels, out_channels, 1, norm=norm[1], act_func=act_func[1], use_bias=use_bias[1], ) def forward(self, x: torch.Tensor) -> torch.Tensor: x = self.depth_conv(x) x = self.point_conv(x) return x class MBConv(nn.Module): def __init__( self, in_channels: int, out_channels: int, kernel_size=3, stride=1, mid_channels=None, expand_ratio=6, use_bias=False, norm=("bn2d", "bn2d", "bn2d"), act_func=("relu6", "relu6", None), ): super().__init__() use_bias = val2tuple(use_bias, 3) norm = val2tuple(norm, 3) act_func = val2tuple(act_func, 3) mid_channels = round(in_channels * expand_ratio) if mid_channels is None else mid_channels self.inverted_conv = ConvLayer( in_channels, mid_channels, 1, stride=1, norm=norm[0], act_func=act_func[0], use_bias=use_bias[0], ) self.depth_conv = ConvLayer( mid_channels, mid_channels, kernel_size, stride=stride, groups=mid_channels, norm=norm[1], act_func=act_func[1], use_bias=use_bias[1], ) self.point_conv = ConvLayer( mid_channels, out_channels, 1, norm=norm[2], act_func=act_func[2], use_bias=use_bias[2], ) def forward(self, x: torch.Tensor) -> torch.Tensor: x = self.inverted_conv(x) x = self.depth_conv(x) x = self.point_conv(x) return x class FusedMBConv(nn.Module): def __init__( self, in_channels: int, out_channels: int, kernel_size=3, stride=1, mid_channels=None, expand_ratio=6, groups=1, use_bias=False, norm=("bn2d", "bn2d"), act_func=("relu6", None), ): super().__init__() use_bias = val2tuple(use_bias, 2) norm = val2tuple(norm, 2) act_func = val2tuple(act_func, 2) mid_channels = round(in_channels * expand_ratio) if mid_channels is None else mid_channels self.spatial_conv = ConvLayer( in_channels, mid_channels, kernel_size, stride, groups=groups, use_bias=use_bias[0], norm=norm[0], act_func=act_func[0], ) self.point_conv = ConvLayer( mid_channels, out_channels, 1, use_bias=use_bias[1], norm=norm[1], act_func=act_func[1], ) def forward(self, x: torch.Tensor) -> torch.Tensor: x = self.spatial_conv(x) x = self.point_conv(x) return x class GLUMBConv(nn.Module): def __init__( self, in_channels: int, out_channels: int, kernel_size=3, stride=1, mid_channels=None, expand_ratio=6, use_bias=False, norm=(None, None, "ln2d"), act_func=("silu", "silu", None), is_video=False, ): super().__init__() use_bias = val2tuple(use_bias, 3) norm = val2tuple(norm, 3) act_func = val2tuple(act_func, 3) mid_channels = round(in_channels * expand_ratio) if mid_channels is None else mid_channels self.glu_act = build_act(act_func[1], inplace=False) self.inverted_conv = ConvLayer( in_channels, mid_channels * 2, 1, use_bias=use_bias[0], norm=norm[0], act_func=act_func[0], is_video=is_video, ) self.depth_conv = ConvLayer( mid_channels * 2, mid_channels * 2, kernel_size, stride=stride, groups=mid_channels * 2, use_bias=use_bias[1], norm=norm[1], act_func=None, is_video=is_video, ) self.point_conv = ConvLayer( mid_channels, out_channels, 1, use_bias=use_bias[2], norm=norm[2], act_func=act_func[2], is_video=is_video, ) def forward(self, x: torch.Tensor) -> torch.Tensor: x = self.inverted_conv(x) x = self.depth_conv(x) x, gate = torch.chunk(x, 2, dim=1) gate = self.glu_act(gate) x = x * gate x = self.point_conv(x) return x class ResBlock(nn.Module): def __init__( self, in_channels: int, out_channels: int, kernel_size=3, stride=1, mid_channels=None, expand_ratio=1, use_bias=False, norm=("bn2d", "bn2d"), act_func=("relu6", None), is_video=False, ): super().__init__() use_bias = val2tuple(use_bias, 2) norm = val2tuple(norm, 2) act_func = val2tuple(act_func, 2) mid_channels = round(in_channels * expand_ratio) if mid_channels is None else mid_channels self.conv1 = ConvLayer( in_channels, mid_channels, kernel_size, stride, use_bias=use_bias[0], norm=norm[0], act_func=act_func[0], is_video=is_video, ) self.conv2 = ConvLayer( mid_channels, out_channels, kernel_size, 1, use_bias=use_bias[1], norm=norm[1], act_func=act_func[1], is_video=is_video, ) def forward(self, x: torch.Tensor) -> torch.Tensor: x = self.conv1(x) x = self.conv2(x) return x class LiteMLA(nn.Module): r"""Lightweight multi-scale linear attention""" def __init__( self, in_channels: int, out_channels: int, heads: Optional[int] = None, heads_ratio: float = 1.0, dim=8, use_bias=False, norm=(None, "bn2d"), act_func=(None, None), kernel_func="relu", scales: tuple[int, ...] = (5,), eps=1.0e-15, is_video=False, ): super().__init__() self.eps = eps heads = int(in_channels // dim * heads_ratio) if heads is None else heads total_dim = heads * dim use_bias = val2tuple(use_bias, 2) norm = val2tuple(norm, 2) act_func = val2tuple(act_func, 2) self.dim = dim self.qkv = ConvLayer( in_channels, 3 * total_dim, 1, use_bias=use_bias[0], norm=norm[0], act_func=act_func[0], is_video=is_video, ) conv_class = nn.Conv2d if not is_video else ChannelChunkConv3d self.aggreg = nn.ModuleList( [ nn.Sequential( conv_class( 3 * total_dim, 3 * total_dim, scale, padding=get_same_padding(scale), groups=3 * total_dim, bias=use_bias[0], ), conv_class(3 * total_dim, 3 * total_dim, 1, groups=3 * heads, bias=use_bias[0]), ) for scale in scales ] ) self.kernel_func = build_act(kernel_func, inplace=False) self.proj = ConvLayer( total_dim * (1 + len(scales)), out_channels, 1, use_bias=use_bias[1], norm=norm[1], act_func=act_func[1], is_video=is_video, ) @torch.autocast(device_type="cuda", enabled=False) def relu_linear_att(self, qkv: torch.Tensor) -> torch.Tensor: if qkv.ndim == 5: B, _, T, H, W = list(qkv.size()) is_video = True else: B, _, H, W = list(qkv.size()) is_video = False if qkv.dtype == torch.float16: qkv = qkv.float() if qkv.ndim == 4: qkv = torch.reshape( qkv, ( B, -1, 3 * self.dim, H * W, ), ) elif qkv.ndim == 5: qkv = torch.reshape( qkv, ( B, -1, 3 * self.dim, H * W * T, ), ) q, k, v = ( qkv[:, :, 0 : self.dim], qkv[:, :, self.dim : 2 * self.dim], qkv[:, :, 2 * self.dim :], ) # lightweight linear attention q = self.kernel_func(q) k = self.kernel_func(k) # linear matmul trans_k = k.transpose(-1, -2) v = F.pad(v, (0, 0, 0, 1), mode="constant", value=1) vk = torch.matmul(v, trans_k) out = torch.matmul(vk, q) if out.dtype == torch.bfloat16: out = out.float() out = out[:, :, :-1] / (out[:, :, -1:] + self.eps) if not is_video: out = torch.reshape(out, (B, -1, H, W)) else: out = torch.reshape(out, (B, -1, T, H, W)) return out @torch.autocast(device_type="cuda", enabled=False) def relu_quadratic_att(self, qkv: torch.Tensor) -> torch.Tensor: B, _, H, W = list(qkv.size()) qkv = torch.reshape( qkv, ( B, -1, 3 * self.dim, H * W, ), ) q, k, v = ( qkv[:, :, 0 : self.dim], qkv[:, :, self.dim : 2 * self.dim], qkv[:, :, 2 * self.dim :], ) q = self.kernel_func(q) k = self.kernel_func(k) att_map = torch.matmul(k.transpose(-1, -2), q) # b h n n original_dtype = att_map.dtype if original_dtype in [torch.float16, torch.bfloat16]: att_map = att_map.float() att_map = att_map / (torch.sum(att_map, dim=2, keepdim=True) + self.eps) # b h n n att_map = att_map.to(original_dtype) out = torch.matmul(v, att_map) # b h d n out = torch.reshape(out, (B, -1, H, W)) return out def forward(self, x: torch.Tensor) -> torch.Tensor: # generate multi-scale q, k, v qkv = self.qkv(x) multi_scale_qkv = [qkv] for op in self.aggreg: multi_scale_qkv.append(op(qkv)) qkv = torch.cat(multi_scale_qkv, dim=1) if qkv.ndim == 4: H, W = list(qkv.size())[-2:] # num_tokens = H * W elif qkv.ndim == 5: _, _, T, H, W = list(qkv.size()) # num_tokens = H * W * T # if num_tokens > self.dim: out = self.relu_linear_att(qkv).to(qkv.dtype) # else: # if self.is_video: # raise NotImplementedError("Video is not supported for quadratic attention") # out = self.relu_quadratic_att(qkv) out = self.proj(out) return out class EfficientViTBlock(nn.Module): def __init__( self, in_channels: int, heads_ratio: float = 1.0, dim=32, expand_ratio: float = 4, scales: tuple[int, ...] = (5,), norm: str = "bn2d", act_func: str = "hswish", context_module: str = "LiteMLA", local_module: str = "MBConv", is_video: bool = False, ): super().__init__() if context_module == "LiteMLA": self.context_module = ResidualBlock( LiteMLA( in_channels=in_channels, out_channels=in_channels, heads_ratio=heads_ratio, dim=dim, norm=(None, norm), scales=scales, is_video=is_video, ), IdentityLayer(), ) else: raise ValueError(f"context_module {context_module} is not supported") if local_module == "MBConv": self.local_module = ResidualBlock( MBConv( in_channels=in_channels, out_channels=in_channels, expand_ratio=expand_ratio, use_bias=(True, True, False), norm=(None, None, norm), act_func=(act_func, act_func, None), is_video=is_video, ), IdentityLayer(), ) elif local_module == "GLUMBConv": self.local_module = ResidualBlock( GLUMBConv( in_channels=in_channels, out_channels=in_channels, expand_ratio=expand_ratio, use_bias=(True, True, False), norm=(None, None, norm), act_func=(act_func, act_func, None), is_video=is_video, ), IdentityLayer(), ) else: raise NotImplementedError(f"local_module {local_module} is not supported") def forward(self, x: torch.Tensor) -> torch.Tensor: x = self.context_module(x) x = self.local_module(x) return x ################################################################################# # Functional Blocks # ################################################################################# class ResidualBlock(nn.Module): def __init__( self, main: Optional[nn.Module], shortcut: Optional[nn.Module], post_act=None, pre_norm: Optional[nn.Module] = None, ): super().__init__() self.pre_norm = pre_norm self.main = main self.shortcut = shortcut self.post_act = build_act(post_act) def forward_main(self, x: torch.Tensor) -> torch.Tensor: if self.pre_norm is None: return self.main(x) else: return self.main(self.pre_norm(x)) def forward(self, x: torch.Tensor) -> torch.Tensor: if self.main is None: res = x elif self.shortcut is None: res = self.forward_main(x) else: res = self.forward_main(x) + self.shortcut(x) if self.post_act: res = self.post_act(res) return res class DAGBlock(nn.Module): def __init__( self, inputs: dict[str, nn.Module], merge: str, post_input: Optional[nn.Module], middle: nn.Module, outputs: dict[str, nn.Module], ): super().__init__() self.input_keys = list(inputs.keys()) self.input_ops = nn.ModuleList(list(inputs.values())) self.merge = merge self.post_input = post_input self.middle = middle self.output_keys = list(outputs.keys()) self.output_ops = nn.ModuleList(list(outputs.values())) def forward(self, feature_dict: dict[str, torch.Tensor]) -> dict[str, torch.Tensor]: feat = [op(feature_dict[key]) for key, op in zip(self.input_keys, self.input_ops)] if self.merge == "add": feat = list_sum(feat) elif self.merge == "cat": feat = torch.concat(feat, dim=1) else: raise NotImplementedError if self.post_input is not None: feat = self.post_input(feat) feat = self.middle(feat) for key, op in zip(self.output_keys, self.output_ops): feature_dict[key] = op(feat) return feature_dict class OpSequential(nn.Module): def __init__(self, op_list: list[Optional[nn.Module]]): super().__init__() valid_op_list = [] for op in op_list: if op is not None: valid_op_list.append(op) self.op_list = nn.ModuleList(valid_op_list) def forward(self, x: torch.Tensor) -> torch.Tensor: for op in self.op_list: x = op(x) return x ================================================ FILE: opensora/models/dc_ae/models/nn/vo_ops.py ================================================ import math from inspect import signature from typing import Any, Callable, Optional, Union import torch import torch.nn.functional as F VERBOSE = False def pixel_shuffle_3d(x, upscale_factor): """ 3D pixelshuffle 操作。 """ B, C, T, H, W = x.shape r = upscale_factor assert C % (r * r * r) == 0, "通道数必须是上采样因子的立方倍数" C_new = C // (r * r * r) x = x.view(B, C_new, r, r, r, T, H, W) if VERBOSE: print("x.view:") print(x) print("x.view.shape:") print(x.shape) x = x.permute(0, 1, 5, 2, 6, 3, 7, 4) if VERBOSE: print("x.permute:") print(x) print("x.permute.shape:") print(x.shape) y = x.reshape(B, C_new, T * r, H * r, W * r) return y def pixel_unshuffle_3d(x, downsample_factor): """ 3D pixel unshuffle 操作。 """ B, C, T, H, W = x.shape r = downsample_factor assert T % r == 0, f"时间维度必须是下采样因子的倍数, got shape {x.shape}" assert H % r == 0, f"高度维度必须是下采样因子的倍数, got shape {x.shape}" assert W % r == 0, f"宽度维度必须是下采样因子的倍数, got shape {x.shape}" T_new = T // r H_new = H // r W_new = W // r C_new = C * (r * r * r) x = x.view(B, C, T_new, r, H_new, r, W_new, r) x = x.permute(0, 1, 3, 5, 7, 2, 4, 6) y = x.reshape(B, C_new, T_new, H_new, W_new) return y def test_pixel_shuffle_3d(): # 输入张量 (B, C, T, H, W) = (1, 16, 2, 4, 4) x = torch.arange(1, 1 + 1 * 16 * 2 * 4 * 4).view(1, 16, 2, 4, 4).float() print("x:") print(x) print("x.shape:") print(x.shape) upscale_factor = 2 # 使用自定义 pixelshuffle_3d y = pixel_shuffle_3d(x, upscale_factor) print("pixelshuffle_3d 结果:") print(y) print("输出形状:", y.shape) # 预期输出形状: (1, 1, 4, 8, 8) # 因为: # - 通道数从8变为1 (8 /(2*2*2)) # - 时间维度从2变为4 (2*2) # - 高度从4变为8 (4*2) # - 宽度从4变为8 (4*2) print(torch.allclose(x, pixel_unshuffle_3d(y, upscale_factor))) def chunked_interpolate(x, scale_factor, mode="nearest"): """ Interpolate large tensors by chunking along the channel dimension. https://discuss.pytorch.org/t/error-using-f-interpolate-for-large-3d-input/207859 Only supports 'nearest' interpolation mode. Args: x (torch.Tensor): Input tensor (B, C, D, H, W) scale_factor: Tuple of scaling factors (d, h, w) Returns: torch.Tensor: Interpolated tensor """ assert ( mode == "nearest" ), "Only the nearest mode is supported" # actually other modes are theoretically supported but not tested if len(x.shape) != 5: raise ValueError("Expected 5D input tensor (B, C, D, H, W)") # Calculate max chunk size to avoid int32 overflow. num_elements < max_int32 # Max int32 is 2^31 - 1 max_elements_per_chunk = 2**31 - 1 # Calculate output spatial dimensions out_d = math.ceil(x.shape[2] * scale_factor[0]) out_h = math.ceil(x.shape[3] * scale_factor[1]) out_w = math.ceil(x.shape[4] * scale_factor[2]) # Calculate max channels per chunk to stay under limit elements_per_channel = out_d * out_h * out_w max_channels = max_elements_per_chunk // (x.shape[0] * elements_per_channel) # Use smaller of max channels or input channels chunk_size = min(max_channels, x.shape[1]) # Ensure at least 1 channel per chunk chunk_size = max(1, chunk_size) if VERBOSE: print(f"Input channels: {x.shape[1]}") print(f"Chunk size: {chunk_size}") print(f"max_channels: {max_channels}") print(f"num_chunks: {math.ceil(x.shape[1] / chunk_size)}") chunks = [] for i in range(0, x.shape[1], chunk_size): start_idx = i end_idx = min(i + chunk_size, x.shape[1]) chunk = x[:, start_idx:end_idx, :, :, :] interpolated_chunk = F.interpolate(chunk, scale_factor=scale_factor, mode="nearest") chunks.append(interpolated_chunk) if not chunks: raise ValueError(f"No chunks were generated. Input shape: {x.shape}") # Concatenate chunks along channel dimension return torch.cat(chunks, dim=1) def test_chunked_interpolate(): # Test case 1: Basic upscaling with scale_factor x1 = torch.randn(2, 16, 16, 32, 32).cuda() scale_factor = (2.0, 2.0, 2.0) assert torch.allclose( chunked_interpolate(x1, scale_factor=scale_factor), F.interpolate(x1, scale_factor=scale_factor, mode="nearest") ) # Test case 3: Downscaling with scale_factor x3 = torch.randn(2, 16, 32, 64, 64).cuda() scale_factor = (0.5, 0.5, 0.5) assert torch.allclose( chunked_interpolate(x3, scale_factor=scale_factor), F.interpolate(x3, scale_factor=scale_factor, mode="nearest") ) # Test case 4: Different scales per dimension x4 = torch.randn(2, 16, 16, 32, 32).cuda() scale_factor = (2.0, 1.5, 1.5) assert torch.allclose( chunked_interpolate(x4, scale_factor=scale_factor), F.interpolate(x4, scale_factor=scale_factor, mode="nearest") ) # Test case 5: Large input tensor x5 = torch.randn(2, 16, 64, 128, 128).cuda() scale_factor = (2.0, 2.0, 2.0) assert torch.allclose( chunked_interpolate(x5, scale_factor=scale_factor), F.interpolate(x5, scale_factor=scale_factor, mode="nearest") ) # Test case 7: Chunk size equal to input depth x7 = torch.randn(2, 16, 8, 32, 32).cuda() scale_factor = (2.0, 2.0, 2.0) assert torch.allclose( chunked_interpolate(x7, scale_factor=scale_factor), F.interpolate(x7, scale_factor=scale_factor, mode="nearest") ) # Test case 8: Single channel input x8 = torch.randn(2, 1, 16, 32, 32).cuda() scale_factor = (2.0, 2.0, 2.0) assert torch.allclose( chunked_interpolate(x8, scale_factor=scale_factor), F.interpolate(x8, scale_factor=scale_factor, mode="nearest") ) # Test case 9: Minimal batch size x9 = torch.randn(1, 16, 32, 64, 64).cuda() scale_factor = (0.5, 0.5, 0.5) assert torch.allclose( chunked_interpolate(x9, scale_factor=scale_factor), F.interpolate(x9, scale_factor=scale_factor, mode="nearest") ) # Test case 10: Non-power-of-2 dimensions x10 = torch.randn(2, 16, 15, 31, 31).cuda() scale_factor = (2.0, 2.0, 2.0) assert torch.allclose( chunked_interpolate(x10, scale_factor=scale_factor), F.interpolate(x10, scale_factor=scale_factor, mode="nearest"), ) # Test case 11: large output tensor def get_same_padding(kernel_size: Union[int, tuple[int, ...]]) -> Union[int, tuple[int, ...]]: if isinstance(kernel_size, tuple): return tuple([get_same_padding(ks) for ks in kernel_size]) else: assert kernel_size % 2 > 0, "kernel size should be odd number" return kernel_size // 2 def resize( x: torch.Tensor, size: Optional[Any] = None, scale_factor: Optional[list[float]] = None, mode: str = "bicubic", align_corners: Optional[bool] = False, ) -> torch.Tensor: if mode in {"bilinear", "bicubic"}: return F.interpolate( x, size=size, scale_factor=scale_factor, mode=mode, align_corners=align_corners, ) elif mode in {"nearest", "area"}: return F.interpolate(x, size=size, scale_factor=scale_factor, mode=mode) else: raise NotImplementedError(f"resize(mode={mode}) not implemented.") def build_kwargs_from_config(config: dict, target_func: Callable) -> dict[str, Any]: valid_keys = list(signature(target_func).parameters) kwargs = {} for key in config: if key in valid_keys: kwargs[key] = config[key] return kwargs if __name__ == "__main__": test_chunked_interpolate() ================================================ FILE: opensora/models/dc_ae/utils/__init__.py ================================================ from .init import * from .list import * ================================================ FILE: opensora/models/dc_ae/utils/init.py ================================================ # Copyright 2024 MIT Han Lab # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # SPDX-License-Identifier: Apache-2.0 from typing import Union import torch import torch.nn as nn from torch.nn.modules.batchnorm import _BatchNorm __all__ = ["init_modules"] def init_modules(model: Union[nn.Module, list[nn.Module]], init_type="trunc_normal") -> None: _DEFAULT_INIT_PARAM = {"trunc_normal": 0.02} if isinstance(model, list): for sub_module in model: init_modules(sub_module, init_type) else: init_params = init_type.split("@") init_params = float(init_params[1]) if len(init_params) > 1 else None if init_type.startswith("trunc_normal"): init_func = lambda param: nn.init.trunc_normal_( param, std=(_DEFAULT_INIT_PARAM["trunc_normal"] if init_params is None else init_params) ) elif init_type.startswith("normal"): init_func = lambda param: nn.init.normal_( param, std=(_DEFAULT_INIT_PARAM["trunc_normal"] if init_params is None else init_params) ) else: raise NotImplementedError for m in model.modules(): if isinstance(m, (nn.Conv2d, nn.Linear, nn.ConvTranspose2d)): init_func(m.weight) if m.bias is not None: m.bias.data.zero_() elif isinstance(m, nn.Embedding): init_func(m.weight) elif isinstance(m, (_BatchNorm, nn.GroupNorm, nn.LayerNorm)): m.weight.data.fill_(1) m.bias.data.zero_() else: weight = getattr(m, "weight", None) bias = getattr(m, "bias", None) if isinstance(weight, torch.nn.Parameter): init_func(weight) if isinstance(bias, torch.nn.Parameter): bias.data.zero_() ================================================ FILE: opensora/models/dc_ae/utils/list.py ================================================ # Copyright 2024 MIT Han Lab # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # SPDX-License-Identifier: Apache-2.0 from typing import Any, Optional, Union __all__ = [ "list_sum", "list_mean", "weighted_list_sum", "list_join", "val2list", "val2tuple", "squeeze_list", ] def list_sum(x: list) -> Any: return x[0] if len(x) == 1 else x[0] + list_sum(x[1:]) def list_mean(x: list) -> Any: return list_sum(x) / len(x) def weighted_list_sum(x: list, weights: list) -> Any: assert len(x) == len(weights) return x[0] * weights[0] if len(x) == 1 else x[0] * weights[0] + weighted_list_sum(x[1:], weights[1:]) def list_join(x: list, sep="\t", format_str="%s") -> str: return sep.join([format_str % val for val in x]) def val2list(x: Union[list, tuple, Any], repeat_time=1) -> list: if isinstance(x, (list, tuple)): return list(x) return [x for _ in range(repeat_time)] def val2tuple(x: Union[list, tuple, Any], min_len: int = 1, idx_repeat: int = -1) -> tuple: x = val2list(x) # repeat elements if necessary if len(x) > 0: x[idx_repeat:idx_repeat] = [x[idx_repeat] for _ in range(min_len - len(x))] return tuple(x) def squeeze_list(x: Optional[list]) -> Union[list, Any]: if x is not None and len(x) == 1: return x[0] else: return x ================================================ FILE: opensora/models/hunyuan_vae/__init__.py ================================================ from pathlib import Path import torch from .autoencoder_kl_causal_3d import CausalVAE3D_HUNYUAN ================================================ FILE: opensora/models/hunyuan_vae/autoencoder_kl_causal_3d.py ================================================ # Modified from diffusers==0.29.2 and HunyuanVideo # # Copyright 2024 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # Copyright 2024 HunyuanVideo # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. from dataclasses import dataclass from typing import Dict, Optional, Tuple, Union import torch import torch.nn as nn from diffusers.configuration_utils import ConfigMixin, register_to_config from opensora.registry import MODELS from opensora.utils.ckpt import load_checkpoint try: # This diffusers is modified and packed in the mirror. from diffusers.loaders import FromOriginalVAEMixin except ImportError: # Use this to be compatible with the original diffusers. from diffusers.loaders.single_file_model import FromOriginalModelMixin as FromOriginalVAEMixin from diffusers.models.attention_processor import ( ADDED_KV_ATTENTION_PROCESSORS, CROSS_ATTENTION_PROCESSORS, Attention, AttentionProcessor, AttnAddedKVProcessor, AttnProcessor, ) from diffusers.models.modeling_utils import ModelMixin from diffusers.utils.accelerate_utils import apply_forward_hook from opensora.models.hunyuan_vae.vae import ( DecoderCausal3D, DecoderOutput, DiagonalGaussianDistribution, EncoderCausal3D, ) @dataclass class AutoEncoder3DConfig: from_pretrained: str | None act_fn: str = "silu" in_channels: int = 3 out_channels: int = 3 latent_channels: int = 16 layers_per_block: int = 2 norm_num_groups: int = 32 scale_factor: float = 0.476986 shift_factor: float = 0 time_compression_ratio: int = 4 spatial_compression_ratio: int = 8 mid_block_add_attention: bool = True block_out_channels: tuple[int] = (128, 256, 512, 512) sample_size: int = 256 sample_tsize: int = 64 use_slicing: bool = False use_spatial_tiling: bool = False use_temporal_tiling: bool = False tile_overlap_factor: float = 0.25 dropout: float = 0.0 channel: bool = False class AutoencoderKLCausal3D(ModelMixin, ConfigMixin, FromOriginalVAEMixin): r""" A VAE model with KL loss for encoding images/videos into latents and decoding latent representations into images/videos. This model inherits from [`ModelMixin`]. Check the superclass documentation for it's generic methods implemented for all models (such as downloading or saving). """ _supports_gradient_checkpointing = True @register_to_config def __init__(self, config: AutoEncoder3DConfig): super().__init__() self.scale_factor = config.scale_factor self.shift_factor = config.shift_factor self.time_compression_ratio = config.time_compression_ratio self.spatial_compression_ratio = config.spatial_compression_ratio self.z_channels = config.latent_channels self.encoder = EncoderCausal3D( in_channels=config.in_channels, out_channels=config.latent_channels, block_out_channels=config.block_out_channels, layers_per_block=config.layers_per_block, act_fn=config.act_fn, norm_num_groups=config.norm_num_groups, double_z=True, time_compression_ratio=config.time_compression_ratio, spatial_compression_ratio=config.spatial_compression_ratio, mid_block_add_attention=config.mid_block_add_attention, dropout=config.dropout, ) self.decoder = DecoderCausal3D( in_channels=config.latent_channels, out_channels=config.out_channels, block_out_channels=config.block_out_channels, layers_per_block=config.layers_per_block, norm_num_groups=config.norm_num_groups, act_fn=config.act_fn, time_compression_ratio=config.time_compression_ratio, spatial_compression_ratio=config.spatial_compression_ratio, mid_block_add_attention=config.mid_block_add_attention, dropout=config.dropout, ) self.quant_conv = nn.Conv3d(2 * config.latent_channels, 2 * config.latent_channels, kernel_size=1) self.post_quant_conv = nn.Conv3d(config.latent_channels, config.latent_channels, kernel_size=1) self.use_slicing = config.use_slicing self.use_spatial_tiling = config.use_spatial_tiling self.use_temporal_tiling = config.use_temporal_tiling # only relevant if vae tiling is enabled self.tile_sample_min_tsize = config.sample_tsize self.tile_latent_min_tsize = config.sample_tsize // config.time_compression_ratio self.tile_sample_min_size = config.sample_size sample_size = config.sample_size[0] if isinstance(config.sample_size, (list, tuple)) else config.sample_size self.tile_latent_min_size = int(sample_size / (2 ** (len(config.block_out_channels) - 1))) self.tile_overlap_factor = config.tile_overlap_factor def enable_temporal_tiling(self, use_tiling: bool = True): self.use_temporal_tiling = use_tiling def disable_temporal_tiling(self): self.enable_temporal_tiling(False) def enable_spatial_tiling(self, use_tiling: bool = True): self.use_spatial_tiling = use_tiling def disable_spatial_tiling(self): self.enable_spatial_tiling(False) def enable_tiling(self, use_tiling: bool = True): r""" Enable tiled VAE decoding. When this option is enabled, the VAE will split the input tensor into tiles to compute decoding and encoding in several steps. This is useful for saving a large amount of memory and to allow processing larger videos. """ self.enable_spatial_tiling(use_tiling) self.enable_temporal_tiling(use_tiling) def disable_tiling(self): r""" Disable tiled VAE decoding. If `enable_tiling` was previously enabled, this method will go back to computing decoding in one step. """ self.disable_spatial_tiling() self.disable_temporal_tiling() def enable_slicing(self): r""" Enable sliced VAE decoding. When this option is enabled, the VAE will split the input tensor in slices to compute decoding in several steps. This is useful to save some memory and allow larger batch sizes. """ self.use_slicing = True def disable_slicing(self): r""" Disable sliced VAE decoding. If `enable_slicing` was previously enabled, this method will go back to computing decoding in one step. """ self.use_slicing = False @property # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors def attn_processors(self) -> Dict[str, AttentionProcessor]: r""" Returns: `dict` of attention processors: A dictionary containing all attention processors used in the model with indexed by its weight name. """ # set recursively processors = {} def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]): if hasattr(module, "get_processor"): processors[f"{name}.processor"] = module.get_processor(return_deprecated_lora=True) for sub_name, child in module.named_children(): fn_recursive_add_processors(f"{name}.{sub_name}", child, processors) return processors for name, module in self.named_children(): fn_recursive_add_processors(name, module, processors) return processors # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.set_attn_processor def set_attn_processor( self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]], _remove_lora=False ): r""" Sets the attention processor to use to compute attention. Parameters: processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`): The instantiated processor class or a dictionary of processor classes that will be set as the processor for **all** `Attention` layers. If `processor` is a dict, the key needs to define the path to the corresponding cross attention processor. This is strongly recommended when setting trainable attention processors. """ count = len(self.attn_processors.keys()) if isinstance(processor, dict) and len(processor) != count: raise ValueError( f"A dict of processors was passed, but the number of processors {len(processor)} does not match the" f" number of attention layers: {count}. Please make sure to pass {count} processor classes." ) def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor): if hasattr(module, "set_processor"): if not isinstance(processor, dict): module.set_processor(processor, _remove_lora=_remove_lora) else: module.set_processor(processor.pop(f"{name}.processor"), _remove_lora=_remove_lora) for sub_name, child in module.named_children(): fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor) for name, module in self.named_children(): fn_recursive_attn_processor(name, module, processor) # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.set_default_attn_processor def set_default_attn_processor(self): """ Disables custom attention processors and sets the default attention implementation. """ if all(proc.__class__ in ADDED_KV_ATTENTION_PROCESSORS for proc in self.attn_processors.values()): processor = AttnAddedKVProcessor() elif all(proc.__class__ in CROSS_ATTENTION_PROCESSORS for proc in self.attn_processors.values()): processor = AttnProcessor() else: raise ValueError( f"Cannot call `set_default_attn_processor` when attention processors are of type {next(iter(self.attn_processors.values()))}" ) self.set_attn_processor(processor, _remove_lora=True) @apply_forward_hook def encode( self, x: torch.FloatTensor, sample_posterior: bool = True, return_posterior: bool = False, generator: Optional[torch.Generator] = None, ) -> Union[torch.FloatTensor, Tuple[DiagonalGaussianDistribution]]: """ Encode a batch of images/videos into latents. Args: x (`torch.FloatTensor`): Input batch of images/videos. return_dict (`bool`, *optional*, defaults to `True`): Whether to return a [`~models.autoencoder_kl.AutoencoderKLOutput`] instead of a plain tuple. Returns: The latent representations of the encoded images/videos. If `return_dict` is True, a [`~models.autoencoder_kl.AutoencoderKLOutput`] is returned, otherwise a plain `tuple` is returned. """ assert len(x.shape) == 5, "The input tensor should have 5 dimensions." if self.use_temporal_tiling and x.shape[2] > self.tile_sample_min_tsize: posterior = self.temporal_tiled_encode(x) elif self.use_spatial_tiling and ( x.shape[-1] > self.tile_sample_min_size or x.shape[-2] > self.tile_sample_min_size ): posterior = self.spatial_tiled_encode(x) else: if self.use_slicing and x.shape[0] > 1: encoded_slices = [self.encoder(x_slice) for x_slice in x.split(1)] h = torch.cat(encoded_slices) else: h = self.encoder(x) moments = self.quant_conv(h) posterior = DiagonalGaussianDistribution(moments) if sample_posterior: z = posterior.sample(generator=generator) else: z = posterior.mode() z = self.scale_factor * (z - self.shift_factor) # shift & scale if return_posterior: return z, posterior else: return z def _decode(self, z: torch.FloatTensor, return_dict: bool = True) -> Union[DecoderOutput, torch.FloatTensor]: assert len(z.shape) == 5, "The input tensor should have 5 dimensions." if self.use_temporal_tiling and z.shape[2] > self.tile_latent_min_tsize: return self.temporal_tiled_decode(z, return_dict=return_dict) if self.use_spatial_tiling and ( z.shape[-1] > self.tile_latent_min_size or z.shape[-2] > self.tile_latent_min_size ): return self.spatial_tiled_decode(z, return_dict=return_dict) z = self.post_quant_conv(z) dec = self.decoder(z) if not return_dict: return (dec,) return DecoderOutput(sample=dec) @apply_forward_hook def decode(self, z: torch.FloatTensor) -> torch.FloatTensor: """ Decode a batch of images/videos. Args: z (`torch.FloatTensor`): Input batch of latent vectors. Returns: [`~models.vae.DecoderOutput`] or `tuple`: If return_dict is True, a [`~models.vae.DecoderOutput`] is returned, otherwise a plain `tuple` is returned. """ z = z / self.scale_factor + self.shift_factor # scale & shift if self.use_slicing and z.shape[0] > 1: decoded_slices = [self._decode(z_slice).sample for z_slice in z.split(1)] decoded = torch.cat(decoded_slices) else: decoded = self._decode(z).sample return decoded def blend_v(self, a: torch.Tensor, b: torch.Tensor, blend_extent: int) -> torch.Tensor: blend_extent = min(a.shape[-2], b.shape[-2], blend_extent) for y in range(blend_extent): b[:, :, :, y, :] = a[:, :, :, -blend_extent + y, :] * (1 - y / blend_extent) + b[:, :, :, y, :] * ( y / blend_extent ) return b def blend_h(self, a: torch.Tensor, b: torch.Tensor, blend_extent: int) -> torch.Tensor: blend_extent = min(a.shape[-1], b.shape[-1], blend_extent) for x in range(blend_extent): b[:, :, :, :, x] = a[:, :, :, :, -blend_extent + x] * (1 - x / blend_extent) + b[:, :, :, :, x] * ( x / blend_extent ) return b def blend_t(self, a: torch.Tensor, b: torch.Tensor, blend_extent: int) -> torch.Tensor: blend_extent = min(a.shape[-3], b.shape[-3], blend_extent) for x in range(blend_extent): b[:, :, x, :, :] = a[:, :, -blend_extent + x, :, :] * (1 - x / blend_extent) + b[:, :, x, :, :] * ( x / blend_extent ) return b def spatial_tiled_encode(self, x: torch.FloatTensor, return_moments: bool = False) -> DiagonalGaussianDistribution: r"""Encode a batch of images/videos using a tiled encoder. When this option is enabled, the VAE will split the input tensor into tiles to compute encoding in several steps. This is useful to keep memory use constant regardless of image/videos size. The end result of tiled encoding is different from non-tiled encoding because each tile uses a different encoder. To avoid tiling artifacts, the tiles overlap and are blended together to form a smooth output. You may still see tile-sized changes in the output, but they should be much less noticeable. Args: x (`torch.FloatTensor`): Input batch of images/videos. return_dict (`bool`, *optional*, defaults to `True`): Whether or not to return a [`~models.autoencoder_kl.AutoencoderKLOutput`] instead of a plain tuple. Returns: [`~models.autoencoder_kl.AutoencoderKLOutput`] or `tuple`: If return_dict is True, a [`~models.autoencoder_kl.AutoencoderKLOutput`] is returned, otherwise a plain `tuple` is returned. """ overlap_size = int(self.tile_sample_min_size * (1 - self.tile_overlap_factor)) blend_extent = int(self.tile_latent_min_size * self.tile_overlap_factor) row_limit = self.tile_latent_min_size - blend_extent # Split video into tiles and encode them separately. rows = [] for i in range(0, x.shape[-2], overlap_size): row = [] for j in range(0, x.shape[-1], overlap_size): tile = x[:, :, :, i : i + self.tile_sample_min_size, j : j + self.tile_sample_min_size] tile = self.encoder(tile) tile = self.quant_conv(tile) row.append(tile) rows.append(row) result_rows = [] for i, row in enumerate(rows): result_row = [] for j, tile in enumerate(row): # blend the above tile and the left tile # to the current tile and add the current tile to the result row if i > 0: tile = self.blend_v(rows[i - 1][j], tile, blend_extent) if j > 0: tile = self.blend_h(row[j - 1], tile, blend_extent) result_row.append(tile[:, :, :, :row_limit, :row_limit]) result_rows.append(torch.cat(result_row, dim=-1)) moments = torch.cat(result_rows, dim=-2) if return_moments: return moments posterior = DiagonalGaussianDistribution(moments) return posterior def spatial_tiled_decode( self, z: torch.FloatTensor, return_dict: bool = True ) -> Union[DecoderOutput, torch.FloatTensor]: r""" Decode a batch of images/videos using a tiled decoder. Args: z (`torch.FloatTensor`): Input batch of latent vectors. return_dict (`bool`, *optional*, defaults to `True`): Whether or not to return a [`~models.vae.DecoderOutput`] instead of a plain tuple. Returns: [`~models.vae.DecoderOutput`] or `tuple`: If return_dict is True, a [`~models.vae.DecoderOutput`] is returned, otherwise a plain `tuple` is returned. """ overlap_size = int(self.tile_latent_min_size * (1 - self.tile_overlap_factor)) blend_extent = int(self.tile_sample_min_size * self.tile_overlap_factor) row_limit = self.tile_sample_min_size - blend_extent # Split z into overlapping tiles and decode them separately. # The tiles have an overlap to avoid seams between tiles. rows = [] for i in range(0, z.shape[-2], overlap_size): row = [] for j in range(0, z.shape[-1], overlap_size): tile = z[:, :, :, i : i + self.tile_latent_min_size, j : j + self.tile_latent_min_size] tile = self.post_quant_conv(tile) decoded = self.decoder(tile) row.append(decoded) rows.append(row) result_rows = [] for i, row in enumerate(rows): result_row = [] for j, tile in enumerate(row): # blend the above tile and the left tile # to the current tile and add the current tile to the result row if i > 0: tile = self.blend_v(rows[i - 1][j], tile, blend_extent) if j > 0: tile = self.blend_h(row[j - 1], tile, blend_extent) result_row.append(tile[:, :, :, :row_limit, :row_limit]) result_rows.append(torch.cat(result_row, dim=-1)) dec = torch.cat(result_rows, dim=-2) if not return_dict: return (dec,) return DecoderOutput(sample=dec) def temporal_tiled_encode(self, x: torch.FloatTensor) -> DiagonalGaussianDistribution: B, C, T, H, W = x.shape overlap_size = int(self.tile_sample_min_tsize * (1 - self.tile_overlap_factor)) blend_extent = int(self.tile_latent_min_tsize * self.tile_overlap_factor) t_limit = self.tile_latent_min_tsize - blend_extent # Split the video into tiles and encode them separately. row = [] for i in range(0, T, overlap_size): tile = x[:, :, i : i + self.tile_sample_min_tsize + 1, :, :] if self.use_spatial_tiling and ( tile.shape[-1] > self.tile_sample_min_size or tile.shape[-2] > self.tile_sample_min_size ): tile = self.spatial_tiled_encode(tile, return_moments=True) else: tile = self.encoder(tile) tile = self.quant_conv(tile) if i > 0: tile = tile[:, :, 1:, :, :] row.append(tile) result_row = [] for i, tile in enumerate(row): if i > 0: tile = self.blend_t(row[i - 1], tile, blend_extent) result_row.append(tile[:, :, :t_limit, :, :]) else: result_row.append(tile[:, :, : t_limit + 1, :, :]) moments = torch.cat(result_row, dim=2) posterior = DiagonalGaussianDistribution(moments) return posterior def temporal_tiled_decode( self, z: torch.FloatTensor, return_dict: bool = True ) -> Union[DecoderOutput, torch.FloatTensor]: # Split z into overlapping tiles and decode them separately. B, C, T, H, W = z.shape overlap_size = int(self.tile_latent_min_tsize * (1 - self.tile_overlap_factor)) blend_extent = int(self.tile_sample_min_tsize * self.tile_overlap_factor) t_limit = self.tile_sample_min_tsize - blend_extent row = [] for i in range(0, T, overlap_size): tile = z[:, :, i : i + self.tile_latent_min_tsize + 1, :, :] if self.use_spatial_tiling and ( tile.shape[-1] > self.tile_latent_min_size or tile.shape[-2] > self.tile_latent_min_size ): decoded = self.spatial_tiled_decode(tile, return_dict=True).sample else: tile = self.post_quant_conv(tile) decoded = self.decoder(tile) if i > 0: decoded = decoded[:, :, 1:, :, :] row.append(decoded) result_row = [] for i, tile in enumerate(row): if i > 0: tile = self.blend_t(row[i - 1], tile, blend_extent) result_row.append(tile[:, :, :t_limit, :, :]) else: result_row.append(tile[:, :, : t_limit + 1, :, :]) dec = torch.cat(result_row, dim=2) if not return_dict: return (dec,) return DecoderOutput(sample=dec) def forward( self, sample: torch.FloatTensor, sample_posterior: bool = True, generator: Optional[torch.Generator] = None, ) -> Tuple[torch.FloatTensor, DiagonalGaussianDistribution, torch.FloatTensor]: r""" Args: sample (`torch.FloatTensor`): Input sample. sample_posterior (`bool`, *optional*, defaults to `False`): Whether to sample from the posterior. return_dict (`bool`, *optional*, defaults to `True`): Whether or not to return a [`DecoderOutput`] instead of a plain tuple. """ x = sample z, posterior = self.encode(x, return_posterior=True, sample_posterior=sample_posterior, generator=generator) dec = self.decode(z) return (dec, posterior, z) # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.fuse_qkv_projections def fuse_qkv_projections(self): """ Enables fused QKV projections. For self-attention modules, all projection matrices (i.e., query, key, value) are fused. For cross-attention modules, key and value projection matrices are fused. This API is 🧪 experimental. """ self.original_attn_processors = None for _, attn_processor in self.attn_processors.items(): if "Added" in str(attn_processor.__class__.__name__): raise ValueError("`fuse_qkv_projections()` is not supported for models having added KV projections.") self.original_attn_processors = self.attn_processors for module in self.modules(): if isinstance(module, Attention): module.fuse_projections(fuse=True) # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.unfuse_qkv_projections def unfuse_qkv_projections(self): """Disables the fused QKV projection if enabled. This API is 🧪 experimental. """ if self.original_attn_processors is not None: self.set_attn_processor(self.original_attn_processors) def get_last_layer(self): return self.decoder.conv_out.conv.weight def get_latent_size(self, input_size: list[int]) -> list[int]: latent_size = [] # T latent_size.append((input_size[0] - 1) // self.time_compression_ratio + 1) # H, w for i in range(1, 3): latent_size.append((input_size[i] - 1) // self.spatial_compression_ratio + 1) return latent_size @MODELS.register_module("hunyuan_vae") def CausalVAE3D_HUNYUAN( from_pretrained: str = None, device_map: str | torch.device = "cuda", torch_dtype: torch.dtype = torch.bfloat16, **kwargs, ) -> AutoencoderKLCausal3D: config = AutoEncoder3DConfig(from_pretrained=from_pretrained, **kwargs) with torch.device(device_map): model = AutoencoderKLCausal3D(config).to(torch_dtype) if from_pretrained: model = load_checkpoint(model, from_pretrained, device_map=device_map, strict=True) return model ================================================ FILE: opensora/models/hunyuan_vae/distributed.py ================================================ from typing import List, Optional, Tuple import torch import torch.distributed as dist from colossalai.shardformer.layer._operation import gather_forward_split_backward, split_forward_gather_backward from colossalai.shardformer.layer.attn import RingComm, _rescale_out_lse from colossalai.shardformer.layer.utils import SeqParallelUtils from diffusers.models.attention_processor import Attention from opensora.models.vae.tensor_parallel import Conv3dTPRow from opensora.models.vae.utils import get_conv3d_n_chunks from .unet_causal_3d_blocks import UpsampleCausal3D try: from xformers.ops.fmha import ( Context, Inputs, _memory_efficient_attention_backward, _memory_efficient_attention_forward_requires_grad, ) HAS_XFORMERS = True except ImportError: HAS_XFORMERS = False SEQ_ALIGN = 32 SEQ_LIMIT = 16 * 1024 def align_atten_bias(attn_bias): B, N, S, S = attn_bias.shape align_size = 8 if S % align_size != 0: expand_S = (S // align_size + 1) * align_size new_shape = [B, N, S, expand_S] attn_bias = torch.empty(new_shape, dtype=attn_bias.dtype, device=attn_bias.device)[:, :, :, :S].copy_(attn_bias) return attn_bias def _attn_fwd( q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, attn_bias: Optional[torch.Tensor] = None, scale: Optional[float] = None, ): attn_bias = align_atten_bias(attn_bias) inp = Inputs(q, k, v, attn_bias, p=0, scale=scale, is_partial=False) out, ctx = _memory_efficient_attention_forward_requires_grad(inp, None) S = attn_bias.shape[-2] if ctx.lse.shape[-1] != S: ctx.lse = ctx.lse[:, :, :S] return out, ctx.lse, ctx.rng_state def _attn_bwd( grad: torch.Tensor, q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, out: torch.Tensor, lse: torch.Tensor, rng_state: torch.Tensor, attn_bias: Optional[torch.Tensor] = None, scale: Optional[float] = None, ): attn_bias = align_atten_bias(attn_bias) inp = Inputs(q, k, v, attn_bias, p=0, scale=scale, output_dtype=q.dtype, is_partial=False) ctx = Context(lse, out, rng_state=rng_state) grads = _memory_efficient_attention_backward(ctx, inp, grad, None) return grads.dq, grads.dk, grads.dv class MemEfficientRingAttention(torch.autograd.Function): ATTN_DONE: torch.cuda.Event = None SP_STREAM: torch.cuda.Stream = None @staticmethod def forward( ctx, q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, sp_group: dist.ProcessGroup, sp_stream: torch.cuda.Stream, softmax_scale: Optional[float] = None, attn_mask: Optional[torch.Tensor] = None, ) -> Tuple[torch.Tensor, torch.Tensor]: """Ring attention forward Args: ctx (_type_): self q (torch.Tensor): shape [B, S/P, N, D] k (torch.Tensor): shape [B, S/P, N, D] v (torch.Tensor): shape [B, S/P, N, D] sp_group (dist.ProcessGroup): sequence parallel group sp_stream (torch.cuda.Stream): sequence parallel stream softmax_scale (Optional[float], optional): softmax scale. Defaults to None. attn_mask (Optional[torch.Tensor], optional): attention mask shape [B, N, S/P, S]. Defaults to None. Returns: 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]. """ if softmax_scale is None: softmax_scale = q.shape[-1] ** (-0.5) sp_size = dist.get_world_size(sp_group) sp_rank = dist.get_rank(sp_group) kv_comms: List[RingComm] = [RingComm(sp_group) for _ in range(2)] block_attn_masks = [None] * sp_size if attn_mask is not None: # if attn_mask is splitted, uncomment the following line # attn_mask = attn_mask.chunk(sp_size, dim=2)[sp_rank] block_attn_masks = attn_mask.chunk(sp_size, dim=-1) # [B, S, N, D] q, k, v = [x.contiguous() for x in [q, k, v]] # Pre-allocate double buffer for overlapping and receiving next step's inputs kv_buffers = [torch.stack((k, v))] # (2, B, S, N, D) kv_buffers.append(torch.empty_like(kv_buffers[0])) # outputs out = None block_out = [None, None] softmax_lse = [None, None] block_softmax_lse = [None, None] # log sum exp, the denominator of softmax in attention rng_states = [None for _ in range(sp_size)] sp_streams = [torch.cuda.current_stream(), sp_stream] def _kv_comm(i): # Avoid overwriting attn input when it shares mem with buffer if not MemEfficientRingAttention.ATTN_DONE.query(): kv_buffers[(i + 1) % 2] = torch.empty_like(kv_buffers[i % 2]) if i < sp_size - 1: kv_comms[i % 2].send_recv(kv_buffers[i % 2], kv_buffers[(i + 1) % 2]) block_idx = sp_rank for i in range(sp_size): with torch.cuda.stream(sp_streams[i % 2]): # Wait for current kv from prev rank # NOTE: waiting outside the current stream will NOT correctly synchronize. if i == 0: _kv_comm(i) else: kv_comms[(i + 1) % 2].wait() kv_block = kv_buffers[i % 2] q_block = q block_out[i % 2], block_softmax_lse[i % 2], rng_states[i] = _attn_fwd( q_block, kv_block[0], kv_block[1], attn_bias=block_attn_masks[block_idx], scale=softmax_scale ) MemEfficientRingAttention.ATTN_DONE.record() # Pipeline the next KV comm with output correction instead of the next flash attn # to minimize idle time when comm takes longer than attn. _kv_comm(i + 1) block_softmax_lse[i % 2] = ( block_softmax_lse[i % 2].transpose(1, 2).unsqueeze(-1).contiguous().float() ) # [B, N, S] -> [B, S, N, 1] assert ( block_out[i % 2].shape[:-1] == block_softmax_lse[i % 2].shape[:-1] ), f"{block_out[i % 2].shape} != {block_softmax_lse[i % 2].shape}" # Output and log sum exp correction. Ideally overlap this with the next flash attn kernel. # In reality this always finishes before next flash attn; no need for extra sync. if i == 0: out = block_out[0] softmax_lse = block_softmax_lse[0] else: out, softmax_lse = _rescale_out_lse(out, block_out[i % 2], softmax_lse, block_softmax_lse[i % 2]) block_idx = (block_idx - 1) % sp_size torch.cuda.current_stream().wait_stream(sp_stream) out = out.to(q.dtype) softmax_lse = softmax_lse.squeeze(-1).transpose(1, 2).contiguous() ctx.softmax_scale = softmax_scale ctx.block_attn_masks = block_attn_masks ctx.sp_group = sp_group ctx.save_for_backward(q, k, v, out, softmax_lse, *rng_states) # lse [B, N, S] return out, softmax_lse @staticmethod def backward(ctx, grad_output, grad_softmax_lse): # q, k, v, out: [B, S, N, D], softmax_lse: [B, N, S] q, k, v, out, softmax_lse, *rng_states = ctx.saved_tensors sp_group = ctx.sp_group sp_size = dist.get_world_size(sp_group) kv_comm = RingComm(sp_group) dkv_comm = RingComm(sp_group) grad_output = grad_output.contiguous() kv_buffers = [torch.stack((k, v))] # (2, B, S, N, D) kv_buffers.append(torch.empty_like(kv_buffers[0])) dq = None dkv_buffers = [torch.empty_like(kv, dtype=torch.float) for kv in kv_buffers] del k, v block_idx = dist.get_rank(sp_group) for i in range(sp_size): if i > 0: kv_comm.wait() if i < sp_size - 1: kv_comm.send_recv(kv_buffers[i % 2], kv_buffers[(i + 1) % 2]) k_block, v_block = kv_buffers[i % 2] dq_block, dk_block, dv_block = _context_chunk_attn_bwd( grad_output, q, k_block, v_block, out, softmax_lse, rng_states[i], attn_bias=ctx.block_attn_masks[block_idx], scale=ctx.softmax_scale, ) if i == 0: dq = dq_block.float() dkv_buffers[i % 2][0] = dk_block.float() dkv_buffers[i % 2][1] = dv_block.float() else: dq += dq_block dkv_comm.wait() dkv_buffers[i % 2][0] += dk_block dkv_buffers[i % 2][1] += dv_block dkv_comm.send_recv(dkv_buffers[i % 2], dkv_buffers[(i + 1) % 2]) block_idx = (block_idx - 1) % sp_size dkv_comm.wait() dkv = dkv_buffers[sp_size % 2] dq, dk, dv = [x.to(q.dtype) for x in (dq, *dkv)] torch.cuda.empty_cache() return dq, dk, dv, None, None, None, None, None, None, None, None, None, None, None, None, None @staticmethod def attention( q, k, v, sp_group, softmax_scale: Optional[float] = None, attn_mask: Optional[torch.Tensor] = None, return_softmax: bool = False, ): """Ring attention Args: q (torch.Tensor): shape [B, S, N, D] k (torch.Tensor): shape [B, S, N, D] v (torch.Tensor): shape [B, S, N, D] sp_group (dist.ProcessGroup): sequence parallel group softmax_scale (Optional[float], optional): softmax scale. Defaults to None. attn_mask (Optional[torch.Tensor], optional): attention mask. Defaults to None. return_softmax (bool, optional): return softmax or not. Defaults to False. Returns: 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]. """ if MemEfficientRingAttention.ATTN_DONE is None: MemEfficientRingAttention.ATTN_DONE = torch.cuda.Event() if MemEfficientRingAttention.SP_STREAM is None: MemEfficientRingAttention.SP_STREAM = torch.cuda.Stream() out, softmax_lse = MemEfficientRingAttention.apply( q, k, v, sp_group, MemEfficientRingAttention.SP_STREAM, softmax_scale, attn_mask ) if return_softmax: return out, softmax_lse return out class MemEfficientRingAttnProcessor: def __init__(self, sp_group: dist.ProcessGroup): self.sp_group = sp_group if not HAS_XFORMERS: raise ImportError("MemEfficientRingAttnProcessor requires xformers, to use it, please install xformers.") def __call__( self, attn: Attention, hidden_states: torch.Tensor, encoder_hidden_states: Optional[torch.Tensor] = None, attention_mask: Optional[torch.Tensor] = None, temb: Optional[torch.Tensor] = None, *args, **kwargs, ) -> torch.Tensor: sp_group = self.sp_group assert sp_group is not None, "sp_group must be provided for MemEfficientRingAttnProcessor" residual = hidden_states if attn.spatial_norm is not None: hidden_states = attn.spatial_norm(hidden_states, temb) input_ndim = hidden_states.ndim if input_ndim == 4: batch_size, channel, height, width = hidden_states.shape hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2) batch_size, sequence_length, _ = ( hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape ) if attention_mask is not None: attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size) # scaled_dot_product_attention expects attention_mask shape to be # (batch, heads, source_length, target_length) attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1]) if attn.group_norm is not None: hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2) hidden_states = split_forward_gather_backward(hidden_states, 1, sp_group) query = attn.to_q(hidden_states) if encoder_hidden_states is None: encoder_hidden_states = hidden_states elif attn.norm_cross: encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states) key = attn.to_k(encoder_hidden_states) value = attn.to_v(encoder_hidden_states) inner_dim = key.shape[-1] head_dim = inner_dim // attn.heads query = query.view(batch_size, -1, attn.heads, head_dim) key = key.view(batch_size, -1, attn.heads, head_dim) value = value.view(batch_size, -1, attn.heads, head_dim) assert ( query.shape[1] % dist.get_world_size(sp_group) == 0 ), f"sequence length ({query.shape[1]}) must be divisible by sp_group size ({dist.get_world_size(sp_group)})" hidden_states = MemEfficientRingAttention.attention(query, key, value, sp_group, attn_mask=attention_mask) hidden_states = hidden_states.reshape(batch_size, -1, attn.heads * head_dim) hidden_states = hidden_states.to(query.dtype) # linear proj hidden_states = attn.to_out[0](hidden_states) # dropout hidden_states = attn.to_out[1](hidden_states) hidden_states = gather_forward_split_backward(hidden_states, 1, sp_group) if input_ndim == 4: hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width) if attn.residual_connection: hidden_states = hidden_states + residual hidden_states = hidden_states / attn.rescale_output_factor return hidden_states class ContextParallelAttention: def __init__(self): raise ImportError(f"ContextParallelAttention should not be initialized directly.") @staticmethod def from_native_module(module: Attention, process_group, *args, **kwargs) -> Attention: """ Convert a native RMSNorm module to colossalai layer norm module, and optionally mark parameters for gradient aggregation. Args: module (nn.Module): The native RMSNorm module to be converted. sp_partial_derived (bool): Whether this module's gradients are partially derived in sequence parallelism. Returns: nn.Module: The RMSNorm module. """ # Since gradients are computed using only a subset of the data, # aggregation of these gradients is necessary during backpropagation. # Therefore, we annotate these parameters in advance to indicate the need for gradient aggregation. SeqParallelUtils.marked_as_sp_partial_derived_param(module.to_q.weight) SeqParallelUtils.marked_as_sp_partial_derived_param(module.to_k.weight) SeqParallelUtils.marked_as_sp_partial_derived_param(module.to_v.weight) if module.to_q.bias is not None: SeqParallelUtils.marked_as_sp_partial_derived_param(module.to_q.bias) SeqParallelUtils.marked_as_sp_partial_derived_param(module.to_k.bias) SeqParallelUtils.marked_as_sp_partial_derived_param(module.to_v.bias) module.set_processor(MemEfficientRingAttnProcessor(process_group)) return module def _context_chunk_attn_fwd( q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, attn_bias: Optional[torch.Tensor], scale: Optional[float], seq_align: int = SEQ_ALIGN, seq_limit: int = SEQ_LIMIT, ): seq_len = q.shape[1] n_chunks = get_conv3d_n_chunks(seq_len, seq_align, seq_limit) q_chunks, k_chunks, v_chunks = q.chunk(n_chunks, dim=1), k.chunk(n_chunks, dim=1), v.chunk(n_chunks, dim=1) attn_bias_chunks = attn_bias.chunk(n_chunks, dim=2) if attn_bias is not None else [None] * n_chunks out_chunks = [] lse_chunks = [] rng_states = [] for q_chunk, attn_bias_chunk in zip(q_chunks, attn_bias_chunks): inner_attn_bias_chunks = ( attn_bias_chunk.chunk(n_chunks, dim=3) if attn_bias_chunk is not None else [None] * n_chunks ) out_chunk = None for k_chunk, v_chunk, inner_attn_bias_chunk in zip(k_chunks, v_chunks, inner_attn_bias_chunks): block_out, block_lse, rng_state = _attn_fwd(q_chunk, k_chunk, v_chunk, inner_attn_bias_chunk, scale) block_lse = block_lse.transpose(1, 2).unsqueeze(-1).contiguous().float() # [B, N, S] -> [B, S, N, 1] rng_states.append(rng_state) if out_chunk is None: out_chunk = block_out lse_chunk = block_lse else: out_chunk, lse_chunk = _rescale_out_lse(out_chunk, block_out, lse_chunk, block_lse) lse_chunk = lse_chunk.squeeze(-1).transpose(1, 2).contiguous() # [B, S, N, 1] -> [B, N, S] out_chunks.append(out_chunk) lse_chunks.append(lse_chunk) out = torch.cat(out_chunks, dim=1) lse = torch.cat(lse_chunks, dim=-1) return out, lse, rng_states def _context_chunk_attn_bwd( grad: torch.Tensor, q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, out: torch.Tensor, lse: torch.Tensor, rng_states: torch.Tensor, attn_bias: Optional[torch.Tensor] = None, scale: Optional[float] = None, seq_align: int = SEQ_ALIGN, seq_limit: int = SEQ_LIMIT, fast_accum: bool = False, ): seq_len = q.shape[1] n_chunks = get_conv3d_n_chunks(seq_len, seq_align, seq_limit) if n_chunks == 1: return _attn_bwd(grad, q, k, v, out, lse, rng_states, attn_bias, scale) q_chunks, k_chunks, v_chunks = q.chunk(n_chunks, dim=1), k.chunk(n_chunks, dim=1), v.chunk(n_chunks, dim=1) attn_bias_chunks = attn_bias.chunk(n_chunks, dim=2) if attn_bias is not None else [None] * n_chunks out_chunks = out.chunk(n_chunks, dim=1) dout_chunks = grad.chunk(n_chunks, dim=1) lse_chunks = lse.chunk(n_chunks, dim=-1) if rng_states is None: rng_states = [None] * (n_chunks * n_chunks) i = 0 acc_dtype = q.dtype if fast_accum else torch.float dq = torch.zeros_like(q, dtype=acc_dtype) dk = torch.zeros_like(k, dtype=acc_dtype) dv = torch.zeros_like(v, dtype=acc_dtype) dq_chunks = dq.chunk(n_chunks, dim=1) dk_chunks = dk.chunk(n_chunks, dim=1) dv_chunks = dv.chunk(n_chunks, dim=1) for q_idx in range(n_chunks): q_chunk = q_chunks[q_idx] attn_bias_chunk = attn_bias_chunks[q_idx] inner_attn_bias_chunks = ( attn_bias_chunk.chunk(n_chunks, dim=3) if attn_bias_chunk is not None else [None] * n_chunks ) out_chunk = out_chunks[q_idx] dout_chunk = dout_chunks[q_idx] lse_chunk = lse_chunks[q_idx] dq_acc = dq_chunks[q_idx] for kv_idx in range(n_chunks): k_chunk = k_chunks[kv_idx] v_chunk = v_chunks[kv_idx] inner_attn_bias_chunk = inner_attn_bias_chunks[kv_idx] dk_acc = dk_chunks[kv_idx] dv_acc = dv_chunks[kv_idx] block_dq, block_dk, block_dv = _attn_bwd( dout_chunk, q_chunk, k_chunk, v_chunk, out_chunk, lse_chunk, rng_states[i], inner_attn_bias_chunk, scale ) dq_acc += block_dq dk_acc += block_dk dv_acc += block_dv i += 1 return dq.to(q.dtype), dk.to(k.dtype), dv.to(v.dtype) def prepare_parallel_causal_attention_mask( parallel_rank: int, parallel_size: int, n_frame: int, n_hw: int, dtype, device, batch_size: int = None ): seq_len = n_frame * n_hw assert seq_len % parallel_size == 0, f"seq_len {seq_len} must be divisible by parallel_size {parallel_size}" local_seq_len = seq_len // parallel_size local_seq_start = local_seq_len * parallel_rank if dtype is torch.bfloat16: # A trick to avoid nan of memory efficient attention, maybe introduce some bias fmin = torch.finfo(torch.float16).min else: fmin = torch.finfo(dtype).min mask = torch.full((local_seq_len, seq_len), fmin, dtype=dtype, device=device) for i in range(local_seq_len): i_frame = (i + local_seq_start) // n_hw mask[i, : (i_frame + 1) * n_hw] = 0 if batch_size is not None: mask = mask.unsqueeze(0).expand(batch_size, -1, -1) return mask def prepare_parallel_attention_mask( self, hidden_states: torch.Tensor, cp_group: dist.ProcessGroup = None ) -> torch.Tensor: B, C, T, H, W = hidden_states.shape attention_mask = prepare_parallel_causal_attention_mask( dist.get_rank(cp_group), dist.get_world_size(cp_group), T, H * W, hidden_states.dtype, hidden_states.device, batch_size=B, ) return attention_mask class TPUpDecoderBlockCausal3D(UpsampleCausal3D): def __init__( self, channels, out_channels=None, kernel_size=3, bias=True, upsample_factor=(2, 2, 2), tp_group=None, split_input: bool = False, split_output: bool = False, conv_=None, shortcut_=None, ): assert tp_group is not None, "tp_group must be provided" super().__init__(channels, out_channels, kernel_size, bias, upsample_factor) conv = conv_ if conv_ is not None else self.conv.conv self.conv.conv = Conv3dTPRow.from_native_module( conv, tp_group, split_input=split_input, split_output=split_output ) self.tp_group = tp_group tp_size = dist.get_world_size(group=self.tp_group) assert self.channels % tp_size == 0, f"channels {self.channels} must be divisible by tp_size {tp_size}" self.channels = self.channels // tp_size def forward(self, input_tensor): input_tensor = split_forward_gather_backward(input_tensor, 1, self.tp_group) return super().forward(input_tensor) def from_native_module(module: UpsampleCausal3D, process_group, **kwargs): conv = module.conv.conv return TPUpDecoderBlockCausal3D( module.channels, module.out_channels, conv.kernel_size[0], conv.bias is not None, module.upsample_factor, conv_=conv, shortcut_=getattr(module, "shortcut", None), tp_group=process_group, **kwargs, ) ================================================ FILE: opensora/models/hunyuan_vae/policy.py ================================================ from functools import partial from typing import Dict, Union import torch.nn as nn from colossalai.shardformer.policies.base_policy import ModulePolicyDescription, Policy, SubModuleReplacementDescription from opensora.models.vae.tensor_parallel import Conv3dTPCol, Conv3dTPRow, GroupNormTP from .distributed import ContextParallelAttention, TPUpDecoderBlockCausal3D, prepare_parallel_attention_mask from .vae import DecoderCausal3D, EncoderCausal3D def gen_resnets_replacements(prefix: str, with_shortcut: bool = False): replacements = [ SubModuleReplacementDescription( suffix=f"{prefix}.norm1", target_module=GroupNormTP, ), SubModuleReplacementDescription( suffix=f"{prefix}.conv1.conv", target_module=Conv3dTPRow, kwargs=dict( split_output=True, ), ), SubModuleReplacementDescription( suffix=f"{prefix}.norm2", target_module=GroupNormTP, ), SubModuleReplacementDescription( suffix=f"{prefix}.conv2.conv", target_module=Conv3dTPRow, kwargs=dict( split_output=True, ), ), ] if with_shortcut: replacements.append( SubModuleReplacementDescription( suffix=f"{prefix}.conv_shortcut.conv", target_module=Conv3dTPRow, kwargs=dict( split_output=True, ), ) ) return replacements class HunyuanVaePolicy(Policy): def config_sanity_check(self): pass def preprocess(self): return self.model def module_policy(self) -> Dict[Union[str, nn.Module], ModulePolicyDescription]: policy = {} policy[EncoderCausal3D] = ModulePolicyDescription( sub_module_replacement=[ SubModuleReplacementDescription( suffix="conv_in.conv", target_module=Conv3dTPCol, ), *gen_resnets_replacements("down_blocks[0].resnets[0]"), *gen_resnets_replacements("down_blocks[0].resnets[1]"), SubModuleReplacementDescription( suffix="down_blocks[0].downsamplers[0].conv.conv", target_module=Conv3dTPRow, kwargs=dict( split_output=True, ), ), *gen_resnets_replacements("down_blocks[1].resnets[0]", with_shortcut=True), *gen_resnets_replacements("down_blocks[1].resnets[1]"), SubModuleReplacementDescription( suffix="down_blocks[1].downsamplers[0].conv.conv", target_module=Conv3dTPRow, ), SubModuleReplacementDescription( suffix="mid_block.attentions[0]", target_module=ContextParallelAttention, ), ], attribute_replacement={ "down_blocks[0].downsamplers[0].channels": self.model.encoder.down_blocks[0].downsamplers[0].channels // self.shard_config.tensor_parallel_size, "down_blocks[1].downsamplers[0].channels": self.model.encoder.down_blocks[1].downsamplers[0].channels // self.shard_config.tensor_parallel_size, # "mid_block.attentions[0].processor": MemEfficientRingAttnProcessor( # self.shard_config.tensor_parallel_process_group # ), }, method_replacement={ "prepare_attention_mask": partial( prepare_parallel_attention_mask, cp_group=self.shard_config.tensor_parallel_process_group ), }, ) policy[DecoderCausal3D] = ModulePolicyDescription( sub_module_replacement=[ SubModuleReplacementDescription( suffix="up_blocks[1].upsamplers[0]", target_module=TPUpDecoderBlockCausal3D, kwargs=dict( split_output=True, ), ), *gen_resnets_replacements("up_blocks[2].resnets[0]", with_shortcut=True), *gen_resnets_replacements("up_blocks[2].resnets[1]"), *gen_resnets_replacements("up_blocks[2].resnets[2]"), SubModuleReplacementDescription( suffix="up_blocks[2].upsamplers[0].conv.conv", target_module=Conv3dTPRow, kwargs=dict( split_output=True, ), ), *gen_resnets_replacements("up_blocks[3].resnets[0]", with_shortcut=True), *gen_resnets_replacements("up_blocks[3].resnets[1]"), *gen_resnets_replacements("up_blocks[3].resnets[2]"), SubModuleReplacementDescription( suffix="conv_norm_out", target_module=GroupNormTP, ), SubModuleReplacementDescription( suffix="conv_out.conv", target_module=Conv3dTPRow, ), SubModuleReplacementDescription( suffix="mid_block.attentions[0]", target_module=ContextParallelAttention, ), ], attribute_replacement={ "up_blocks[2].upsamplers[0].channels": self.model.decoder.up_blocks[2].upsamplers[0].channels // self.shard_config.tensor_parallel_size, # "mid_block.attentions[0].processor": MemEfficientRingAttnProcessor( # self.shard_config.tensor_parallel_process_group # ), }, method_replacement={ "prepare_attention_mask": partial( prepare_parallel_attention_mask, cp_group=self.shard_config.tensor_parallel_process_group ), }, ) return policy def postprocess(self): return self.model ================================================ FILE: opensora/models/hunyuan_vae/unet_causal_3d_blocks.py ================================================ # Modified from diffusers==0.29.2 and HunyuanVideo # # Copyright 2024 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # # Copyright 2024 HunyuanVideo # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. from typing import Optional, Tuple, Union import numpy as np import torch import torch.nn.functional as F from diffusers.models.activations import get_activation from diffusers.models.attention_processor import Attention from diffusers.utils import logging from einops import rearrange from torch import nn from opensora.acceleration.checkpoint import auto_grad_checkpoint from opensora.models.vae.utils import ChannelChunkConv3d, get_conv3d_n_chunks logger = logging.get_logger(__name__) # pylint: disable=invalid-name INTERPOLATE_NUMEL_LIMIT = 2**31 - 1 def chunk_nearest_interpolate( x: torch.Tensor, scale_factor, ): limit = INTERPOLATE_NUMEL_LIMIT // np.prod(scale_factor) n_chunks = get_conv3d_n_chunks(x.numel(), x.size(1), limit) x_chunks = x.chunk(n_chunks, dim=1) x_chunks = [F.interpolate(x_chunk, scale_factor=scale_factor, mode="nearest") for x_chunk in x_chunks] return torch.cat(x_chunks, dim=1) def prepare_causal_attention_mask(n_frame: int, n_hw: int, dtype, device, batch_size: int = None): seq_len = n_frame * n_hw mask = torch.full((seq_len, seq_len), float("-inf"), dtype=dtype, device=device) for i in range(seq_len): i_frame = i // n_hw mask[i, : (i_frame + 1) * n_hw] = 0 if batch_size is not None: mask = mask.unsqueeze(0).expand(batch_size, -1, -1) return mask class CausalConv3d(nn.Module): """ Implements a causal 3D convolution layer where each position only depends on previous timesteps and current spatial locations. This maintains temporal causality in video generation tasks. """ def __init__( self, chan_in, chan_out, kernel_size: Union[int, Tuple[int, int, int]], stride: Union[int, Tuple[int, int, int]] = 1, dilation: Union[int, Tuple[int, int, int]] = 1, pad_mode="replicate", **kwargs, ): super().__init__() self.pad_mode = pad_mode padding = ( kernel_size // 2, kernel_size // 2, kernel_size // 2, kernel_size // 2, kernel_size - 1, 0, ) # W, H, T self.time_causal_padding = padding self.conv = ChannelChunkConv3d(chan_in, chan_out, kernel_size, stride=stride, dilation=dilation, **kwargs) def forward(self, x): x = F.pad(x, self.time_causal_padding, mode=self.pad_mode) return self.conv(x) class UpsampleCausal3D(nn.Module): """ A 3D upsampling layer with an optional convolution. """ def __init__( self, channels: int, out_channels: Optional[int] = None, kernel_size: int = 3, bias=True, upsample_factor=(2, 2, 2), ): super().__init__() self.channels = channels self.out_channels = out_channels or channels self.upsample_factor = upsample_factor self.conv = CausalConv3d(self.channels, self.out_channels, kernel_size=kernel_size, bias=bias) def forward( self, input_tensor: torch.FloatTensor, ) -> torch.FloatTensor: assert input_tensor.shape[1] == self.channels ####################### # handle hidden states ####################### hidden_states = input_tensor # Cast to float32 to as 'upsample_nearest2d_out_frame' op does not support bfloat16 # dtype = hidden_states.dtype # if dtype == torch.bfloat16: # hidden_states = hidden_states.to(torch.float32) # upsample_nearest_nhwc fails with large batch sizes. see https://github.com/huggingface/diffusers/issues/984 if hidden_states.shape[0] >= 64: hidden_states = hidden_states.contiguous() # interpolate H & W only for the first frame; interpolate T & H & W for the rest T = hidden_states.size(2) first_h, other_h = hidden_states.split((1, T - 1), dim=2) # process non-1st frames if T > 1: other_h = chunk_nearest_interpolate(other_h, scale_factor=self.upsample_factor) # proess 1st fram first_h = first_h.squeeze(2) first_h = chunk_nearest_interpolate(first_h, scale_factor=self.upsample_factor[1:]) first_h = first_h.unsqueeze(2) # concat together if T > 1: hidden_states = torch.cat((first_h, other_h), dim=2) else: hidden_states = first_h # If the input is bfloat16, we cast back to bfloat16 # if dtype == torch.bfloat16: # hidden_states = hidden_states.to(dtype) hidden_states = self.conv(hidden_states) return hidden_states class DownsampleCausal3D(nn.Module): """ A 3D downsampling layer with an optional convolution. """ def __init__( self, channels: int, kernel_size=3, bias=True, stride=2, ): super().__init__() self.channels = channels self.out_channels = channels self.conv = CausalConv3d(self.channels, self.out_channels, kernel_size=kernel_size, stride=stride, bias=bias) def forward(self, input_tensor: torch.FloatTensor) -> torch.FloatTensor: assert input_tensor.shape[1] == self.channels hidden_states = self.conv(input_tensor) return hidden_states class ResnetBlockCausal3D(nn.Module): r""" A Resnet block. """ def __init__( self, *, in_channels: int, out_channels: Optional[int] = None, dropout: float = 0.0, groups: int = 32, groups_out: Optional[int] = None, pre_norm: bool = True, eps: float = 1e-6, non_linearity: str = "swish", output_scale_factor: float = 1.0, use_in_shortcut: Optional[bool] = None, conv_shortcut_bias: bool = True, conv_3d_out_channels: Optional[int] = None, ): super().__init__() self.pre_norm = pre_norm self.pre_norm = True self.in_channels = in_channels out_channels = in_channels if out_channels is None else out_channels self.out_channels = out_channels self.output_scale_factor = output_scale_factor if groups_out is None: groups_out = groups self.norm1 = torch.nn.GroupNorm(num_groups=groups, num_channels=in_channels, eps=eps, affine=True) self.conv1 = CausalConv3d(in_channels, out_channels, kernel_size=3, stride=1) self.norm2 = torch.nn.GroupNorm(num_groups=groups_out, num_channels=out_channels, eps=eps, affine=True) self.dropout = torch.nn.Dropout(dropout) conv_3d_out_channels = conv_3d_out_channels or out_channels self.conv2 = CausalConv3d(out_channels, conv_3d_out_channels, kernel_size=3, stride=1) self.nonlinearity = get_activation(non_linearity) self.upsample = self.downsample = None self.use_in_shortcut = self.in_channels != conv_3d_out_channels if use_in_shortcut is None else use_in_shortcut self.conv_shortcut = None if self.use_in_shortcut: self.conv_shortcut = CausalConv3d( in_channels, conv_3d_out_channels, kernel_size=1, stride=1, bias=conv_shortcut_bias, ) def forward( self, input_tensor: torch.FloatTensor, ) -> torch.FloatTensor: hidden_states = input_tensor hidden_states = self.norm1(hidden_states) hidden_states = self.nonlinearity(hidden_states) hidden_states = self.conv1(hidden_states) hidden_states = self.norm2(hidden_states) hidden_states = self.nonlinearity(hidden_states) hidden_states = self.dropout(hidden_states) hidden_states = self.conv2(hidden_states) if self.conv_shortcut is not None: input_tensor = self.conv_shortcut(input_tensor) output_tensor = (input_tensor + hidden_states) / self.output_scale_factor return output_tensor class UNetMidBlockCausal3D(nn.Module): """ A 3D UNet mid-block [`UNetMidBlockCausal3D`] with multiple residual blocks and optional attention blocks. """ def __init__( self, in_channels: int, dropout: float = 0.0, num_layers: int = 1, resnet_eps: float = 1e-6, resnet_act_fn: str = "swish", resnet_groups: int = 32, attn_groups: Optional[int] = None, resnet_pre_norm: bool = True, add_attention: bool = True, attention_head_dim: int = 1, output_scale_factor: float = 1.0, ): super().__init__() resnet_groups = resnet_groups if resnet_groups is not None else min(in_channels // 4, 32) self.add_attention = add_attention if attn_groups is None: attn_groups = resnet_groups # there is always at least one resnet resnets = [ ResnetBlockCausal3D( in_channels=in_channels, out_channels=in_channels, eps=resnet_eps, groups=resnet_groups, dropout=dropout, non_linearity=resnet_act_fn, output_scale_factor=output_scale_factor, pre_norm=resnet_pre_norm, ) ] attentions = [] if attention_head_dim is None: logger.warn( f"It is not recommend to pass `attention_head_dim=None`. Defaulting `attention_head_dim` to `in_channels`: {in_channels}." ) attention_head_dim = in_channels for _ in range(num_layers): if self.add_attention: attentions.append( Attention( in_channels, heads=in_channels // attention_head_dim, dim_head=attention_head_dim, rescale_output_factor=output_scale_factor, eps=resnet_eps, norm_num_groups=attn_groups, spatial_norm_dim=None, residual_connection=True, bias=True, upcast_softmax=True, _from_deprecated_attn_block=True, ) ) else: attentions.append(None) resnets.append( ResnetBlockCausal3D( in_channels=in_channels, out_channels=in_channels, eps=resnet_eps, groups=resnet_groups, dropout=dropout, non_linearity=resnet_act_fn, output_scale_factor=output_scale_factor, pre_norm=resnet_pre_norm, ) ) self.attentions = nn.ModuleList(attentions) self.resnets = nn.ModuleList(resnets) def forward(self, hidden_states: torch.FloatTensor, attention_mask: Optional[torch.Tensor]) -> torch.FloatTensor: hidden_states = self.resnets[0](hidden_states) for attn, resnet in zip(self.attentions, self.resnets[1:]): if attn is not None: B, C, T, H, W = hidden_states.shape hidden_states = rearrange(hidden_states, "b c f h w -> b (f h w) c") hidden_states = attn(hidden_states, attention_mask=attention_mask) hidden_states = rearrange(hidden_states, "b (f h w) c -> b c f h w", f=T, h=H, w=W) hidden_states = resnet(hidden_states) return hidden_states class DownEncoderBlockCausal3D(nn.Module): def __init__( self, in_channels: int, out_channels: int, dropout: float = 0.0, num_layers: int = 1, resnet_eps: float = 1e-6, resnet_act_fn: str = "swish", resnet_groups: int = 32, resnet_pre_norm: bool = True, output_scale_factor: float = 1.0, add_downsample: bool = True, downsample_stride: int = 2, ): super().__init__() resnets = [] for i in range(num_layers): in_channels = in_channels if i == 0 else out_channels resnets.append( ResnetBlockCausal3D( in_channels=in_channels, out_channels=out_channels, eps=resnet_eps, groups=resnet_groups, dropout=dropout, non_linearity=resnet_act_fn, output_scale_factor=output_scale_factor, pre_norm=resnet_pre_norm, ) ) self.resnets = nn.ModuleList(resnets) if add_downsample: self.downsamplers = nn.ModuleList( [ DownsampleCausal3D( out_channels, stride=downsample_stride, ) ] ) else: self.downsamplers = None def forward(self, hidden_states: torch.FloatTensor) -> torch.FloatTensor: for resnet in self.resnets: hidden_states = auto_grad_checkpoint(resnet, hidden_states) if self.downsamplers is not None: for downsampler in self.downsamplers: hidden_states = auto_grad_checkpoint(downsampler, hidden_states) return hidden_states class UpDecoderBlockCausal3D(nn.Module): def __init__( self, in_channels: int, out_channels: int, resolution_idx: Optional[int] = None, dropout: float = 0.0, num_layers: int = 1, resnet_eps: float = 1e-6, resnet_act_fn: str = "swish", resnet_groups: int = 32, resnet_pre_norm: bool = True, output_scale_factor: float = 1.0, add_upsample: bool = True, upsample_scale_factor=(2, 2, 2), ): super().__init__() resnets = [] for i in range(num_layers): input_channels = in_channels if i == 0 else out_channels resnets.append( ResnetBlockCausal3D( in_channels=input_channels, out_channels=out_channels, eps=resnet_eps, groups=resnet_groups, dropout=dropout, non_linearity=resnet_act_fn, output_scale_factor=output_scale_factor, pre_norm=resnet_pre_norm, ) ) self.resnets = nn.ModuleList(resnets) if add_upsample: self.upsamplers = nn.ModuleList( [ UpsampleCausal3D( out_channels, out_channels=out_channels, upsample_factor=upsample_scale_factor, ) ] ) else: self.upsamplers = None self.resolution_idx = resolution_idx def forward(self, hidden_states: torch.FloatTensor) -> torch.FloatTensor: for resnet in self.resnets: hidden_states = auto_grad_checkpoint(resnet, hidden_states) if self.upsamplers is not None: for upsampler in self.upsamplers: hidden_states = auto_grad_checkpoint(upsampler, hidden_states) return hidden_states ================================================ FILE: opensora/models/hunyuan_vae/vae.py ================================================ # Modified from HunyuanVideo # # Copyright 2024 HunyuanVideo # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. from dataclasses import dataclass from typing import Optional, Tuple import numpy as np import torch import torch.nn as nn from diffusers.utils import BaseOutput from diffusers.utils.torch_utils import randn_tensor from opensora.acceleration.checkpoint import auto_grad_checkpoint, checkpoint from opensora.models.hunyuan_vae.unet_causal_3d_blocks import ( CausalConv3d, DownEncoderBlockCausal3D, UNetMidBlockCausal3D, UpDecoderBlockCausal3D, prepare_causal_attention_mask, ) @dataclass class DecoderOutput(BaseOutput): r""" Output of decoding method. Args: sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`): The decoded output sample from the last layer of the model. """ sample: torch.FloatTensor class EncoderCausal3D(nn.Module): r""" The `EncoderCausal3D` layer of a variational autoencoder that encodes its input into a latent representation. """ def __init__( self, in_channels: int = 3, out_channels: int = 3, block_out_channels: Tuple[int, ...] = (64,), layers_per_block: int = 2, norm_num_groups: int = 32, act_fn: str = "silu", double_z: bool = True, mid_block_add_attention=True, time_compression_ratio: int = 4, spatial_compression_ratio: int = 8, dropout: float = 0.0, ): super().__init__() self.layers_per_block = layers_per_block self.conv_in = CausalConv3d(in_channels, block_out_channels[0], kernel_size=3, stride=1) self.mid_block = None self.down_blocks = nn.ModuleList([]) # down output_channel = block_out_channels[0] for i, _ in enumerate(block_out_channels): input_channel = output_channel output_channel = block_out_channels[i] is_final_block = i == len(block_out_channels) - 1 num_spatial_downsample_layers = int(np.log2(spatial_compression_ratio)) num_time_downsample_layers = int(np.log2(time_compression_ratio)) if time_compression_ratio == 4: add_spatial_downsample = bool(i < num_spatial_downsample_layers) add_time_downsample = bool( i >= (len(block_out_channels) - 1 - num_time_downsample_layers) and not is_final_block ) elif time_compression_ratio == 8: add_spatial_downsample = bool(i < num_spatial_downsample_layers) add_time_downsample = bool(i < num_spatial_downsample_layers) else: raise ValueError(f"Unsupported time_compression_ratio: {time_compression_ratio}.") downsample_stride_HW = (2, 2) if add_spatial_downsample else (1, 1) downsample_stride_T = (2,) if add_time_downsample else (1,) downsample_stride = tuple(downsample_stride_T + downsample_stride_HW) down_block = DownEncoderBlockCausal3D( num_layers=self.layers_per_block, in_channels=input_channel, out_channels=output_channel, dropout=dropout, add_downsample=bool(add_spatial_downsample or add_time_downsample), downsample_stride=downsample_stride, resnet_eps=1e-6, resnet_act_fn=act_fn, resnet_groups=norm_num_groups, ) self.down_blocks.append(down_block) # mid self.mid_block = UNetMidBlockCausal3D( in_channels=block_out_channels[-1], resnet_eps=1e-6, resnet_act_fn=act_fn, output_scale_factor=1, attention_head_dim=block_out_channels[-1], resnet_groups=norm_num_groups, add_attention=mid_block_add_attention, ) # out self.conv_norm_out = nn.GroupNorm(num_channels=block_out_channels[-1], num_groups=norm_num_groups, eps=1e-6) self.conv_act = nn.SiLU() conv_out_channels = 2 * out_channels if double_z else out_channels self.conv_out = CausalConv3d(block_out_channels[-1], conv_out_channels, kernel_size=3) def prepare_attention_mask(self, hidden_states: torch.Tensor) -> torch.Tensor: B, C, T, H, W = hidden_states.shape attention_mask = prepare_causal_attention_mask( T, H * W, hidden_states.dtype, hidden_states.device, batch_size=B ) return attention_mask def forward(self, sample: torch.FloatTensor) -> torch.FloatTensor: r"""The forward method of the `EncoderCausal3D` class.""" assert len(sample.shape) == 5, "The input tensor should have 5 dimensions" sample = self.conv_in(sample) # down for down_block in self.down_blocks: sample = down_block(sample) # middle if self.mid_block.add_attention: attention_mask = self.prepare_attention_mask(sample) else: attention_mask = None sample = auto_grad_checkpoint(self.mid_block, sample, attention_mask) # post-process sample = self.conv_norm_out(sample) sample = self.conv_act(sample) sample = self.conv_out(sample) return sample class DecoderCausal3D(nn.Module): r""" The `DecoderCausal3D` layer of a variational autoencoder that decodes its latent representation into an output sample. """ def __init__( self, in_channels: int = 3, out_channels: int = 3, block_out_channels: Tuple[int, ...] = (64,), layers_per_block: int = 2, norm_num_groups: int = 32, act_fn: str = "silu", mid_block_add_attention=True, time_compression_ratio: int = 4, spatial_compression_ratio: int = 8, dropout: float = 0.0, ): super().__init__() self.layers_per_block = layers_per_block self.conv_in = CausalConv3d(in_channels, block_out_channels[-1], kernel_size=3, stride=1) self.mid_block = None self.up_blocks = nn.ModuleList([]) # mid self.mid_block = UNetMidBlockCausal3D( in_channels=block_out_channels[-1], resnet_eps=1e-6, resnet_act_fn=act_fn, output_scale_factor=1, attention_head_dim=block_out_channels[-1], resnet_groups=norm_num_groups, add_attention=mid_block_add_attention, ) # up reversed_block_out_channels = list(reversed(block_out_channels)) output_channel = reversed_block_out_channels[0] for i, _ in enumerate(block_out_channels): prev_output_channel = output_channel output_channel = reversed_block_out_channels[i] is_final_block = i == len(block_out_channels) - 1 num_spatial_upsample_layers = int(np.log2(spatial_compression_ratio)) num_time_upsample_layers = int(np.log2(time_compression_ratio)) if time_compression_ratio == 4: add_spatial_upsample = bool(i < num_spatial_upsample_layers) add_time_upsample = bool( i >= len(block_out_channels) - 1 - num_time_upsample_layers and not is_final_block ) elif time_compression_ratio == 8: add_spatial_upsample = bool(i < num_spatial_upsample_layers) add_time_upsample = bool(i < num_spatial_upsample_layers) else: raise ValueError(f"Unsupported time_compression_ratio: {time_compression_ratio}.") upsample_scale_factor_HW = (2, 2) if add_spatial_upsample else (1, 1) upsample_scale_factor_T = (2,) if add_time_upsample else (1,) upsample_scale_factor = tuple(upsample_scale_factor_T + upsample_scale_factor_HW) up_block = UpDecoderBlockCausal3D( num_layers=self.layers_per_block + 1, in_channels=prev_output_channel, out_channels=output_channel, resolution_idx=None, dropout=dropout, add_upsample=bool(add_spatial_upsample or add_time_upsample), upsample_scale_factor=upsample_scale_factor, resnet_eps=1e-6, resnet_act_fn=act_fn, resnet_groups=norm_num_groups, ) self.up_blocks.append(up_block) prev_output_channel = output_channel self.conv_norm_out = nn.GroupNorm(num_channels=block_out_channels[0], num_groups=norm_num_groups, eps=1e-6) self.conv_act = nn.SiLU() self.conv_out = CausalConv3d(block_out_channels[0], out_channels, kernel_size=3) def post_process(self, sample: torch.Tensor) -> torch.Tensor: sample = self.conv_norm_out(sample) sample = self.conv_act(sample) return sample def prepare_attention_mask(self, hidden_states: torch.Tensor) -> torch.Tensor: B, C, T, H, W = hidden_states.shape attention_mask = prepare_causal_attention_mask( T, H * W, hidden_states.dtype, hidden_states.device, batch_size=B ) return attention_mask def forward( self, sample: torch.FloatTensor, ) -> torch.FloatTensor: r"""The forward method of the `DecoderCausal3D` class.""" assert len(sample.shape) == 5, "The input tensor should have 5 dimensions." sample = self.conv_in(sample) upscale_dtype = next(iter(self.up_blocks.parameters())).dtype # middle if self.mid_block.add_attention: attention_mask = self.prepare_attention_mask(sample) else: attention_mask = None sample = auto_grad_checkpoint(self.mid_block, sample, attention_mask) sample = sample.to(upscale_dtype) # up for up_block in self.up_blocks: sample = up_block(sample) # post-process if getattr(self, "grad_checkpointing", False): sample = checkpoint(self.post_process, sample, use_reentrant=True) else: sample = self.post_process(sample) sample = self.conv_out(sample) return sample class DiagonalGaussianDistribution(object): def __init__(self, parameters: torch.Tensor, deterministic: bool = False): if parameters.ndim == 3: dim = 2 # (B, L, C) elif parameters.ndim == 5 or parameters.ndim == 4: dim = 1 # (B, C, T, H ,W) / (B, C, H, W) else: raise NotImplementedError self.parameters = parameters self.mean, self.logvar = torch.chunk(parameters, 2, dim=dim) self.logvar = torch.clamp(self.logvar, -30.0, 20.0) self.deterministic = deterministic self.std = torch.exp(0.5 * self.logvar) self.var = torch.exp(self.logvar) if self.deterministic: self.var = self.std = torch.zeros_like( self.mean, device=self.parameters.device, dtype=self.parameters.dtype ) def sample(self, generator: Optional[torch.Generator] = None) -> torch.FloatTensor: # make sure sample is on the same device as the parameters and has same dtype sample = randn_tensor( self.mean.shape, generator=generator, device=self.parameters.device, dtype=self.parameters.dtype, ) x = self.mean + self.std * sample return x def kl(self, other: "DiagonalGaussianDistribution" = None) -> torch.Tensor: if self.deterministic: return torch.Tensor([0.0]) else: reduce_dim = list(range(1, self.mean.ndim)) if other is None: return 0.5 * torch.sum( torch.pow(self.mean, 2) + self.var - 1.0 - self.logvar, dim=reduce_dim, ) else: return 0.5 * torch.sum( torch.pow(self.mean - other.mean, 2) / other.var + self.var / other.var - 1.0 - self.logvar + other.logvar, dim=reduce_dim, ) def nll(self, sample: torch.Tensor, dims: Tuple[int, ...] = [1, 2, 3]) -> torch.Tensor: if self.deterministic: return torch.Tensor([0.0]) logtwopi = np.log(2.0 * np.pi) return 0.5 * torch.sum( logtwopi + self.logvar + torch.pow(sample - self.mean, 2) / self.var, dim=dims, ) def mode(self) -> torch.Tensor: return self.mean ================================================ FILE: opensora/models/mmdit/__init__.py ================================================ from .model import Flux ================================================ FILE: opensora/models/mmdit/distributed.py ================================================ from functools import partial from typing import Dict, List, Optional, Tuple, Union import torch import torch.distributed as dist import torch.nn as nn from colossalai.shardformer.layer import (FusedLinear1D_Col, FusedLinear1D_Row, Linear1D_Col, Linear1D_Row) from colossalai.shardformer.layer._operation import all_to_all_comm from colossalai.shardformer.layer.attn import RingComm, _rescale_out_lse from colossalai.shardformer.layer.utils import is_share_sp_tp from colossalai.shardformer.policies.base_policy import ( ModulePolicyDescription, Policy, SubModuleReplacementDescription) from colossalai.shardformer.shard import ShardConfig from einops import rearrange from flash_attn.flash_attn_interface import (_flash_attn_backward, _flash_attn_forward) from liger_kernel.ops.rope import LigerRopeFunction try: from flash_attn_interface import \ _flash_attn_backward as _flash_attn_backward_v3 from flash_attn_interface import \ _flash_attn_forward as _flash_attn_forward_v3 SUPPORT_FA3 = True except: SUPPORT_FA3 = False from torch import Tensor from opensora.acceleration.checkpoint import auto_grad_checkpoint from .layers import DoubleStreamBlock, SingleStreamBlock from .math import apply_rope, attention from .model import MMDiTModel class _SplitForwardGatherBackwardVarLen(torch.autograd.Function): """ Split the input and keep only the corresponding chuck to the rank. Args: input_ (`torch.Tensor`): input matrix. dim (int): the dimension to perform split and gather process_group (`torch.distributed.ProcessGroup`): the process group used for collective communication """ @staticmethod def forward(ctx, input_, dim, process_group, splits: List[int]): ctx.process_group = process_group ctx.dim = dim rank = dist.get_rank(process_group) ctx.grad_scale = splits[rank] / sum(splits) ctx.splits = splits return torch.split(input_, splits, dim=dim)[rank].clone() @staticmethod def backward(ctx, grad_output): grad_output = grad_output * ctx.grad_scale grad_output = grad_output.contiguous() world_size = dist.get_world_size(ctx.process_group) shapes = [list(grad_output.shape) for _ in range(world_size)] for i, shape in enumerate(shapes): shape[ctx.dim] = ctx.splits[i] tensor_list = [torch.empty(shape, dtype=grad_output.dtype, device=grad_output.device) for shape in shapes] dist.all_gather(tensor_list, grad_output, group=ctx.process_group) return torch.cat(tensor_list, dim=ctx.dim), None, None, None def split_forward_gather_backward_var_len(input_, dim, process_group, splits: List[int]): return _SplitForwardGatherBackwardVarLen.apply(input_, dim, process_group, splits) class _GatherForwardSplitBackwardVarLen(torch.autograd.Function): """ Split the input and keep only the corresponding chuck to the rank. Args: input_ (`torch.Tensor`): input matrix. dim (int): the dimension to perform split and gather process_group (`torch.distributed.ProcessGroup`): the process group used for collective communication """ @staticmethod def forward(ctx, input_, dim, process_group, splits: List[int]): input_ = input_.contiguous() ctx.process_group = process_group ctx.dim = dim rank = dist.get_rank(process_group) ctx.grad_scale = sum(splits) / splits[rank] ctx.splits = splits world_size = dist.get_world_size(ctx.process_group) shapes = [list(input_.shape) for _ in range(world_size)] for i, shape in enumerate(shapes): shape[dim] = splits[i] tensor_list = [torch.empty(shape, dtype=input_.dtype, device=input_.device) for shape in shapes] dist.all_gather(tensor_list, input_, group=ctx.process_group) return torch.cat(tensor_list, dim=dim) @staticmethod def backward(ctx, grad_output): grad_output = grad_output * ctx.grad_scale rank = dist.get_rank(ctx.process_group) return torch.split(grad_output, ctx.splits, dim=ctx.dim)[rank].clone(), None, None, None def gather_forward_split_backward_var_len(input_, dim, process_group, splits: List[int]): return _GatherForwardSplitBackwardVarLen.apply(input_, dim, process_group, splits) def _fa_forward( q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, dropout_p: float = 0.0, softmax_scale: Optional[float] = None ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: if SUPPORT_FA3: out, softmax_lse, *_ = _flash_attn_forward_v3( q, k, v, None, None, None, None, # k_new, q_new, qv, out None, None, None, # cu_seqlens_q, cu_seqlens_k, cu_seqlens_k_new None, None, None, None, # seqused_q, seqused_k, max_seqlen_q, max_seqlen_k None, None, None, # page_table, kv_batch_idx, leftpad_k None, None, # rotary_cos/sin None, None, None, # q_descale, k_descale, v_descale softmax_scale, False, # causal (-1, -1), ) rng_state = None else: out, softmax_lse, _, rng_state = _flash_attn_forward( q, k, v, dropout_p, softmax_scale, causal=False, window_size_left=-1, window_size_right=-1, softcap=0.0, alibi_slopes=None, return_softmax=False, ) return out, softmax_lse, rng_state def _fa_backward( dout: torch.Tensor, q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, out: torch.Tensor, softmax_lse: torch.Tensor, dq: torch.Tensor, dk: torch.Tensor, dv: torch.Tensor, rng_state: torch.Tensor, dropout_p: float = 0.0, softmax_scale: Optional[float] = None, deterministic: bool = False, ) -> None: if SUPPORT_FA3: _flash_attn_backward_v3( dout, q, k, v, out, softmax_lse, None, None, None, None, None, None, dq, dk, dv, softmax_scale, False, # causal (-1, -1), deterministic=deterministic, ) else: _flash_attn_backward( dout, q, k, v, out, softmax_lse, dq, dk, dv, dropout_p=dropout_p, softmax_scale=softmax_scale, causal=False, window_size_left=-1, window_size_right=-1, softcap=0.0, alibi_slopes=None, deterministic=deterministic, rng_state=rng_state, ) class RingAttention(torch.autograd.Function): ATTN_DONE: torch.cuda.Event = None SP_STREAM: torch.cuda.Stream = None @staticmethod def forward( ctx, q: torch.Tensor, k: torch.Tensor, v: torch.Tensor, sp_group: dist.ProcessGroup, sp_stream: torch.cuda.Stream, dropout_p: float = 0.0, softmax_scale: Optional[float] = None, deterministic: Optional[bool] = False, ) -> Tuple[torch.Tensor, torch.Tensor]: """Ring attention forward Args: ctx (_type_): self q (torch.Tensor): shape [B, S, N, D] k (torch.Tensor): shape [B, S, N, D] v (torch.Tensor): shape [B, S, N, D] sp_group (dist.ProcessGroup): sequence parallel group sp_stream (torch.cuda.Stream): sequence parallel stream dropout_p (float, optional): dropout prob. Defaults to 0.0. softmax_scale (Optional[float], optional): softmax scale. Defaults to None. deterministic (Optional[bool], optional): backward deterministic mode. Defaults to False. Returns: 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]. """ if softmax_scale is None: softmax_scale = q.shape[-1] ** (-0.5) sp_size = dist.get_world_size(sp_group) kv_comms: List[RingComm] = [RingComm(sp_group) for _ in range(2)] # [B, S, N, D] q, k, v = [x.contiguous() for x in [q, k, v]] # Pre-allocate double buffer for overlapping and receiving next step's inputs kv_buffers = [torch.stack((k, v))] # (2, B, S, N, D) kv_buffers.append(torch.empty_like(kv_buffers[0])) # outputs out = None block_out = [None, None] softmax_lse = [None, None] block_softmax_lse = [None, None] # log sum exp, the denominator of softmax in attention rng_states = [None for _ in range(sp_size)] sp_streams = [torch.cuda.current_stream(), sp_stream] def _kv_comm(i): # Avoid overwriting attn input when it shares mem with buffer if not RingAttention.ATTN_DONE.query(): kv_buffers[(i + 1) % 2] = torch.empty_like(kv_buffers[i % 2]) if i < sp_size - 1: kv_comms[i % 2].send_recv(kv_buffers[i % 2], kv_buffers[(i + 1) % 2]) for i in range(sp_size): with torch.cuda.stream(sp_streams[i % 2]): # Wait for current kv from prev rank # NOTE: waiting outside the current stream will NOT correctly synchronize. if i == 0: _kv_comm(i) else: kv_comms[(i + 1) % 2].wait() kv_block = kv_buffers[i % 2] q_block = q block_out[i % 2], block_softmax_lse[i % 2], rng_states[i] = _fa_forward( q_block, kv_block[0], kv_block[1], dropout_p, softmax_scale ) RingAttention.ATTN_DONE.record() # Pipeline the next KV comm with output correction instead of the next flash attn # to minimize idle time when comm takes longer than attn. _kv_comm(i + 1) block_softmax_lse[i % 2] = ( block_softmax_lse[i % 2].transpose(1, 2).unsqueeze(-1).contiguous().float() ) # [B, N, S] -> [B, S, N, 1] assert block_out[i % 2].shape[:-1] == block_softmax_lse[i % 2].shape[:-1] # Output and log sum exp correction. Ideally overlap this with the next flash attn kernel. # In reality this always finishes before next flash attn; no need for extra sync. if i == 0: out = block_out[0] softmax_lse = block_softmax_lse[0] else: out, softmax_lse = _rescale_out_lse(out, block_out[i % 2], softmax_lse, block_softmax_lse[i % 2]) torch.cuda.current_stream().wait_stream(sp_stream) out = out.to(q.dtype) softmax_lse = softmax_lse.squeeze(-1).transpose(1, 2).contiguous() ctx.dropout_p = dropout_p ctx.softmax_scale = softmax_scale ctx.deterministic = deterministic ctx.sp_group = sp_group ctx.save_for_backward(q, k, v, out, softmax_lse, *rng_states) # lse [B, N, S] return out, softmax_lse @staticmethod def backward(ctx, grad_output, grad_softmax_lse): # q, k, v, out: [B, S, N, D], softmax_lse: [B, N, S] q, k, v, out, softmax_lse, *rng_states = ctx.saved_tensors sp_group = ctx.sp_group sp_size = dist.get_world_size(sp_group) kv_comm = RingComm(sp_group) dkv_comm = RingComm(sp_group) grad_output = grad_output.contiguous() kv_buffers = [torch.stack((k, v))] # (2, B, S, N, D) kv_buffers.append(torch.empty_like(kv_buffers[0])) dq = None dq_block = torch.empty_like(q) dk_block = torch.empty_like(k) dv_block = torch.empty_like(v) dkv_buffers = [torch.empty_like(kv, dtype=torch.float) for kv in kv_buffers] del k, v for i in range(sp_size): if i > 0: kv_comm.wait() if i < sp_size - 1: kv_comm.send_recv(kv_buffers[i % 2], kv_buffers[(i + 1) % 2]) k_block, v_block = kv_buffers[i % 2] _fa_backward( grad_output, q, k_block, v_block, out, softmax_lse, dq_block, dk_block, dv_block, rng_states[i], dropout_p=ctx.dropout_p, softmax_scale=ctx.softmax_scale, deterministic=ctx.deterministic, ) if i == 0: dq = dq_block.float() dkv_buffers[i % 2][0] = dk_block.float() dkv_buffers[i % 2][1] = dv_block.float() else: dq += dq_block dkv_comm.wait() dkv_buffers[i % 2][0] += dk_block dkv_buffers[i % 2][1] += dv_block dkv_comm.send_recv(dkv_buffers[i % 2], dkv_buffers[(i + 1) % 2]) dkv_comm.wait() dkv = dkv_buffers[sp_size % 2] dq, dk, dv = [x.to(q.dtype) for x in (dq, *dkv)] return dq, dk, dv, None, None, None, None, None, None, None, None, None, None, None, None, None, None @staticmethod def attention( q, k, v, sp_group, dropout_p: float = 0.0, softmax_scale: Optional[float] = None, deterministic: bool = False, return_softmax: bool = False, ): """Ring attention Args: q (torch.Tensor): shape [B, S, N, D] k (torch.Tensor): shape [B, S, N, D] v (torch.Tensor): shape [B, S, N, D] sp_group (dist.ProcessGroup): sequence parallel group dropout_p (float, optional): dropout prob. Defaults to 0.0. softmax_scale (Optional[float], optional): softmax scale. Defaults to None. deterministic (Optional[bool], optional): backward deterministic mode. Defaults to False. return_softmax (bool, optional): return softmax or not. Defaults to False. Returns: 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]. """ if RingAttention.ATTN_DONE is None: RingAttention.ATTN_DONE = torch.cuda.Event() if RingAttention.SP_STREAM is None: RingAttention.SP_STREAM = torch.cuda.Stream() out, softmax_lse = RingAttention.apply( q, k, v, sp_group, RingAttention.SP_STREAM, dropout_p, softmax_scale, deterministic ) if return_softmax: return out, softmax_lse return out def ring_attention(q: Tensor, k: Tensor, v: Tensor, pe: Tensor, sp_group: dist.ProcessGroup) -> Tensor: if isinstance(pe, torch.Tensor): q, k = apply_rope(q, k, pe) else: cos, sin = pe q, k = LigerRopeFunction.apply(q, k, cos, sin) q, k, v = [x.transpose(1, 2) for x in (q, k, v)] # [B, H, L, D] -> [B, L, H, D] x = RingAttention.attention(q, k, v, sp_group) x = rearrange(x, "B L H D -> B L (H D)") return x class DistributedDoubleStreamBlockProcessor: def __init__(self, shard_config: ShardConfig) -> None: self.shard_config = shard_config def __call__( self, attn: DoubleStreamBlock, img: Tensor, txt: Tensor, vec: Tensor, pe: Tensor ) -> tuple[Tensor, Tensor]: img_mod1, img_mod2 = attn.img_mod(vec) txt_mod1, txt_mod2 = attn.txt_mod(vec) # prepare image for attention img_modulated = attn.img_norm1(img) img_modulated = (1 + img_mod1.scale) * img_modulated + img_mod1.shift if attn.img_attn.fused_qkv: img_qkv = attn.img_attn.qkv(img_modulated) 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) else: img_q = rearrange(attn.img_attn.q_proj(img_modulated), "B L (H D) -> B L H D", H=attn.num_heads) img_k = rearrange(attn.img_attn.k_proj(img_modulated), "B L (H D) -> B L H D", H=attn.num_heads) img_v = rearrange(attn.img_attn.v_proj(img_modulated), "B L (H D) -> B L H D", H=attn.num_heads) img_q, img_k = attn.img_attn.norm(img_q, img_k, img_v) if not attn.img_attn.fused_qkv: img_q = rearrange(img_q, "B L H D -> B H L D") img_k = rearrange(img_k, "B L H D -> B H L D") img_v = rearrange(img_v, "B L H D -> B H L D") # prepare txt for attention txt_modulated = attn.txt_norm1(txt) txt_modulated = (1 + txt_mod1.scale) * txt_modulated + txt_mod1.shift if attn.txt_attn.fused_qkv: txt_qkv = attn.txt_attn.qkv(txt_modulated) 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) else: txt_q = rearrange(attn.txt_attn.q_proj(txt_modulated), "B L (H D) -> B L H D", H=attn.num_heads) txt_k = rearrange(attn.txt_attn.k_proj(txt_modulated), "B L (H D) -> B L H D", H=attn.num_heads) txt_v = rearrange(attn.txt_attn.v_proj(txt_modulated), "B L (H D) -> B L H D", H=attn.num_heads) txt_q, txt_k = attn.txt_attn.norm(txt_q, txt_k, txt_v) if not attn.txt_attn.fused_qkv: txt_q = rearrange(txt_q, "B L H D -> B H L D") txt_k = rearrange(txt_k, "B L H D -> B H L D") txt_v = rearrange(txt_v, "B L H D -> B H L D") txt_len = txt_q.size(2) # run actual attention q = torch.cat((txt_q, img_q), dim=2) k = torch.cat((txt_k, img_k), dim=2) v = torch.cat((txt_v, img_v), dim=2) if ( self.shard_config.enable_sequence_parallelism and self.shard_config.sequence_parallelism_mode == "all_to_all" ): assert ( attn.num_heads % self.shard_config.sequence_parallel_size == 0 ), f"Expected num heads({attn.num_heads}) % sp size({self.shard_config.sequence_parallel_size}) == 0" # TODO: overlap the communication with computation q = all_to_all_comm(q, self.shard_config.sequence_parallel_process_group, scatter_dim=1, gather_dim=2) k = all_to_all_comm(k, self.shard_config.sequence_parallel_process_group, scatter_dim=1, gather_dim=2) v = all_to_all_comm(v, self.shard_config.sequence_parallel_process_group, scatter_dim=1, gather_dim=2) if self.shard_config.enable_sequence_parallelism and self.shard_config.sequence_parallelism_mode == "ring_attn": attn1 = ring_attention(q, k, v, pe, self.shard_config.sequence_parallel_process_group) else: attn1 = attention(q, k, v, pe=pe) if ( self.shard_config.enable_sequence_parallelism and self.shard_config.sequence_parallelism_mode == "all_to_all" ): attn1 = all_to_all_comm( attn1, self.shard_config.sequence_parallel_process_group, scatter_dim=1, gather_dim=2 ) txt_attn, img_attn = attn1[:, :txt_len], attn1[:, txt_len:] # calculate the img bloks img = img + img_mod1.gate * attn.img_attn.proj(img_attn) img = img + img_mod2.gate * attn.img_mlp((1 + img_mod2.scale) * attn.img_norm2(img) + img_mod2.shift) # calculate the txt bloks txt = txt + txt_mod1.gate * attn.txt_attn.proj(txt_attn) txt = txt + txt_mod2.gate * attn.txt_mlp((1 + txt_mod2.scale) * attn.txt_norm2(txt) + txt_mod2.shift) return img, txt class DistributedSingleStreamBlockProcessor: def __init__(self, shard_config: ShardConfig) -> None: self.shard_config = shard_config def __call__(self, attn: SingleStreamBlock, x: Tensor, vec: Tensor, pe: Tensor) -> Tensor: mod, _ = attn.modulation(vec) x_mod = (1 + mod.scale) * attn.pre_norm(x) + mod.shift if attn.fused_qkv: qkv, mlp = torch.split(attn.linear1(x_mod), [3 * attn.hidden_size, attn.mlp_hidden_dim], dim=-1) q, k, v = rearrange(qkv, "B L (K H D) -> K B H L D", K=3, H=attn.num_heads) else: q = rearrange(attn.q_proj(x_mod), "B L (H D) -> B L H D", H=attn.num_heads) k = rearrange(attn.k_proj(x_mod), "B L (H D) -> B L H D", H=attn.num_heads) v, mlp = torch.split(attn.v_mlp(x_mod), [attn.hidden_size, attn.mlp_hidden_dim], dim=-1) v = rearrange(v, "B L (H D) -> B L H D", H=attn.num_heads) q, k = attn.norm(q, k, v) if not attn.fused_qkv: q = rearrange(q, "B L H D -> B H L D") k = rearrange(k, "B L H D -> B H L D") v = rearrange(v, "B L H D -> B H L D") if ( self.shard_config.enable_sequence_parallelism and self.shard_config.sequence_parallelism_mode == "all_to_all" ): assert ( attn.num_heads % self.shard_config.sequence_parallel_size == 0 ), f"Expected num heads({attn.num_heads}) % sp size({self.shard_config.sequence_parallel_size}) == 0" q = all_to_all_comm(q, self.shard_config.sequence_parallel_process_group, scatter_dim=1, gather_dim=2) k = all_to_all_comm(k, self.shard_config.sequence_parallel_process_group, scatter_dim=1, gather_dim=2) v = all_to_all_comm(v, self.shard_config.sequence_parallel_process_group, scatter_dim=1, gather_dim=2) # compute attention if self.shard_config.enable_sequence_parallelism and self.shard_config.sequence_parallelism_mode == "ring_attn": attn_1 = ring_attention(q, k, v, pe, self.shard_config.sequence_parallel_process_group) else: attn_1 = attention(q, k, v, pe=pe) if ( self.shard_config.enable_sequence_parallelism and self.shard_config.sequence_parallelism_mode == "all_to_all" ): attn_1 = all_to_all_comm( attn_1, self.shard_config.sequence_parallel_process_group, scatter_dim=1, gather_dim=2 ) # compute activation in mlp stream, cat again and run second linear layer output = attn.linear2(torch.cat((attn_1, attn.mlp_act(mlp)), 2)) output = x + mod.gate * output return output class _TempSwitchCP(torch.autograd.Function): @staticmethod def forward(ctx, input_, shard_config: ShardConfig, value: bool): ctx.old_value = shard_config.enable_sequence_parallelism ctx.shard_config = shard_config shard_config.enable_sequence_parallelism = value return input_ @staticmethod def backward(ctx, grad_output): print(f"in backward, sp mode: {ctx.shard_config.enable_sequence_parallelism}") ctx.shard_config.enable_sequence_parallelism = ctx.old_value return grad_output, None, None def switch_sequence_parallelism(input_, shard_config: ShardConfig, value: bool): return _TempSwitchCP.apply(input_, shard_config, value) def mmdit_model_forward( self: MMDiTModel, img: Tensor, img_ids: Tensor, txt: Tensor, txt_ids: Tensor, timesteps: Tensor, y_vec: Tensor, cond: Tensor = None, guidance: Tensor | None = None, shard_config: ShardConfig = None, stage_index: Optional[List[int]] = None, internal_img: Optional[Tensor] = None, internal_txt: Optional[Tensor] = None, internal_pe: Optional[Tensor] = None, internal_vec: Optional[Tensor] = None, **kwargs, ): txt_len = txt.shape[1] if shard_config.pipeline_stage_manager is None or shard_config.pipeline_stage_manager.is_first_stage(): img, txt, vec, pe = self.prepare_block_inputs(img, img_ids, txt, txt_ids, timesteps, y_vec, cond, guidance) has_grad = img.grad_fn is not None old_sequence_parallelism = shard_config.enable_sequence_parallelism if shard_config.enable_sequence_parallelism: assert ( txt.shape[1] + img.shape[1] ) % shard_config.sequence_parallel_size == 0, ( f"Expected {txt.shape[1] +img.shape[1]} % {shard_config.sequence_parallel_size} == 0" ) mask = torch.zeros(txt.shape[1] + img.shape[1], dtype=bool) mask[txt.shape[1] :] = 1 mask_chunks = mask.chunk(shard_config.sequence_parallel_size) cur_mask = mask_chunks[dist.get_rank(shard_config.sequence_parallel_process_group)] txt_splits = [len(c) - c.sum().item() for c in mask_chunks] img_splits = [c.sum().item() for c in mask_chunks] if 0 in img_splits: # temporarily disable sequence parallelism to avoid stucking img = switch_sequence_parallelism(img, shard_config, False) else: img = split_forward_gather_backward_var_len( img, 1, shard_config.sequence_parallel_process_group, img_splits ) txt = split_forward_gather_backward_var_len( txt, 1, shard_config.sequence_parallel_process_group, txt_splits ) if shard_config.sequence_parallelism_mode == "ring_attn": # pe does not require grad sp_rank = dist.get_rank(shard_config.sequence_parallel_process_group) if isinstance(pe, torch.Tensor): pe = pe.chunk(shard_config.sequence_parallel_size, dim=2)[sp_rank].clone() else: cos, sin = pe cos = cos.chunk(shard_config.sequence_parallel_size, dim=1)[sp_rank].clone() sin = sin.chunk(shard_config.sequence_parallel_size, dim=1)[sp_rank].clone() pe = (cos, sin) else: img, txt, vec, pe = internal_img, internal_txt, internal_vec, internal_pe double_start, double_end = 0, len(self.double_blocks) if shard_config.pipeline_stage_manager is not None: double_start = stage_index[0] double_end = min(stage_index[1], len(self.double_blocks)) for block in self.double_blocks[double_start:double_end]: img, txt = auto_grad_checkpoint(block, img, txt, vec, pe) if shard_config.pipeline_stage_manager is not None and stage_index[1] <= len(self.double_blocks): return { "internal_img": img, "internal_txt": txt, "internal_pe": pe, "internal_vec": vec, } single_start, single_end = 0, len(self.single_blocks) if shard_config.pipeline_stage_manager is not None: single_start = max(stage_index[0] - len(self.double_blocks), 0) single_end = stage_index[1] - len(self.double_blocks) if single_start == 0: img = torch.cat((txt, img), 1) for block in self.single_blocks[single_start:single_end]: img = auto_grad_checkpoint(block, img, vec, pe) if shard_config.pipeline_stage_manager is not None and single_end < len(self.single_blocks): return { "internal_img": img, "internal_pe": pe, "internal_vec": vec, } if shard_config.enable_sequence_parallelism: img = img[:, cur_mask] else: img = img[:, txt_len:] img = self.final_layer(img, vec) # (N, T, patch_size ** 2 * out_channels) if shard_config.enable_sequence_parallelism: img = gather_forward_split_backward_var_len(img, 1, shard_config.sequence_parallel_process_group, img_splits) if not has_grad: shard_config.enable_sequence_parallelism = old_sequence_parallelism return img class MMDiTPolicy(Policy): def config_sanity_check(self): if self.shard_config.enable_sequence_parallelism and is_share_sp_tp( self.shard_config.sequence_parallelism_mode ): assert self.shard_config.enable_tensor_parallelism, "Tensor parallelism should be enabled" def preprocess(self) -> nn.Module: return self.model def postprocess(self) -> nn.Module: return self.model def tie_weight_check(self) -> bool: return False def module_policy(self) -> Dict[Union[str, nn.Module], ModulePolicyDescription]: policy = { DoubleStreamBlock: ModulePolicyDescription(attribute_replacement={}, sub_module_replacement=[]), SingleStreamBlock: ModulePolicyDescription(attribute_replacement={}, sub_module_replacement=[]), } if self.shard_config.enable_sequence_parallelism: if not is_share_sp_tp(self.shard_config.sequence_parallelism_mode): policy[DoubleStreamBlock].attribute_replacement["processor"] = DistributedDoubleStreamBlockProcessor( self.shard_config ) policy[SingleStreamBlock].attribute_replacement["processor"] = DistributedSingleStreamBlockProcessor( self.shard_config ) if self.shard_config.enable_sequence_parallelism or self.shard_config.pipeline_stage_manager is not None: fwd_fn = partial(mmdit_model_forward, shard_config=self.shard_config) if self.shard_config.pipeline_stage_manager is not None: layers_per_stage = self.shard_config.pipeline_stage_manager.distribute_layers( len(self.model.double_blocks) + len(self.model.single_blocks) ) if self.shard_config.pipeline_stage_manager.is_interleave: self.shard_config.pipeline_stage_manager.stage_indices = ( self.shard_config.pipeline_stage_manager.get_stage_index(layers_per_stage) ) else: stage_index = self.shard_config.pipeline_stage_manager.get_stage_index(layers_per_stage) fwd_fn = partial(mmdit_model_forward, shard_config=self.shard_config, stage_index=stage_index) self.append_or_create_method_replacement( description={ "forward": fwd_fn, }, policy=policy, target_key=MMDiTModel, ) if self.shard_config.enable_tensor_parallelism: mlp_hidden_size = int(self.model.config.hidden_size * self.model.config.mlp_ratio) assert ( self.model.config.num_heads % self.shard_config.tensor_parallel_size == 0 and mlp_hidden_size % self.shard_config.tensor_parallel_size == 0 ), "num_heads and hidden_size should be divisible by tensor_parallel_size" for n in ["img", "txt"]: if self.model.config.fused_qkv: policy[DoubleStreamBlock].sub_module_replacement.append( SubModuleReplacementDescription( suffix=f"{n}_attn.qkv", target_module=FusedLinear1D_Col, kwargs={ "split_sizes": [self.model.config.hidden_size] * 3, "seq_parallel_mode": self.shard_config.sequence_parallelism_mode, }, ), ) else: policy[DoubleStreamBlock].sub_module_replacement.extend( [ SubModuleReplacementDescription( suffix=f"{n}_attn.q_proj", target_module=Linear1D_Col, kwargs={"seq_parallel_mode": self.shard_config.sequence_parallelism_mode}, ), SubModuleReplacementDescription( suffix=f"{n}_attn.k_proj", target_module=Linear1D_Col, kwargs={"seq_parallel_mode": self.shard_config.sequence_parallelism_mode}, ), SubModuleReplacementDescription( suffix=f"{n}_attn.v_proj", target_module=Linear1D_Col, kwargs={"seq_parallel_mode": self.shard_config.sequence_parallelism_mode}, ), ] ) policy[DoubleStreamBlock].sub_module_replacement.extend( [ SubModuleReplacementDescription( suffix=f"{n}_attn.proj", target_module=Linear1D_Row, kwargs={"seq_parallel_mode": self.shard_config.sequence_parallelism_mode}, ), SubModuleReplacementDescription( suffix=f"{n}_mlp[0]", target_module=Linear1D_Col, kwargs={"seq_parallel_mode": self.shard_config.sequence_parallelism_mode}, ), SubModuleReplacementDescription( suffix=f"{n}_mlp[2]", target_module=Linear1D_Row, kwargs={"seq_parallel_mode": self.shard_config.sequence_parallelism_mode}, ), ] ) policy[DoubleStreamBlock].attribute_replacement["num_heads"] = ( self.model.config.num_heads // self.shard_config.tensor_parallel_size ) policy[SingleStreamBlock].attribute_replacement.update( { "num_heads": self.model.config.num_heads // self.shard_config.tensor_parallel_size, "hidden_size": self.model.config.hidden_size // self.shard_config.tensor_parallel_size, "mlp_hidden_dim": mlp_hidden_size // self.shard_config.tensor_parallel_size, } ) if self.model.config.fused_qkv: policy[SingleStreamBlock].sub_module_replacement.append( SubModuleReplacementDescription( suffix="linear1", target_module=FusedLinear1D_Col, kwargs={ "split_sizes": [self.model.config.hidden_size] * 3 + [mlp_hidden_size], "seq_parallel_mode": self.shard_config.sequence_parallelism_mode, }, ), ) else: policy[SingleStreamBlock].sub_module_replacement.extend( [ SubModuleReplacementDescription( suffix="q_proj", target_module=Linear1D_Col, kwargs={"seq_parallel_mode": self.shard_config.sequence_parallelism_mode}, ), SubModuleReplacementDescription( suffix="k_proj", target_module=Linear1D_Col, kwargs={"seq_parallel_mode": self.shard_config.sequence_parallelism_mode}, ), SubModuleReplacementDescription( suffix="v_mlp", target_module=FusedLinear1D_Col, kwargs={ "split_sizes": [self.model.config.hidden_size] + [mlp_hidden_size], "seq_parallel_mode": self.shard_config.sequence_parallelism_mode, }, ), ] ) policy[SingleStreamBlock].sub_module_replacement.extend( [ SubModuleReplacementDescription( suffix="linear2", target_module=FusedLinear1D_Row, kwargs={ "split_sizes": [self.model.config.hidden_size, mlp_hidden_size], "seq_parallel_mode": self.shard_config.sequence_parallelism_mode, }, ), ], ) return policy def get_held_layers(self) -> List[nn.Module]: stage_manager = self.shard_config.pipeline_stage_manager assert stage_manager is not None, "Pipeline stage manager is not set" held_layers = [] total_blocks = [*self.model.double_blocks, *self.model.single_blocks] if stage_manager.is_first_stage(ignore_chunk=stage_manager.is_interleave): held_layers.extend( [ self.model.pe_embedder, self.model.img_in, self.model.time_in, self.model.vector_in, self.model.guidance_in, self.model.cond_in, self.model.txt_in, ] ) layers_per_stage = stage_manager.distribute_layers(len(total_blocks)) if stage_manager.is_interleave: assert stage_manager.num_model_chunks is not None stage_indices = stage_manager.get_stage_index(layers_per_stage) for start_idx, end_idx in stage_indices: held_layers.extend(total_blocks[start_idx:end_idx]) else: start_idx, end_idx = stage_manager.get_stage_index(layers_per_stage) held_layers.extend(total_blocks[start_idx:end_idx]) if stage_manager.is_last_stage(ignore_chunk=stage_manager.is_interleave): held_layers.append(self.model.final_layer) return held_layers ================================================ FILE: opensora/models/mmdit/layers.py ================================================ # Modified from Flux # # Copyright 2024 Black Forest Labs # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import math from dataclasses import dataclass import torch from einops import rearrange from liger_kernel.ops.rms_norm import LigerRMSNormFunction from torch import Tensor, nn from .math import attention, liger_rope, rope class EmbedND(nn.Module): def __init__(self, dim: int, theta: int, axes_dim: list[int]): super().__init__() self.dim = dim self.theta = theta self.axes_dim = axes_dim def forward(self, ids: Tensor) -> Tensor: n_axes = ids.shape[-1] emb = torch.cat( [rope(ids[..., i], self.axes_dim[i], self.theta) for i in range(n_axes)], dim=-3, ) return emb.unsqueeze(1) class LigerEmbedND(nn.Module): def __init__(self, dim: int, theta: int, axes_dim: list[int]): super().__init__() self.dim = dim self.theta = theta self.axes_dim = axes_dim def forward(self, ids: Tensor) -> Tensor: n_axes = ids.shape[-1] cos_list = [] sin_list = [] for i in range(n_axes): cos, sin = liger_rope(ids[..., i], self.axes_dim[i], self.theta) cos_list.append(cos) sin_list.append(sin) cos_emb = torch.cat(cos_list, dim=-1).repeat(1, 1, 2).contiguous() sin_emb = torch.cat(sin_list, dim=-1).repeat(1, 1, 2).contiguous() return (cos_emb, sin_emb) @torch.compile(mode="max-autotune-no-cudagraphs", dynamic=True) def timestep_embedding(t: Tensor, dim, max_period=10000, time_factor: float = 1000.0): """ Create sinusoidal timestep embeddings. :param t: a 1-D Tensor of N indices, one per batch element. These may be fractional. :param dim: the dimension of the output. :param max_period: controls the minimum frequency of the embeddings. :return: an (N, D) Tensor of positional embeddings. """ t = time_factor * t half = dim // 2 freqs = torch.exp(-math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half).to(t.device) args = t[:, None].float() * freqs[None] embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1) if dim % 2: embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1) if torch.is_floating_point(t): embedding = embedding.to(t) return embedding class MLPEmbedder(nn.Module): def __init__(self, in_dim: int, hidden_dim: int): super().__init__() self.in_layer = nn.Linear(in_dim, hidden_dim, bias=True) self.silu = nn.SiLU() self.out_layer = nn.Linear(hidden_dim, hidden_dim, bias=True) def forward(self, x: Tensor) -> Tensor: return self.out_layer(self.silu(self.in_layer(x))) class RMSNorm(torch.nn.Module): def __init__(self, dim: int): super().__init__() self.scale = nn.Parameter(torch.ones(dim)) def forward(self, x: Tensor): x_dtype = x.dtype x = x.float() rrms = torch.rsqrt(torch.mean(x**2, dim=-1, keepdim=True) + 1e-6) return (x * rrms).to(dtype=x_dtype) * self.scale class FusedRMSNorm(RMSNorm): def forward(self, x: Tensor): return LigerRMSNormFunction.apply( x, self.scale, 1e-6, 0.0, "llama", False, ) class QKNorm(torch.nn.Module): def __init__(self, dim: int): super().__init__() self.query_norm = FusedRMSNorm(dim) self.key_norm = FusedRMSNorm(dim) def forward(self, q: Tensor, k: Tensor, v: Tensor) -> tuple[Tensor, Tensor]: q = self.query_norm(q) k = self.key_norm(k) return q.to(v), k.to(v) class SelfAttention(nn.Module): def __init__(self, dim: int, num_heads: int = 8, qkv_bias: bool = False, fused_qkv: bool = True): super().__init__() self.num_heads = num_heads self.fused_qkv = fused_qkv head_dim = dim // num_heads if fused_qkv: self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) else: self.q_proj = nn.Linear(dim, dim, bias=qkv_bias) self.k_proj = nn.Linear(dim, dim, bias=qkv_bias) self.v_proj = nn.Linear(dim, dim, bias=qkv_bias) self.norm = QKNorm(head_dim) self.proj = nn.Linear(dim, dim) def forward(self, x: Tensor, pe: Tensor) -> Tensor: if self.fused_qkv: qkv = self.qkv(x) q, k, v = rearrange(qkv, "B L (K H D) -> K B H L D", K=3, H=self.num_heads) else: q = rearrange(self.q_proj(x), "B L (H D) -> B L H D", H=self.num_heads) k = rearrange(self.k_proj(x), "B L (H D) -> B L H D", H=self.num_heads) v = rearrange(self.v_proj(x), "B L (H D) -> B L H D", H=self.num_heads) q, k = self.norm(q, k, v) if not self.fused_qkv: q = rearrange(q, "B L H D -> B H L D") k = rearrange(k, "B L H D -> B H L D") v = rearrange(v, "B L H D -> B H L D") x = attention(q, k, v, pe=pe) x = self.proj(x) return x @dataclass class ModulationOut: shift: Tensor scale: Tensor gate: Tensor class Modulation(nn.Module): def __init__(self, dim: int, double: bool): super().__init__() self.is_double = double self.multiplier = 6 if double else 3 self.lin = nn.Linear(dim, self.multiplier * dim, bias=True) def forward(self, vec: Tensor) -> tuple[ModulationOut, ModulationOut | None]: out = self.lin(nn.functional.silu(vec))[:, None, :].chunk(self.multiplier, dim=-1) return ( ModulationOut(*out[:3]), ModulationOut(*out[3:]) if self.is_double else None, ) class DoubleStreamBlockProcessor: def __call__(self, attn: nn.Module, img: Tensor, txt: Tensor, vec: Tensor, pe: Tensor) -> tuple[Tensor, Tensor]: # attn is the DoubleStreamBlock; # process img and txt separately while both is influenced by text vec # vec will interact with image latent and text context img_mod1, img_mod2 = attn.img_mod(vec) # get shift, scale, gate for each mod txt_mod1, txt_mod2 = attn.txt_mod(vec) # prepare image for attention img_modulated = attn.img_norm1(img) img_modulated = (1 + img_mod1.scale) * img_modulated + img_mod1.shift if attn.img_attn.fused_qkv: img_qkv = attn.img_attn.qkv(img_modulated) 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) else: img_q = rearrange(attn.img_attn.q_proj(img_modulated), "B L (H D) -> B L H D", H=attn.num_heads) img_k = rearrange(attn.img_attn.k_proj(img_modulated), "B L (H D) -> B L H D", H=attn.num_heads) img_v = rearrange(attn.img_attn.v_proj(img_modulated), "B L (H D) -> B L H D", H=attn.num_heads) img_q, img_k = attn.img_attn.norm(img_q, img_k, img_v) # RMSNorm for QK Norm as in SD3 paper if not attn.img_attn.fused_qkv: img_q = rearrange(img_q, "B L H D -> B H L D") img_k = rearrange(img_k, "B L H D -> B H L D") img_v = rearrange(img_v, "B L H D -> B H L D") # prepare txt for attention txt_modulated = attn.txt_norm1(txt) txt_modulated = (1 + txt_mod1.scale) * txt_modulated + txt_mod1.shift if attn.txt_attn.fused_qkv: txt_qkv = attn.txt_attn.qkv(txt_modulated) 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) else: txt_q = rearrange(attn.txt_attn.q_proj(txt_modulated), "B L (H D) -> B L H D", H=attn.num_heads) txt_k = rearrange(attn.txt_attn.k_proj(txt_modulated), "B L (H D) -> B L H D", H=attn.num_heads) txt_v = rearrange(attn.txt_attn.v_proj(txt_modulated), "B L (H D) -> B L H D", H=attn.num_heads) txt_q, txt_k = attn.txt_attn.norm(txt_q, txt_k, txt_v) if not attn.txt_attn.fused_qkv: txt_q = rearrange(txt_q, "B L H D -> B H L D") txt_k = rearrange(txt_k, "B L H D -> B H L D") txt_v = rearrange(txt_v, "B L H D -> B H L D") # run actual attention, image and text attention are calculated together by concat different attn heads q = torch.cat((txt_q, img_q), dim=2) k = torch.cat((txt_k, img_k), dim=2) v = torch.cat((txt_v, img_v), dim=2) attn1 = attention(q, k, v, pe=pe) txt_attn, img_attn = attn1[:, : txt_q.shape[2]], attn1[:, txt_q.shape[2] :] # calculate the img bloks img = img + img_mod1.gate * attn.img_attn.proj(img_attn) img = img + img_mod2.gate * attn.img_mlp((1 + img_mod2.scale) * attn.img_norm2(img) + img_mod2.shift) # calculate the txt bloks txt = txt + txt_mod1.gate * attn.txt_attn.proj(txt_attn) txt = txt + txt_mod2.gate * attn.txt_mlp((1 + txt_mod2.scale) * attn.txt_norm2(txt) + txt_mod2.shift) return img, txt class DoubleStreamBlock(nn.Module): def __init__( self, hidden_size: int, num_heads: int, mlp_ratio: float, qkv_bias: bool = False, fused_qkv: bool = True, ): super().__init__() mlp_hidden_dim = int(hidden_size * mlp_ratio) self.num_heads = num_heads self.hidden_size = hidden_size self.head_dim = hidden_size // num_heads # image stream self.img_mod = Modulation(hidden_size, double=True) self.img_norm1 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6) self.img_attn = SelfAttention(dim=hidden_size, num_heads=num_heads, qkv_bias=qkv_bias, fused_qkv=fused_qkv) self.img_norm2 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6) self.img_mlp = nn.Sequential( nn.Linear(hidden_size, mlp_hidden_dim, bias=True), nn.GELU(approximate="tanh"), nn.Linear(mlp_hidden_dim, hidden_size, bias=True), ) # text stream self.txt_mod = Modulation(hidden_size, double=True) self.txt_norm1 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6) self.txt_attn = SelfAttention(dim=hidden_size, num_heads=num_heads, qkv_bias=qkv_bias, fused_qkv=fused_qkv) self.txt_norm2 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6) self.txt_mlp = nn.Sequential( nn.Linear(hidden_size, mlp_hidden_dim, bias=True), nn.GELU(approximate="tanh"), nn.Linear(mlp_hidden_dim, hidden_size, bias=True), ) # processor processor = DoubleStreamBlockProcessor() self.set_processor(processor) def set_processor(self, processor) -> None: self.processor = processor def get_processor(self): return self.processor def forward(self, img: Tensor, txt: Tensor, vec: Tensor, pe: Tensor, **kwargs) -> tuple[Tensor, Tensor]: return self.processor(self, img, txt, vec, pe) class SingleStreamBlockProcessor: def __call__(self, attn: nn.Module, x: Tensor, vec: Tensor, pe: Tensor) -> Tensor: mod, _ = attn.modulation(vec) x_mod = (1 + mod.scale) * attn.pre_norm(x) + mod.shift if attn.fused_qkv: qkv, mlp = torch.split(attn.linear1(x_mod), [3 * attn.hidden_size, attn.mlp_hidden_dim], dim=-1) q, k, v = rearrange(qkv, "B L (K H D) -> K B H L D", K=3, H=attn.num_heads) else: q = rearrange(attn.q_proj(x_mod), "B L (H D) -> B L H D", H=attn.num_heads) k = rearrange(attn.k_proj(x_mod), "B L (H D) -> B L H D", H=attn.num_heads) v, mlp = torch.split(attn.v_mlp(x_mod), [attn.hidden_size, attn.mlp_hidden_dim], dim=-1) v = rearrange(v, "B L (H D) -> B L H D", H=attn.num_heads) q, k = attn.norm(q, k, v) if not attn.fused_qkv: q = rearrange(q, "B L H D -> B H L D") k = rearrange(k, "B L H D -> B H L D") v = rearrange(v, "B L H D -> B H L D") # compute attention attn_1 = attention(q, k, v, pe=pe) # compute activation in mlp stream, cat again and run second linear layer output = attn.linear2(torch.cat((attn_1, attn.mlp_act(mlp)), 2)) output = x + mod.gate * output return output class SingleStreamBlock(nn.Module): """ A DiT block with parallel linear layers as described in https://arxiv.org/abs/2302.05442 and adapted modulation interface. """ def __init__( self, hidden_size: int, num_heads: int, mlp_ratio: float = 4.0, qk_scale: float | None = None, fused_qkv: bool = True, ): super().__init__() self.hidden_dim = hidden_size self.num_heads = num_heads self.head_dim = hidden_size // num_heads self.scale = qk_scale or self.head_dim**-0.5 self.fused_qkv = fused_qkv self.mlp_hidden_dim = int(hidden_size * mlp_ratio) if fused_qkv: # qkv and mlp_in self.linear1 = nn.Linear(hidden_size, hidden_size * 3 + self.mlp_hidden_dim) else: self.q_proj = nn.Linear(hidden_size, hidden_size) self.k_proj = nn.Linear(hidden_size, hidden_size) self.v_mlp = nn.Linear(hidden_size, hidden_size + self.mlp_hidden_dim) # proj and mlp_out self.linear2 = nn.Linear(hidden_size + self.mlp_hidden_dim, hidden_size) self.norm = QKNorm(self.head_dim) self.hidden_size = hidden_size self.pre_norm = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6) self.mlp_act = nn.GELU(approximate="tanh") self.modulation = Modulation(hidden_size, double=False) processor = SingleStreamBlockProcessor() self.set_processor(processor) def set_processor(self, processor) -> None: self.processor = processor def get_processor(self): return self.processor def forward(self, x: Tensor, vec: Tensor, pe: Tensor, **kwargs) -> Tensor: return self.processor(self, x, vec, pe) class LastLayer(nn.Module): def __init__(self, hidden_size: int, patch_size: int, out_channels: int): super().__init__() self.norm_final = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6) self.linear = nn.Linear(hidden_size, patch_size * patch_size * out_channels, bias=True) self.adaLN_modulation = nn.Sequential(nn.SiLU(), nn.Linear(hidden_size, 2 * hidden_size, bias=True)) def forward(self, x: Tensor, vec: Tensor) -> Tensor: shift, scale = self.adaLN_modulation(vec).chunk(2, dim=1) x = (1 + scale[:, None, :]) * self.norm_final(x) + shift[:, None, :] x = self.linear(x) return x ================================================ FILE: opensora/models/mmdit/math.py ================================================ import torch from einops import rearrange from flash_attn import flash_attn_func as flash_attn_func_v2 from liger_kernel.ops.rope import LigerRopeFunction from torch import Tensor from typing import Tuple try: from flash_attn_interface import flash_attn_func as flash_attn_func_v3 SUPPORT_FA3 = True except: SUPPORT_FA3 = False def flash_attn_func(q: Tensor, k: Tensor, v: Tensor) -> Tensor: if SUPPORT_FA3: return flash_attn_func_v3(q, k, v)[0] return flash_attn_func_v2(q, k, v) def attention(q: Tensor, k: Tensor, v: Tensor, pe) -> Tensor: if isinstance(pe, torch.Tensor): q, k = apply_rope(q, k, pe) else: cos, sin = pe q, k = LigerRopeFunction.apply(q, k, cos, sin) # to compare with the original implementation # k = reverse_rearrange_tensor(k) q = rearrange(q, "B H L D -> B L H D") k = rearrange(k, "B H L D -> B L H D") v = rearrange(v, "B H L D -> B L H D") x = flash_attn_func(q, k, v) x = rearrange(x, "B L H D -> B L (H D)") return x def liger_rope(pos: Tensor, dim: int, theta: int) -> Tuple: assert dim % 2 == 0 scale = torch.arange(0, dim, 2, dtype=torch.float32, device=pos.device) / dim omega = 1.0 / (theta**scale) out = torch.einsum("...n,d->...nd", pos, omega) # (b, seq, dim//2) cos = out.cos() sin = out.sin() return (cos, sin) def rope(pos: Tensor, dim: int, theta: int) -> Tuple: assert dim % 2 == 0 scale = torch.arange(0, dim, 2, dtype=torch.float64, device=pos.device) / dim omega = 1.0 / (theta**scale) out = torch.einsum("...n,d->...nd", pos, omega) out = torch.stack([torch.cos(out), -torch.sin(out), torch.sin(out), torch.cos(out)], dim=-1) out = rearrange(out, "b n d (i j) -> b n d i j", i=2, j=2) return out.float() def apply_rope(xq: Tensor, xk: Tensor, freqs_cis: Tensor) -> tuple[Tensor, Tensor]: xq_ = xq.float().reshape(*xq.shape[:-1], -1, 1, 2) xk_ = xk.float().reshape(*xk.shape[:-1], -1, 1, 2) xq_out = freqs_cis[..., 0] * xq_[..., 0] + freqs_cis[..., 1] * xq_[..., 1] xk_out = freqs_cis[..., 0] * xk_[..., 0] + freqs_cis[..., 1] * xk_[..., 1] return xq_out.reshape(*xq.shape).type_as(xq), xk_out.reshape(*xk.shape).type_as(xk) def rearrange_tensor(tensor): """ Rearranges the last dimension (D) of the input tensor based on the specified mapping: 2d -> d, 2d+1 -> D/2 + d. Args: tensor (torch.Tensor): Input tensor of shape [B, H, L, D], where D is even. Returns: torch.Tensor: Tensor with rearranged last dimension, same shape as input. """ B, H, L, D = tensor.shape if D % 2 != 0: raise ValueError("The last dimension D must be even.") half_D = D // 2 indices = torch.empty(D, dtype=torch.long, device=tensor.device) # Fill the indices based on the mapping rule indices[:half_D] = torch.arange(0, D, 2, device=tensor.device) indices[half_D:] = torch.arange(1, D, 2, device=tensor.device) # Rearrange the tensor based on the computed indices return tensor.index_select(dim=-1, index=indices) def reverse_rearrange_tensor(tensor): """ Restores the original order of the last dimension (D) of the input tensor based on the reverse mapping: d -> 2d, D/2 + d -> 2d + 1. Args: tensor (torch.Tensor): Input tensor of shape [B, H, L, D], where D is even. Returns: torch.Tensor: Tensor with restored original last dimension order, same shape as input. """ B, H, L, D = tensor.shape if D % 2 != 0: raise ValueError("The last dimension D must be even.") half_D = D // 2 reverse_indices = torch.empty(D, dtype=torch.long, device=tensor.device) # Fill the reverse indices to restore the original order reverse_indices[::2] = torch.arange(half_D, device=tensor.device) reverse_indices[1::2] = torch.arange(half_D, D, device=tensor.device) # Rearrange the tensor based on the reverse indices return tensor.index_select(dim=-1, index=reverse_indices) ================================================ FILE: opensora/models/mmdit/model.py ================================================ # Modified from Flux # # Copyright 2024 Black Forest Labs # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. from dataclasses import dataclass import torch from torch import Tensor, nn from opensora.acceleration.checkpoint import auto_grad_checkpoint from opensora.models.mmdit.layers import ( DoubleStreamBlock, EmbedND, LastLayer, LigerEmbedND, MLPEmbedder, SingleStreamBlock, timestep_embedding, ) from opensora.registry import MODELS from opensora.utils.ckpt import load_checkpoint @dataclass class MMDiTConfig: model_type = "MMDiT" from_pretrained: str cache_dir: str in_channels: int vec_in_dim: int context_in_dim: int hidden_size: int mlp_ratio: float num_heads: int depth: int depth_single_blocks: int axes_dim: list[int] theta: int qkv_bias: bool guidance_embed: bool cond_embed: bool = False fused_qkv: bool = True grad_ckpt_settings: tuple[int, int] | None = None use_liger_rope: bool = False patch_size: int = 2 def get(self, attribute_name, default=None): return getattr(self, attribute_name, default) def __contains__(self, attribute_name): return hasattr(self, attribute_name) class MMDiTModel(nn.Module): config_class = MMDiTConfig def __init__(self, config: MMDiTConfig): super().__init__() self.config = config self.in_channels = config.in_channels self.out_channels = self.in_channels self.patch_size = config.patch_size if config.hidden_size % config.num_heads != 0: raise ValueError( f"Hidden size {config.hidden_size} must be divisible by num_heads {config.num_heads}" ) pe_dim = config.hidden_size // config.num_heads if sum(config.axes_dim) != pe_dim: raise ValueError( f"Got {config.axes_dim} but expected positional dim {pe_dim}" ) self.hidden_size = config.hidden_size self.num_heads = config.num_heads pe_embedder_cls = LigerEmbedND if config.use_liger_rope else EmbedND self.pe_embedder = pe_embedder_cls( dim=pe_dim, theta=config.theta, axes_dim=config.axes_dim ) self.img_in = nn.Linear(self.in_channels, self.hidden_size, bias=True) self.time_in = MLPEmbedder(in_dim=256, hidden_dim=self.hidden_size) self.vector_in = MLPEmbedder(config.vec_in_dim, self.hidden_size) self.guidance_in = ( MLPEmbedder(in_dim=256, hidden_dim=self.hidden_size) if config.guidance_embed else nn.Identity() ) self.cond_in = ( nn.Linear( self.in_channels + self.patch_size**2, self.hidden_size, bias=True ) if config.cond_embed else nn.Identity() ) self.txt_in = nn.Linear(config.context_in_dim, self.hidden_size) self.double_blocks = nn.ModuleList( [ DoubleStreamBlock( self.hidden_size, self.num_heads, mlp_ratio=config.mlp_ratio, qkv_bias=config.qkv_bias, fused_qkv=config.fused_qkv, ) for _ in range(config.depth) ] ) self.single_blocks = nn.ModuleList( [ SingleStreamBlock( self.hidden_size, self.num_heads, mlp_ratio=config.mlp_ratio, fused_qkv=config.fused_qkv, ) for _ in range(config.depth_single_blocks) ] ) self.final_layer = LastLayer(self.hidden_size, 1, self.out_channels) self.initialize_weights() if self.config.grad_ckpt_settings: self.forward = self.forward_selective_ckpt else: self.forward = self.forward_ckpt self._input_requires_grad = False def initialize_weights(self): if self.config.cond_embed: nn.init.zeros_(self.cond_in.weight) nn.init.zeros_(self.cond_in.bias) def prepare_block_inputs( self, img: Tensor, img_ids: Tensor, txt: Tensor, # t5 encoded vec txt_ids: Tensor, timesteps: Tensor, y_vec: Tensor, # clip encoded vec cond: Tensor = None, guidance: Tensor | None = None, ): """ obtain the processed: img: projected noisy img latent, txt: text context (from t5), vec: clip encoded vector, pe: the positional embeddings for concatenated img and txt """ if img.ndim != 3 or txt.ndim != 3: raise ValueError("Input img and txt tensors must have 3 dimensions.") # running on sequences img img = self.img_in(img) if self.config.cond_embed: if cond is None: raise ValueError("Didn't get conditional input for conditional model.") img = img + self.cond_in(cond) vec = self.time_in(timestep_embedding(timesteps, 256)) if self.config.guidance_embed: if guidance is None: raise ValueError( "Didn't get guidance strength for guidance distilled model." ) vec = vec + self.guidance_in(timestep_embedding(guidance, 256)) vec = vec + self.vector_in(y_vec) txt = self.txt_in(txt) # concat: 4096 + t*h*2/4 ids = torch.cat((txt_ids, img_ids), dim=1) pe = self.pe_embedder(ids) if self._input_requires_grad: # we only apply lora to double/single blocks, thus we only need to enable grad for these inputs img.requires_grad_() txt.requires_grad_() return img, txt, vec, pe def enable_input_require_grads(self): """Fit peft lora. This method should not be called manually.""" self._input_requires_grad = True def forward_ckpt( self, img: Tensor, img_ids: Tensor, txt: Tensor, txt_ids: Tensor, timesteps: Tensor, y_vec: Tensor, cond: Tensor = None, guidance: Tensor | None = None, **kwargs, ) -> Tensor: img, txt, vec, pe = self.prepare_block_inputs( img, img_ids, txt, txt_ids, timesteps, y_vec, cond, guidance ) for block in self.double_blocks: img, txt = auto_grad_checkpoint(block, img, txt, vec, pe) img = torch.cat((txt, img), 1) for block in self.single_blocks: img = auto_grad_checkpoint(block, img, vec, pe) img = img[:, txt.shape[1] :, ...] img = self.final_layer(img, vec) # (N, T, patch_size ** 2 * out_channels) return img def forward_selective_ckpt( self, img: Tensor, img_ids: Tensor, txt: Tensor, txt_ids: Tensor, timesteps: Tensor, y_vec: Tensor, cond: Tensor = None, guidance: Tensor | None = None, **kwargs, ) -> Tensor: img, txt, vec, pe = self.prepare_block_inputs( img, img_ids, txt, txt_ids, timesteps, y_vec, cond, guidance ) ckpt_depth_double = self.config.grad_ckpt_settings[0] for block in self.double_blocks[:ckpt_depth_double]: img, txt = auto_grad_checkpoint(block, img, txt, vec, pe) for block in self.double_blocks[ckpt_depth_double:]: img, txt = block(img, txt, vec, pe) ckpt_depth_single = self.config.grad_ckpt_settings[1] img = torch.cat((txt, img), 1) for block in self.single_blocks[:ckpt_depth_single]: img = auto_grad_checkpoint(block, img, vec, pe) for block in self.single_blocks[ckpt_depth_single:]: img = block(img, vec, pe) img = img[:, txt.shape[1] :, ...] img = self.final_layer(img, vec) # (N, T, patch_size ** 2 * out_channels) return img @MODELS.register_module("flux") def Flux( cache_dir: str = None, from_pretrained: str = None, device_map: str | torch.device = "cuda", torch_dtype: torch.dtype = torch.bfloat16, strict_load: bool = False, **kwargs, ) -> MMDiTModel: config = MMDiTConfig( from_pretrained=from_pretrained, cache_dir=cache_dir, **kwargs, ) low_precision_init = from_pretrained is not None and len(from_pretrained) > 0 if low_precision_init: default_dtype = torch.get_default_dtype() torch.set_default_dtype(torch_dtype) with torch.device(device_map): model = MMDiTModel(config) if low_precision_init: torch.set_default_dtype(default_dtype) else: model = model.to(torch_dtype) if from_pretrained: model = load_checkpoint( model, from_pretrained, cache_dir=cache_dir, device_map=device_map, strict=strict_load, ) return model ================================================ FILE: opensora/models/mmdit/policy.py ================================================ from functools import partial from typing import Dict, Union import torch.nn as nn from colossalai.shardformer.policies.base_policy import ModulePolicyDescription, Policy, SubModuleReplacementDescription from opensora.models.vae.tensor_parallel import Conv3dTPCol, Conv3dTPRow, GroupNormTP from .distributed import ContextParallelAttention, TPUpDecoderBlockCausal3D, prepare_parallel_attention_mask from .vae import DecoderCausal3D, EncoderCausal3D def gen_resnets_replacements(prefix: str, with_shortcut: bool = False): replacements = [ SubModuleReplacementDescription( suffix=f"{prefix}.norm1", target_module=GroupNormTP, ), SubModuleReplacementDescription( suffix=f"{prefix}.conv1.conv", target_module=Conv3dTPRow, kwargs=dict( split_output=True, ), ), SubModuleReplacementDescription( suffix=f"{prefix}.norm2", target_module=GroupNormTP, ), SubModuleReplacementDescription( suffix=f"{prefix}.conv2.conv", target_module=Conv3dTPRow, kwargs=dict( split_output=True, ), ), ] if with_shortcut: replacements.append( SubModuleReplacementDescription( suffix=f"{prefix}.conv_shortcut.conv", target_module=Conv3dTPRow, kwargs=dict( split_output=True, ), ) ) return replacements class HunyuanVaePolicy(Policy): def config_sanity_check(self): pass def preprocess(self): return self.model def module_policy(self) -> Dict[Union[str, nn.Module], ModulePolicyDescription]: policy = {} policy[EncoderCausal3D] = ModulePolicyDescription( sub_module_replacement=[ SubModuleReplacementDescription( suffix="conv_in.conv", target_module=Conv3dTPCol, ), *gen_resnets_replacements("down_blocks[0].resnets[0]"), *gen_resnets_replacements("down_blocks[0].resnets[1]"), SubModuleReplacementDescription( suffix="down_blocks[0].downsamplers[0].conv.conv", target_module=Conv3dTPRow, kwargs=dict( split_output=True, ), ), *gen_resnets_replacements("down_blocks[1].resnets[0]", with_shortcut=True), *gen_resnets_replacements("down_blocks[1].resnets[1]"), SubModuleReplacementDescription( suffix="down_blocks[1].downsamplers[0].conv.conv", target_module=Conv3dTPRow, ), SubModuleReplacementDescription( suffix="mid_block.attentions[0]", target_module=ContextParallelAttention, ), ], attribute_replacement={ "down_blocks[0].downsamplers[0].channels": self.model.encoder.down_blocks[0].downsamplers[0].channels // self.shard_config.tensor_parallel_size, "down_blocks[1].downsamplers[0].channels": self.model.encoder.down_blocks[1].downsamplers[0].channels // self.shard_config.tensor_parallel_size, # "mid_block.attentions[0].processor": MemEfficientRingAttnProcessor( # self.shard_config.tensor_parallel_process_group # ), }, method_replacement={ "prepare_attention_mask": partial( prepare_parallel_attention_mask, cp_group=self.shard_config.tensor_parallel_process_group ), }, ) policy[DecoderCausal3D] = ModulePolicyDescription( sub_module_replacement=[ SubModuleReplacementDescription( suffix="up_blocks[1].upsamplers[0]", target_module=TPUpDecoderBlockCausal3D, kwargs=dict( split_output=True, ), ), *gen_resnets_replacements("up_blocks[2].resnets[0]", with_shortcut=True), *gen_resnets_replacements("up_blocks[2].resnets[1]"), *gen_resnets_replacements("up_blocks[2].resnets[2]"), SubModuleReplacementDescription( suffix="up_blocks[2].upsamplers[0].conv.conv", target_module=Conv3dTPRow, kwargs=dict( split_output=True, ), ), *gen_resnets_replacements("up_blocks[3].resnets[0]", with_shortcut=True), *gen_resnets_replacements("up_blocks[3].resnets[1]"), *gen_resnets_replacements("up_blocks[3].resnets[2]"), SubModuleReplacementDescription( suffix="conv_norm_out", target_module=GroupNormTP, ), SubModuleReplacementDescription( suffix="conv_out.conv", target_module=Conv3dTPRow, ), SubModuleReplacementDescription( suffix="mid_block.attentions[0]", target_module=ContextParallelAttention, ), ], attribute_replacement={ "up_blocks[2].upsamplers[0].channels": self.model.decoder.up_blocks[2].upsamplers[0].channels // self.shard_config.tensor_parallel_size, # "mid_block.attentions[0].processor": MemEfficientRingAttnProcessor( # self.shard_config.tensor_parallel_process_group # ), }, method_replacement={ "prepare_attention_mask": partial( prepare_parallel_attention_mask, cp_group=self.shard_config.tensor_parallel_process_group ), }, ) return policy def postprocess(self): return self.model ================================================ FILE: opensora/models/text/__init__.py ================================================ from .conditioner import HFEmbedder ================================================ FILE: opensora/models/text/conditioner.py ================================================ from colossalai.shardformer import ShardConfig, ShardFormer from torch import Tensor, nn from transformers import CLIPTextModel, CLIPTokenizer, T5EncoderModel, T5Tokenizer from opensora.acceleration.shardformer.policy.t5_encoder import T5EncoderPolicy from opensora.registry import MODELS @MODELS.register_module("text_embedder") class HFEmbedder(nn.Module): def __init__(self, from_pretrained: str, max_length: int, shardformer: bool = False, **hf_kwargs): super().__init__() self.is_clip = "openai" in from_pretrained self.max_length = max_length self.output_key = "pooler_output" if self.is_clip else "last_hidden_state" if self.is_clip: self.tokenizer: CLIPTokenizer = CLIPTokenizer.from_pretrained(from_pretrained, max_length=max_length) self.hf_module: CLIPTextModel = CLIPTextModel.from_pretrained(from_pretrained, **hf_kwargs) assert not shardformer, "Shardformer is not supported for CLIP" else: self.tokenizer: T5Tokenizer = T5Tokenizer.from_pretrained( from_pretrained, max_length=max_length, legacy=True ) self.hf_module: T5EncoderModel = T5EncoderModel.from_pretrained(from_pretrained, **hf_kwargs) if shardformer: self.hf_module = shardformer_t5(self.hf_module) self.hf_module = self.hf_module.eval().requires_grad_(False) def forward(self, text: list[str], added_tokens: int = 0, seq_align: int = 1) -> Tensor: batch_encoding = self.tokenizer( text, truncation=True, max_length=self.max_length, return_length=False, return_overflowing_tokens=False, padding="max_length", return_tensors="pt", ) seq_len = batch_encoding["input_ids"].shape[1] if (added_tokens + seq_len) % seq_align != 0: num_pad_tokens = seq_align - (added_tokens + seq_len) % seq_align batch_encoding["input_ids"] = nn.functional.pad( batch_encoding["input_ids"], (0, num_pad_tokens), value=self.tokenizer.pad_token_id ) outputs = self.hf_module( input_ids=batch_encoding["input_ids"].to(self.hf_module.device), attention_mask=None, output_hidden_states=False, ) return outputs[self.output_key] def shardformer_t5(t5: T5EncoderModel) -> T5EncoderModel: """ Shardformer for T5 model Args: t5: T5 model to be optimized Returns: optimized T5 model """ dtype = t5.shared.weight.dtype shard_config = ShardConfig( enable_tensor_parallelism=False, enable_jit_fused=True, ) shard_former = ShardFormer(shard_config=shard_config) optim_model, _ = shard_former.optimize(t5, policy=T5EncoderPolicy()) optim_model = optim_model.to(dtype).eval().requires_grad_(False) return optim_model ================================================ FILE: opensora/models/vae/__init__.py ================================================ from .autoencoder_2d import AutoEncoderFlux from .discriminator import N_LAYER_DISCRIMINATOR_3D ================================================ FILE: opensora/models/vae/autoencoder_2d.py ================================================ # Modified from Flux # # Copyright 2024 Black Forest Labs # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. from dataclasses import dataclass import torch from einops import rearrange from torch import Tensor, nn from torch.nn.functional import silu as swish from opensora.registry import MODELS from opensora.utils.ckpt import load_checkpoint from .utils import DiagonalGaussianDistribution @dataclass class AutoEncoderConfig: from_pretrained: str | None cache_dir: str | None resolution: int in_channels: int ch: int out_ch: int ch_mult: list[int] num_res_blocks: int z_channels: int scale_factor: float shift_factor: float sample: bool = True class AttnBlock(nn.Module): def __init__(self, in_channels: int): super().__init__() self.norm = nn.GroupNorm(num_groups=32, num_channels=in_channels, eps=1e-6, affine=True) self.q = nn.Conv2d(in_channels, in_channels, kernel_size=1) self.k = nn.Conv2d(in_channels, in_channels, kernel_size=1) self.v = nn.Conv2d(in_channels, in_channels, kernel_size=1) self.proj_out = nn.Conv2d(in_channels, in_channels, kernel_size=1) def attention(self, h_: Tensor) -> Tensor: h_ = self.norm(h_) q = self.q(h_) k = self.k(h_) v = self.v(h_) b, c, h, w = q.shape q = rearrange(q, "b c h w -> b 1 (h w) c").contiguous() k = rearrange(k, "b c h w -> b 1 (h w) c").contiguous() v = rearrange(v, "b c h w -> b 1 (h w) c").contiguous() h_ = nn.functional.scaled_dot_product_attention(q, k, v) return rearrange(h_, "b 1 (h w) c -> b c h w", h=h, w=w) def forward(self, x: Tensor) -> Tensor: return x + self.proj_out(self.attention(x)) class ResnetBlock(nn.Module): def __init__(self, in_channels: int, out_channels: int): super().__init__() self.in_channels = in_channels out_channels = in_channels if out_channels is None else out_channels self.out_channels = out_channels self.norm1 = nn.GroupNorm(num_groups=32, num_channels=in_channels, eps=1e-6, affine=True) self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=1, padding=1) self.norm2 = nn.GroupNorm(num_groups=32, num_channels=out_channels, eps=1e-6, affine=True) self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=3, stride=1, padding=1) if self.in_channels != self.out_channels: self.nin_shortcut = nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=1, padding=0) def forward(self, x): h = x h = self.norm1(h) h = swish(h) h = self.conv1(h) h = self.norm2(h) h = swish(h) h = self.conv2(h) if self.in_channels != self.out_channels: x = self.nin_shortcut(x) return x + h class Downsample(nn.Module): def __init__(self, in_channels: int): super().__init__() self.conv = nn.Conv2d(in_channels, in_channels, kernel_size=3, stride=2, padding=0) def forward(self, x: Tensor) -> Tensor: pad = (0, 1, 0, 1) x = nn.functional.pad(x, pad, mode="constant", value=0) return self.conv(x) class Upsample(nn.Module): def __init__(self, in_channels: int): super().__init__() self.conv = nn.Conv2d(in_channels, in_channels, kernel_size=3, stride=1, padding=1) def forward(self, x: Tensor) -> Tensor: x = nn.functional.interpolate(x, scale_factor=2.0, mode="nearest") return self.conv(x) class Encoder(nn.Module): def __init__(self, config: AutoEncoderConfig): super().__init__() self.ch = config.ch self.num_resolutions = len(config.ch_mult) self.num_res_blocks = config.num_res_blocks self.resolution = config.resolution self.in_channels = config.in_channels # downsampling self.conv_in = nn.Conv2d(config.in_channels, self.ch, kernel_size=3, stride=1, padding=1) curr_res = config.resolution in_ch_mult = (1,) + tuple(config.ch_mult) self.in_ch_mult = in_ch_mult self.down = nn.ModuleList() block_in = self.ch for i_level in range(self.num_resolutions): block = nn.ModuleList() attn = nn.ModuleList() block_in = config.ch * in_ch_mult[i_level] block_out = config.ch * config.ch_mult[i_level] for _ in range(self.num_res_blocks): block.append(ResnetBlock(in_channels=block_in, out_channels=block_out)) block_in = block_out down = nn.Module() down.block = block down.attn = attn if i_level != self.num_resolutions - 1: down.downsample = Downsample(block_in) curr_res = curr_res // 2 self.down.append(down) # middle self.mid = nn.Module() self.mid.block_1 = ResnetBlock(in_channels=block_in, out_channels=block_in) self.mid.attn_1 = AttnBlock(block_in) self.mid.block_2 = ResnetBlock(in_channels=block_in, out_channels=block_in) # end self.norm_out = nn.GroupNorm(num_groups=32, num_channels=block_in, eps=1e-6, affine=True) self.conv_out = nn.Conv2d(block_in, 2 * config.z_channels, kernel_size=3, stride=1, padding=1) def forward(self, x: Tensor) -> Tensor: # downsampling hs = [self.conv_in(x)] for i_level in range(self.num_resolutions): for i_block in range(self.num_res_blocks): h = self.down[i_level].block[i_block](hs[-1]) if len(self.down[i_level].attn) > 0: h = self.down[i_level].attn[i_block](h) hs.append(h) if i_level != self.num_resolutions - 1: hs.append(self.down[i_level].downsample(hs[-1])) # middle h = hs[-1] h = self.mid.block_1(h) h = self.mid.attn_1(h) h = self.mid.block_2(h) # end h = self.norm_out(h) h = swish(h) h = self.conv_out(h) return h class Decoder(nn.Module): def __init__(self, config: AutoEncoderConfig): super().__init__() self.ch = config.ch self.num_resolutions = len(config.ch_mult) self.num_res_blocks = config.num_res_blocks self.resolution = config.resolution self.in_channels = config.in_channels self.ffactor = 2 ** (self.num_resolutions - 1) block_in = config.ch * config.ch_mult[self.num_resolutions - 1] curr_res = config.resolution // 2 ** (self.num_resolutions - 1) self.z_shape = (1, config.z_channels, curr_res, curr_res) # z to block_in self.conv_in = nn.Conv2d(config.z_channels, block_in, kernel_size=3, stride=1, padding=1) # middle self.mid = nn.Module() self.mid.block_1 = ResnetBlock(in_channels=block_in, out_channels=block_in) self.mid.attn_1 = AttnBlock(block_in) self.mid.block_2 = ResnetBlock(in_channels=block_in, out_channels=block_in) # upsampling self.up = nn.ModuleList() for i_level in reversed(range(self.num_resolutions)): block = nn.ModuleList() attn = nn.ModuleList() block_out = config.ch * config.ch_mult[i_level] for _ in range(self.num_res_blocks + 1): block.append(ResnetBlock(in_channels=block_in, out_channels=block_out)) block_in = block_out up = nn.Module() up.block = block up.attn = attn if i_level != 0: up.upsample = Upsample(block_in) curr_res = curr_res * 2 self.up.insert(0, up) # prepend to get consistent order # end self.norm_out = nn.GroupNorm(num_groups=32, num_channels=block_in, eps=1e-6, affine=True) self.conv_out = nn.Conv2d(block_in, config.out_ch, kernel_size=3, stride=1, padding=1) def forward(self, z: Tensor) -> Tensor: # z to block_in h = self.conv_in(z) # middle h = self.mid.block_1(h) h = self.mid.attn_1(h) h = self.mid.block_2(h) # upsampling for i_level in reversed(range(self.num_resolutions)): for i_block in range(self.num_res_blocks + 1): h = self.up[i_level].block[i_block](h) if len(self.up[i_level].attn) > 0: h = self.up[i_level].attn[i_block](h) if i_level != 0: h = self.up[i_level].upsample(h) # end h = self.norm_out(h) h = swish(h) return self.conv_out(h) class AutoEncoder(nn.Module): def __init__(self, config: AutoEncoderConfig): super().__init__() self.encoder = Encoder(config) self.decoder = Decoder(config) self.scale_factor = config.scale_factor self.shift_factor = config.shift_factor self.sample = config.sample def encode_(self, x: Tensor) -> tuple[Tensor, DiagonalGaussianDistribution]: T = x.shape[2] x = rearrange(x, "b c t h w -> (b t) c h w") params = self.encoder(x) params = rearrange(params, "(b t) c h w -> b c t h w", t=T) posterior = DiagonalGaussianDistribution(params) if self.sample: z = posterior.sample() else: z = posterior.mode() z = self.scale_factor * (z - self.shift_factor) return z, posterior def encode(self, x: Tensor) -> Tensor: return self.encode_(x)[0] def decode(self, z: Tensor) -> Tensor: T = z.shape[2] z = rearrange(z, "b c t h w -> (b t) c h w") z = z / self.scale_factor + self.shift_factor x = self.decoder(z) x = rearrange(x, "(b t) c h w -> b c t h w", t=T) return x def forward(self, x: Tensor) -> tuple[Tensor, DiagonalGaussianDistribution, Tensor]: # encode x.shape[2] z, posterior = self.encode_(x) # decode x_rec = self.decode(z) return x_rec, posterior, z def get_last_layer(self): return self.decoder.conv_out.weight @MODELS.register_module("autoencoder_2d") def AutoEncoderFlux( from_pretrained: str, cache_dir=None, resolution=256, in_channels=3, ch=128, out_ch=3, ch_mult=[1, 2, 4, 4], num_res_blocks=2, z_channels=16, scale_factor=0.3611, shift_factor=0.1159, device_map: str | torch.device = "cuda", torch_dtype: torch.dtype = torch.bfloat16, ) -> AutoEncoder: config = AutoEncoderConfig( from_pretrained=from_pretrained, cache_dir=cache_dir, resolution=resolution, in_channels=in_channels, ch=ch, out_ch=out_ch, ch_mult=ch_mult, num_res_blocks=num_res_blocks, z_channels=z_channels, scale_factor=scale_factor, shift_factor=shift_factor, ) with torch.device(device_map): model = AutoEncoder(config).to(torch_dtype) if from_pretrained: model = load_checkpoint(model, from_pretrained, cache_dir=cache_dir, device_map=device_map) return model ================================================ FILE: opensora/models/vae/discriminator.py ================================================ import os import torch.nn as nn from opensora.registry import MODELS from opensora.utils.ckpt import load_checkpoint def weights_init(m): classname = m.__class__.__name__ if classname.find("Conv") != -1: nn.init.normal_(m.weight.data, 0.0, 0.02) elif classname.find("BatchNorm") != -1: nn.init.normal_(m.weight.data, 1.0, 0.02) nn.init.constant_(m.bias.data, 0) def weights_init_conv(m): if hasattr(m, "conv"): m = m.conv classname = m.__class__.__name__ if classname.find("Conv") != -1: nn.init.normal_(m.weight.data, 0.0, 0.02) elif classname.find("BatchNorm") != -1: nn.init.normal_(m.weight.data, 1.0, 0.02) nn.init.constant_(m.bias.data, 0) class NLayerDiscriminator3D(nn.Module): """Defines a 3D PatchGAN discriminator as in Pix2Pix but for 3D inputs.""" def __init__( self, input_nc=1, ndf=64, n_layers=5, norm_layer=nn.BatchNorm3d, conv_cls="conv3d", dropout=0.30, ): """ Construct a 3D PatchGAN discriminator Parameters: input_nc (int) -- the number of channels in input volumes ndf (int) -- the number of filters in the last conv layer n_layers (int) -- the number of conv layers in the discriminator use_actnorm (bool) -- flag to use actnorm instead of batchnorm """ super(NLayerDiscriminator3D, self).__init__() assert conv_cls == "conv3d" use_bias = False kw = 3 padw = 1 sequence = [nn.Conv3d(input_nc, ndf, kernel_size=kw, stride=2, padding=padw), nn.LeakyReLU(0.2, True)] nf_mult = 1 nf_mult_prev = 1 for n in range(1, n_layers): # gradually increase the number of filters nf_mult_prev = nf_mult nf_mult = min(2**n, 8) sequence += [ nn.Conv3d( ndf * nf_mult_prev, ndf * nf_mult, kernel_size=(kw, kw, kw), stride=2 if n == 1 else (1, 2, 2), padding=padw, bias=use_bias, ), norm_layer(ndf * nf_mult), nn.LeakyReLU(0.2, True), nn.Dropout(dropout), ] nf_mult_prev = nf_mult nf_mult = min(2**n_layers, 8) sequence += [ nn.Conv3d( ndf * nf_mult_prev, ndf * nf_mult, kernel_size=(kw, kw, kw), stride=1, padding=padw, bias=use_bias, ), norm_layer(ndf * nf_mult), nn.LeakyReLU(0.2, True), nn.Dropout(dropout), nn.Conv3d(ndf * nf_mult, 1, kernel_size=kw, stride=1, padding=padw), ] self.main = nn.Sequential(*sequence) def forward(self, x): """Standard forward.""" return self.main(x) @MODELS.register_module("N_Layer_discriminator_3D") def N_LAYER_DISCRIMINATOR_3D(from_pretrained=None, force_huggingface=None, **kwargs): model = NLayerDiscriminator3D(**kwargs).apply(weights_init) if from_pretrained is not None: if force_huggingface or from_pretrained is not None and not os.path.exists(from_pretrained): raise NotImplementedError else: load_checkpoint(model, from_pretrained) print(f"loaded model from: {from_pretrained}") return model ================================================ FILE: opensora/models/vae/losses.py ================================================ import torch import torch.nn.functional as F from einops import rearrange from torch import Tensor, nn from opensora.models.vae.lpips import LPIPS def hinge_d_loss(logits_real, logits_fake): loss_real = torch.mean(F.relu(1.0 - logits_real)) loss_fake = torch.mean(F.relu(1.0 + logits_fake)) d_loss = 0.5 * (loss_real + loss_fake) return d_loss def vanilla_d_loss(logits_real, logits_fake): d_loss = 0.5 * ( torch.mean(torch.nn.functional.softplus(-logits_real)) + torch.mean(torch.nn.functional.softplus(logits_fake)) ) return d_loss def wgan_gp_loss(logits_real, logits_fake): d_loss = 0.5 * (-logits_real.mean() + logits_fake.mean()) return d_loss def adopt_weight(weight, global_step, threshold=0, value=0.0): if global_step < threshold: weight = value return weight def measure_perplexity(predicted_indices, n_embed): # src: https://github.com/karpathy/deep-vector-quantization/blob/main/model.py # eval cluster perplexity. when perplexity == num_embeddings then all clusters are used exactly equally encodings = F.one_hot(predicted_indices, n_embed).float().reshape(-1, n_embed) avg_probs = encodings.mean(0) perplexity = (-(avg_probs * torch.log(avg_probs + 1e-10)).sum()).exp() cluster_use = torch.sum(avg_probs > 0) return perplexity, cluster_use def l1(x, y): return torch.abs(x - y) def l2(x, y): return torch.pow((x - y), 2) def batch_mean(x): return torch.sum(x) / x.shape[0] def sigmoid_cross_entropy_with_logits(labels, logits): # The final formulation is: max(x, 0) - x * z + log(1 + exp(-abs(x))) zeros = torch.zeros_like(logits, dtype=logits.dtype) condition = logits >= zeros relu_logits = torch.where(condition, logits, zeros) neg_abs_logits = torch.where(condition, -logits, logits) return relu_logits - logits * labels + torch.log1p(torch.exp(neg_abs_logits)) def lecam_reg(real_pred, fake_pred, ema_real_pred, ema_fake_pred): assert real_pred.ndim == 0 and ema_fake_pred.ndim == 0 lecam_loss = torch.mean(torch.pow(nn.ReLU()(real_pred - ema_fake_pred), 2)) lecam_loss += torch.mean(torch.pow(nn.ReLU()(ema_real_pred - fake_pred), 2)) return lecam_loss def gradient_penalty_fn(images, output): gradients = torch.autograd.grad( outputs=output, inputs=images, grad_outputs=torch.ones(output.size(), device=images.device), create_graph=True, retain_graph=True, only_inputs=True, )[0] gradients = rearrange(gradients, "b ... -> b (...)") return ((gradients.norm(2, dim=1) - 1) ** 2).mean() class VAELoss(nn.Module): def __init__( self, logvar_init=0.0, perceptual_loss_weight=1.0, kl_loss_weight=5e-4, device="cpu", dtype="bf16", ): super().__init__() if type(dtype) == str: if dtype == "bf16": dtype = torch.bfloat16 elif dtype == "fp16": dtype = torch.float16 elif dtype == "fp32": dtype = torch.float32 else: raise NotImplementedError(f"dtype: {dtype}") # KL Loss self.kl_weight = kl_loss_weight # Perceptual Loss self.perceptual_loss_fn = LPIPS().eval().to(device, dtype) self.perceptual_loss_fn.requires_grad_(False) self.perceptual_loss_weight = perceptual_loss_weight self.logvar = nn.Parameter(torch.ones(size=()) * logvar_init) def forward( self, video, recon_video, posterior, ) -> dict: video.size(0) video = rearrange(video, "b c t h w -> (b t) c h w").contiguous() recon_video = rearrange(recon_video, "b c t h w -> (b t) c h w").contiguous() # reconstruction loss recon_loss = l1(video, recon_video) # perceptual loss perceptual_loss = self.perceptual_loss_fn(video, recon_video) # nll loss (from reconstruction loss and perceptual loss) nll_loss = recon_loss + perceptual_loss * self.perceptual_loss_weight nll_loss = nll_loss / torch.exp(self.logvar) + self.logvar # Batch Mean nll_loss = batch_mean(nll_loss) recon_loss = batch_mean(recon_loss) numel_elements = video.numel() // video.size(0) perceptual_loss = batch_mean(perceptual_loss) * numel_elements # KL Loss if posterior is None: kl_loss = torch.tensor(0.0).to(video.device, video.dtype) else: kl_loss = posterior.kl() kl_loss = batch_mean(kl_loss) weighted_kl_loss = kl_loss * self.kl_weight return { "nll_loss": nll_loss, "kl_loss": weighted_kl_loss, "recon_loss": recon_loss, "perceptual_loss": perceptual_loss, } class GeneratorLoss(nn.Module): def __init__(self, gen_start=2001, disc_factor=1.0, disc_weight=0.5): super().__init__() self.disc_factor = disc_factor self.gen_start = gen_start self.disc_weight = disc_weight def calculate_adaptive_weight(self, nll_loss, g_loss, last_layer): nll_grads = torch.autograd.grad(nll_loss, last_layer, retain_graph=True)[0] g_grads = torch.autograd.grad(g_loss, last_layer, retain_graph=True)[0] d_weight = torch.norm(nll_grads) / (torch.norm(g_grads) + 1e-4) d_weight = torch.clamp(d_weight, 0.0, 1e4).detach() d_weight = d_weight * self.disc_weight return d_weight def forward( self, logits_fake, nll_loss, last_layer, global_step, is_training=True, ): g_loss = -torch.mean(logits_fake) if self.disc_factor is not None and self.disc_factor > 0.0: d_weight = self.calculate_adaptive_weight(nll_loss, g_loss, last_layer) else: d_weight = torch.tensor(1.0) disc_factor = adopt_weight(self.disc_factor, global_step, threshold=self.gen_start) weighted_gen_loss = d_weight * disc_factor * g_loss return weighted_gen_loss, g_loss class DiscriminatorLoss(nn.Module): def __init__(self, disc_start=2001, disc_factor=1.0, disc_loss_type="hinge"): super().__init__() assert disc_loss_type in ["hinge", "vanilla", "wgan-gp"] self.disc_factor = disc_factor self.disc_start = disc_start self.disc_loss_type = disc_loss_type if self.disc_loss_type == "hinge": self.loss_fn = hinge_d_loss elif self.disc_loss_type == "vanilla": self.loss_fn = vanilla_d_loss elif self.disc_loss_type == "wgan-gp": self.loss_fn = wgan_gp_loss else: raise ValueError(f"Unknown GAN loss '{self.disc_loss_type}'.") def forward( self, real_logits, fake_logits, global_step, ): if self.disc_factor is not None and self.disc_factor > 0.0: disc_factor = adopt_weight(self.disc_factor, global_step, threshold=self.disc_start) disc_loss = self.loss_fn(real_logits, fake_logits) weighted_discriminator_loss = disc_factor * disc_loss else: weighted_discriminator_loss = 0 return weighted_discriminator_loss ================================================ FILE: opensora/models/vae/lpips.py ================================================ import hashlib import os from collections import namedtuple import requests import torch import torch.nn as nn from torchvision import models from tqdm import tqdm from opensora.acceleration.checkpoint import checkpoint URL_MAP = {"vgg_lpips": "https://heibox.uni-heidelberg.de/f/607503859c864bc1b30b/?dl=1"} CKPT_MAP = {"vgg_lpips": "vgg.pth"} MD5_MAP = {"vgg_lpips": "d507d7349b931f0638a25a48a722f98a"} def md5_hash(path): with open(path, "rb") as f: content = f.read() return hashlib.md5(content).hexdigest() def download(url, local_path, chunk_size=1024): os.makedirs(os.path.split(local_path)[0], exist_ok=True) with requests.get(url, stream=True) as r: total_size = int(r.headers.get("content-length", 0)) with tqdm(total=total_size, unit="B", unit_scale=True) as pbar: with open(local_path, "wb") as f: for data in r.iter_content(chunk_size=chunk_size): if data: f.write(data) pbar.update(chunk_size) def get_ckpt_path(name, root=".", check=False): assert name in URL_MAP path = os.path.join(root, CKPT_MAP[name]) if not os.path.exists(path) or (check and not md5_hash(path) == MD5_MAP[name]): print("Downloading {} model from {} to {}".format(name, URL_MAP[name], path)) download(URL_MAP[name], path) md5 = md5_hash(path) assert md5 == MD5_MAP[name], md5 return path class LPIPS(nn.Module): # Learned perceptual metric def __init__(self, use_dropout=True): super().__init__() self.scaling_layer = ScalingLayer() self.chns = [64, 128, 256, 512, 512] # vg16 features self.net = vgg16(pretrained=True, requires_grad=False) self.lin0 = NetLinLayer(self.chns[0], use_dropout=use_dropout) self.lin1 = NetLinLayer(self.chns[1], use_dropout=use_dropout) self.lin2 = NetLinLayer(self.chns[2], use_dropout=use_dropout) self.lin3 = NetLinLayer(self.chns[3], use_dropout=use_dropout) self.lin4 = NetLinLayer(self.chns[4], use_dropout=use_dropout) self.lins = [self.lin0, self.lin1, self.lin2, self.lin3, self.lin4] self.load_from_pretrained() for param in self.parameters(): param.requires_grad = False def load_from_pretrained(self, name="vgg_lpips"): path = os.path.expanduser("~/.cache/opensora/taming/modules/autoencoder/lpips") ckpt = get_ckpt_path(name, path) self.load_state_dict(torch.load(ckpt, map_location=torch.device("cpu")), strict=False) @classmethod def from_pretrained(cls, name="vgg_lpips"): if name != "vgg_lpips": raise NotImplementedError model = cls() ckpt = get_ckpt_path(name) model.load_state_dict(torch.load(ckpt, map_location=torch.device("cpu")), strict=False) return model def forward_old(self, input, target): in0_input, in1_input = (self.scaling_layer(input), self.scaling_layer(target)) outs0, outs1 = self.net(in0_input), self.net(in1_input) feats0, feats1, diffs = {}, {}, {} lins = [self.lin0, self.lin1, self.lin2, self.lin3, self.lin4] for kk in range(len(self.chns)): feats0[kk], feats1[kk] = normalize_tensor(outs0[kk]), normalize_tensor(outs1[kk]) diffs[kk] = (feats0[kk] - feats1[kk]) ** 2 res = [spatial_average(lins[kk].model(diffs[kk]), keepdim=True) for kk in range(len(self.chns))] val = res[0] for l in range(1, len(self.chns)): val += res[l] return val def get_layer_loss(self, input, target, i): input, target = getattr(self.net, f"slice{i+1}")(input), getattr(self.net, f"slice{i+1}")(target) feats0, feats1 = normalize_tensor(input), normalize_tensor(target) diff = (feats0 - feats1) ** 2 avg = spatial_average(self.lins[i].model(diff), keepdim=True) return avg, input, target def forward(self, input, target): input, target = (self.scaling_layer(input), self.scaling_layer(target)) val = None for i in range(len(self.chns)): avg, input, target = checkpoint(self.get_layer_loss, input, target, i, use_reentrant=False) val = avg if val is None else val + avg return val class ScalingLayer(nn.Module): def __init__(self): super(ScalingLayer, self).__init__() self.register_buffer("shift", torch.Tensor([-0.030, -0.088, -0.188])[None, :, None, None]) self.register_buffer("scale", torch.Tensor([0.458, 0.448, 0.450])[None, :, None, None]) def forward(self, inp): return (inp - self.shift) / self.scale class NetLinLayer(nn.Module): """A single linear layer which does a 1x1 conv""" def __init__(self, chn_in, chn_out=1, use_dropout=False): super(NetLinLayer, self).__init__() layers = ( [ nn.Dropout(), ] if (use_dropout) else [] ) layers += [ nn.Conv2d(chn_in, chn_out, 1, stride=1, padding=0, bias=False), ] self.model = nn.Sequential(*layers) class vgg16(torch.nn.Module): def __init__(self, requires_grad=False, pretrained=True): super(vgg16, self).__init__() vgg_pretrained_features = models.vgg16(pretrained=pretrained).features self.slice1 = torch.nn.Sequential() self.slice2 = torch.nn.Sequential() self.slice3 = torch.nn.Sequential() self.slice4 = torch.nn.Sequential() self.slice5 = torch.nn.Sequential() self.N_slices = 5 for x in range(4): self.slice1.add_module(str(x), vgg_pretrained_features[x]) for x in range(4, 9): self.slice2.add_module(str(x), vgg_pretrained_features[x]) for x in range(9, 16): self.slice3.add_module(str(x), vgg_pretrained_features[x]) for x in range(16, 23): self.slice4.add_module(str(x), vgg_pretrained_features[x]) for x in range(23, 30): self.slice5.add_module(str(x), vgg_pretrained_features[x]) if not requires_grad: for param in self.parameters(): param.requires_grad = False def forward(self, X): h = self.slice1(X) h_relu1_2 = h h = self.slice2(h) h_relu2_2 = h h = self.slice3(h) h_relu3_3 = h h = self.slice4(h) h_relu4_3 = h h = self.slice5(h) h_relu5_3 = h vgg_outputs = namedtuple("VggOutputs", ["relu1_2", "relu2_2", "relu3_3", "relu4_3", "relu5_3"]) out = vgg_outputs(h_relu1_2, h_relu2_2, h_relu3_3, h_relu4_3, h_relu5_3) return out def normalize_tensor(x, eps=1e-10): norm_factor = torch.sqrt(torch.sum(x**2, dim=1, keepdim=True)) return x / (norm_factor + eps) def spatial_average(x, keepdim=True): return x.mean([2, 3], keepdim=keepdim) ================================================ FILE: opensora/models/vae/tensor_parallel.py ================================================ from typing import List, Optional, Union import torch import torch.distributed as dist import torch.nn as nn import torch.nn.functional as F from colossalai.device.device_mesh import DeviceMesh from colossalai.shardformer.layer._operation import ( gather_forward_split_backward, reduce_forward, split_forward_gather_backward, ) from colossalai.shardformer.layer.parallel_module import ParallelModule from colossalai.tensor.d_tensor.api import ( distribute_tensor, is_distributed_tensor, shard_rowwise, sharded_tensor_to_existing_param, ) from colossalai.tensor.d_tensor.sharding_spec import ShardingSpec from torch.distributed import ProcessGroup from torch.nn.parameter import Parameter from .utils import ChannelChunkConv3d, channel_chunk_conv3d def shard_channelwise( tensor: torch.Tensor, group_or_device_mesh: Union[ProcessGroup, DeviceMesh] = None ) -> torch.Tensor: """ Shard the second dim of the given tensor. Args: tensor (torch.Tensor): The tensor to be sharded. group_or_device_mesh (Union[ProcessGroup, DeviceMesh], optional): The group or device mesh to shard the tensor. If None, the tensor will be sharded with respect to the global process group. Defaults to None. inplace (bool, optional): Whether to shard the tensor in-place. Defaults to False. Returns: torch.Tensor: The sharded tensor. """ # if the group_or_device_mesh is None, we shard the tensor with respect to the global process group if group_or_device_mesh is None: group_or_device_mesh = dist.GroupMember.WORLD if isinstance(group_or_device_mesh, ProcessGroup): device_mesh = DeviceMesh.from_process_group(group_or_device_mesh) else: assert len(group_or_device_mesh.shape) == 1, "Only 1D DeviceMesh is accepted for row-wise sharding." device_mesh = group_or_device_mesh sharding_spec = ShardingSpec(dim_size=tensor.dim(), dim_partition_dict={1: [0]}) return distribute_tensor(tensor, device_mesh, sharding_spec) class Conv3dTPCol(nn.Conv3d): """Conv3d with column-wise tensor parallelism. This is only for inference.""" def __init__( self, in_channels: int, out_channels: int, kernel_size: int, stride: int = 1, padding: int = 0, dilation: int = 1, groups: int = 1, bias: bool = True, padding_mode: str = "zeros", device=None, dtype=None, tp_group=None, gather_output: bool = False, weight: Optional[Parameter] = None, bias_: Optional[Parameter] = None, ) -> None: super().__init__( in_channels, out_channels, kernel_size, stride, padding, dilation, groups, bias, padding_mode, device, dtype ) self.tp_group = tp_group self.gather_output = gather_output self.tp_size = dist.get_world_size(tp_group) self.tp_rank = dist.get_rank(tp_group) # sanity check if weight is not None: assert not bias or bias_ is not None, "bias_ must be provided if bias is True when weight is not None" else: assert bias_ is None, "bias_ must be None if weight is None" # Parameters. if weight is None: assert weight is not None, "weight must be provided" else: weight.data = weight.data.to(device=device, dtype=dtype) self.weight = weight if not is_distributed_tensor(self.weight): sharded_weight = shard_rowwise(self.weight.data, self.tp_group) sharded_tensor_to_existing_param(sharded_weight, self.weight) if bias: if bias_ is None: assert bias is not None, "bias must be provided" else: bias_.data = bias_.data.to(device=device, dtype=dtype) self.bias = bias_ if not is_distributed_tensor(self.bias): sharded_bias = shard_rowwise(self.bias.data, self.tp_group) sharded_tensor_to_existing_param(sharded_bias, self.bias) else: self.bias = None @staticmethod def from_native_module( module: nn.Conv3d, process_group: Union[ProcessGroup, List[ProcessGroup]], **kwargs ) -> ParallelModule: r""" Convert a native PyTorch conv3d layer to a tensor parallelized layer. """ # ensure only one process group is passed if isinstance(process_group, (list, tuple)): assert len(process_group) == 1, f"Expected only one process group, got {len(process_group)}." process_group = process_group[0] conv3d_tp = Conv3dTPCol( in_channels=module.in_channels, out_channels=module.out_channels, kernel_size=module.kernel_size, stride=module.stride, padding=module.padding, dilation=module.dilation, groups=module.groups, bias=module.bias is not None, padding_mode=module.padding_mode, device=module.weight.device, dtype=module.weight.dtype, tp_group=process_group, weight=module.weight, bias_=module.bias, **kwargs, ) return conv3d_tp def forward(self, input: torch.Tensor) -> torch.Tensor: weight = self.weight bias = None if self.bias is not None: bias = self.bias out = channel_chunk_conv3d( input, weight, bias, self.stride, self.padding, self.dilation, self.groups, ChannelChunkConv3d.CONV3D_NUMEL_LIMIT, ) if not self.gather_output: return out gathered_out = gather_forward_split_backward(out, 1, self.tp_group) return gathered_out class Conv3dTPRow(nn.Conv3d): """Conv3d with row-wise tensor parallelism. This is only for inference.""" def __init__( self, in_channels: int, out_channels: int, kernel_size: int, stride: int = 1, padding: int = 0, dilation: int = 1, groups: int = 1, bias: bool = True, padding_mode: str = "zeros", device=None, dtype=None, tp_group=None, split_input: bool = False, split_output: bool = False, weight: Optional[Parameter] = None, bias_: Optional[Parameter] = None, ) -> None: super().__init__( in_channels, out_channels, kernel_size, stride, padding, dilation, groups, bias, padding_mode, device, dtype ) self.tp_group = tp_group self.split_input = split_input self.split_output = split_output self.tp_size = dist.get_world_size(tp_group) self.tp_rank = dist.get_rank(tp_group) # sanity check if weight is not None: assert not bias or bias_ is not None, "bias_ must be provided if bias is True when weight is not None" else: assert bias_ is None, "bias_ must be None if weight is None" # Parameters. if weight is None: assert weight is not None, "weight must be provided" else: weight.data = weight.data.to(device=device, dtype=dtype) self.weight = weight if not is_distributed_tensor(self.weight): sharded_weight = shard_channelwise(self.weight.data, self.tp_group) sharded_tensor_to_existing_param(sharded_weight, self.weight) if bias: if bias_ is None: assert bias is not None, "bias must be provided" else: bias_.data = bias_.data.to(device=device, dtype=dtype) self.bias = bias_ else: self.bias = None @staticmethod def from_native_module( module: nn.Conv3d, process_group: Union[ProcessGroup, List[ProcessGroup]], **kwargs ) -> ParallelModule: r""" Convert a native PyTorch conv3d layer to a tensor parallelized layer. """ conv3d_tp = Conv3dTPRow( in_channels=module.in_channels, out_channels=module.out_channels, kernel_size=module.kernel_size, stride=module.stride, padding=module.padding, dilation=module.dilation, groups=module.groups, bias=module.bias is not None, padding_mode=module.padding_mode, device=module.weight.device, dtype=module.weight.dtype, tp_group=process_group, weight=module.weight, bias_=module.bias, **kwargs, ) return conv3d_tp def forward(self, input: torch.Tensor) -> torch.Tensor: if self.split_input: input = split_forward_gather_backward(input, 1, self.tp_group) weight = self.weight out = channel_chunk_conv3d( input, weight, None, self.stride, self.padding, self.dilation, self.groups, ChannelChunkConv3d.CONV3D_NUMEL_LIMIT, ) # del input out = reduce_forward(out, self.tp_group) if self.bias is not None: out = out + self.bias[:, None, None, None] if self.split_output: out = split_forward_gather_backward(out, 1, self.tp_group) return out class Conv2dTPRow(nn.Conv2d): """Conv2d with row-wise tensor parallelism. This is only for inference.""" def __init__( self, in_channels: int, out_channels: int, kernel_size: int, stride: int = 1, padding: int = 0, dilation: int = 1, groups: int = 1, bias: bool = True, padding_mode: str = "zeros", device=None, dtype=None, tp_group=None, split_input: bool = False, split_output: bool = False, weight: Optional[Parameter] = None, bias_: Optional[Parameter] = None, ) -> None: super().__init__( in_channels, out_channels, kernel_size, stride, padding, dilation, groups, bias, padding_mode, device, dtype ) self.tp_group = tp_group self.split_input = split_input self.split_output = split_output self.tp_size = dist.get_world_size(tp_group) self.tp_rank = dist.get_rank(tp_group) # sanity check if weight is not None: assert not bias or bias_ is not None, "bias_ must be provided if bias is True when weight is not None" else: assert bias_ is None, "bias_ must be None if weight is None" # Parameters. if weight is None: assert weight is not None, "weight must be provided" else: weight.data = weight.data.to(device=device, dtype=dtype) self.weight = weight if not is_distributed_tensor(self.weight): sharded_weight = shard_channelwise(self.weight.data, self.tp_group) sharded_tensor_to_existing_param(sharded_weight, self.weight) if bias: if bias_ is None: assert bias is not None, "bias must be provided" else: bias_.data = bias_.data.to(device=device, dtype=dtype) self.bias = bias_ else: self.bias = None def forward(self, input: torch.Tensor) -> torch.Tensor: if self.split_input: input = split_forward_gather_backward(input, 1, self.tp_group) weight = self.weight out = F.conv2d( input, weight, None, self.stride, self.padding, self.dilation, self.groups, ) # del input dist.all_reduce(out, group=self.tp_group) if self.bias is not None: out += self.bias[:, None, None] if self.split_output: out = split_forward_gather_backward(out, 1, self.tp_group) return out @staticmethod def from_native_module( module: nn.Conv2d, process_group: Union[ProcessGroup, List[ProcessGroup]], **kwargs ) -> ParallelModule: r""" Convert a native PyTorch conv2d layer to a tensor parallelized layer. """ conv2d_tp = Conv2dTPRow( in_channels=module.in_channels, out_channels=module.out_channels, kernel_size=module.kernel_size, stride=module.stride, padding=module.padding, dilation=module.dilation, groups=module.groups, bias=module.bias is not None, padding_mode=module.padding_mode, device=module.weight.device, dtype=module.weight.dtype, tp_group=process_group, weight=module.weight, bias_=module.bias, **kwargs, ) conv2d_tp.weight = module.weight conv2d_tp.bias = module.bias return conv2d_tp class Conv1dTPRow(nn.Conv1d): """Conv1d with row-wise tensor parallelism. This is only for inference.""" def __init__( self, in_channels: int, out_channels: int, kernel_size: int, stride: int = 1, padding: int = 0, dilation: int = 1, groups: int = 1, bias: bool = True, padding_mode: str = "zeros", device=None, dtype=None, tp_group=None, split_input: bool = False, split_output: bool = False, weight: Optional[Parameter] = None, bias_: Optional[Parameter] = None, ) -> None: super().__init__( in_channels, out_channels, kernel_size, stride, padding, dilation, groups, bias, padding_mode, device, dtype ) self.tp_group = tp_group self.split_input = split_input self.split_output = split_output self.tp_size = dist.get_world_size(tp_group) self.tp_rank = dist.get_rank(tp_group) # sanity check if weight is not None: assert not bias or bias_ is not None, "bias_ must be provided if bias is True when weight is not None" else: assert bias_ is None, "bias_ must be None if weight is None" # Parameters. if weight is None: assert weight is not None, "weight must be provided" else: weight.data = weight.data.to(device=device, dtype=dtype) self.weight = weight if not is_distributed_tensor(self.weight): sharded_weight = shard_channelwise(self.weight.data, self.tp_group) sharded_tensor_to_existing_param(sharded_weight, self.weight) if bias: if bias_ is None: assert bias is not None, "bias must be provided" else: bias_.data = bias_.data.to(device=device, dtype=dtype) self.bias = bias_ else: self.bias = None def forward(self, input: torch.Tensor) -> torch.Tensor: if self.split_input: input = split_forward_gather_backward(input, 1, self.tp_group) weight = self.weight out = F.conv1d( input, weight, None, self.stride, self.padding, self.dilation, self.groups, ) # del input dist.all_reduce(out, group=self.tp_group) if self.bias is not None: out += self.bias[:, None] if self.split_output: out = split_forward_gather_backward(out, 1, self.tp_group) return out @staticmethod def from_native_module( module: nn.Conv1d, process_group: Union[ProcessGroup, List[ProcessGroup]], **kwargs ) -> ParallelModule: r""" Convert a native PyTorch conv1d layer to a tensor parallelized layer. """ conv1d_tp = Conv1dTPRow( in_channels=module.in_channels, out_channels=module.out_channels, kernel_size=module.kernel_size, stride=module.stride, padding=module.padding, dilation=module.dilation, groups=module.groups, bias=module.bias is not None, padding_mode=module.padding_mode, device=module.weight.device, dtype=module.weight.dtype, tp_group=process_group, weight=module.weight, bias_=module.bias, **kwargs, ) conv1d_tp.weight = module.weight conv1d_tp.bias = module.bias return conv1d_tp class GroupNormTP(nn.GroupNorm): def __init__( self, num_groups: int, num_channels: int, eps: float = 0.00001, affine: bool = True, device=None, dtype=None, tp_group=None, weight: Optional[Parameter] = None, bias: Optional[Parameter] = None, ) -> None: super().__init__(num_groups, num_channels, eps, affine, device, dtype) self.tp_group = tp_group self.tp_size = dist.get_world_size(tp_group) self.tp_rank = dist.get_rank(tp_group) if affine: assert weight is not None, "weight must be provided" weight.data = weight.data.to(device=device, dtype=dtype) self.weight = weight if not is_distributed_tensor(self.weight): sharded_weight = shard_rowwise(self.weight.data, self.tp_group) sharded_tensor_to_existing_param(sharded_weight, self.weight) assert bias is not None, "bias must be provided" bias.data = bias.data.to(device=device, dtype=dtype) self.bias = bias if not is_distributed_tensor(self.bias): sharded_bias = shard_rowwise(self.bias.data, self.tp_group) sharded_tensor_to_existing_param(sharded_bias, self.bias) else: self.weight = None self.bias = None def forward(self, input: torch.Tensor) -> torch.Tensor: return F.group_norm( input, self.num_groups // self.tp_size, self.weight, self.bias, self.eps, ) @staticmethod def from_native_module( module: nn.GroupNorm, process_group: Union[ProcessGroup, List[ProcessGroup]], **kwargs ) -> ParallelModule: r""" Convert a native PyTorch nn.GroupNorm layer to a tensor parallelized layer. """ group_norm_tp = GroupNormTP( num_groups=module.num_groups, num_channels=module.num_channels, eps=module.eps, affine=module.affine, device=module.weight.device, dtype=module.weight.dtype, tp_group=process_group, weight=module.weight, bias=module.bias, **kwargs, ) return group_norm_tp ================================================ FILE: opensora/models/vae/utils.py ================================================ import math import numpy as np import torch import torch.nn.functional as F from torch import Tensor, nn NUMEL_LIMIT = 2**30 def ceil_to_divisible(n: int, dividend: int) -> int: return math.ceil(dividend / (dividend // n)) def chunked_avg_pool1d(input, kernel_size, stride=None, padding=0, ceil_mode=False, count_include_pad=True): n_chunks = math.ceil(input.numel() / NUMEL_LIMIT) if n_chunks == 1: return F.avg_pool1d(input, kernel_size, stride, padding, ceil_mode, count_include_pad) else: l_in = input.shape[-1] l_out = math.floor((l_in + 2 * padding - kernel_size) / stride + 1) output_shape = list(input.shape) output_shape[-1] = l_out out_list = [] for inp_chunk in input.chunk(n_chunks, dim=0): out_chunk = F.avg_pool1d(inp_chunk, kernel_size, stride, padding, ceil_mode, count_include_pad) out_list.append(out_chunk) return torch.cat(out_list, dim=0) def chunked_interpolate(input, scale_factor): output_shape = list(input.shape) output_shape = output_shape[:2] + [int(i * scale_factor) for i in output_shape[2:]] n_chunks = math.ceil(torch.Size(output_shape).numel() / NUMEL_LIMIT) if n_chunks == 1: return F.interpolate(input, scale_factor=scale_factor) else: out_list = [] n_chunks += 1 for inp_chunk in input.chunk(n_chunks, dim=1): out_chunk = F.interpolate(inp_chunk, scale_factor=scale_factor) out_list.append(out_chunk) return torch.cat(out_list, dim=1) def get_conv3d_output_shape( input_shape: torch.Size, out_channels: int, kernel_size: list, stride: list, padding: int, dilation: list ) -> list: output_shape = [out_channels] if len(input_shape) == 5: output_shape.insert(0, input_shape[0]) for i, d in enumerate(input_shape[-3:]): d_out = math.floor((d + 2 * padding[i] - dilation[i] * (kernel_size[i] - 1) - 1) / stride[i] + 1) output_shape.append(d_out) return output_shape def get_conv3d_n_chunks(numel: int, n_channels: int, numel_limit: int): n_chunks = math.ceil(numel / numel_limit) n_chunks = ceil_to_divisible(n_chunks, n_channels) return n_chunks def channel_chunk_conv3d( input: torch.Tensor, weight: torch.Tensor, bias: torch.Tensor, stride: list, padding: list, dilation: list, groups: int, numel_limit: int, ): out_channels, in_channels = weight.shape[:2] kernel_size = weight.shape[2:] output_shape = get_conv3d_output_shape(input.shape, out_channels, kernel_size, stride, padding, dilation) n_in_chunks = get_conv3d_n_chunks(input.numel(), in_channels, numel_limit) n_out_chunks = get_conv3d_n_chunks( np.prod(output_shape), out_channels, numel_limit, ) if n_in_chunks == 1 and n_out_chunks == 1: return F.conv3d(input, weight, bias, stride, padding, dilation, groups) # output = torch.empty(output_shape, device=input.device, dtype=input.dtype) # outputs = output.chunk(n_out_chunks, dim=1) input_shards = input.chunk(n_in_chunks, dim=1) weight_chunks = weight.chunk(n_out_chunks) output_list = [] if bias is not None: bias_chunks = bias.chunk(n_out_chunks) else: bias_chunks = [None] * n_out_chunks for weight_, bias_ in zip(weight_chunks, bias_chunks): weight_shards = weight_.chunk(n_in_chunks, dim=1) o = None for x, w in zip(input_shards, weight_shards): if o is None: o = F.conv3d(x, w, None, stride, padding, dilation, groups).float() else: o += F.conv3d(x, w, None, stride, padding, dilation, groups).float() o = o.to(input.dtype) if bias_ is not None: o += bias_[None, :, None, None, None] # inplace operation cannot be used during training # output_.copy_(o) output_list.append(o) return torch.cat(output_list, dim=1) class DiagonalGaussianDistribution(object): def __init__( self, parameters, deterministic=False, ): """Stripped version of https://github.com/richzhang/PerceptualSimilarity/tree/master/models""" self.parameters = parameters self.mean, self.logvar = torch.chunk(parameters, 2, dim=1) self.logvar = torch.clamp(self.logvar, -30.0, 20.0) self.deterministic = deterministic self.std = torch.exp(0.5 * self.logvar) self.var = torch.exp(self.logvar) if self.deterministic: self.var = self.std = torch.zeros_like(self.mean).to(device=self.parameters.device, dtype=self.mean.dtype) def sample(self): # torch.randn: standard normal distribution x = self.mean + self.std * torch.randn(self.mean.shape).to(device=self.parameters.device, dtype=self.mean.dtype) return x def kl(self, other=None): if self.deterministic: return torch.Tensor([0.0]) else: if other is None: # SCH: assumes other is a standard normal distribution return 0.5 * torch.sum(torch.pow(self.mean, 2) + self.var - 1.0 - self.logvar, dim=[1, 3, 4]).flatten(0) else: return 0.5 * torch.sum( torch.pow(self.mean - other.mean, 2) / other.var + self.var / other.var - 1.0 - self.logvar + other.logvar, dim=[1, 3, 4], ).flatten(0) def mode(self): return self.mean class ChannelChunkConv3d(nn.Conv3d): CONV3D_NUMEL_LIMIT = 2**31 def _get_output_numel(self, input_shape: torch.Size) -> int: numel = self.out_channels if len(input_shape) == 5: numel *= input_shape[0] for i, d in enumerate(input_shape[-3:]): d_out = math.floor( (d + 2 * self.padding[i] - self.dilation[i] * (self.kernel_size[i] - 1) - 1) / self.stride[i] + 1 ) numel *= d_out return numel def _get_n_chunks(self, numel: int, n_channels: int): n_chunks = math.ceil(numel / ChannelChunkConv3d.CONV3D_NUMEL_LIMIT) n_chunks = ceil_to_divisible(n_chunks, n_channels) return n_chunks def forward(self, input: Tensor) -> Tensor: if input.numel() // input.size(0) < ChannelChunkConv3d.CONV3D_NUMEL_LIMIT: return super().forward(input) n_in_chunks = self._get_n_chunks(input.numel(), self.in_channels) n_out_chunks = self._get_n_chunks(self._get_output_numel(input.shape), self.out_channels) if n_in_chunks == 1 and n_out_chunks == 1: return super().forward(input) outputs = [] input_shards = input.chunk(n_in_chunks, dim=1) for weight, bias in zip(self.weight.chunk(n_out_chunks), self.bias.chunk(n_out_chunks)): weight_shards = weight.chunk(n_in_chunks, dim=1) o = None for x, w in zip(input_shards, weight_shards): if o is None: o = F.conv3d(x, w, bias, self.stride, self.padding, self.dilation, self.groups) else: o += F.conv3d(x, w, None, self.stride, self.padding, self.dilation, self.groups) outputs.append(o) return torch.cat(outputs, dim=1) @torch.compile(mode="max-autotune-no-cudagraphs", dynamic=True) def pad_for_conv3d(x: torch.Tensor, width_pad: int, height_pad: int, time_pad: int) -> torch.Tensor: if width_pad > 0 or height_pad > 0: x = F.pad(x, (width_pad, width_pad, height_pad, height_pad), mode="constant", value=0) if time_pad > 0: x = F.pad(x, (0, 0, 0, 0, time_pad, time_pad), mode="replicate") return x def pad_for_conv3d_kernel_3x3x3(x: torch.Tensor) -> torch.Tensor: n_chunks = math.ceil(x.numel() / NUMEL_LIMIT) if n_chunks == 1: x = F.pad(x, (1, 1, 1, 1), mode="constant", value=0) x = F.pad(x, (0, 0, 0, 0, 1, 1), mode="replicate") else: out_list = [] n_chunks += 1 for inp_chunk in x.chunk(n_chunks, dim=1): out_chunk = F.pad(inp_chunk, (1, 1, 1, 1), mode="constant", value=0) out_chunk = F.pad(out_chunk, (0, 0, 0, 0, 1, 1), mode="replicate") out_list.append(out_chunk) x = torch.cat(out_list, dim=1) return x class PadConv3D(nn.Module): """ pad the first frame in temporal dimension """ def __init__(self, in_channels: int, out_channels: int, kernel_size: int = 3): super().__init__() if isinstance(kernel_size, int): kernel_size = (kernel_size,) * 3 self.kernel_size = kernel_size # == specific padding == time_kernel_size, height_kernel_size, width_kernel_size = kernel_size assert time_kernel_size == height_kernel_size == width_kernel_size, "only support cubic kernel size" if time_kernel_size == 3: self.pad = pad_for_conv3d_kernel_3x3x3 else: assert time_kernel_size == 1, f"only support kernel size 1/3 for now, got {kernel_size}" self.pad = lambda x: x self.conv = nn.Conv3d( in_channels, out_channels, kernel_size=kernel_size, stride=1, padding=0, ) def forward(self, x: Tensor) -> Tensor: x = self.pad(x) x = self.conv(x) return x @torch.compile(mode="max-autotune-no-cudagraphs", dynamic=True) class ChannelChunkPadConv3D(PadConv3D): def __init__(self, in_channels: int, out_channels: int, kernel_size: int = 3): super().__init__(in_channels, out_channels, kernel_size) self.conv = ChannelChunkConv3d(in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1) ================================================ FILE: opensora/registry.py ================================================ from copy import deepcopy import torch.nn as nn from mmengine.registry import Registry def build_module(module: dict | nn.Module, builder: Registry, **kwargs) -> nn.Module | None: """Build module from config or return the module itself. Args: module (dict | nn.Module): The module to build. builder (Registry): The registry to build module. *args, **kwargs: Arguments passed to build function. Returns: (None | nn.Module): The created model. """ if module is None: return None if isinstance(module, dict): cfg = deepcopy(module) for k, v in kwargs.items(): cfg[k] = v return builder.build(cfg) elif isinstance(module, nn.Module): return module elif module is None: return None else: raise TypeError(f"Only support dict and nn.Module, but got {type(module)}.") MODELS = Registry( "model", locations=["opensora.models"], ) DATASETS = Registry( "dataset", locations=["opensora.datasets"], ) ================================================ FILE: opensora/utils/__init__.py ================================================ ================================================ FILE: opensora/utils/cai.py ================================================ import colossalai import torch import torch.distributed as dist from colossalai.booster import Booster from colossalai.cluster import DistCoordinator from opensora.acceleration.parallel_states import ( get_sequence_parallel_group, get_tensor_parallel_group, set_sequence_parallel_group, ) from opensora.models.hunyuan_vae.policy import HunyuanVaePolicy from opensora.models.mmdit.distributed import MMDiTPolicy from opensora.utils.logger import is_distributed from opensora.utils.train import create_colossalai_plugin from .logger import log_message def set_group_size(plugin_config: dict): """ Set the group size for tensor parallelism and sequence parallelism. Args: plugin_config (dict): Plugin configuration. """ tp_size = int(plugin_config.get("tp_size", 1)) sp_size = int(plugin_config.get("sp_size", 1)) if tp_size > 1: assert sp_size == 1 plugin_config["tp_size"] = tp_size = min(tp_size, torch.cuda.device_count()) log_message(f"Using TP with size {tp_size}") if sp_size > 1: assert tp_size == 1 plugin_config["sp_size"] = sp_size = min(sp_size, torch.cuda.device_count()) log_message(f"Using SP with size {sp_size}") def init_inference_environment(): """ Initialize the inference environment. """ if is_distributed(): colossalai.launch_from_torch({}) coordinator = DistCoordinator() enable_sequence_parallelism = coordinator.world_size > 1 if enable_sequence_parallelism: set_sequence_parallel_group(dist.group.WORLD) def get_booster(cfg: dict, ae: bool = False): suffix = "_ae" if ae else "" policy = HunyuanVaePolicy if ae else MMDiTPolicy plugin_type = cfg.get(f"plugin{suffix}", "zero2") plugin_config = cfg.get(f"plugin_config{suffix}", {}) plugin_kwargs = {} booster = None if plugin_type == "hybrid": set_group_size(plugin_config) plugin_kwargs = dict(custom_policy=policy) plugin = create_colossalai_plugin( plugin=plugin_type, dtype=cfg.get("dtype", "bf16"), grad_clip=cfg.get("grad_clip", 0), **plugin_config, **plugin_kwargs, ) booster = Booster(plugin=plugin) return booster def get_is_saving_process(cfg: dict): """ Check if the current process is the one that saves the model. Args: plugin_config (dict): Plugin configuration. Returns: bool: True if the current process is the one that saves the model. """ plugin_type = cfg.get("plugin", "zero2") plugin_config = cfg.get("plugin_config", {}) is_saving_process = ( plugin_type != "hybrid" or (plugin_config["tp_size"] > 1 and dist.get_rank(get_tensor_parallel_group()) == 0) or (plugin_config["sp_size"] > 1 and dist.get_rank(get_sequence_parallel_group()) == 0) ) return is_saving_process ================================================ FILE: opensora/utils/ckpt.py ================================================ import functools import json import operator import os import re import shutil from glob import glob from typing import Dict, Optional import torch import torch.distributed as dist import torch.nn as nn from colossalai.booster import Booster from colossalai.checkpoint_io import GeneralCheckpointIO from colossalai.utils.safetensors import save as async_save from colossalai.zero.low_level import LowLevelZeroOptimizer from huggingface_hub import hf_hub_download from safetensors.torch import load_file from tensornvme.async_file_io import AsyncFileWriter from torch.optim import Optimizer from torch.optim.lr_scheduler import _LRScheduler from opensora.acceleration.parallel_states import get_data_parallel_group from .logger import log_message hf_endpoint = os.environ.get("HF_ENDPOINT") if hf_endpoint is None: hf_endpoint = "https://huggingface.co" os.environ["TENSORNVME_DEBUG"] = "1" def load_from_hf_hub(repo_path: str, cache_dir: str = None) -> str: """ Loads a checkpoint from the Hugging Face Hub. Args: repo_path (str): The path to the checkpoint on the Hugging Face Hub. cache_dir (str): The directory to cache the downloaded checkpoint. Returns: str: The path to the downloaded checkpoint. """ repo_id = "/".join(repo_path.split("/")[:-1]) repo_file = repo_path.split("/")[-1] ckpt_path = hf_hub_download(repo_id=repo_id, filename=repo_file, cache_dir=cache_dir) return ckpt_path def load_from_sharded_state_dict(model: nn.Module, ckpt_path: str, model_name: str = "model", strict=False): """ Loads a model from a sharded checkpoint. Args: model (nn.Module): The model to load the checkpoint into. ckpt_path (str): The path to the checkpoint. model_name (str): The name of the model in the checkpoint. strict (bool): Whether to strictly enforce that the keys in the checkpoint match the keys in the model. """ ckpt_io = GeneralCheckpointIO() ckpt_io.load_model(model, os.path.join(ckpt_path, model_name), strict=strict) def print_load_warning(missing: list[str], unexpected: list[str]) -> None: """ Prints a warning if there are missing or unexpected keys when loading a model. Args: missing (list[str]): The missing keys. unexpected (list[str]): The unexpected keys. """ if len(missing) > 0 and len(unexpected) > 0: log_message(f"Got {len(missing)} missing keys:\n\t" + "\n\t".join(missing)) log_message("\n" + "-" * 79 + "\n") log_message(f"Got {len(unexpected)} unexpected keys:\n\t" + "\n\t".join(unexpected)) elif len(missing) > 0: log_message(f"Got {len(missing)} missing keys:\n\t" + "\n\t".join(missing)) elif len(unexpected) > 0: log_message(f"Got {len(unexpected)} unexpected keys:\n\t" + "\n\t".join(unexpected)) else: log_message("Model loaded successfully") def load_checkpoint( model: nn.Module, path: str, cache_dir: str = None, device_map: torch.device | str = "cpu", cai_model_name: str = "model", strict: bool = False, 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 ) -> nn.Module: """ Loads a checkpoint into model from a path. Support three types of checkpoints: 1. huggingface safetensors 2. local .pt or .pth 3. colossalai sharded checkpoint Args: model (nn.Module): The model to load the checkpoint into. path (str): The path to the checkpoint. cache_dir (str): The directory to cache the downloaded checkpoint. device_map (torch.device | str): The device to map the checkpoint to. cai_model_name (str): The name of the model in the checkpoint. Returns: nn.Module: The model with the loaded checkpoint. """ if not os.path.exists(path): log_message(f"Checkpoint not found at {path}, trying to download from Hugging Face Hub") path = load_from_hf_hub(path, cache_dir) assert os.path.exists(path), f"Could not find checkpoint at {path}" log_message(f"Loading checkpoint from {path}") if path.endswith(".safetensors"): ckpt = load_file(path, device='cpu') if rename_keys is not None: # rename keys in the loaded state_dict with old_key_prefix to with new_key_prefix. renamed_ckpt = {} for old_key, v in ckpt.items(): new_key = old_key for old_key_prefix, new_key_prefix in rename_keys.items(): if old_key_prefix in old_key: new_key = old_key.replace(old_key_prefix, new_key_prefix) print(f"Renamed {old_key} to {new_key} in the loaded state_dict") break renamed_ckpt[new_key] = v ckpt = renamed_ckpt missing, unexpected = model.load_state_dict(ckpt, strict=strict) print_load_warning(missing, unexpected) elif path.endswith(".pt") or path.endswith(".pth"): ckpt = torch.load(path, map_location=device_map) missing, unexpected = model.load_state_dict(ckpt, strict=strict) print_load_warning(missing, unexpected) else: assert os.path.isdir(path), f"Invalid checkpoint path: {path}" load_from_sharded_state_dict(model, path, model_name=cai_model_name, strict=strict) return model def rm_checkpoints( save_dir: str, keep_n_latest: int = 0, ): """ Remove old checkpoints. Args: save_dir (str): The directory to save the checkpoints. keep_n_latest (int): The number of latest checkpoints to keep. """ if keep_n_latest <= 0 or dist.get_rank() != 0: return files = glob(os.path.join(save_dir, "epoch*-global_step*")) files = sorted( files, key=lambda s: tuple(map(int, re.search(r"epoch(\d+)-global_step(\d+)", s).groups())), reverse=True ) to_remove = files[keep_n_latest:] for f in to_remove: # shutil.rmtree(f) for item in glob(os.path.join(f, "*")): if os.path.isdir(item): dir_name = os.path.basename(item) if dir_name != "eval": shutil.rmtree(item) else: os.remove(item) def model_sharding(model: torch.nn.Module, device: torch.device = None): """ Sharding the model parameters across multiple GPUs. Args: model (torch.nn.Module): The model to shard. device (torch.device): The device to shard the model to. """ global_rank = dist.get_rank() world_size = dist.get_world_size() for _, param in model.named_parameters(): if device is None: device = param.device padding_size = (world_size - param.numel() % world_size) % world_size if padding_size > 0: padding_param = torch.nn.functional.pad(param.data.view(-1), [0, padding_size]) else: padding_param = param.data.view(-1) splited_params = padding_param.split(padding_param.numel() // world_size) splited_params = splited_params[global_rank] param.data = splited_params.to(device) def model_gathering(model: torch.nn.Module, model_shape_dict: dict, pinned_state_dict: dict) -> None: """ Gather the model parameters from multiple GPUs. Args: model (torch.nn.Module): The model to gather. model_shape_dict (dict): The shape of the model parameters. device (torch.device): The device to gather the model to. """ global_rank = dist.get_rank() global_size = dist.get_world_size() params = set() for name, param in model.named_parameters(): params.add(name) all_params = [torch.empty_like(param.data) for _ in range(global_size)] dist.all_gather(all_params, param.data, group=dist.group.WORLD) if int(global_rank) == 0: all_params = torch.cat(all_params) gathered_param = remove_padding(all_params, model_shape_dict[name]).view(model_shape_dict[name]) pinned_state_dict[name].copy_(gathered_param) if int(global_rank) == 0: for k, v in model.state_dict(keep_vars=True).items(): if k not in params: pinned_state_dict[k].copy_(v) dist.barrier() def remove_padding(tensor: torch.Tensor, original_shape: tuple) -> torch.Tensor: """ Remove padding from a tensor. Args: tensor (torch.Tensor): The tensor to remove padding from. original_shape (tuple): The original shape of the tensor. """ return tensor[: functools.reduce(operator.mul, original_shape)] def record_model_param_shape(model: torch.nn.Module) -> dict: """ Record the shape of the model parameters. Args: model (torch.nn.Module): The model to record the parameter shape of. Returns: dict: The shape of the model parameters. """ param_shape = {} for name, param in model.named_parameters(): param_shape[name] = param.shape return param_shape def load_json(file_path: str) -> dict: """ Load a JSON file. Args: file_path (str): The path to the JSON file. Returns: dict: The loaded JSON file. """ with open(file_path, "r", encoding="utf-8") as f: return json.load(f) def save_json(data, file_path: str): """ Save a dictionary to a JSON file. Args: data: The dictionary to save. file_path (str): The path to save the JSON file. """ with open(file_path, "w", encoding="utf-8") as f: json.dump(data, f, indent=4) def _prepare_ema_pinned_state_dict(model: nn.Module, ema_shape_dict: dict): ema_pinned_state_dict = dict() for name, p in model.named_parameters(): ema_pinned_state_dict[name] = torch.empty(ema_shape_dict[name], pin_memory=True, device="cpu", dtype=p.dtype) sd = model.state_dict(keep_vars=True) # handle buffers for k, v in sd.items(): if k not in ema_pinned_state_dict: ema_pinned_state_dict[k] = torch.empty(v.shape, pin_memory=True, device="cpu", dtype=v.dtype) return ema_pinned_state_dict def _search_valid_path(path: str) -> str: if os.path.exists(f"{path}.safetensors"): return f"{path}.safetensors" elif os.path.exists(f"{path}.pt"): return f"{path}.pt" return path def master_weights_gathering(model: torch.nn.Module, optimizer: LowLevelZeroOptimizer, pinned_state_dict: dict) -> None: """ Gather the model parameters from multiple GPUs. Args: model (torch.nn.Module): The model to gather. model_shape_dict (dict): The shape of the model parameters. device (torch.device): The device to gather the model to. """ w2m = optimizer.get_working_to_master_map() for name, param in model.named_parameters(): master_p = w2m[id(param)] zero_pg = optimizer.param_to_pg[param] world_size = dist.get_world_size(zero_pg) all_params = [torch.empty_like(master_p) for _ in range(world_size)] dist.all_gather(all_params, master_p, group=zero_pg) if dist.get_rank() == 0: all_params = torch.cat(all_params) gathered_param = remove_padding(all_params, param.shape).view(param.shape) pinned_state_dict[name].copy_(gathered_param) dist.barrier() def load_master_weights(model: torch.nn.Module, optimizer: LowLevelZeroOptimizer, state_dict: dict) -> None: pg = get_data_parallel_group(get_mixed_dp_pg=True) world_size = dist.get_world_size(pg) rank = dist.get_rank(pg) w2m = optimizer.get_working_to_master_map() for name, param in model.named_parameters(): master_p = w2m[id(param)] state = state_dict[name].view(-1) padding_size = len(master_p) * world_size - len(state) state = torch.nn.functional.pad(state, [0, padding_size]) target_chunk = state.chunk(world_size)[rank].to(master_p.dtype) master_p[: len(target_chunk)].copy_(target_chunk) class CheckpointIO: def __init__(self, n_write_entries: int = 32): self.n_write_entries = n_write_entries self.writer: Optional[AsyncFileWriter] = None self.pinned_state_dict: Optional[Dict[str, torch.Tensor]] = None self.master_pinned_state_dict: Optional[Dict[str, torch.Tensor]] = None self.master_writer: Optional[AsyncFileWriter] = None def _sync_io(self): if self.writer is not None: self.writer.synchronize() self.writer = None if self.master_writer is not None: self.master_writer.synchronize() self.master_writer = None def __del__(self): self._sync_io() def _prepare_pinned_state_dict(self, ema: nn.Module, ema_shape_dict: dict): if self.pinned_state_dict is None and dist.get_rank() == 0: self.pinned_state_dict = _prepare_ema_pinned_state_dict(ema, ema_shape_dict) def _prepare_master_pinned_state_dict(self, model: nn.Module, optimizer: LowLevelZeroOptimizer): if self.master_pinned_state_dict is None and dist.get_rank() == 0: sd = {} w2m = optimizer.get_working_to_master_map() for n, p in model.named_parameters(): master_p = w2m[id(p)] sd[n] = torch.empty(p.shape, dtype=master_p.dtype, pin_memory=True, device="cpu") self.master_pinned_state_dict = sd def save( self, booster: Booster, save_dir: str, model: nn.Module = None, ema: nn.Module = None, optimizer: Optimizer = None, lr_scheduler: _LRScheduler = None, sampler=None, epoch: int = None, step: int = None, global_step: int = None, batch_size: int = None, lora: bool = False, actual_update_step: int = None, ema_shape_dict: dict = None, async_io: bool = True, include_master_weights: bool = False, ) -> str: """ Save a checkpoint. Args: booster (Booster): The Booster object. save_dir (str): The directory to save the checkpoint to. model (nn.Module): The model to save the checkpoint from. ema (nn.Module): The EMA model to save the checkpoint from. optimizer (Optimizer): The optimizer to save the checkpoint from. lr_scheduler (_LRScheduler): The learning rate scheduler to save the checkpoint from. sampler: The sampler to save the checkpoint from. epoch (int): The epoch of the checkpoint. step (int): The step of the checkpoint. global_step (int): The global step of the checkpoint. batch_size (int): The batch size of the checkpoint. lora (bool): Whether the model is trained with LoRA. Returns: str: The path to the saved checkpoint """ self._sync_io() save_dir = os.path.join(save_dir, f"epoch{epoch}-global_step{actual_update_step}") os.environ["TENSORNVME_DEBUG_LOG"] = os.path.join(save_dir, "async_file_io.log") if model is not None: if not lora: os.makedirs(os.path.join(save_dir, "model"), exist_ok=True) booster.save_model( model, os.path.join(save_dir, "model"), shard=True, use_safetensors=True, size_per_shard=4096, use_async=async_io, ) else: os.makedirs(os.path.join(save_dir, "lora"), exist_ok=True) booster.save_lora_as_pretrained(model, os.path.join(save_dir, "lora")) if optimizer is not None: booster.save_optimizer( optimizer, os.path.join(save_dir, "optimizer"), shard=True, size_per_shard=4096, use_async=async_io ) if include_master_weights: self._prepare_master_pinned_state_dict(model, optimizer) master_weights_gathering(model, optimizer, self.master_pinned_state_dict) if lr_scheduler is not None: booster.save_lr_scheduler(lr_scheduler, os.path.join(save_dir, "lr_scheduler")) if ema is not None: self._prepare_pinned_state_dict(ema, ema_shape_dict) model_gathering(ema, ema_shape_dict, self.pinned_state_dict) if dist.get_rank() == 0: running_states = { "epoch": epoch, "step": step, "global_step": global_step, "batch_size": batch_size, "actual_update_step": actual_update_step, } save_json(running_states, os.path.join(save_dir, "running_states.json")) if ema is not None: if async_io: self.writer = async_save(os.path.join(save_dir, "ema.safetensors"), self.pinned_state_dict) else: torch.save(ema.state_dict(), os.path.join(save_dir, "ema.pt")) if sampler is not None: # only for VariableVideoBatchSampler torch.save(sampler.state_dict(step), os.path.join(save_dir, "sampler")) if optimizer is not None and include_master_weights: self.master_writer = async_save( os.path.join(save_dir, "master.safetensors"), self.master_pinned_state_dict ) dist.barrier() return save_dir def load( self, booster: Booster, load_dir: str, model: nn.Module = None, ema: nn.Module = None, optimizer: Optimizer = None, lr_scheduler: _LRScheduler = None, sampler=None, strict: bool = False, include_master_weights: bool = False, ) -> tuple[int, int]: """ Load a checkpoint. Args: booster (Booster): The Booster object. load_dir (str): The directory to load the checkpoint from. model (nn.Module): The model to load the checkpoint into. ema (nn.Module): The EMA model to load the checkpoint into. optimizer (Optimizer): The optimizer to load the checkpoint into. lr_scheduler (_LRScheduler): The learning rate scheduler to load the checkpoint into. sampler: The sampler to load the checkpoint into. Returns: tuple[int, int]: The epoch and step of the checkpoint. """ assert os.path.exists(load_dir), f"Checkpoint directory {load_dir} does not exist" assert os.path.exists(os.path.join(load_dir, "running_states.json")), "running_states.json does not exist" running_states = load_json(os.path.join(load_dir, "running_states.json")) if model is not None: booster.load_model( model, _search_valid_path(os.path.join(load_dir, "model")), strict=strict, low_cpu_mem_mode=False, num_threads=32, ) if ema is not None: if os.path.exists(os.path.join(load_dir, "ema.safetensors")): ema_state_dict = load_file(os.path.join(load_dir, "ema.safetensors")) else: ema_state_dict = torch.load(os.path.join(load_dir, "ema.pt"), map_location=torch.device("cpu")) # ema is not boosted, so we don't use booster.load_model ema.load_state_dict(ema_state_dict, strict=strict, assign=True) if optimizer is not None: booster.load_optimizer( optimizer, os.path.join(load_dir, "optimizer"), low_cpu_mem_mode=False, num_threads=32 ) if include_master_weights: master_state_dict = load_file(os.path.join(load_dir, "master.safetensors")) load_master_weights(model, optimizer, master_state_dict) if lr_scheduler is not None: booster.load_lr_scheduler(lr_scheduler, os.path.join(load_dir, "lr_scheduler")) if sampler is not None: sampler.load_state_dict(torch.load(os.path.join(load_dir, "sampler"))) dist.barrier() return (running_states["epoch"], running_states["step"]) ================================================ FILE: opensora/utils/config.py ================================================ import argparse import ast import json import os from datetime import datetime import torch from mmengine.config import Config from .logger import is_distributed, is_main_process def parse_args() -> tuple[str, argparse.Namespace]: """ This function parses the command line arguments. Returns: tuple[str, argparse.Namespace]: The path to the configuration file and the command line arguments. """ parser = argparse.ArgumentParser() parser.add_argument("config", type=str, help="model config file path") args, unknown_args = parser.parse_known_args() return args.config, unknown_args def read_config(config_path: str) -> Config: """ This function reads the configuration file. Args: config_path (str): The path to the configuration file. Returns: Config: The configuration object. """ cfg = Config.fromfile(config_path) return cfg def parse_configs() -> Config: """ This function parses the configuration file and command line arguments. Returns: Config: The configuration object. """ config, args = parse_args() cfg = read_config(config) cfg = merge_args(cfg, args) cfg.config_path = config # hard-coded for spatial compression if cfg.get("ae_spatial_compression", None) is not None: os.environ["AE_SPATIAL_COMPRESSION"] = str(cfg.ae_spatial_compression) return cfg def merge_args(cfg: Config, args: argparse.Namespace) -> Config: """ This function merges the configuration file and command line arguments. Args: cfg (Config): The configuration object. args (argparse.Namespace): The command line arguments. Returns: Config: The configuration object. """ for k, v in zip(args[::2], args[1::2]): assert k.startswith("--"), f"Invalid argument: {k}" k = k[2:].replace("-", "_") k_split = k.split(".") target = cfg for key in k_split[:-1]: assert key in cfg, f"Key {key} not found in config" target = target[key] if v.lower() == "none": v = None elif k in target: v_type = type(target[k]) if v_type == bool: v = auto_convert(v) else: v = type(target[k])(v) else: v = auto_convert(v) target[k_split[-1]] = v return cfg def auto_convert(value: str) -> int | float | bool | list | dict | None: """ Automatically convert a string to the appropriate Python data type, including int, float, bool, list, dict, etc. Args: value (str): The string to convert. Returns: int, float, bool, list | dict: The converted value. """ # Handle empty string if value == "": return value # Handle None if value.lower() == "none": return None # Handle boolean values lower_value = value.lower() if lower_value == "true": return True elif lower_value == "false": return False # Try to convert the string to an integer or float try: # Try converting to an integer return int(value) except ValueError: pass try: # Try converting to a float return float(value) except ValueError: pass # Try to convert the string to a list, dict, tuple, etc. try: return ast.literal_eval(value) except (ValueError, SyntaxError): pass # If all attempts fail, return the original string return value def sync_string(value: str): """ This function synchronizes a string across all processes. """ if not is_distributed(): return value bytes_value = value.encode("utf-8") max_len = 256 bytes_tensor = torch.zeros(max_len, dtype=torch.uint8).cuda() bytes_tensor[: len(bytes_value)] = torch.tensor( list(bytes_value), dtype=torch.uint8 ) torch.distributed.broadcast(bytes_tensor, 0) synced_value = bytes_tensor.cpu().numpy().tobytes().decode("utf-8").rstrip("\x00") return synced_value def create_experiment_workspace( output_dir: str, model_name: str = None, config: dict = None, exp_name: str = None ) -> tuple[str, str]: """ This function creates a folder for experiment tracking. Args: output_dir: The path to the output directory. model_name: The name of the model. exp_name: The given name of the experiment, if None will use default. Returns: tuple[str, str]: The experiment name and the experiment directory. """ if exp_name is None: # Make outputs folder (holds all experiment subfolders) experiment_index = datetime.now().strftime("%y%m%d_%H%M%S") experiment_index = sync_string(experiment_index) # Create an experiment folder model_name = ( "-" + model_name.replace("/", "-") if model_name is not None else "" ) exp_name = f"{experiment_index}{model_name}" exp_dir = f"{output_dir}/{exp_name}" if is_main_process(): os.makedirs(exp_dir, exist_ok=True) # Save the config with open(f"{exp_dir}/config.txt", "w", encoding="utf-8") as f: json.dump(config, f, indent=4) return exp_name, exp_dir def config_to_name(cfg: Config) -> str: filename = cfg._filename filename = filename.replace("configs/", "") filename = filename.replace(".py", "") filename = filename.replace("/", "_") return filename def parse_alias(cfg: Config) -> Config: if cfg.get("resolution", None) is not None: cfg.sampling_option.resolution = cfg.resolution if cfg.get("guidance", None) is not None: cfg.sampling_option.guidance = float(cfg.guidance) if cfg.get("guidance_img", None) is not None: cfg.sampling_option.guidance_img = float(cfg.guidance_img) if cfg.get("num_steps", None) is not None: cfg.sampling_option.num_steps = int(cfg.num_steps) if cfg.get("num_frames", None) is not None: cfg.sampling_option.num_frames = int(cfg.num_frames) if cfg.get("aspect_ratio", None) is not None: cfg.sampling_option.aspect_ratio = cfg.aspect_ratio if cfg.get("ckpt_path", None) is not None: cfg.model.from_pretrained = cfg.ckpt_path return cfg ================================================ FILE: opensora/utils/inference.py ================================================ import copy import os import re from enum import Enum import torch from torch import nn from opensora.datasets import save_sample from opensora.datasets.aspect import get_image_size from opensora.datasets.utils import read_from_path, rescale_image_by_path from opensora.utils.logger import log_message from opensora.utils.prompt_refine import refine_prompts class SamplingMethod(Enum): I2V = "i2v" # for open sora video generation DISTILLED = "distill" # for flux image generation def create_tmp_csv(save_dir: str, prompt: str, ref: str = None, create=True) -> str: """ Create a temporary CSV file with the prompt text. Args: save_dir (str): The directory where the CSV file will be saved. prompt (str): The prompt text. Returns: str: The path to the temporary CSV file. """ tmp_file = os.path.join(save_dir, "prompt.csv") if not create: return tmp_file with open(tmp_file, "w", encoding="utf-8") as f: if ref is not None: f.write(f'text,ref\n"{prompt}","{ref}"') else: f.write(f'text\n"{prompt}"') return tmp_file def modify_option_to_t2i(sampling_option, distilled: bool = False, img_resolution: str = "1080px"): """ Modify the sampling option to be used for text-to-image generation. """ sampling_option_t2i = copy.copy(sampling_option) if distilled: sampling_option_t2i.method = SamplingMethod.DISTILLED sampling_option_t2i.num_frames = 1 sampling_option_t2i.height, sampling_option_t2i.width = get_image_size(img_resolution, sampling_option.aspect_ratio) sampling_option_t2i.guidance = 4.0 sampling_option_t2i.resized_resolution = sampling_option.resolution return sampling_option_t2i def get_save_path_name( save_dir, sub_dir, save_prefix="", name=None, fallback_name=None, index=None, num_sample_pos=None, # idx for prompt as path prompt_as_path=False, # save sample with same name as prompt prompt=None, ): """ Get the save path for the generated samples. """ if prompt_as_path: # for vbench cleaned_prompt = prompt.strip(".") fname = f"{cleaned_prompt}-{num_sample_pos}" else: if name is not None: fname = save_prefix + name else: fname = f"{save_prefix + fallback_name}_{index:04d}" if num_sample_pos > 0: fname += f"_{num_sample_pos}" return os.path.join(save_dir, sub_dir, fname) def get_names_from_path(path): """ Get the filename and extension from a path. Args: path (str): The path to the file. Returns: tuple[str, str]: The filename and the extension. """ filename = os.path.basename(path) name, _ = os.path.splitext(filename) return name def process_and_save( x: torch.Tensor, batch: dict, cfg: dict, sub_dir: str, generate_sampling_option, epoch: int, start_index: int, saving: bool = True, ): """ Process the generated samples and save them to disk. """ fallback_name = cfg.dataset.data_path.split("/")[-1].split(".")[0] prompt_as_path = cfg.get("prompt_as_path", False) fps_save = cfg.get("fps_save", 16) save_dir = cfg.save_dir names = batch["name"] if "name" in batch else [None] * len(x) indices = batch["index"] if "index" in batch else [None] * len(x) if "index" in batch: indices = [idx + start_index for idx in indices] prompts = batch["text"] ret_names = [] is_image = generate_sampling_option.num_frames == 1 for img, name, index, prompt in zip(x, names, indices, prompts): # == get save path == save_path = get_save_path_name( save_dir, sub_dir, save_prefix=cfg.get("save_prefix", ""), name=name, fallback_name=fallback_name, index=index, num_sample_pos=epoch, prompt_as_path=prompt_as_path, prompt=prompt, ) ret_name = get_names_from_path(save_path) ret_names.append(ret_name) if saving: # == write txt to disk == with open(save_path + ".txt", "w", encoding="utf-8") as f: f.write(prompt) # == save samples == save_sample(img, save_path=save_path, fps=fps_save) # == resize image for t2i2v == if ( cfg.get("use_t2i2v", False) and is_image and generate_sampling_option.resolution != generate_sampling_option.resized_resolution ): log_message("Rescaling image to %s...", generate_sampling_option.resized_resolution) height, width = get_image_size( generate_sampling_option.resized_resolution, generate_sampling_option.aspect_ratio ) rescale_image_by_path(save_path + ".png", width, height) return ret_names def check_fps_added(sentence): """ Check if the sentence ends with the FPS information. """ pattern = r"\d+ FPS\.$" if re.search(pattern, sentence): return True return False def ensure_sentence_ends_with_period(sentence: str): """ Ensure that the sentence ends with a period. """ sentence = sentence.strip() if not sentence.endswith("."): sentence += "." return sentence def add_fps_info_to_text(text: list[str], fps: int = 16): """ Add the FPS information to the text. """ mod_text = [] for item in text: item = ensure_sentence_ends_with_period(item) if not check_fps_added(item): item = item + f" {fps} FPS." mod_text.append(item) return mod_text def add_motion_score_to_text(text, motion_score: int | str): """ Add the motion score to the text. """ if motion_score == "dynamic": ms = refine_prompts(text, type="motion_score") return [f"{t} {ms[i]}." for i, t in enumerate(text)] else: return [f"{t} {motion_score} motion score." for t in text] def add_noise_to_ref(masked_ref: torch.Tensor, masks: torch.Tensor, t: float, sigma_min: float = 1e-5): z_1 = torch.randn_like(masked_ref) z_noisy = (1 - (1 - sigma_min) * t) * masked_ref + t * z_1 return masks * z_noisy def collect_references_batch( reference_paths: list[str], cond_type: str, model_ae: nn.Module, image_size: tuple[int, int], is_causal=False, ): refs_x = [] # refs_x: [batch, ref_num, C, T, H, W] device = next(model_ae.parameters()).device dtype = next(model_ae.parameters()).dtype for reference_path in reference_paths: if reference_path == "": refs_x.append(None) continue ref_path = reference_path.split(";") ref = [] if "v2v" in cond_type: r = read_from_path(ref_path[0], image_size, transform_name="resize_crop") # size [C, T, H, W] actual_t = r.size(1) target_t = ( 64 if (actual_t >= 64 and "easy" in cond_type) else 32 ) # if reference not long enough, default to shorter ref if is_causal: target_t += 1 assert actual_t >= target_t, f"need at least {target_t} reference frames for v2v generation" if "head" in cond_type: # v2v head r = r[:, :target_t] elif "tail" in cond_type: # v2v tail r = r[:, -target_t:] else: raise NotImplementedError r_x = model_ae.encode(r.unsqueeze(0).to(device, dtype)) r_x = r_x.squeeze(0) # size [C, T, H, W] ref.append(r_x) elif cond_type == "i2v_head": # take the 1st frame from first ref_path r = read_from_path(ref_path[0], image_size, transform_name="resize_crop") # size [C, T, H, W] r = r[:, :1] r_x = model_ae.encode(r.unsqueeze(0).to(device, dtype)) r_x = r_x.squeeze(0) # size [C, T, H, W] ref.append(r_x) elif cond_type == "i2v_tail": # take the last frame from last ref_path r = read_from_path(ref_path[-1], image_size, transform_name="resize_crop") # size [C, T, H, W] r = r[:, -1:] r_x = model_ae.encode(r.unsqueeze(0).to(device, dtype)) r_x = r_x.squeeze(0) # size [C, T, H, W] ref.append(r_x) elif cond_type == "i2v_loop": # first frame r_head = read_from_path(ref_path[0], image_size, transform_name="resize_crop") # size [C, T, H, W] r_head = r_head[:, :1] r_x_head = model_ae.encode(r_head.unsqueeze(0).to(device, dtype)) r_x_head = r_x_head.squeeze(0) # size [C, T, H, W] ref.append(r_x_head) # last frame r_tail = read_from_path(ref_path[-1], image_size, transform_name="resize_crop") # size [C, T, H, W] r_tail = r_tail[:, -1:] r_x_tail = model_ae.encode(r_tail.unsqueeze(0).to(device, dtype)) r_x_tail = r_x_tail.squeeze(0) # size [C, T, H, W] ref.append(r_x_tail) else: raise NotImplementedError(f"Unknown condition type {cond_type}") refs_x.append(ref) return refs_x def prepare_inference_condition( z: torch.Tensor, mask_cond: str, ref_list: list[list[torch.Tensor]] = None, causal: bool = True, ) -> torch.Tensor: """ Prepare the visual condition for the model, using causal vae. Args: z (torch.Tensor): The latent noise tensor, of shape [B, C, T, H, W] mask_cond (dict): The condition configuration. 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. Returns: torch.Tensor: The visual condition tensor. """ # x has shape [b, c, t, h, w], where b is the batch size B, C, T, H, W = z.shape masks = torch.zeros(B, 1, T, H, W) masked_z = torch.zeros(B, C, T, H, W) if ref_list is None: assert mask_cond == "t2v", f"reference is required for {mask_cond}" for i in range(B): ref = ref_list[i] # warning message if ref is None and mask_cond != "t2v": print("no reference found. will default to cond_type t2v!") if ref is not None and T > 1: # video # Apply the selected mask condition directly on the masks tensor if mask_cond == "i2v_head": # equivalent to masking the first timestep masks[i, :, 0, :, :] = 1 masked_z[i, :, 0, :, :] = ref[0][:, 0, :, :] elif mask_cond == "i2v_tail": # mask the last timestep masks[i, :, -1, :, :] = 1 masked_z[i, :, -1, :, :] = ref[-1][:, -1, :, :] elif mask_cond == "v2v_head": k = 8 + int(causal) masks[i, :, :k, :, :] = 1 masked_z[i, :, :k, :, :] = ref[0][:, :k, :, :] elif mask_cond == "v2v_tail": k = 8 + int(causal) masks[i, :, -k:, :, :] = 1 masked_z[i, :, -k:, :, :] = ref[0][:, -k:, :, :] elif mask_cond == "v2v_head_easy": k = 16 + int(causal) masks[i, :, :k, :, :] = 1 masked_z[i, :, :k, :, :] = ref[0][:, :k, :, :] elif mask_cond == "v2v_tail_easy": k = 16 + int(causal) masks[i, :, -k:, :, :] = 1 masked_z[i, :, -k:, :, :] = ref[0][:, -k:, :, :] elif mask_cond == "i2v_loop": # mask first and last timesteps masks[i, :, 0, :, :] = 1 masks[i, :, -1, :, :] = 1 masked_z[i, :, 0, :, :] = ref[0][:, 0, :, :] masked_z[i, :, -1, :, :] = ref[-1][:, -1, :, :] # last frame of last referenced content else: # "t2v" is the fallback case where no specific condition is specified assert mask_cond == "t2v", f"Unknown mask condition {mask_cond}" masks = masks.to(z.device, z.dtype) masked_z = masked_z.to(z.device, z.dtype) return masks, masked_z ================================================ FILE: opensora/utils/logger.py ================================================ import logging import os import torch.distributed as dist def is_distributed() -> bool: """ Check if the code is running in a distributed setting. Returns: bool: True if running in a distributed setting, False otherwise """ return os.environ.get("WORLD_SIZE", None) is not None def is_main_process() -> bool: """ Check if the current process is the main process. Returns: bool: True if the current process is the main process, False otherwise. """ return not is_distributed() or dist.get_rank() == 0 def get_world_size() -> int: """ Get the number of processes in the distributed setting. Returns: int: The number of processes. """ if is_distributed(): return dist.get_world_size() else: return 1 def create_logger(logging_dir: str = None) -> logging.Logger: """ Create a logger that writes to a log file and stdout. Only the main process logs. Args: logging_dir (str): The directory to save the log file. Returns: logging.Logger: The logger. """ if is_main_process(): additional_args = dict() if logging_dir is not None: additional_args["handlers"] = [ logging.StreamHandler(), logging.FileHandler(f"{logging_dir}/log.txt"), ] logging.basicConfig( level=logging.INFO, format="[\033[34m%(asctime)s\033[0m] %(message)s", datefmt="%Y-%m-%d %H:%M:%S", **additional_args, ) logger = logging.getLogger(__name__) if logging_dir is not None: logger.info("Experiment directory created at %s", logging_dir) else: logger = logging.getLogger(__name__) logger.addHandler(logging.NullHandler()) return logger def log_message(*args, level: str = "info"): """ Log a message to the logger. Args: *args: The message to log. level (str): The logging level. """ logger = logging.getLogger(__name__) if level == "info": logger.info(*args) elif level == "warning": logger.warning(*args) elif level == "error": logger.error(*args) elif level == "print": print(*args) else: raise ValueError(f"Invalid logging level: {level}") ================================================ FILE: opensora/utils/misc.py ================================================ import os import time from collections import OrderedDict from collections.abc import Sequence from contextlib import nullcontext import numpy as np import psutil import torch import torch.distributed as dist import torch.nn as nn from colossalai.cluster.dist_coordinator import DistCoordinator from torch.utils.tensorboard import SummaryWriter from opensora.acceleration.parallel_states import get_data_parallel_group from .logger import log_message def create_tensorboard_writer(exp_dir: str) -> SummaryWriter: """ Create a tensorboard writer. Args: exp_dir (str): The directory to save tensorboard logs. Returns: SummaryWriter: The tensorboard writer. """ tensorboard_dir = f"{exp_dir}/tensorboard" os.makedirs(tensorboard_dir, exist_ok=True) writer = SummaryWriter(tensorboard_dir) return writer # ====================================================== # Memory # ====================================================== GIGABYTE = 1024**3 def log_cuda_memory(stage: str = None): """ Log the current CUDA memory usage. Args: stage (str): The stage of the training process. """ text = "CUDA memory usage" if stage is not None: text += f" at {stage}" log_message(text + ": %.1f GB", torch.cuda.memory_allocated() / GIGABYTE) def log_cuda_max_memory(stage: str = None): """ Log the max CUDA memory usage. Args: stage (str): The stage of the training process. """ torch.cuda.synchronize() max_memory_allocated = torch.cuda.max_memory_allocated() max_memory_reserved = torch.cuda.max_memory_reserved() log_message("CUDA max memory max memory allocated at " + stage + ": %.1f GB", max_memory_allocated / GIGABYTE) log_message("CUDA max memory max memory reserved at " + stage + ": %.1f GB", max_memory_reserved / GIGABYTE) # ====================================================== # Number of parameters # ====================================================== def get_model_numel(model: torch.nn.Module) -> tuple[int, int]: """ Get the number of parameters in a model. Args: model (torch.nn.Module): The model. Returns: tuple[int, int]: The total number of parameters and the number of trainable parameters. """ num_params = 0 num_params_trainable = 0 for p in model.parameters(): num_params += p.numel() if p.requires_grad: num_params_trainable += p.numel() return num_params, num_params_trainable def log_model_params(model: nn.Module): """ Log the number of parameters in a model. Args: model (torch.nn.Module): The model. """ num_params, num_params_trainable = get_model_numel(model) model_name = model.__class__.__name__ log_message(f"[{model_name}] Number of parameters: {format_numel_str(num_params)}") log_message(f"[{model_name}] Number of trainable parameters: {format_numel_str(num_params_trainable)}") # ====================================================== # String # ====================================================== def format_numel_str(numel: int) -> str: """ Format a number of elements to a human-readable string. Args: numel (int): The number of elements. Returns: str: The formatted string. """ B = 1024**3 M = 1024**2 K = 1024 if numel >= B: return f"{numel / B:.2f} B" elif numel >= M: return f"{numel / M:.2f} M" elif numel >= K: return f"{numel / K:.2f} K" else: return f"{numel}" def format_duration(seconds: int) -> str: days, remainder = divmod(seconds, 86400) # Extract days hours, remainder = divmod(remainder, 3600) # Extract hours minutes, seconds = divmod(remainder, 60) # Extract minutes and seconds parts = [] if days > 0: parts.append(f"{days}d") if hours > 0: parts.append(f"{hours}h") if minutes > 0: parts.append(f"{minutes}m") if seconds > 0 or not parts: # Always show seconds if nothing else parts.append(f"{seconds}s") return " ".join(parts) # ====================================================== # PyTorch # ====================================================== def all_reduce_mean(tensor: torch.Tensor) -> torch.Tensor: dist.all_reduce(tensor=tensor, group=get_data_parallel_group()) tensor.div_(dist.get_world_size(group=get_data_parallel_group())) return tensor def all_reduce_sum(tensor: torch.Tensor) -> torch.Tensor: dist.all_reduce(tensor=tensor, group=get_data_parallel_group()) return tensor def to_tensor(data: torch.Tensor | np.ndarray | Sequence | int | float) -> torch.Tensor: """Convert objects of various python types to :obj:`torch.Tensor`. Supported types are: :class:`numpy.ndarray`, :class:`torch.Tensor`, :class:`Sequence`, :class:`int` and :class:`float`. Args: data (torch.Tensor | numpy.ndarray | Sequence | int | float): Data to be converted. Returns: torch.Tensor: The converted tensor. """ if isinstance(data, torch.Tensor): return data elif isinstance(data, np.ndarray): return torch.from_numpy(data) elif isinstance(data, Sequence) and not isinstance(data, str): return torch.tensor(data) elif isinstance(data, int): return torch.LongTensor([data]) elif isinstance(data, float): return torch.FloatTensor([data]) else: raise TypeError(f"type {type(data)} cannot be converted to tensor.") def to_ndarray(data: torch.Tensor | np.ndarray | Sequence | int | float) -> np.ndarray: """Convert objects of various python types to :obj:`numpy.ndarray`. Supported types are: :class:`numpy.ndarray`, :class:`torch.Tensor`, :class:`Sequence`, :class:`int` and :class:`float`. Args: data (torch.Tensor | numpy.ndarray | Sequence | int | float): Data to be converted. Returns: numpy.ndarray: The converted ndarray. """ if isinstance(data, torch.Tensor): return data.numpy() elif isinstance(data, np.ndarray): return data elif isinstance(data, Sequence): return np.array(data) elif isinstance(data, int): return np.ndarray([data], dtype=int) elif isinstance(data, float): return np.array([data], dtype=float) else: raise TypeError(f"type {type(data)} cannot be converted to ndarray.") def to_torch_dtype(dtype: str | torch.dtype) -> torch.dtype: """ Convert a string or a torch.dtype to a torch.dtype. Args: dtype (str | torch.dtype): The input dtype. Returns: torch.dtype: The converted dtype. """ if isinstance(dtype, torch.dtype): return dtype elif isinstance(dtype, str): dtype_mapping = { "float64": torch.float64, "float32": torch.float32, "float16": torch.float16, "fp32": torch.float32, "fp16": torch.float16, "half": torch.float16, "bf16": torch.bfloat16, } if dtype not in dtype_mapping: raise ValueError(f"Unsupported dtype {dtype}") dtype = dtype_mapping[dtype] return dtype else: raise ValueError(f"Unsupported dtype {dtype}") # ====================================================== # Profile # ====================================================== class Timer: def __init__(self, name, log=False, barrier=False, coordinator: DistCoordinator | None = None): self.name = name self.start_time = None self.end_time = None self.log = log self.barrier = barrier self.coordinator = coordinator @property def elapsed_time(self) -> float: return self.end_time - self.start_time def __enter__(self): torch.cuda.synchronize() if self.barrier: dist.barrier() self.start_time = time.time() return self def __exit__(self, exc_type, exc_val, exc_tb): if self.coordinator is not None: self.coordinator.block_all() torch.cuda.synchronize() if self.barrier: dist.barrier() self.end_time = time.time() if self.log: print(f"Elapsed time for {self.name}: {self.elapsed_time:.2f} s") class Timers: def __init__(self, record_time: bool, record_barrier: bool = False, coordinator: DistCoordinator | None = None): self.timers = OrderedDict() self.record_time = record_time self.record_barrier = record_barrier self.coordinator = coordinator def __getitem__(self, name: str) -> Timer: if name not in self.timers: if self.record_time: self.timers[name] = Timer(name, barrier=self.record_barrier, coordinator=self.coordinator) else: self.timers[name] = nullcontext() return self.timers[name] def to_dict(self): return {f"time_debug/{name}": timer.elapsed_time for name, timer in self.timers.items()} def to_str(self, epoch: int, step: int) -> str: log_str = f"Rank {dist.get_rank()} | Epoch {epoch} | Step {step} | " for name, timer in self.timers.items(): log_str += f"{name}: {timer.elapsed_time:.2f} s | " return log_str def is_pipeline_enabled(plugin_type: str, plugin_config: dict) -> bool: return plugin_type == "hybrid" and plugin_config.get("pp_size", 1) > 1 def is_log_process(plugin_type: str, plugin_config: dict) -> bool: if is_pipeline_enabled(plugin_type, plugin_config): return dist.get_rank() == dist.get_world_size() - 1 return dist.get_rank() == 0 class NsysRange: def __init__(self, range_name: str): self.range_name = range_name def __enter__(self): torch.cuda.nvtx.range_push(self.range_name) return self def __exit__(self, exc_type, exc_val, exc_tb): torch.cuda.nvtx.range_pop() class NsysProfiler: """ Use NVIDIA Nsight Systems to profile the code. Example (~30MB): ```bash /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 \ 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 ``` Example (~130MB + 2G): ```bash /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 \ 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 ``` To generate summary statistics, use `--stats=true`. To disable stack traces, use use `-s none --cudabacktrace=none`. To use stack traces, use `-s process-tree --cudabacktrace=all`. To enable timer, use `--record_time True --record_barrier True` for `scripts/diffusion/train.py`. """ def __init__(self, warmup_steps: int = 0, num_steps: int = 1, enabled: bool = True): self.warmup_steps = warmup_steps self.num_steps = num_steps self.current_step = 0 self.enabled = enabled def step(self): if not self.enabled: return self.current_step += 1 if self.current_step == self.warmup_steps: torch.cuda.cudart().cudaProfilerStart() elif self.current_step >= self.warmup_steps + self.num_steps: torch.cuda.cudart().cudaProfilerStop() def range(self, range_name: str) -> NsysRange: if not self.enabled: return nullcontext() return NsysRange(range_name) class ProfilerContext: def __init__( self, save_path: str = "./log", record_shapes: bool = False, with_stack: bool = True, wait: int = 1, warmup: int = 1, active: int = 1, repeat: int = 1, enable: bool = True, **kwargs, ): self.enable = enable self.prof = None self.step_cnt = 0 self.total_steps = (wait + warmup + active) * repeat if enable: self.prof = torch.profiler.profile( activities=[ torch.profiler.ProfilerActivity.CPU, torch.profiler.ProfilerActivity.CUDA, ], schedule=torch.profiler.schedule(wait=wait, warmup=warmup, active=active, repeat=repeat), record_shapes=record_shapes, with_stack=with_stack, on_trace_ready=torch.profiler.tensorboard_trace_handler(save_path), **kwargs, ) def step(self): if self.enable: if self.step_cnt == 0: self.prof.__enter__() self.prof.step() self.step_cnt += 1 if self.is_profile_end(): self.prof.__exit__(None, None, None) exit(0) def is_profile_end(self): return self.step_cnt >= self.total_steps def get_process_mem(): process = psutil.Process(os.getpid()) return process.memory_info().rss / 1024**3 def get_total_mem(): return psutil.virtual_memory().used / 1024**3 def print_mem(prefix: str = ""): rank = dist.get_rank() print( f"[{rank}] {prefix} process memory: {get_process_mem():.2f} GB, total memory: {get_total_mem():.2f} GB", flush=True, ) ================================================ FILE: opensora/utils/optimizer.py ================================================ import torch from colossalai.nn.lr_scheduler import CosineAnnealingWarmupLR from colossalai.nn.optimizer import HybridAdam from torch.optim.lr_scheduler import _LRScheduler def create_optimizer( model: torch.nn.Module, optimizer_config: dict, ) -> torch.optim.Optimizer: """ Create an optimizer. Args: model (torch.nn.Module): The model to be optimized. optimizer_config (dict): The configuration of the optimizer. Returns: torch.optim.Optimizer: The optimizer. """ optimizer_name = optimizer_config.pop("cls", "HybridAdam") if optimizer_name == "HybridAdam": optimizer_cls = HybridAdam else: raise ValueError(f"Unknown optimizer: {optimizer_name}") optimizer = optimizer_cls( filter(lambda p: p.requires_grad, model.parameters()), **optimizer_config, ) return optimizer def create_lr_scheduler( optimizer: torch.optim.Optimizer, num_steps_per_epoch: int, epochs: int = 1000, warmup_steps: int | None = None, use_cosine_scheduler: bool = False, initial_lr: float = 1e-6, ) -> _LRScheduler | None: """ Create a learning rate scheduler. Args: optimizer (torch.optim.Optimizer): The optimizer to be used. num_steps_per_epoch (int): The number of steps per epoch. epochs (int): The number of epochs. warmup_steps (int | None): The number of warmup steps. use_cosine_scheduler (bool): Whether to use cosine scheduler. Returns: _LRScheduler | None: The learning rate scheduler """ if warmup_steps is None and not use_cosine_scheduler: lr_scheduler = None elif use_cosine_scheduler: lr_scheduler = CosineAnnealingWarmupLR( optimizer, total_steps=num_steps_per_epoch * epochs, warmup_steps=warmup_steps, ) else: lr_scheduler = LinearWarmupLR(optimizer, initial_lr=1e-6, warmup_steps=warmup_steps) # lr_scheduler = LinearWarmupLR(optimizer, warmup_steps=warmup_steps) return lr_scheduler class LinearWarmupLR(_LRScheduler): """Linearly warmup learning rate and then linearly decay. Args: optimizer (:class:`torch.optim.Optimizer`): Wrapped optimizer. warmup_steps (int, optional): Number of warmup steps, defaults to 0 last_step (int, optional): The index of last step, defaults to -1. When last_step=-1, the schedule is started from the beginning or When last_step=-1, sets initial lr as lr. """ def __init__(self, optimizer, initial_lr=0, warmup_steps: int = 0, last_epoch: int = -1): self.initial_lr = initial_lr self.warmup_steps = warmup_steps super().__init__(optimizer, last_epoch=last_epoch) def get_lr(self): if self.last_epoch < self.warmup_steps: return [ self.initial_lr + (self.last_epoch + 1) / (self.warmup_steps + 1) * (lr - self.initial_lr) for lr in self.base_lrs ] else: return self.base_lrs ================================================ FILE: opensora/utils/prompt_refine.py ================================================ import base64 import os from mimetypes import guess_type from openai import OpenAI sys_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. For 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. There are a few rules to follow: You will only ever output a single video description per user request. You should not simply make the description longer. Video descriptions must have the same num of words as examples below. Extra words will be ignored. """ sys_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. For 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. There are a few rules to follow: You will only ever output a single image description per user request. You should not simply make the description longer. Image captions must have the same num of words as examples. Extra words will be ignored. Note: The input image is the first frame of the video, and the output image caption should include dynamic information. Note: Don't contain camera transitions!!! Don't contain screen switching!!! Don't contain perspective shifts !!! Note: Use daily language to describe the video, don't use complex words or phrases!!! """ sys_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. Give 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. The 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. Answers 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". Note: 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!!! Note: 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!!! Note: Use daily language to describe the video, don't use complex words or phrases!!! """ sys_prompt_motion_score = """ We 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: • For runway videos featuring models, a motion score of 4 is ideal. • For static videos, a motion score of 1 is preferred. Output format: “{} motion score”, where {} is an integer between 1 and 15. User input: """ def image_to_url(image_path): mime_type, _ = guess_type(image_path) if mime_type is None: mime_type = "application/octet-stream" with open(image_path, "rb") as image_file: base64_encoded_data = base64.b64encode(image_file.read()).decode("utf-8") return f"data:{mime_type};base64,{base64_encoded_data}" def refine_prompt(prompt: str, retry_times: int = 3, type: str = "t2v", image_path: str = None): """ Refine a prompt to a format that can be used by the model for inference """ client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY")) text = prompt.strip() response = None for i in range(retry_times): if type == "t2v": response = client.chat.completions.create( messages=[ {"role": "system", "content": f"{sys_prompt_t2v}"}, { "role": "user", "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."', }, { "role": "assistant", "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.", }, { "role": "user", "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."', }, { "role": "assistant", "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.", }, { "role": "user", "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."', }, { "role": "assistant", "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.", }, { "role": "user", "content": f'Create an imaginative video descriptive caption or modify an earlier caption in ENGLISH for the user input: " {text} "', }, ], model="gpt-4o", # glm-4-plus and gpt-4o have be tested temperature=0.01, top_p=0.7, stream=False, max_tokens=250, ) elif type == "t2i": response = client.chat.completions.create( messages=[ {"role": "system", "content": f"{sys_prompt_t2i}"}, { "role": "user", "content": 'Create an imaginative image descriptive caption or modify an earlier caption for the user input : "a girl on the beach"', }, { "role": "assistant", "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.", }, { "role": "user", "content": 'Create an imaginative image descriptive caption or modify an earlier caption for the user input : "A man in a blue shirt"', }, { "role": "assistant", "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.", }, { "role": "user", "content": f'Create an imaginative image descriptive caption or modify an earlier caption in ENGLISH for the user input: " {text} "', }, ], model="gpt-4o", # glm-4-plus and gpt-4o have be tested temperature=0.01, top_p=0.7, stream=False, max_tokens=250, ) elif type == "i2v": response = client.chat.completions.create( model="gpt-4o", messages=[ {"role": "system", "content": f"{sys_prompt_i2v}"}, { "role": "user", "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."', }, { "role": "assistant", "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.", }, { "role": "user", "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."', }, { "role": "assistant", "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.", }, { "role": "user", "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."', }, { "role": "assistant", "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.", }, { "role": "user", "content": f'Create an imaginative video descriptive caption or modify an earlier caption in ENGLISH for the user input based on the image: " {text} "', }, { "role": "user", "content": [ { "type": "image_url", "image_url": { "url": image_to_url(image_path), }, }, ], }, ], temperature=0.01, top_p=0.7, stream=False, max_tokens=250, ) elif type == "motion_score": response = client.chat.completions.create( messages=[ {"role": "system", "content": f"{sys_prompt_motion_score}"}, { "role": "user", "content": f"{text}", }, ], model="gpt-4o", # glm-4-plus and gpt-4o have be tested temperature=0.01, top_p=0.7, stream=False, max_tokens=100, ) if response is None: continue if response.choices: return response.choices[0].message.content return prompt def refine_prompts(prompts: list[str], retry_times: int = 3, type: str = "t2v", image_paths: list[str] = None): if image_paths is None: image_paths = [None] * len(prompts) refined_prompts = [] for prompt, image_path in zip(prompts, image_paths): refined_prompt = refine_prompt(prompt, retry_times=retry_times, type=type, image_path=image_path) refined_prompts.append(refined_prompt) return refined_prompts ================================================ FILE: opensora/utils/sampling.py ================================================ import math import os import random from abc import ABC, abstractmethod from dataclasses import dataclass, replace import torch from einops import rearrange, repeat from mmengine.config import Config from peft import PeftModel from torch import Tensor, nn from opensora.datasets.aspect import get_image_size from opensora.models.mmdit.model import MMDiTModel from opensora.models.text.conditioner import HFEmbedder from opensora.registry import MODELS, build_module from opensora.utils.inference import ( SamplingMethod, collect_references_batch, prepare_inference_condition, ) # ====================================================== # Sampling Options # ====================================================== @dataclass class SamplingOption: # The width of the image/video. width: int | None = None # The height of the image/video. height: int | None = None # The resolution of the image/video. If provided, it will override the height and width. resolution: str | None = None # The aspect ratio of the image/video. If provided, it will override the height and width. aspect_ratio: str | None = None # The number of frames. num_frames: int = 1 # The number of sampling steps. num_steps: int = 50 # The classifier-free guidance (text). guidance: float = 4.0 # use oscillation for text guidance text_osci: bool = False # The classifier-free guidance (image), or for the guidance on condition for i2v and v2v guidance_img: float | None = None # use oscillation for image guidance image_osci: bool = False # use temporal scaling for image guidance scale_temporal_osci: bool = False # The seed for the random number generator. seed: int | None = None # Whether to shift the schedule. shift: bool = True # The sampling method. method: str | SamplingMethod = SamplingMethod.I2V # Temporal reduction temporal_reduction: int = 1 # is causal vae is_causal_vae: bool = False # flow shift flow_shift: float | None = None def sanitize_sampling_option(sampling_option: SamplingOption) -> SamplingOption: """ Sanitize the sampling options. Args: sampling_option (SamplingOption): The sampling options. Returns: SamplingOption: The sanitized sampling options. """ if ( sampling_option.resolution is not None or sampling_option.aspect_ratio is not None ): assert ( sampling_option.resolution is not None and sampling_option.aspect_ratio is not None ), "Both resolution and aspect ratio must be provided" resolution = sampling_option.resolution aspect_ratio = sampling_option.aspect_ratio height, width = get_image_size(resolution, aspect_ratio, training=False) else: assert ( sampling_option.height is not None and sampling_option.width is not None ), "Both height and width must be provided" height, width = sampling_option.height, sampling_option.width height = (height // 16 + (1 if height % 16 else 0)) * 16 width = (width // 16 + (1 if width % 16 else 0)) * 16 replace_dict = dict(height=height, width=width) if isinstance(sampling_option.method, str): method = SamplingMethod(sampling_option.method) replace_dict["method"] = method return replace(sampling_option, **replace_dict) def get_oscillation_gs(guidance_scale: float, i: int, force_num=10): """ get oscillation guidance for cfg. Args: guidance_scale: original guidance value i: denoising step force_num: before which don't apply oscillation """ if i < force_num or (i >= force_num and i % 2 == 0): gs = guidance_scale else: gs = 1.0 return gs # ====================================================== # Denoising # ====================================================== class Denoiser(ABC): @abstractmethod def denoise(self, model: MMDiTModel, **kwargs) -> Tensor: """Denoise the input.""" @abstractmethod def prepare_guidance( self, text: list[str], optional_models: dict[str, nn.Module], device: torch.device, dtype: torch.dtype, **kwargs, ) -> dict[str, Tensor]: """Prepare the guidance for the model. This method will alter text.""" class I2VDenoiser(Denoiser): def denoise(self, model: MMDiTModel, **kwargs) -> Tensor: img = kwargs.pop("img") timesteps = kwargs.pop("timesteps") guidance = kwargs.pop("guidance") guidance_img = kwargs.pop("guidance_img") # cond ref arguments masks = kwargs.pop("masks") masked_ref = kwargs.pop("masked_ref") kwargs.pop("sigma_min") # oscillation guidance text_osci = kwargs.pop("text_osci", False) image_osci = kwargs.pop("image_osci", False) scale_temporal_osci = kwargs.pop("scale_temporal_osci", False) # patch size patch_size = kwargs.pop("patch_size", 2) guidance_vec = torch.full( (img.shape[0],), guidance, device=img.device, dtype=img.dtype ) for i, (t_curr, t_prev) in enumerate(zip(timesteps[:-1], timesteps[1:])): # timesteps t_vec = torch.full( (img.shape[0],), t_curr, dtype=img.dtype, device=img.device ) b, c, t, w, h = masked_ref.size() cond = torch.cat((masks, masked_ref), dim=1) cond = pack(cond, patch_size=patch_size) kwargs["cond"] = torch.cat([cond, cond, torch.zeros_like(cond)], dim=0) # forward preparation cond_x = img[: len(img) // 3] img = torch.cat([cond_x, cond_x, cond_x], dim=0) # forward pred = model( img=img, **kwargs, timesteps=t_vec, guidance=guidance_vec, ) # prepare guidance text_gs = get_oscillation_gs(guidance, i) if text_osci else guidance image_gs = ( get_oscillation_gs(guidance_img, i) if image_osci else guidance_img ) cond, uncond, uncond_2 = pred.chunk(3, dim=0) if image_gs > 1.0 and scale_temporal_osci: # image_gs decrease with each denoising step step_upper_image_gs = torch.linspace(image_gs, 1.0, len(timesteps))[i] # image_gs increase along the temporal axis of the latent video image_gs = torch.linspace(1.0, step_upper_image_gs, t)[ None, None, :, None, None ].repeat(b, c, 1, h, w) image_gs = pack(image_gs, patch_size=patch_size).to(cond.device, cond.dtype) # update pred = uncond_2 + image_gs * (uncond - uncond_2) + text_gs * (cond - uncond) pred = torch.cat([pred, pred, pred], dim=0) img = img + (t_prev - t_curr) * pred img = img[: len(img) // 3] return img def prepare_guidance( self, text: list[str], optional_models: dict[str, nn.Module], device: torch.device, dtype: torch.dtype, **kwargs, ) -> tuple[list[str], dict[str, Tensor]]: ret = {} neg = kwargs.get("neg", None) ret["guidance_img"] = kwargs.pop("guidance_img") # text if neg is None: neg = [""] * len(text) text = text + neg + neg return text, ret class DistilledDenoiser(Denoiser): def denoise(self, model: MMDiTModel, **kwargs) -> Tensor: img = kwargs.pop("img") timesteps = kwargs.pop("timesteps") guidance = kwargs.pop("guidance") guidance_vec = torch.full( (img.shape[0],), guidance, device=img.device, dtype=img.dtype ) for t_curr, t_prev in zip(timesteps[:-1], timesteps[1:]): # timesteps t_vec = torch.full( (img.shape[0],), t_curr, dtype=img.dtype, device=img.device ) # forward pred = model( img=img, **kwargs, timesteps=t_vec, guidance=guidance_vec, ) # update img = img + (t_prev - t_curr) * pred return img def prepare_guidance( self, text: list[str], optional_models: dict[str, nn.Module], device: torch.device, dtype: torch.dtype, **kwargs, ) -> tuple[list[str], dict[str, Tensor]]: return text, {} SamplingMethodDict = { SamplingMethod.I2V: I2VDenoiser(), SamplingMethod.DISTILLED: DistilledDenoiser(), } # ====================================================== # Timesteps # ====================================================== def time_shift(alpha: float, t: Tensor) -> Tensor: return alpha * t / (1 + (alpha - 1) * t) def get_res_lin_function( x1: float = 256, y1: float = 1, x2: float = 4096, y2: float = 3 ) -> callable: m = (y2 - y1) / (x2 - x1) b = y1 - m * x1 return lambda x: m * x + b def get_schedule( num_steps: int, image_seq_len: int, num_frames: int, shift_alpha: float | None = None, base_shift: float = 1, max_shift: float = 3, shift: bool = True, ) -> list[float]: # extra step for zero timesteps = torch.linspace(1, 0, num_steps + 1) # shifting the schedule to favor high timesteps for higher signal images if shift: if shift_alpha is None: # estimate mu based on linear estimation between two points # spatial scale shift_alpha = get_res_lin_function(y1=base_shift, y2=max_shift)( image_seq_len ) # temporal scale shift_alpha *= math.sqrt(num_frames) # calculate shifted timesteps timesteps = time_shift(shift_alpha, timesteps) return timesteps.tolist() def get_noise( num_samples: int, height: int, width: int, num_frames: int, device: torch.device, dtype: torch.dtype, seed: int, patch_size: int = 2, channel: int = 16, ) -> Tensor: """ Generate a noise tensor. Args: num_samples (int): Number of samples. height (int): Height of the noise tensor. width (int): Width of the noise tensor. num_frames (int): Number of frames. device (torch.device): Device to put the noise tensor on. dtype (torch.dtype): Data type of the noise tensor. seed (int): Seed for the random number generator. Returns: Tensor: The noise tensor. """ D = int(os.environ.get("AE_SPATIAL_COMPRESSION", 16)) return torch.randn( num_samples, channel, num_frames, # allow for packing patch_size * math.ceil(height / D), patch_size * math.ceil(width / D), device=device, dtype=dtype, generator=torch.Generator(device=device).manual_seed(seed), ) def pack(x: Tensor, patch_size: int = 2) -> Tensor: return rearrange( x, "b c t (h ph) (w pw) -> b (t h w) (c ph pw)", ph=patch_size, pw=patch_size ) def unpack( x: Tensor, height: int, width: int, num_frames: int, patch_size: int = 2 ) -> Tensor: D = int(os.environ.get("AE_SPATIAL_COMPRESSION", 16)) return rearrange( x, "b (t h w) (c ph pw) -> b c t (h ph) (w pw)", h=math.ceil(height / D), w=math.ceil(width / D), t=num_frames, ph=patch_size, pw=patch_size, ) # ====================================================== # Prepare # ====================================================== def prepare( t5, clip: HFEmbedder, img: Tensor, prompt: str | list[str], seq_align: int = 1, patch_size: int = 2, ) -> dict[str, Tensor]: """ Prepare the input for the model. Args: t5 (HFEmbedder): The T5 model. clip (HFEmbedder): The CLIP model. img (Tensor): The image tensor. prompt (str | list[str]): The prompt(s). Returns: dict[str, Tensor]: The input dictionary. img_ids: used for positional embedding in T,H,W dimensions later text_ids: for positional embedding, but set to 0 for now since our text encoder already encodes positional information """ bs, c, t, h, w = img.shape device, dtype = img.device, img.dtype if isinstance(prompt, str): prompt = [prompt] if bs != len(prompt): bs = len(prompt) img = rearrange( img, "b c t (h ph) (w pw) -> b (t h w) (c ph pw)", ph=patch_size, pw=patch_size ) if img.shape[0] != bs: img = repeat(img, "b ... -> (repeat b) ...", repeat=bs // img.shape[0]) img_ids = torch.zeros(t, h // patch_size, w // patch_size, 3) img_ids[..., 0] = img_ids[..., 0] + torch.arange(t)[:, None, None] img_ids[..., 1] = img_ids[..., 1] + torch.arange(h // patch_size)[None, :, None] img_ids[..., 2] = img_ids[..., 2] + torch.arange(w // patch_size)[None, None, :] img_ids = repeat(img_ids, "t h w c -> b (t h w) c", b=bs) # Encode the tokenized prompts txt = t5(prompt, added_tokens=img_ids.shape[1], seq_align=seq_align) if txt.shape[0] == 1 and bs > 1: txt = repeat(txt, "1 ... -> bs ...", bs=bs) txt_ids = torch.zeros(bs, txt.shape[1], 3) vec = clip(prompt) if vec.shape[0] == 1 and bs > 1: vec = repeat(vec, "1 ... -> bs ...", bs=bs) return { "img": img, "img_ids": img_ids.to(device, dtype), "txt": txt.to(device, dtype), "txt_ids": txt_ids.to(device, dtype), "y_vec": vec.to(device, dtype), } def prepare_ids( img: Tensor, t5_embedding: Tensor, clip_embedding: Tensor, ) -> dict[str, Tensor]: """ Prepare the input for the model. Args: img (Tensor): The image tensor. t5_embedding (Tensor): The T5 embedding. clip_embedding (Tensor): The CLIP embedding. Returns: dict[str, Tensor]: The input dictionary. img_ids: used for positional embedding in T,H,W dimensions later text_ids: for positional embedding, but set to 0 for now since our text encoder already encodes positional information """ bs, c, t, h, w = img.shape device, dtype = img.device, img.dtype img = rearrange(img, "b c t (h ph) (w pw) -> b (t h w) (c ph pw)", ph=2, pw=2) if img.shape[0] != bs: img = repeat(img, "b ... -> (repeat b) ...", repeat=bs // img.shape[0]) img_ids = torch.zeros(t, h // 2, w // 2, 3) img_ids[..., 0] = img_ids[..., 0] + torch.arange(t)[:, None, None] img_ids[..., 1] = img_ids[..., 1] + torch.arange(h // 2)[None, :, None] img_ids[..., 2] = img_ids[..., 2] + torch.arange(w // 2)[None, None, :] img_ids = repeat(img_ids, "t h w c -> b (t h w) c", b=bs) # Encode the tokenized prompts if t5_embedding.shape[0] == 1 and bs > 1: t5_embedding = repeat(t5_embedding, "1 ... -> bs ...", bs=bs) txt_ids = torch.zeros(bs, t5_embedding.shape[1], 3) if clip_embedding.shape[0] == 1 and bs > 1: clip_embedding = repeat(clip_embedding, "1 ... -> bs ...", bs=bs) return { "img": img, "img_ids": img_ids.to(device, dtype), "txt": t5_embedding.to(device, dtype), "txt_ids": txt_ids.to(device, dtype), "y_vec": clip_embedding.to(device, dtype), } def prepare_models( cfg: Config, device: torch.device, dtype: torch.dtype, offload_model: bool = False, ) -> tuple[nn.Module, nn.Module, nn.Module, nn.Module, dict[str, nn.Module]]: """ Prepare models for inference. Args: cfg (Config): The configuration object. device (torch.device): The device to use. dtype (torch.dtype): The data type to use. Returns: 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. """ model_device = ( "cpu" if offload_model and cfg.get("img_flux", None) is not None else device ) model = build_module( cfg.model, MODELS, device_map=model_device, torch_dtype=dtype ).eval() model_ae = build_module( cfg.ae, MODELS, device_map=model_device, torch_dtype=dtype ).eval() model_t5 = build_module(cfg.t5, MODELS, device_map=device, torch_dtype=dtype).eval() model_clip = build_module( cfg.clip, MODELS, device_map=device, torch_dtype=dtype ).eval() if cfg.get("pretrained_lora_path", None) is not None: model = PeftModel.from_pretrained( model, cfg.pretrained_lora_path, is_trainable=False ) # optional models optional_models = {} if cfg.get("img_flux", None) is not None: model_img_flux = build_module( cfg.img_flux, MODELS, device_map=device, torch_dtype=dtype ).eval() model_ae_img_flux = build_module( cfg.img_flux_ae, MODELS, device_map=device, torch_dtype=dtype ).eval() optional_models["img_flux"] = model_img_flux optional_models["img_flux_ae"] = model_ae_img_flux return model, model_ae, model_t5, model_clip, optional_models def prepare_api( model: nn.Module, model_ae: nn.Module, model_t5: nn.Module, model_clip: nn.Module, optional_models: dict[str, nn.Module], ) -> callable: """ Prepare the API function for inference. Args: model (nn.Module): The diffusion model. model_ae (nn.Module): The autoencoder model. model_t5 (nn.Module): The T5 model. model_clip (nn.Module): The CLIP model. Returns: callable: The API function for inference. """ @torch.inference_mode() def api_fn( opt: SamplingOption, cond_type: str = "t2v", seed: int = None, sigma_min: float = 1e-5, text: list[str] = None, neg: list[str] = None, patch_size: int = 2, channel: int = 16, **kwargs, ): """ The API function for inference. Args: opt (SamplingOption): The sampling options. text (list[str], optional): The text prompts. Defaults to None. neg (list[str], optional): The negative text prompts. Defaults to None. Returns: torch.Tensor: The generated images. """ device = next(model.parameters()).device dtype = next(model.parameters()).dtype # passing seed will overwrite opt seed if seed is None: # random seed if not provided seed = opt.seed if opt.seed is not None else random.randint(0, 2**32 - 1) if opt.is_causal_vae: num_frames = ( 1 if opt.num_frames == 1 else (opt.num_frames - 1) // opt.temporal_reduction + 1 ) else: num_frames = ( 1 if opt.num_frames == 1 else opt.num_frames // opt.temporal_reduction ) z = get_noise( len(text), opt.height, opt.width, num_frames, device, dtype, seed, patch_size=patch_size, channel=channel // (patch_size**2), ) denoiser = SamplingMethodDict[opt.method] # i2v reference conditions references = [None] * len(text) if cond_type != "t2v" and "ref" in kwargs: reference_path_list = kwargs.pop("ref") references = collect_references_batch( reference_path_list, cond_type, model_ae, (opt.height, opt.width), is_causal=opt.is_causal_vae, ) elif cond_type != "t2v": print( "your csv file doesn't have a ref column or is not processed properly. will default to cond_type t2v!" ) cond_type = "t2v" # timestep editing timesteps = get_schedule( opt.num_steps, (z.shape[-1] * z.shape[-2]) // patch_size**2, num_frames, shift=opt.shift, shift_alpha=opt.flow_shift, ) # prepare classifier-free guidance data (method specific) text, additional_inp = denoiser.prepare_guidance( text=text, optional_models=optional_models, device=device, dtype=dtype, neg=neg, guidance_img=opt.guidance_img, ) inp = prepare(model_t5, model_clip, z, prompt=text, patch_size=patch_size) inp.update(additional_inp) if opt.method in [SamplingMethod.I2V]: # prepare references masks, masked_ref = prepare_inference_condition( z, cond_type, ref_list=references, causal=opt.is_causal_vae ) inp["masks"] = masks inp["masked_ref"] = masked_ref inp["sigma_min"] = sigma_min x = denoiser.denoise( model, **inp, timesteps=timesteps, guidance=opt.guidance, text_osci=opt.text_osci, image_osci=opt.image_osci, scale_temporal_osci=( opt.scale_temporal_osci and "i2v" in cond_type ), # don't use temporal osci for v2v or t2v flow_shift=opt.flow_shift, patch_size=patch_size, ) x = unpack(x, opt.height, opt.width, num_frames, patch_size=patch_size) # replace for image condition if cond_type == "i2v_head": x[0, :, :1] = references[0][0] elif cond_type == "i2v_tail": x[0, :, -1:] = references[0][0] elif cond_type == "i2v_loop": x[0, :, :1] = references[0][0] x[0, :, -1:] = references[0][1] x = model_ae.decode(x) x = x[:, :, : opt.num_frames] # image # remove the duplicate frames if not opt.is_causal_vae: if cond_type == "i2v_head": pad_len = model_ae.compression[0] - 1 x = x[:, :, pad_len:] elif cond_type == "i2v_tail": pad_len = model_ae.compression[0] - 1 x = x[:, :, :-pad_len] elif cond_type == "i2v_loop": pad_len = model_ae.compression[0] - 1 x = x[:, :, pad_len:-pad_len] return x return api_fn ================================================ FILE: opensora/utils/train.py ================================================ import random import warnings from collections import OrderedDict from datetime import timedelta import torch import torch.distributed as dist import torch.nn.functional as F from colossalai.booster.plugin import HybridParallelPlugin, LowLevelZeroPlugin from colossalai.cluster import DistCoordinator from colossalai.utils import get_current_device from einops import rearrange from torch import nn from torch.optim.lr_scheduler import _LRScheduler from tqdm import tqdm from opensora.acceleration.parallel_states import ( set_data_parallel_group, set_sequence_parallel_group, set_tensor_parallel_group, ) from opensora.utils.optimizer import LinearWarmupLR def set_lr( optimizer: torch.optim.Optimizer, lr_scheduler: _LRScheduler, lr: float, initial_lr: float = None, ): for param_group in optimizer.param_groups: param_group["lr"] = lr if isinstance(lr_scheduler, LinearWarmupLR): lr_scheduler.base_lrs = [lr] * len(lr_scheduler.base_lrs) if initial_lr is not None: lr_scheduler.initial_lr = initial_lr def set_warmup_steps( lr_scheduler: _LRScheduler, warmup_steps: int, ): if isinstance(lr_scheduler, LinearWarmupLR): lr_scheduler.warmup_steps = warmup_steps def set_eps( optimizer: torch.optim.Optimizer, eps: float = None, ): if eps is not None: for param_group in optimizer.param_groups: param_group["eps"] = eps def setup_device() -> tuple[torch.device, DistCoordinator]: """ Setup the device and the distributed coordinator. Returns: tuple[torch.device, DistCoordinator]: The device and the distributed coordinator. """ assert torch.cuda.is_available(), "Training currently requires at least one GPU." # NOTE: A very large timeout is set to avoid some processes exit early dist.init_process_group(backend="nccl", timeout=timedelta(hours=24)) torch.cuda.set_device(dist.get_rank() % torch.cuda.device_count()) coordinator = DistCoordinator() device = get_current_device() return device, coordinator def create_colossalai_plugin( plugin: str, dtype: str, grad_clip: float, **kwargs, ) -> LowLevelZeroPlugin | HybridParallelPlugin: """ Create a ColossalAI plugin. Args: plugin (str): The plugin name. dtype (str): The data type. grad_clip (float): The gradient clip value. Returns: LowLevelZeroPlugin | HybridParallelPlugin: The plugin. """ plugin_kwargs = dict( precision=dtype, initial_scale=2**16, max_norm=grad_clip, overlap_allgather=True, cast_inputs=False, reduce_bucket_size_in_m=20, ) plugin_kwargs.update(kwargs) sp_size = plugin_kwargs.get("sp_size", 1) if plugin == "zero1" or plugin == "zero2": assert sp_size == 1, "Zero plugin does not support sequence parallelism" stage = 1 if plugin == "zero1" else 2 plugin = LowLevelZeroPlugin( stage=stage, **plugin_kwargs, ) set_data_parallel_group(dist.group.WORLD) elif plugin == "hybrid": plugin_kwargs["find_unused_parameters"] = True reduce_bucket_size_in_m = plugin_kwargs.pop("reduce_bucket_size_in_m") if "zero_bucket_size_in_m" not in plugin_kwargs: plugin_kwargs["zero_bucket_size_in_m"] = reduce_bucket_size_in_m plugin_kwargs.pop("cast_inputs") plugin_kwargs["enable_metadata_cache"] = False custom_policy = plugin_kwargs.pop("custom_policy", None) if custom_policy is not None: custom_policy = custom_policy() plugin = HybridParallelPlugin( custom_policy=custom_policy, **plugin_kwargs, ) set_tensor_parallel_group(plugin.tp_group) set_sequence_parallel_group(plugin.sp_group) set_data_parallel_group(plugin.dp_group) else: raise ValueError(f"Unknown plugin {plugin}") return plugin @torch.no_grad() def update_ema( ema_model: torch.nn.Module, model: torch.nn.Module, optimizer=None, decay: float = 0.9999, sharded: bool = True ): """ Step the EMA model towards the current model. Args: ema_model (torch.nn.Module): The EMA model. model (torch.nn.Module): The current model. optimizer (torch.optim.Optimizer): The optimizer. decay (float): The decay rate. sharded (bool): Whether the model is sharded. """ ema_params = OrderedDict(ema_model.named_parameters()) model_params = OrderedDict(model.named_parameters()) for name, param in model_params.items(): if name == "pos_embed": continue if not param.requires_grad: continue if not sharded: param_data = param.data ema_params[name].mul_(decay).add_(param_data, alpha=1 - decay) else: if param.data.dtype != torch.float32: param_id = id(param) master_param = optimizer.get_working_to_master_map()[param_id] param_data = master_param.data else: param_data = param.data ema_params[name].mul_(decay).add_(param_data, alpha=1 - decay) def dropout_condition(prob: float, txt: torch.Tensor, null_txt: torch.Tensor) -> torch.Tensor: """ Apply dropout to the text tensor. Args: prob (float): The dropout probability. txt (torch.Tensor): The text tensor. null_txt (torch.Tensor): The null text tensor. Returns: torch.Tensor: The text tensor with dropout applied. """ if prob == 0: warnings.warn("Dropout probability is 0, skipping dropout") drop_ids = torch.rand(txt.shape[0], device=txt.device) < prob drop_ids = drop_ids.view((drop_ids.shape[0],) + (1,) * (txt.ndim - 1)) new_txt = torch.where(drop_ids, null_txt, txt) return new_txt def prepare_visual_condition_uncausal( x: torch.Tensor, condition_config: dict, model_ae: torch.nn.Module, pad: bool = False ) -> torch.Tensor: """ Prepare the visual condition for the model. Args: x: (torch.Tensor): The input video tensor. condition_config (dict): The condition configuration. model_ae (torch.nn.Module): The video encoder module. Returns: torch.Tensor: The visual condition tensor. """ # x has shape [b, c, t, h, w], where b is the batch size B = x.shape[0] C = model_ae.cfg.latent_channels T, H, W = model_ae.get_latent_size(x.shape[-3:]) # Initialize masks tensor to match the shape of x, but only the time dimension will be masked masks = torch.zeros(B, 1, T, H, W).to( x.device, x.dtype ) # broadcasting over channel, concat to masked_x with 1 + 16 = 17 channesl # to prevent information leakage, image must be encoded separately and copied to latent latent = torch.zeros(B, C, T, H, W).to(x.device, x.dtype) x_0 = torch.zeros(B, C, T, H, W).to(x.device, x.dtype) if T > 1: # video # certain v2v conditions not are applicable for short videos if T <= 32 // model_ae.time_compression_ratio: condition_config.pop("v2v_head", None) # given first 32 frames condition_config.pop("v2v_tail", None) # given last 32 frames condition_config.pop("v2v_head_easy", None) # given first 64 frames condition_config.pop("v2v_tail_easy", None) # given last 64 frames if T <= 64 // model_ae.time_compression_ratio: condition_config.pop("v2v_head_easy", None) # given first 64 frames condition_config.pop("v2v_tail_easy", None) # given last 64 frames mask_cond_options = list(condition_config.keys()) # list of mask conditions mask_cond_weights = list(condition_config.values()) # corresponding probabilities for i in range(B): # Randomly select a mask condition based on the provided probabilities mask_cond = random.choices(mask_cond_options, weights=mask_cond_weights, k=1)[0] # Apply the selected mask condition directly on the masks tensor if mask_cond == "i2v_head": # NOTE: modify video, mask first latent frame # padded video such that the first latent frame correspond to image only masks[i, :, 0, :, :] = 1 if pad: pad_num = model_ae.time_compression_ratio - 1 # 32 --> new video: 7 + (1+31-7) padded_x = torch.cat([x[i, :, :1]] * pad_num + [x[i, :, :-pad_num]], dim=1).unsqueeze(0) x_0[i] = model_ae.encode(padded_x)[0] else: x_0[i] = model_ae.encode(x[i : i + 1])[0] # condition: encode the image only latent[i, :, :1, :, :] = model_ae.encode( x[i, :, :1, :, :].unsqueeze(0) ) # since the first dimension of right hand side is singleton, torch auto-ignores it elif mask_cond == "i2v_loop": # # NOTE: modify video, mask first and last latent frame # pad video such that first and last latent frame correspond to image only masks[i, :, 0, :, :] = 1 masks[i, :, -1, :, :] = 1 if pad: pad_num = model_ae.time_compression_ratio - 1 padded_x = torch.cat( [x[i, :, :1]] * pad_num + [x[i, :, : -pad_num * 2]] + [x[i, :, -pad_num * 2 - 1].unsqueeze(1)] * pad_num, dim=1, ).unsqueeze( 0 ) # remove the last pad_num * 2 frames from the end of the video x_0[i] = model_ae.encode(padded_x)[0] # condition: encode the image only latent[i, :, :1, :, :] = model_ae.encode(x[i, :, :1, :, :].unsqueeze(0)) latent[i, :, -1:, :, :] = model_ae.encode(x[i, :, -pad_num * 2 - 1, :, :].unsqueeze(1).unsqueeze(0)) else: x_0[i] = model_ae.encode(x[i : i + 1])[0] latent[i, :, :1, :, :] = model_ae.encode(x[i, :, :1, :, :].unsqueeze(0)) latent[i, :, -1:, :, :] = model_ae.encode(x[i, :, -1:, :, :].unsqueeze(0)) elif mask_cond == "i2v_tail": # mask the last latent frame masks[i, :, -1, :, :] = 1 if pad: pad_num = model_ae.time_compression_ratio - 1 padded_x = torch.cat([x[i, :, pad_num:]] + [x[i, :, -1:]] * pad_num, dim=1).unsqueeze(0) x_0[i] = model_ae.encode(padded_x)[0] latent[i, :, -1:, :, :] = model_ae.encode(x[i, :, -pad_num * 2 - 1, :, :].unsqueeze(1).unsqueeze(0)) else: x_0[i] = model_ae.encode(x[i : i + 1])[0] latent[i, :, -1:, :, :] = model_ae.encode(x[i, :, -1:, :, :].unsqueeze(0)) elif mask_cond == "v2v_head": # mask the first 32 video frames assert T > 32 // model_ae.time_compression_ratio conditioned_t = 32 // model_ae.time_compression_ratio masks[i, :, :conditioned_t, :, :] = 1 x_0[i] = model_ae.encode(x[i].unsqueeze(0))[0] latent[i, :, :conditioned_t, :, :] = x_0[i, :, :conditioned_t, :, :] elif mask_cond == "v2v_tail": # mask the last 32 video frames assert T > 32 // model_ae.time_compression_ratio conditioned_t = 32 // model_ae.time_compression_ratio masks[i, :, -conditioned_t:, :, :] = 1 x_0[i] = model_ae.encode(x[i].unsqueeze(0))[0] latent[i, :, -conditioned_t:, :, :] = x_0[i, :, -conditioned_t:, :, :] elif mask_cond == "v2v_head_easy": # mask the first 64 video frames assert T > 64 // model_ae.time_compression_ratio conditioned_t = 64 // model_ae.time_compression_ratio masks[i, :, :conditioned_t, :, :] = 1 x_0[i] = model_ae.encode(x[i].unsqueeze(0))[0] latent[i, :, :conditioned_t, :, :] = x_0[i, :, :conditioned_t, :, :] elif mask_cond == "v2v_tail_easy": # mask the last 64 video frames assert T > 64 // model_ae.time_compression_ratio conditioned_t = 64 // model_ae.time_compression_ratio masks[i, :, -conditioned_t:, :, :] = 1 x_0[i] = model_ae.encode(x[i].unsqueeze(0))[0] latent[i, :, -conditioned_t:, :, :] = x_0[i, :, -conditioned_t:, :, :] # elif mask_cond == "v2v_head": # mask from the beginning to a random point # masks[i, :, : random.randint(1, T - 2), :, :] = 1 # elif mask_cond == "v2v_tail": # mask from a random point to the end # masks[i, :, -random.randint(1, T - 2) :, :, :] = 1 else: # "t2v" is the fallback case where no specific condition is specified assert mask_cond == "t2v", f"Unknown mask condition {mask_cond}" x_0[i] = model_ae.encode(x[i].unsqueeze(0))[0] else: # image x_0 = model_ae.encode(x) # latent video latent = masks * latent # condition latent # merge the masks and the masked_x into a single tensor cond = torch.cat((masks, latent), dim=1) return x_0, cond def prepare_visual_condition_causal(x: torch.Tensor, condition_config: dict, model_ae: torch.nn.Module) -> torch.Tensor: """ Prepare the visual condition for the model. Args: x: (torch.Tensor): The input video tensor. condition_config (dict): The condition configuration. model_ae (torch.nn.Module): The video encoder module. Returns: torch.Tensor: The visual condition tensor. """ # x has shape [b, c, t, h, w], where b is the batch size B = x.shape[0] C = model_ae.cfg.latent_channels T, H, W = model_ae.get_latent_size(x.shape[-3:]) # Initialize masks tensor to match the shape of x, but only the time dimension will be masked masks = torch.zeros(B, 1, T, H, W).to( x.device, x.dtype ) # broadcasting over channel, concat to masked_x with 1 + 16 = 17 channesl # to prevent information leakage, image must be encoded separately and copied to latent latent = torch.zeros(B, C, T, H, W).to(x.device, x.dtype) x_0 = torch.zeros(B, C, T, H, W).to(x.device, x.dtype) if T > 1: # video # certain v2v conditions not are applicable for short videos if T <= (32 // model_ae.time_compression_ratio) + 1: condition_config.pop("v2v_head", None) # given first 33 frames condition_config.pop("v2v_tail", None) # given last 33 frames condition_config.pop("v2v_head_easy", None) # given first 65 frames condition_config.pop("v2v_tail_easy", None) # given last 65 frames if T <= (64 // model_ae.time_compression_ratio) + 1: condition_config.pop("v2v_head_easy", None) # given first 65 frames condition_config.pop("v2v_tail_easy", None) # given last 65 frames mask_cond_options = list(condition_config.keys()) # list of mask conditions mask_cond_weights = list(condition_config.values()) # corresponding probabilities for i in range(B): # Randomly select a mask condition based on the provided probabilities mask_cond = random.choices(mask_cond_options, weights=mask_cond_weights, k=1)[0] # Apply the selected mask condition directly on the masks tensor if mask_cond == "i2v_head": # NOTE: modify video, mask first latent frame masks[i, :, 0, :, :] = 1 x_0[i] = model_ae.encode(x[i].unsqueeze(0))[0] # condition: encode the image only latent[i, :, :1, :, :] = model_ae.encode(x[i, :, :1, :, :].unsqueeze(0)) elif mask_cond == "i2v_loop": # # NOTE: modify video, mask first and last latent frame # pad video such that first and last latent frame correspond to image only masks[i, :, 0, :, :] = 1 masks[i, :, -1, :, :] = 1 x_0[i] = model_ae.encode(x[i].unsqueeze(0))[0] # condition: encode the image only latent[i, :, :1, :, :] = model_ae.encode(x[i, :, :1, :, :].unsqueeze(0)) latent[i, :, -1:, :, :] = model_ae.encode(x[i, :, -1:, :, :].unsqueeze(0)) elif mask_cond == "i2v_tail": # mask the last latent frame masks[i, :, -1, :, :] = 1 x_0[i] = model_ae.encode(x[i].unsqueeze(0))[0] # condition: encode the last image only latent[i, :, -1:, :, :] = model_ae.encode(x[i, :, -1:, :, :].unsqueeze(0)) elif "v2v_head" in mask_cond: # mask the first 33 video frames ref_t = 33 if not "easy" in mask_cond else 65 assert (ref_t - 1) % model_ae.time_compression_ratio == 0 conditioned_t = (ref_t - 1) // model_ae.time_compression_ratio + 1 masks[i, :, :conditioned_t, :, :] = 1 x_0[i] = model_ae.encode(x[i].unsqueeze(0))[0] # encode the first ref_t frame video separately latent[i, :, :conditioned_t, :, :] = model_ae.encode(x[i, :, :ref_t, :, :].unsqueeze(0)) elif "v2v_tail" in mask_cond: # mask the last 32 video frames ref_t = 33 if not "easy" in mask_cond else 65 assert (ref_t - 1) % model_ae.time_compression_ratio == 0 conditioned_t = (ref_t - 1) // model_ae.time_compression_ratio + 1 masks[i, :, -conditioned_t:, :, :] = 1 x_0[i] = model_ae.encode(x[i].unsqueeze(0))[0] # encode the first ref_t frame video separately latent[i, :, -conditioned_t:, :, :] = model_ae.encode(x[i, :, -ref_t:, :, :].unsqueeze(0)) else: # "t2v" is the fallback case where no specific condition is specified assert mask_cond == "t2v", f"Unknown mask condition {mask_cond}" x_0[i] = model_ae.encode(x[i].unsqueeze(0))[0] else: # image x_0 = model_ae.encode(x) # latent video latent = masks * latent # condition latent # merge the masks and the masked_x into a single tensor cond = torch.cat((masks, latent), dim=1) return x_0, cond def get_batch_loss(model_pred, v_t, masks=None): # for I2V, only include the generated frames in loss calculation if masks is not None: # shape [B, T, H, W] num_frames, height, width = masks.shape[-3:] masks = masks[:, :, 0, 0] # only look at [B, T] model_pred = rearrange( model_pred, "b (t h w) (c ph pw) -> b c t (h ph) (w pw)", h=height // 2, w=width // 2, t=num_frames, ph=2, pw=2, ) v_t = rearrange( v_t, "b (t h w) (c ph pw) -> b c t (h ph) (w pw)", h=height // 2, w=width // 2, t=num_frames, ph=2, pw=2, ) batch_loss = 0 for i in range(model_pred.size(0)): pred_val = model_pred[i] target_val = v_t[i] if masks[i][0] == 1 and (not 1 in masks[i][1:-1]): # have front padding pred_val = pred_val[:, 1:] target_val = target_val[:, 1:] if masks[i][-1] == 1 and (not 1 in masks[i][1:-1]): # have tail padding pred_val = pred_val[:, :-1] target_val = target_val[:, :-1] batch_loss += F.mse_loss(pred_val.float(), target_val.float(), reduction="mean") # print(f"mask {masks[i]}, pred_val shape: {pred_val.size()}") loss = batch_loss / model_pred.size(0) else: # use reduction mean so that each batch will have same level of influence regardless of batch size loss = F.mse_loss(model_pred.float(), v_t.float(), reduction="mean") return loss @torch.no_grad() def warmup_ae(model_ae: nn.Module, shapes: list[tuple[int, ...]], device: torch.device, dtype: torch.dtype): progress_bar = tqdm(shapes, desc="Warmup AE", disable=dist.get_rank() != 0) for x_shape in progress_bar: x = torch.randn(*x_shape, device=device, dtype=dtype) _ = model_ae.encode(x) ================================================ FILE: requirements.txt ================================================ torch==2.4.0 torchvision==0.19.0 colossalai>=0.4.4 mmengine>=0.10.3 ftfy>=6.2.0 # for t5 accelerate>=0.29.2 # for t5 av==13.1.0 # for video loading liger-kernel==0.5.2 pandas>=2.0.3 pandarallel>=1.6.5 openai>=1.52.2 wandb>=0.17.0 tensorboard>=2.14.0 pre-commit>=3.5.0 omegaconf>=2.3.0 pyarrow ================================================ FILE: scripts/cnv/meta.py ================================================ import argparse import numpy as np import pandas as pd from pandarallel import pandarallel from torchvision.io.video import read_video from tqdm import tqdm def set_parallel(num_workers: int = None) -> callable: if num_workers == 0: return lambda x, *args, **kwargs: x.progress_apply(*args, **kwargs) else: if num_workers is not None: pandarallel.initialize(progress_bar=True, nb_workers=num_workers) else: pandarallel.initialize(progress_bar=True) return lambda x, *args, **kwargs: x.parallel_apply(*args, **kwargs) def get_video_info(path: str) -> pd.Series: vframes, _, vinfo = read_video(path, pts_unit="sec", output_format="TCHW") num_frames, C, height, width = vframes.shape fps = round(vinfo["video_fps"], 3) aspect_ratio = height / width if width > 0 else np.nan resolution = height * width ret = pd.Series( [height, width, fps, num_frames, aspect_ratio, resolution], index=[ "height", "width", "fps", "num_frames", "aspect_ratio", "resolution", ], dtype=object, ) return ret def parse_args(): parser = argparse.ArgumentParser() parser.add_argument("--input", type=str, required=True, help="Input file path") parser.add_argument("--output", type=str, required=True, help="Output file path") parser.add_argument( "--num_workers", type=int, default=None, help="Number of workers" ) return parser.parse_args() def main(): args = parse_args() input_path = args.input output_path = args.output num_workers = args.num_workers df = pd.read_csv(input_path) tqdm.pandas() apply = set_parallel(num_workers) result = apply(df["path"], get_video_info) for col in result.columns: df[col] = result[col] df.to_csv(output_path, index=False) if __name__ == "__main__": main() ================================================ FILE: scripts/cnv/shard.py ================================================ import os import pandas as pd from tqdm import tqdm try: import dask.dataframe as dd SUPPORT_DASK = True except: SUPPORT_DASK = False def shard_parquet(input_path, k): # 检查输入路径是否存在 if not os.path.exists(input_path): raise FileNotFoundError(f"Input file {input_path} does not exist.") # 读取 Parquet 文件为 Pandas DataFrame if SUPPORT_DASK: df = dd.read_parquet(input_path).compute() else: df = pd.read_parquet(input_path) # 去除指定的列 columns_to_remove = [ "num_frames", "height", "width", "aspect_ratio", "fps", "resolution", ] df = df.drop(columns=[col for col in columns_to_remove if col in df.columns]) # 计算每个分片的大小 total_rows = len(df) rows_per_shard = (total_rows + k - 1) // k # 向上取整 # 创建与原始文件同名的文件夹 base_dir = os.path.dirname(input_path) base_name = os.path.splitext(os.path.basename(input_path))[0] output_dir = os.path.join(base_dir, base_name) os.makedirs(output_dir, exist_ok=True) # 创建分片并保存到文件夹 for i in tqdm(range(k)): start_idx = i * rows_per_shard end_idx = min(start_idx + rows_per_shard, total_rows) shard_df = df.iloc[start_idx:end_idx] if shard_df.empty: continue shard_file_name = f"{i + 1:05d}.parquet" shard_path = os.path.join(output_dir, shard_file_name) shard_df.to_parquet(shard_path, index=False) # print(f"Shard saved to {shard_path}, rows: {len(shard_df)}") if __name__ == "__main__": import argparse parser = argparse.ArgumentParser(description="Shard a Parquet file.") parser.add_argument("input_path", type=str, help="Path to the input Parquet file.") parser.add_argument( "k", type=int, help="Number of shards to create.", default=10000 ) args = parser.parse_args() shard_parquet(args.input_path, args.k) ================================================ FILE: scripts/diffusion/inference.py ================================================ import os import time import warnings from pprint import pformat warnings.filterwarnings("ignore", category=FutureWarning) warnings.filterwarnings("ignore", category=UserWarning) import torch import torch.distributed as dist from colossalai.utils import set_seed from tqdm import tqdm from opensora.acceleration.parallel_states import get_data_parallel_group from opensora.datasets.dataloader import prepare_dataloader from opensora.registry import DATASETS, build_module from opensora.utils.cai import ( get_booster, get_is_saving_process, init_inference_environment, ) from opensora.utils.config import parse_alias, parse_configs from opensora.utils.inference import ( add_fps_info_to_text, add_motion_score_to_text, create_tmp_csv, modify_option_to_t2i, process_and_save, ) from opensora.utils.logger import create_logger, is_main_process from opensora.utils.misc import log_cuda_max_memory, to_torch_dtype from opensora.utils.prompt_refine import refine_prompts from opensora.utils.sampling import ( SamplingOption, prepare_api, prepare_models, sanitize_sampling_option, ) @torch.inference_mode() def main(): # ====================================================== # 1. configs & runtime variables # ====================================================== torch.set_grad_enabled(False) # == parse configs == cfg = parse_configs() cfg = parse_alias(cfg) # == device and dtype == device = "cuda" if torch.cuda.is_available() else "cpu" dtype = to_torch_dtype(cfg.get("dtype", "bf16")) seed = cfg.get("seed", 1024) if seed is not None: set_seed(seed) # == init distributed env == init_inference_environment() logger = create_logger() logger.info("Inference configuration:\n %s", pformat(cfg.to_dict())) is_saving_process = get_is_saving_process(cfg) booster = get_booster(cfg) booster_ae = get_booster(cfg, ae=True) # ====================================================== # 2. build dataset and dataloader # ====================================================== logger.info("Building dataset...") # save directory save_dir = cfg.save_dir os.makedirs(save_dir, exist_ok=True) # == build dataset == if cfg.get("prompt"): cfg.dataset.data_path = create_tmp_csv(save_dir, cfg.prompt, cfg.get("ref", None), create=is_main_process()) dist.barrier() dataset = build_module(cfg.dataset, DATASETS) # range selection start_index = cfg.get("start_index", 0) end_index = cfg.get("end_index", None) if end_index is None: end_index = start_index + cfg.get("num_samples", len(dataset.data) + 1) dataset.data = dataset.data[start_index:end_index] logger.info("Dataset contains %s samples.", len(dataset)) # == build dataloader == dataloader_args = dict( dataset=dataset, batch_size=cfg.get("batch_size", 1), num_workers=cfg.get("num_workers", 4), seed=cfg.get("seed", 1024), shuffle=False, drop_last=False, pin_memory=True, process_group=get_data_parallel_group(), prefetch_factor=cfg.get("prefetch_factor", None), ) dataloader, _ = prepare_dataloader(**dataloader_args) # == prepare default params == sampling_option = SamplingOption(**cfg.sampling_option) sampling_option = sanitize_sampling_option(sampling_option) cond_type = cfg.get("cond_type", "t2v") prompt_refine = cfg.get("prompt_refine", False) fps_save = cfg.get("fps_save", 16) num_sample = cfg.get("num_sample", 1) type_name = "image" if cfg.sampling_option.num_frames == 1 else "video" sub_dir = f"{type_name}_{cfg.sampling_option.resolution}" os.makedirs(os.path.join(save_dir, sub_dir), exist_ok=True) use_t2i2v = cfg.get("use_t2i2v", False) img_sub_dir = os.path.join(sub_dir, "generated_condition") if use_t2i2v: os.makedirs(os.path.join(save_dir, sub_dir, "generated_condition"), exist_ok=True) # ====================================================== # 3. build model # ====================================================== logger.info("Building models...") # == build flux model == model, model_ae, model_t5, model_clip, optional_models = prepare_models( cfg, device, dtype, offload_model=cfg.get("offload_model", False) ) log_cuda_max_memory("build model") if booster: model, _, _, _, _ = booster.boost(model=model) model = model.unwrap() if booster_ae: model_ae, _, _, _, _ = booster_ae.boost(model=model_ae) model_ae = model_ae.unwrap() api_fn = prepare_api(model, model_ae, model_t5, model_clip, optional_models) # prepare image flux model if t2i2v if use_t2i2v: api_fn_img = prepare_api( optional_models["img_flux"], optional_models["img_flux_ae"], model_t5, model_clip, optional_models ) # ====================================================== # 4. inference # ====================================================== for epoch in range(num_sample): # generate multiple samples with different seeds dataloader_iter = iter(dataloader) with tqdm( enumerate(dataloader_iter, start=0), desc="Inference progress", disable=not is_main_process(), initial=0, total=len(dataloader), ) as pbar: for _, batch in pbar: original_text = batch.pop("text") if use_t2i2v: batch["text"] = original_text if not prompt_refine else refine_prompts(original_text, type="t2i") sampling_option_t2i = modify_option_to_t2i( sampling_option, distilled=True, img_resolution=cfg.get("img_resolution", "768px"), ) if cfg.get("offload_model", False): model_move_start = time.time() model = model.to("cpu", dtype) model_ae = model_ae.to("cpu", dtype) optional_models["img_flux"].to(device, dtype) optional_models["img_flux_ae"].to(device, dtype) logger.info( "offload video diffusion model to cpu, load image flux model to gpu: %s s", time.time() - model_move_start, ) logger.info("Generating image condition by flux...") x_cond = api_fn_img( sampling_option_t2i, "t2v", seed=sampling_option.seed + epoch if sampling_option.seed else None, channel=cfg["img_flux"]["in_channels"], **batch, ).cpu() # save image to disk batch["name"] = process_and_save( x_cond, batch, cfg, img_sub_dir, sampling_option_t2i, epoch, start_index, saving=is_saving_process, ) dist.barrier() if cfg.get("offload_model", False): model_move_start = time.time() model = model.to(device, dtype) model_ae = model_ae.to(device, dtype) optional_models["img_flux"].to("cpu", dtype) optional_models["img_flux_ae"].to("cpu", dtype) logger.info( "load video diffusion model to gpu, offload image flux model to cpu: %s s", time.time() - model_move_start, ) ref_dir = os.path.join(save_dir, os.path.join(sub_dir, "generated_condition")) batch["ref"] = [os.path.join(ref_dir, f"{x}.png") for x in batch["name"]] cond_type = "i2v_head" batch["text"] = original_text if prompt_refine: batch["text"] = refine_prompts( original_text, type="t2v" if cond_type == "t2v" else "t2i", image_paths=batch.get("ref", None) ) batch["text"] = add_fps_info_to_text(batch.pop("text"), fps=fps_save) if "motion_score" in cfg: batch["text"] = add_motion_score_to_text(batch.pop("text"), cfg.get("motion_score", 5)) logger.info("Generating video...") x = api_fn( sampling_option, cond_type, seed=sampling_option.seed + epoch if sampling_option.seed else None, patch_size=cfg.get("patch_size", 2), save_prefix=cfg.get("save_prefix", ""), channel=cfg["model"]["in_channels"], **batch, ).cpu() if is_saving_process: process_and_save(x, batch, cfg, sub_dir, sampling_option, epoch, start_index) dist.barrier() logger.info("Inference finished.") log_cuda_max_memory("inference") if __name__ == "__main__": main() ================================================ FILE: scripts/diffusion/train.py ================================================ import gc import math import os import subprocess import warnings from contextlib import nullcontext from copy import deepcopy from pprint import pformat warnings.filterwarnings("ignore", category=FutureWarning) warnings.filterwarnings("ignore", category=UserWarning) gc.disable() import torch import torch.distributed as dist import torch.nn.functional as F import wandb from colossalai.booster import Booster from colossalai.utils import set_seed from peft import LoraConfig from tqdm import tqdm from opensora.acceleration.checkpoint import ( GLOBAL_ACTIVATION_MANAGER, set_grad_checkpoint, ) from opensora.acceleration.parallel_states import get_data_parallel_group from opensora.datasets.aspect import bucket_to_shapes from opensora.datasets.dataloader import prepare_dataloader from opensora.datasets.pin_memory_cache import PinMemoryCache from opensora.models.mmdit.distributed import MMDiTPolicy from opensora.registry import DATASETS, MODELS, build_module from opensora.utils.ckpt import ( CheckpointIO, model_sharding, record_model_param_shape, rm_checkpoints, ) from opensora.utils.config import ( config_to_name, create_experiment_workspace, parse_configs, ) from opensora.utils.logger import create_logger from opensora.utils.misc import ( NsysProfiler, Timers, all_reduce_mean, create_tensorboard_writer, is_log_process, is_pipeline_enabled, log_cuda_max_memory, log_cuda_memory, log_model_params, print_mem, to_torch_dtype, ) from opensora.utils.optimizer import create_lr_scheduler, create_optimizer from opensora.utils.sampling import ( get_res_lin_function, pack, prepare, prepare_ids, time_shift, ) from opensora.utils.train import ( create_colossalai_plugin, dropout_condition, get_batch_loss, prepare_visual_condition_causal, prepare_visual_condition_uncausal, set_eps, set_lr, setup_device, update_ema, warmup_ae, ) torch.backends.cudnn.benchmark = False # True leads to slow down in conv3d def main(): # ====================================================== # 1. configs & runtime variables # ====================================================== # == parse configs == cfg = parse_configs() # == get dtype & device == dtype = to_torch_dtype(cfg.get("dtype", "bf16")) device, coordinator = setup_device() grad_ckpt_buffer_size = cfg.get("grad_ckpt_buffer_size", 0) if grad_ckpt_buffer_size > 0: GLOBAL_ACTIVATION_MANAGER.setup_buffer(grad_ckpt_buffer_size, dtype) checkpoint_io = CheckpointIO() set_seed(cfg.get("seed", 1024)) PinMemoryCache.force_dtype = dtype pin_memory_cache_pre_alloc_numels = cfg.get("pin_memory_cache_pre_alloc_numels", None) PinMemoryCache.pre_alloc_numels = pin_memory_cache_pre_alloc_numels # == init ColossalAI booster == plugin_type = cfg.get("plugin", "zero2") plugin_config = cfg.get("plugin_config", {}) plugin_kwargs = {} if plugin_type == "hybrid": plugin_kwargs["custom_policy"] = MMDiTPolicy plugin = create_colossalai_plugin( plugin=plugin_type, dtype=cfg.get("dtype", "bf16"), grad_clip=cfg.get("grad_clip", 0), **plugin_config, **plugin_kwargs, ) booster = Booster(plugin=plugin) seq_align = plugin_config.get("sp_size", 1) # == init exp_dir == exp_name, exp_dir = create_experiment_workspace( cfg.get("outputs", "./outputs"), model_name=config_to_name(cfg), config=cfg.to_dict(), exp_name=cfg.get("exp_name", None), # useful for automatic restart to specify the exp_name ) if is_log_process(plugin_type, plugin_config): print(f"changing {exp_dir} to share") os.system(f"chgrp -R share {exp_dir}") # == init logger, tensorboard & wandb == logger = create_logger(exp_dir) logger.info("Training configuration:\n %s", pformat(cfg.to_dict())) tb_writer = None if coordinator.is_master(): tb_writer = create_tensorboard_writer(exp_dir) if cfg.get("wandb", False): wandb.init( project=cfg.get("wandb_project", "Open-Sora"), name=exp_name, config=cfg.to_dict(), dir=exp_dir, ) num_gpus = dist.get_world_size() if dist.is_initialized() else 1 tp_size = cfg["plugin_config"].get("tp_size", 1) sp_size = cfg["plugin_config"].get("sp_size", 1) pp_size = cfg["plugin_config"].get("pp_size", 1) num_groups = num_gpus // (tp_size * sp_size * pp_size) logger.info("Number of GPUs: %s", num_gpus) logger.info("Number of groups: %s", num_groups) # ====================================================== # 2. build dataset and dataloader # ====================================================== logger.info("Building dataset...") # == build dataset == dataset = build_module(cfg.dataset, DATASETS) logger.info("Dataset contains %s samples.", len(dataset)) # == build dataloader == cache_pin_memory = pin_memory_cache_pre_alloc_numels is not None dataloader_args = dict( dataset=dataset, batch_size=cfg.get("batch_size", None), num_workers=cfg.get("num_workers", 4), seed=cfg.get("seed", 1024), shuffle=True, drop_last=True, pin_memory=True, process_group=get_data_parallel_group(), prefetch_factor=cfg.get("prefetch_factor", None), cache_pin_memory=cache_pin_memory, num_groups=num_groups, ) print_mem("before prepare_dataloader") dataloader, sampler = prepare_dataloader( bucket_config=cfg.get("bucket_config", None), num_bucket_build_workers=cfg.get("num_bucket_build_workers", 1), **dataloader_args, ) print_mem("after prepare_dataloader") num_steps_per_epoch = len(dataloader) dataset.to_efficient() # ====================================================== # 3. build model # ====================================================== logger.info("Building models...") # == build model model == model = build_module(cfg.model, MODELS, device_map=device, torch_dtype=dtype).train() if cfg.get("grad_checkpoint", True): set_grad_checkpoint(model) log_cuda_memory("diffusion") log_model_params(model) # == build EMA model == use_lora = cfg.get("lora_config", None) is not None if cfg.get("ema_decay", None) is not None and not use_lora: ema = deepcopy(model).cpu().eval().requires_grad_(False) ema_shape_dict = record_model_param_shape(ema) logger.info("EMA model created.") else: ema = ema_shape_dict = None logger.info("No EMA model created.") log_cuda_memory("EMA") # == enable LoRA == if use_lora: lora_config = LoraConfig(**cfg.get("lora_config", None)) model = booster.enable_lora( model=model, lora_config=lora_config, pretrained_dir=cfg.get("lora_checkpoint", None), ) log_cuda_memory("lora") log_model_params(model) if not cfg.get("cached_video", False): # == buildn autoencoder == model_ae = build_module(cfg.ae, MODELS, device_map=device, torch_dtype=dtype).eval().requires_grad_(False) del model_ae.decoder log_cuda_memory("autoencoder") log_model_params(model_ae) model_ae.encode = torch.compile(model_ae.encoder, dynamic=True) if not cfg.get("cached_text", False): # == build text encoder (t5) == model_t5 = build_module(cfg.t5, MODELS, device_map=device, torch_dtype=dtype).eval().requires_grad_(False) log_cuda_memory("t5") log_model_params(model_t5) # == build text encoder (clip) == model_clip = build_module(cfg.clip, MODELS, device_map=device, torch_dtype=dtype).eval().requires_grad_(False) log_cuda_memory("clip") log_model_params(model_clip) # == setup optimizer == optimizer = create_optimizer(model, cfg.optim) # == setup lr scheduler == lr_scheduler = create_lr_scheduler( optimizer=optimizer, num_steps_per_epoch=num_steps_per_epoch, epochs=cfg.get("epochs", 1000), warmup_steps=cfg.get("warmup_steps", None), use_cosine_scheduler=cfg.get("use_cosine_scheduler", False), ) log_cuda_memory("optimizer") # == prepare null vectors for dropout == if cfg.get("cached_text", False): null_txt = torch.load("/mnt/ddn/sora/tmp_load/null_t5.pt", map_location=device) null_vec = torch.load("/mnt/ddn/sora/tmp_load/null_clip.pt", map_location=device) else: null_txt = model_t5("") null_vec = model_clip("") # ======================================================= # 4. distributed training preparation with colossalai # ======================================================= logger.info("Preparing for distributed training...") # == boosting == torch.set_default_dtype(dtype) model, optimizer, _, dataloader, lr_scheduler = booster.boost( model=model, optimizer=optimizer, lr_scheduler=lr_scheduler, dataloader=dataloader, ) torch.set_default_dtype(torch.float) logger.info("Boosted model for distributed training") log_cuda_memory("boost") # == global variables == cfg_epochs = cfg.get("epochs", 1000) log_step = acc_step = 0 running_loss = 0.0 timers = Timers(record_time=cfg.get("record_time", False), record_barrier=cfg.get("record_barrier", False)) nsys = NsysProfiler( warmup_steps=cfg.get("nsys_warmup_steps", 2), num_steps=cfg.get("nsys_num_steps", 2), enabled=cfg.get("nsys", False), ) logger.info("Training for %s epochs with %s steps per epoch", cfg_epochs, num_steps_per_epoch) # == resume == load_master_weights = cfg.get("load_master_weights", False) save_master_weights = cfg.get("save_master_weights", False) start_epoch = cfg.get("start_epoch", None) start_step = cfg.get("start_step", None) if cfg.get("load", None) is not None: logger.info("Loading checkpoint from %s", cfg.load) lr_scheduler_to_load = lr_scheduler if cfg.get("update_warmup_steps", False): lr_scheduler_to_load = None ret = checkpoint_io.load( booster, cfg.load, model=model, ema=ema, optimizer=optimizer, lr_scheduler=lr_scheduler_to_load, sampler=( None if start_step is not None else sampler ), # if specify start step, set last_micro_batch_access_index of a new sampler instead include_master_weights=load_master_weights, ) start_epoch = start_epoch if start_epoch is not None else ret[0] start_step = start_step if start_step is not None else ret[1] logger.info("Loaded checkpoint %s at epoch %s step %s", cfg.load, ret[0], ret[1]) # load optimizer and scheduler will overwrite some of the hyperparameters, so we need to reset them set_lr(optimizer, lr_scheduler, cfg.optim.lr, cfg.get("initial_lr", None)) set_eps(optimizer, cfg.optim.eps) if cfg.get("update_warmup_steps", False): assert ( cfg.get("warmup_steps", None) is not None ), "you need to set warmup_steps in order to pass --update-warmup-steps True" # set_warmup_steps(lr_scheduler, cfg.warmup_steps) lr_scheduler.step(start_epoch * num_steps_per_epoch + start_step) logger.info("The learning rate starts from %s", optimizer.param_groups[0]["lr"]) if start_step is not None: # if start step exceeds data length, go to next epoch if start_step > num_steps_per_epoch: start_epoch = ( start_epoch + start_step // num_steps_per_epoch if start_epoch is not None else start_step // num_steps_per_epoch ) start_step = start_step % num_steps_per_epoch else: start_step = 0 sampler.set_step(start_step) start_epoch = start_epoch if start_epoch is not None else 0 logger.info("Starting from epoch %s step %s", start_epoch, start_step) # == sharding EMA model == if ema is not None: model_sharding(ema) ema = ema.to(device) log_cuda_memory("sharding EMA") # == warmup autoencoder == if cfg.get("warmup_ae", False): shapes = bucket_to_shapes(cfg.get("bucket_config", None), batch_size=cfg.ae.batch_size) warmup_ae(model_ae, shapes, device, dtype) # ======================================================= # 5. training iter # ======================================================= sigma_min = cfg.get("sigma_min", 1e-5) accumulation_steps = cfg.get("accumulation_steps", 1) ckpt_every = cfg.get("ckpt_every", 0) if cfg.get("is_causal_vae", False): prepare_visual_condition = prepare_visual_condition_causal else: prepare_visual_condition = prepare_visual_condition_uncausal @torch.no_grad() def prepare_inputs(batch): inp = dict() x = batch.pop("video") y = batch.pop("text") bs = x.shape[0] # == encode video == with nsys.range("encode_video"), timers["encode_video"]: # == prepare condition == if cfg.get("condition_config", None) is not None: # condition for i2v & v2v x_0, cond = prepare_visual_condition(x, cfg.condition_config, model_ae) cond = pack(cond, patch_size=cfg.get("patch_size", 2)) inp["cond"] = cond else: if cfg.get("cached_video", False): x_0 = batch.pop("video_latents").to(device=device, dtype=dtype) else: x_0 = model_ae.encode(x) # == prepare timestep == # follow SD3 time shift, shift_alpha = 1 for 256px and shift_alpha = 3 for 1024px shift_alpha = get_res_lin_function()((x_0.shape[-1] * x_0.shape[-2]) // 4) # add temporal influence shift_alpha *= math.sqrt(x_0.shape[-3]) # for image, T=1 so no effect t = torch.sigmoid(torch.randn((bs), device=device)) t = time_shift(shift_alpha, t).to(dtype) if cfg.get("cached_text", False): # == encode text == t5_embedding = batch.pop("text_t5").to(device=device, dtype=dtype) clip_embedding = batch.pop("text_clip").to(device=device, dtype=dtype) with nsys.range("encode_text"), timers["encode_text"]: inp_ = prepare_ids(x_0, t5_embedding, clip_embedding) inp.update(inp_) x_0 = pack(x_0, patch_size=cfg.get("patch_size", 2)) else: # == encode text == with nsys.range("encode_text"), timers["encode_text"]: inp_ = prepare( model_t5, model_clip, x_0, prompt=y, seq_align=seq_align, patch_size=cfg.get("patch_size", 2), ) inp.update(inp_) x_0 = pack(x_0, patch_size=cfg.get("patch_size", 2)) # == dropout == if cfg.get("dropout_ratio", None) is not None: cur_null_txt = null_txt num_pad_null_txt = inp["txt"].shape[1] - cur_null_txt.shape[1] if num_pad_null_txt > 0: cur_null_txt = torch.cat([cur_null_txt] + [cur_null_txt[:, -1:]] * num_pad_null_txt, dim=1) inp["txt"] = dropout_condition( cfg.dropout_ratio.get("t5", 0.0), inp["txt"], cur_null_txt, ) inp["y_vec"] = dropout_condition( cfg.dropout_ratio.get("clip", 0.0), inp["y_vec"], null_vec, ) # == prepare noise vector == x_1 = torch.randn_like(x_0, dtype=torch.float32).to(device, dtype) t_rev = 1 - t x_t = t_rev[:, None, None] * x_0 + (1 - (1 - sigma_min) * t_rev[:, None, None]) * x_1 inp["img"] = x_t inp["timesteps"] = t.to(dtype) inp["guidance"] = torch.full((x_t.shape[0],), cfg.get("guidance", 4), device=x_t.device, dtype=x_t.dtype) return inp, x_0, x_1 def run_iter(inp, x_0, x_1): if is_pipeline_enabled(plugin_type, plugin_config): inp["target"] = (1 - sigma_min) * x_1 - x_0 # follow MovieGen, modify V_t accordingly with nsys.range("forward-backward"), timers["forward-backward"]: data_iter = iter([inp]) if cfg.get("no_i2v_ref_loss", False): loss_fn = ( lambda out, input_: get_batch_loss(out, input_["target"], input_.pop("masks", None)) / accumulation_steps ) else: loss_fn = ( lambda out, input_: F.mse_loss(out.float(), input_["target"].float(), reduction="mean") / accumulation_steps ) loss = booster.execute_pipeline(data_iter, model, loss_fn, optimizer)["loss"] loss = loss * accumulation_steps if loss is not None else loss loss_item = all_reduce_mean(loss.data.clone().detach()) else: with nsys.range("forward"), timers["forward"]: model_pred = model(**inp) # B, T, L v_t = (1 - sigma_min) * x_1 - x_0 if cfg.get("no_i2v_ref_loss", False): loss = get_batch_loss(model_pred, v_t, inp.pop("masks", None)) else: loss = F.mse_loss(model_pred.float(), v_t.float(), reduction="mean") loss_item = all_reduce_mean(loss.data.clone().detach()).item() # == backward & update == dist.barrier() with nsys.range("backward"), timers["backward"]: ctx = ( booster.no_sync(model, optimizer) if cfg.get("plugin", "zero2") in ("zero1", "zero1-seq") and (step + 1) % accumulation_steps != 0 else nullcontext() ) with ctx: booster.backward(loss=(loss / accumulation_steps), optimizer=optimizer) with nsys.range("optim"), timers["optim"]: if (step + 1) % accumulation_steps == 0: booster.checkpoint_io.synchronize() optimizer.step() optimizer.zero_grad() if lr_scheduler is not None: lr_scheduler.step() # == update EMA == if ema is not None: with nsys.range("update_ema"), timers["update_ema"]: update_ema( ema, model.unwrap(), optimizer=optimizer, decay=cfg.get("ema_decay", 0.9999), ) return loss_item # ======================================================= # 6. training loop # ======================================================= dist.barrier() for epoch in range(start_epoch, cfg_epochs): # == set dataloader to new epoch == sampler.set_epoch(epoch) dataloader_iter = iter(dataloader) logger.info("Beginning epoch %s...", epoch) # == training loop in an epoch == with tqdm( enumerate(dataloader_iter, start=start_step), desc=f"Epoch {epoch}", disable=not is_log_process(plugin_type, plugin_config), initial=start_step, total=num_steps_per_epoch, ) as pbar: pbar_iter = iter(pbar) # prefetch one for non-blocking data loading def fetch_data(): step, batch = next(pbar_iter) # print(f"==debug== rank{dist.get_rank()} {dataloader_iter.get_cache_info()}") pinned_video = batch["video"] batch["video"] = pinned_video.to(device, dtype, non_blocking=True) return batch, step, pinned_video batch_, step_, pinned_video_ = fetch_data() for _ in range(start_step, num_steps_per_epoch): nsys.step() # == load data === with nsys.range("load_data"), timers["load_data"]: batch, step, pinned_video = batch_, step_, pinned_video_ if step + 1 < num_steps_per_epoch: # only fetch new data if not last step batch_, step_, pinned_video_ = fetch_data() # == run iter == with nsys.range("iter"), timers["iter"]: inp, x_0, x_1 = prepare_inputs(batch) if cache_pin_memory: dataloader_iter.remove_cache(pinned_video) loss = run_iter(inp, x_0, x_1) # == update log info == if loss is not None: running_loss += loss # == log config == global_step = epoch * num_steps_per_epoch + step actual_update_step = (global_step + 1) // accumulation_steps log_step += 1 acc_step += 1 # == logging == if (global_step + 1) % accumulation_steps == 0: if actual_update_step % cfg.get("log_every", 1) == 0: if is_log_process(plugin_type, plugin_config): avg_loss = running_loss / log_step # progress bar pbar.set_postfix( { "loss": avg_loss, "global_grad_norm": optimizer.get_grad_norm(), "step": step, "global_step": global_step, # "actual_update_step": actual_update_step, "lr": optimizer.param_groups[0]["lr"], } ) # tensorboard if tb_writer is not None: tb_writer.add_scalar("loss", loss, actual_update_step) # wandb if cfg.get("wandb", False): wandb_dict = { "iter": global_step, "acc_step": acc_step, "epoch": epoch, "loss": loss, "avg_loss": avg_loss, "lr": optimizer.param_groups[0]["lr"], "eps": optimizer.param_groups[0]["eps"], "global_grad_norm": optimizer.get_grad_norm(), # test grad norm } if cfg.get("record_time", False): wandb_dict.update(timers.to_dict()) wandb.log(wandb_dict, step=actual_update_step) running_loss = 0.0 log_step = 0 # == checkpoint saving == # uncomment below 3 lines to forcely clean cache with nsys.range("clean_cache"), timers["clean_cache"]: if ckpt_every > 0 and actual_update_step % ckpt_every == 0 and coordinator.is_master(): subprocess.run("sudo drop_cache", shell=True) with nsys.range("checkpoint"), timers["checkpoint"]: if ckpt_every > 0 and actual_update_step % ckpt_every == 0: # mannual garbage collection gc.collect() save_dir = checkpoint_io.save( booster, exp_dir, model=model, ema=ema, optimizer=optimizer, lr_scheduler=lr_scheduler, sampler=sampler, epoch=epoch, step=step + 1, global_step=global_step + 1, batch_size=cfg.get("batch_size", None), lora=use_lora, actual_update_step=actual_update_step, ema_shape_dict=ema_shape_dict, async_io=cfg.get("async_io", False), include_master_weights=save_master_weights, ) if is_log_process(plugin_type, plugin_config): os.system(f"chgrp -R share {save_dir}") logger.info( "Saved checkpoint at epoch %s, step %s, global_step %s to %s", epoch, step + 1, actual_update_step, save_dir, ) # remove old checkpoints rm_checkpoints(exp_dir, keep_n_latest=cfg.get("keep_n_latest", -1)) logger.info("Removed old checkpoints and kept %s latest ones.", cfg.get("keep_n_latest", -1)) # uncomment below 3 lines to benchmark checkpoint # if ckpt_every > 0 and actual_update_step % ckpt_every == 0: # booster.checkpoint_io._sync_io() # checkpoint_io._sync_io() # == terminal timer == if cfg.get("record_time", False): print(timers.to_str(epoch, step)) sampler.reset() start_step = 0 log_cuda_max_memory("final") if __name__ == "__main__": main() ================================================ FILE: scripts/vae/inference.py ================================================ import os from pprint import pformat import colossalai import torch from colossalai.utils import get_current_device, set_seed from tqdm import tqdm from opensora.acceleration.parallel_states import get_data_parallel_group from opensora.datasets import save_sample from opensora.datasets.dataloader import prepare_dataloader from opensora.registry import DATASETS, MODELS, build_module from opensora.utils.config import parse_configs from opensora.utils.logger import create_logger, is_distributed, is_main_process from opensora.utils.misc import log_cuda_max_memory, log_model_params, to_torch_dtype @torch.inference_mode() def main(): torch.set_grad_enabled(False) # ====================================================== # configs & runtime variables # ====================================================== # == parse configs == cfg = parse_configs() # == get dtype & device == dtype = to_torch_dtype(cfg.get("dtype", "fp32")) device = "cuda" if torch.cuda.is_available() else "cpu" if is_distributed(): colossalai.launch_from_torch({}) device = get_current_device() set_seed(cfg.get("seed", 1024)) # == init logger == logger = create_logger() logger.info("Inference configuration:\n %s", pformat(cfg.to_dict())) verbose = cfg.get("verbose", 1) # ====================================================== # build model & loss # ====================================================== if cfg.get("ckpt_path", None) is not None: cfg.model.from_pretrained = cfg.ckpt_path logger.info("Building models...") model = build_module(cfg.model, MODELS, device_map=device, torch_dtype=dtype).eval() log_model_params(model) # ====================================================== # build dataset and dataloader # ====================================================== logger.info("Building dataset...") # == build dataset == dataset = build_module(cfg.dataset, DATASETS) logger.info("Dataset contains %s samples.", len(dataset)) # == build dataloader == dataloader_args = dict( dataset=dataset, batch_size=cfg.get("batch_size", None), num_workers=cfg.get("num_workers", 4), seed=cfg.get("seed", 1024), shuffle=False, drop_last=False, pin_memory=True, process_group=get_data_parallel_group(), prefetch_factor=cfg.get("prefetch_factor", None), ) if cfg.get("eval_setting", None) is not None: # e.g. 32x256, 1x1024 num_frames = int(cfg.eval_setting.split("x")[0]) resolution = str(cfg.eval_setting.split("x")[-1]) bucket_config = { resolution + "px" + "_ar1:1": {num_frames: (1.0, 1)}, } print("eval setting:\n", bucket_config) else: bucket_config = cfg.get("bucket_config", None) dataloader, sampler = prepare_dataloader( bucket_config=bucket_config, num_bucket_build_workers=cfg.get("num_bucket_build_workers", 1), **dataloader_args, ) dataiter = iter(dataloader) num_steps_per_epoch = len(dataloader) # ====================================================== # inference # ====================================================== # prepare arguments save_fps = cfg.get("fps", 16) // cfg.get("frame_interval", 1) save_dir = cfg.get("save_dir", None) save_dir_orig = os.path.join(save_dir, "orig") save_dir_recn = os.path.join(save_dir, "recn") os.makedirs(save_dir_orig, exist_ok=True) os.makedirs(save_dir_recn, exist_ok=True) running_sum = running_var = 0.0 num_samples = 0 # Iter over the dataset with tqdm( enumerate(dataiter), disable=not is_main_process() or verbose < 1, total=num_steps_per_epoch, initial=0, ) as pbar: for _, batch in pbar: # == load data == x = batch["video"].to(device, dtype) # [B, C, T, H, W] path = batch["path"] # == vae encoding & decoding === x_rec, posterior, z = model(x) num_samples += 1 running_sum += z.mean() running_var += (z - running_sum / num_samples).pow(2).mean() if num_samples % 10 == 0: logger.info( "VAE feature per channel stats: mean %s, var %s", (running_sum / num_samples).item(), (running_var / num_samples).sqrt().item(), ) # == save samples == if is_main_process() and save_dir is not None: for idx, x_orig in enumerate(x): fname = os.path.splitext(os.path.basename(path[idx]))[0] save_path_orig = os.path.join(save_dir_orig, f"{fname}_orig") save_sample(x_orig, save_path=save_path_orig, fps=save_fps) save_path_rec = os.path.join(save_dir_recn, f"{fname}_recn") save_sample(x_rec[idx], save_path=save_path_rec, fps=save_fps) logger.info("Inference finished.") log_cuda_max_memory("inference") if __name__ == "__main__": main() ================================================ FILE: scripts/vae/stats.py ================================================ from pprint import pformat import colossalai import torch from colossalai.utils import get_current_device, set_seed from tqdm import tqdm from opensora.acceleration.parallel_states import get_data_parallel_group from opensora.datasets.dataloader import prepare_dataloader from opensora.registry import DATASETS, MODELS, build_module from opensora.utils.config import parse_configs from opensora.utils.logger import create_logger, is_distributed, is_main_process from opensora.utils.misc import log_cuda_max_memory, log_model_params, to_torch_dtype @torch.inference_mode() def main(): torch.set_grad_enabled(False) # ====================================================== # configs & runtime variables # ====================================================== # == parse configs == cfg = parse_configs() # == get dtype & device == dtype = to_torch_dtype(cfg.get("dtype", "bf16")) device = "cuda" if torch.cuda.is_available() else "cpu" if is_distributed(): colossalai.launch_from_torch({}) device = get_current_device() set_seed(cfg.get("seed", 1024)) # == init logger == logger = create_logger() logger.info("Inference configuration:\n %s", pformat(cfg.to_dict())) verbose = cfg.get("verbose", 1) # ====================================================== # build model & loss # ====================================================== if cfg.get("ckpt_path", None) is not None: cfg.model.from_pretrained = cfg.ckpt_path logger.info("Building models...") model = build_module(cfg.model, MODELS, device_map=device, torch_dtype=dtype).eval() log_model_params(model) # ====================================================== # build dataset and dataloader # ====================================================== logger.info("Building dataset...") # == build dataset == dataset = build_module(cfg.dataset, DATASETS) logger.info("Dataset contains %s samples.", len(dataset)) # == build dataloader == dataloader_args = dict( dataset=dataset, batch_size=cfg.get("batch_size", None), num_workers=cfg.get("num_workers", 4), seed=cfg.get("seed", 1024), shuffle=False, drop_last=False, pin_memory=True, process_group=get_data_parallel_group(), prefetch_factor=cfg.get("prefetch_factor", None), ) if cfg.get("eval_setting", None) is not None: # e.g. 32x256x256, 1x1024x1024 num_frames = int(cfg.eval_setting.split("x")[0]) resolution = str(cfg.eval_setting.split("x")[-1]) bucket_config = { resolution + "px_ar1:1": {num_frames: (1.0, 1)}, } print("eval setting:\n", bucket_config) else: bucket_config = cfg.get("bucket_config", None) dataloader, _ = prepare_dataloader( bucket_config=bucket_config, num_bucket_build_workers=cfg.get("num_bucket_build_workers", 1), **dataloader_args, ) dataiter = iter(dataloader) num_steps_per_epoch = len(dataloader) # ====================================================== # inference # ====================================================== num_samples = 0 running_sum = running_var = 0.0 # Iter over the dataset with tqdm( enumerate(dataiter), disable=not is_main_process() or verbose < 1, total=num_steps_per_epoch, initial=0, ) as pbar: for _, batch in pbar: # == load data == x = batch["video"].to(device, dtype) # [B, C, T, H, W] # == vae encoding & decoding === z = model.encode(x) num_samples += 1 running_sum += z.mean().item() running_var += (z - running_sum / num_samples).pow(2).mean().item() shift = running_sum / num_samples scale = (running_var / num_samples) ** 0.5 pbar.set_postfix({"mean": shift, "std": scale}) logger.info("Mean: %.4f, std: %.4f", shift, scale) log_cuda_max_memory("inference") if __name__ == "__main__": main() ================================================ FILE: scripts/vae/train.py ================================================ import gc import os import random import subprocess import warnings from contextlib import nullcontext from copy import deepcopy from pprint import pformat warnings.filterwarnings("ignore", category=FutureWarning) warnings.filterwarnings("ignore", category=UserWarning) gc.disable() import torch import torch.distributed as dist from colossalai.booster import Booster from colossalai.utils import set_seed from torch.profiler import ProfilerActivity, profile, schedule from tqdm import tqdm import wandb from opensora.acceleration.checkpoint import set_grad_checkpoint from opensora.acceleration.parallel_states import get_data_parallel_group from opensora.datasets.dataloader import prepare_dataloader from opensora.datasets.pin_memory_cache import PinMemoryCache from opensora.models.vae.losses import DiscriminatorLoss, GeneratorLoss, VAELoss from opensora.registry import DATASETS, MODELS, build_module from opensora.utils.ckpt import CheckpointIO, model_sharding, record_model_param_shape, rm_checkpoints from opensora.utils.config import config_to_name, create_experiment_workspace, parse_configs from opensora.utils.logger import create_logger from opensora.utils.misc import ( Timer, all_reduce_sum, create_tensorboard_writer, is_log_process, log_model_params, to_torch_dtype, ) from opensora.utils.optimizer import create_lr_scheduler, create_optimizer from opensora.utils.train import create_colossalai_plugin, set_lr, set_warmup_steps, setup_device, update_ema torch.backends.cudnn.benchmark = True WAIT = 1 WARMUP = 10 ACTIVE = 20 my_schedule = schedule( wait=WAIT, # number of warmup steps warmup=WARMUP, # number of warmup steps with profiling active=ACTIVE, # number of active steps with profiling ) def main(): # ====================================================== # 1. configs & runtime variables # ====================================================== # == parse configs == cfg = parse_configs() # == get dtype & device == dtype = to_torch_dtype(cfg.get("dtype", "bf16")) device, coordinator = setup_device() checkpoint_io = CheckpointIO() set_seed(cfg.get("seed", 1024)) PinMemoryCache.force_dtype = dtype pin_memory_cache_pre_alloc_numels = cfg.get("pin_memory_cache_pre_alloc_numels", None) PinMemoryCache.pre_alloc_numels = pin_memory_cache_pre_alloc_numels # == init ColossalAI booster == plugin_type = cfg.get("plugin", "zero2") plugin_config = cfg.get("plugin_config", {}) plugin = ( create_colossalai_plugin( plugin=plugin_type, dtype=cfg.get("dtype", "bf16"), grad_clip=cfg.get("grad_clip", 0), **plugin_config, ) if plugin_type != "none" else None ) booster = Booster(plugin=plugin) # == init exp_dir == exp_name, exp_dir = create_experiment_workspace( cfg.get("outputs", "./outputs"), model_name=config_to_name(cfg), config=cfg.to_dict(), ) if is_log_process(plugin_type, plugin_config): print(f"changing {exp_dir} to share") os.system(f"chgrp -R share {exp_dir}") # == init logger, tensorboard & wandb == logger = create_logger(exp_dir) logger.info("Training configuration:\n %s", pformat(cfg.to_dict())) tb_writer = None if coordinator.is_master(): tb_writer = create_tensorboard_writer(exp_dir) if cfg.get("wandb", False): wandb.init( project=cfg.get("wandb_project", "Open-Sora"), name=cfg.get("wandb_expr_name", exp_name), config=cfg.to_dict(), dir=exp_dir, ) # ====================================================== # 2. build dataset and dataloader # ====================================================== logger.info("Building dataset...") # == build dataset == dataset = build_module(cfg.dataset, DATASETS) logger.info("Dataset contains %s samples.", len(dataset)) # == build dataloader == cache_pin_memory = pin_memory_cache_pre_alloc_numels is not None dataloader_args = dict( dataset=dataset, batch_size=cfg.get("batch_size", None), num_workers=cfg.get("num_workers", 4), seed=cfg.get("seed", 1024), shuffle=True, drop_last=True, pin_memory=True, process_group=get_data_parallel_group(), prefetch_factor=cfg.get("prefetch_factor", None), cache_pin_memory=cache_pin_memory, ) dataloader, sampler = prepare_dataloader( bucket_config=cfg.get("bucket_config", None), num_bucket_build_workers=cfg.get("num_bucket_build_workers", 1), **dataloader_args, ) num_steps_per_epoch = len(dataloader) # ====================================================== # 3. build model # ====================================================== logger.info("Building models...") # == build vae model == model = build_module(cfg.model, MODELS, device_map=device, torch_dtype=dtype).train() log_model_params(model) if cfg.get("grad_checkpoint", False): set_grad_checkpoint(model) vae_loss_fn = VAELoss(**cfg.vae_loss_config, device=device, dtype=dtype) # == build EMA model == if cfg.get("ema_decay", None) is not None: ema = deepcopy(model).cpu().eval().requires_grad_(False) ema_shape_dict = record_model_param_shape(ema) logger.info("EMA model created.") else: ema = ema_shape_dict = None logger.info("No EMA model created.") # == build discriminator model == use_discriminator = cfg.get("discriminator", None) is not None if use_discriminator: discriminator = build_module(cfg.discriminator, MODELS).to(device, dtype).train() log_model_params(discriminator) generator_loss_fn = GeneratorLoss(**cfg.gen_loss_config) discriminator_loss_fn = DiscriminatorLoss(**cfg.disc_loss_config) # == setup optimizer == optimizer = create_optimizer(model, cfg.optim) # == setup lr scheduler == lr_scheduler = create_lr_scheduler( optimizer=optimizer, num_steps_per_epoch=num_steps_per_epoch, epochs=cfg.get("epochs", 1000), **cfg.lr_scheduler ) # == setup discriminator optimizer == if use_discriminator: disc_optimizer = create_optimizer(discriminator, cfg.optim_discriminator) disc_lr_scheduler = create_lr_scheduler( optimizer=disc_optimizer, num_steps_per_epoch=num_steps_per_epoch, epochs=cfg.get("epochs", 1000), **cfg.disc_lr_scheduler, ) # ======================================================= # 4. distributed training preparation with colossalai # ======================================================= logger.info("Preparing for distributed training...") # == boosting == torch.set_default_dtype(dtype) model, optimizer, _, dataloader, lr_scheduler = booster.boost( model=model, optimizer=optimizer, lr_scheduler=lr_scheduler, dataloader=dataloader, ) if use_discriminator: discriminator, disc_optimizer, _, _, disc_lr_scheduler = booster.boost( model=discriminator, optimizer=disc_optimizer, lr_scheduler=disc_lr_scheduler, ) torch.set_default_dtype(torch.float) logger.info("Boosted model for distributed training") # == global variables == cfg_epochs = cfg.get("epochs", 1000) mixed_strategy = cfg.get("mixed_strategy", None) mixed_image_ratio = cfg.get("mixed_image_ratio", 0.0) # modulate mixed image ratio since we force rank 0 to be video num_ranks = dist.get_world_size() modulated_mixed_image_ratio = ( num_ranks * mixed_image_ratio / (num_ranks - 1) if num_ranks > 1 else mixed_image_ratio ) if is_log_process(plugin_type, plugin_config): print("modulated mixed image ratio:", modulated_mixed_image_ratio) start_epoch = start_step = log_step = acc_step = 0 running_loss = dict( # loss accumulated over config.log_every steps all=0.0, nll=0.0, nll_rec=0.0, nll_per=0.0, kl=0.0, gen=0.0, gen_w=0.0, disc=0.0, debug=0.0, ) def log_loss(name, loss, loss_dict, use_video): # only calculate loss for video if use_video == 0: loss.data = torch.tensor(0.0, device=device, dtype=dtype) all_reduce_sum(loss.data) num_video = torch.tensor(use_video, device=device, dtype=dtype) all_reduce_sum(num_video) loss_item = loss.item() / num_video.item() loss_dict[name] = loss_item running_loss[name] += loss_item logger.info("Training for %s epochs with %s steps per epoch", cfg_epochs, num_steps_per_epoch) # == resume == if cfg.get("load", None) is not None: logger.info("Loading checkpoint from %s", cfg.load) start_epoch = cfg.get("start_epoch", None) start_step = cfg.get("start_step", None) ret = checkpoint_io.load( booster, cfg.load, model=model, ema=ema, optimizer=optimizer, lr_scheduler=lr_scheduler, sampler=( None if start_step is not None else sampler ), # if specify start step, set last_micro_batch_access_index of a new sampler instead ) if start_step is not None: # if start step exceeds data length, go to next epoch if start_step > num_steps_per_epoch: start_epoch = ( start_epoch + start_step // num_steps_per_epoch if start_epoch is not None else start_step // num_steps_per_epoch ) start_step = start_step % num_steps_per_epoch sampler.set_step(start_step) start_epoch = start_epoch if start_epoch is not None else ret[0] start_step = start_step if start_step is not None else ret[1] if ( use_discriminator and os.path.exists(os.path.join(cfg.load, "discriminator")) and not cfg.get("restart_disc", False) ): booster.load_model(discriminator, os.path.join(cfg.load, "discriminator")) if cfg.get("load_optimizer", True): booster.load_optimizer(disc_optimizer, os.path.join(cfg.load, "disc_optimizer")) if disc_lr_scheduler is not None: booster.load_lr_scheduler(disc_lr_scheduler, os.path.join(cfg.load, "disc_lr_scheduler")) if cfg.get("disc_lr", None) is not None: set_lr(disc_optimizer, disc_lr_scheduler, cfg.disc_lr) logger.info("Loaded checkpoint %s at epoch %s step %s", cfg.load, start_epoch, start_step) if cfg.get("lr", None) is not None: set_lr(optimizer, lr_scheduler, cfg.lr, cfg.get("initial_lr", None)) if cfg.get("update_warmup_steps", False): assert ( cfg.lr_scheduler.get("warmup_steps", None) is not None ), "you need to set lr_scheduler.warmup_steps in order to pass --update-warmup-steps True" set_warmup_steps(lr_scheduler, cfg.lr_scheduler.warmup_steps) if use_discriminator: assert ( cfg.disc_lr_scheduler.get("warmup_steps", None) is not None ), "you need to set disc_lr_scheduler.warmup_steps in order to pass --update-warmup-steps True" set_warmup_steps(disc_lr_scheduler, cfg.disc_lr_scheduler.warmup_steps) # == sharding EMA model == if ema is not None: model_sharding(ema) ema = ema.to(device) if cfg.get("freeze_layers", None) == "all": for param in model.module.parameters(): param.requires_grad = False print("all layers frozen") # model.module.requires_grad_(False) # ======================================================= # 5. training loop # ======================================================= dist.barrier() accumulation_steps = int(cfg.get("accumulation_steps", 1)) for epoch in range(start_epoch, cfg_epochs): # == set dataloader to new epoch == sampler.set_epoch(epoch) dataiter = iter(dataloader) logger.info("Beginning epoch %s...", epoch) random.seed(1024 + dist.get_rank()) # load vid/img for each rank # == training loop in an epoch == with tqdm( enumerate(dataiter, start=start_step), desc=f"Epoch {epoch}", disable=not coordinator.is_master(), total=num_steps_per_epoch, initial=start_step, ) as pbar: pbar_iter = iter(pbar) def fetch_data(): step, batch = next(pbar_iter) pinned_video = batch["video"] batch["video"] = pinned_video.to(device, dtype, non_blocking=True) return batch, step, pinned_video batch_, step_, pinned_video_ = fetch_data() profiler_ctxt = ( profile( activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA], schedule=my_schedule, on_trace_ready=torch.profiler.tensorboard_trace_handler("./log/profile"), record_shapes=True, profile_memory=True, with_stack=True, ) if cfg.get("profile", False) else nullcontext() ) with profiler_ctxt: for _ in range(start_step, num_steps_per_epoch): if cfg.get("profile", False) and _ == WARMUP + ACTIVE + WAIT + 3: break # == load data === batch, step, pinned_video = batch_, step_, pinned_video_ if step + 1 < num_steps_per_epoch: batch_, step_, pinned_video_ = fetch_data() # == log config == global_step = epoch * num_steps_per_epoch + step actual_update_step = (global_step + 1) // accumulation_steps log_step += 1 acc_step += 1 # == mixed strategy == x = batch["video"] t_length = x.size(2) use_video = 1 if mixed_strategy == "mixed_video_image": if random.random() < modulated_mixed_image_ratio and dist.get_rank() != 0: # NOTE: enable the first rank to use video t_length = 1 use_video = 0 elif mixed_strategy == "mixed_video_random": t_length = random.randint(1, x.size(2)) x = x[:, :, :t_length, :, :] with Timer("model", log=True) if cfg.get("profile", False) else nullcontext(): # == forward pass == x_rec, posterior, z = model(x) if cfg.get("profile", False): profiler_ctxt.step() if cache_pin_memory: dataiter.remove_cache(pinned_video) # == loss initialization == vae_loss = torch.tensor(0.0, device=device, dtype=dtype) loss_dict = {} # loss at every step # == reconstruction loss == ret = vae_loss_fn(x, x_rec, posterior) nll_loss = ret["nll_loss"] kl_loss = ret["kl_loss"] recon_loss = ret["recon_loss"] perceptual_loss = ret["perceptual_loss"] vae_loss += nll_loss + kl_loss # == generator loss == if use_discriminator: # turn off grad update for disc discriminator.requires_grad_(False) fake_logits = discriminator(x_rec.contiguous()) generator_loss, g_loss = generator_loss_fn( fake_logits, nll_loss, model.module.get_last_layer(), actual_update_step, is_training=model.training, ) # print(f"generator_loss: {generator_loss}, recon_loss: {recon_loss}, perceptual_loss: {perceptual_loss}") vae_loss += generator_loss # turn on disc training discriminator.requires_grad_(True) # == generator backward & update == ctx = ( booster.no_sync(model, optimizer) if cfg.get("plugin", "zero2") in ("zero1", "zero1-seq") and (step + 1) % accumulation_steps != 0 else nullcontext() ) with Timer("backward", log=True) if cfg.get("profile", False) else nullcontext(): with ctx: booster.backward(loss=vae_loss / accumulation_steps, optimizer=optimizer) with Timer("optimizer", log=True) if cfg.get("profile", False) else nullcontext(): if (step + 1) % accumulation_steps == 0: optimizer.step() optimizer.zero_grad() if lr_scheduler is not None: lr_scheduler.step( actual_update_step, ) # == update EMA == if ema is not None: update_ema( ema, model.unwrap(), optimizer=optimizer, decay=cfg.get("ema_decay", 0.9999), ) # == logging == log_loss("all", vae_loss, loss_dict, use_video) log_loss("nll", nll_loss, loss_dict, use_video) log_loss("nll_rec", recon_loss, loss_dict, use_video) log_loss("nll_per", perceptual_loss, loss_dict, use_video) log_loss("kl", kl_loss, loss_dict, use_video) if use_discriminator: log_loss("gen_w", generator_loss, loss_dict, use_video) log_loss("gen", g_loss, loss_dict, use_video) # == loss: discriminator adversarial == if use_discriminator: real_logits = discriminator(x.detach().contiguous()) fake_logits = discriminator(x_rec.detach().contiguous()) disc_loss = discriminator_loss_fn( real_logits, fake_logits, actual_update_step, ) # == discriminator backward & update == ctx = ( booster.no_sync(discriminator, disc_optimizer) if cfg.get("plugin", "zero2") in ("zero1", "zero1-seq") and (step + 1) % accumulation_steps != 0 else nullcontext() ) with ctx: booster.backward(loss=disc_loss / accumulation_steps, optimizer=disc_optimizer) if (step + 1) % accumulation_steps == 0: disc_optimizer.step() disc_optimizer.zero_grad() if disc_lr_scheduler is not None: disc_lr_scheduler.step(actual_update_step) # log log_loss("disc", disc_loss, loss_dict, use_video) # == logging == if (global_step + 1) % accumulation_steps == 0: if coordinator.is_master() and actual_update_step % cfg.get("log_every", 1) == 0: avg_loss = {k: v / log_step for k, v in running_loss.items()} # progress bar pbar.set_postfix( { # "step": step, # "global_step": global_step, # "actual_update_step": actual_update_step, # "lr": optimizer.param_groups[0]["lr"], **{k: f"{v:.2f}" for k, v in avg_loss.items()}, } ) # tensorboard tb_writer.add_scalar("loss", vae_loss.item(), actual_update_step) # wandb if cfg.get("wandb", False): wandb.log( { "iter": global_step, "epoch": epoch, "lr": optimizer.param_groups[0]["lr"], "avg_loss_": avg_loss, "avg_loss": avg_loss["all"], "loss_": loss_dict, "loss": vae_loss.item(), "global_grad_norm": optimizer.get_grad_norm(), }, step=actual_update_step, ) running_loss = {k: 0.0 for k in running_loss} log_step = 0 # == checkpoint saving == ckpt_every = cfg.get("ckpt_every", 0) if ckpt_every > 0 and actual_update_step % ckpt_every == 0 and coordinator.is_master(): subprocess.run("sudo drop_cache", shell=True) if ckpt_every > 0 and actual_update_step % ckpt_every == 0: # mannually garbage collection gc.collect() save_dir = checkpoint_io.save( booster, exp_dir, model=model, ema=ema, optimizer=optimizer, lr_scheduler=lr_scheduler, sampler=sampler, epoch=epoch, step=step + 1, global_step=global_step + 1, batch_size=cfg.get("batch_size", None), actual_update_step=actual_update_step, ema_shape_dict=ema_shape_dict, async_io=True, ) if is_log_process(plugin_type, plugin_config): os.system(f"chgrp -R share {save_dir}") if use_discriminator: booster.save_model(discriminator, os.path.join(save_dir, "discriminator"), shard=True) booster.save_optimizer( disc_optimizer, os.path.join(save_dir, "disc_optimizer"), shard=True, size_per_shard=4096, ) if disc_lr_scheduler is not None: booster.save_lr_scheduler( disc_lr_scheduler, os.path.join(save_dir, "disc_lr_scheduler") ) dist.barrier() logger.info( "Saved checkpoint at epoch %s, step %s, global_step %s to %s", epoch, step + 1, actual_update_step, save_dir, ) # remove old checkpoints rm_checkpoints(exp_dir, keep_n_latest=cfg.get("keep_n_latest", -1)) logger.info( "Removed old checkpoints and kept %s latest ones.", cfg.get("keep_n_latest", -1) ) if cfg.get("profile", False): profiler_ctxt.export_chrome_trace("./log/profile/trace.json") sampler.reset() start_step = 0 if __name__ == "__main__": main() ================================================ FILE: setup.py ================================================ from typing import List from setuptools import find_packages, setup def fetch_requirements(paths) -> List[str]: """ This function reads the requirements file. Args: path (str): the path to the requirements file. Returns: The lines in the requirements file. """ if not isinstance(paths, list): paths = [paths] requirements = [] for path in paths: with open(path, "r") as fd: requirements += [r.strip() for r in fd.readlines()] return requirements def fetch_readme() -> str: """ This function reads the README.md file in the current directory. Returns: The lines in the README file. """ with open("README.md", encoding="utf-8") as f: return f.read() setup( name="opensora", version="2.0.0", packages=find_packages( exclude=( "assets", "configs", "docs", "eval", "evaluation_results", "gradio", "logs", "notebooks", "outputs", "pretrained_models", "samples", "scripts", "*.egg-info", ) ), description="Democratizing Efficient Video Production for All", long_description=fetch_readme(), long_description_content_type="text/markdown", license="Apache Software License 2.0", url="https://github.com/hpcaitech/Open-Sora", project_urls={ "Bug Tracker": "https://github.com/hpcaitech/Open-Sora/issues", "Examples": "https://hpcaitech.github.io/Open-Sora/", "Documentation": "https://github.com/hpcaitech/Open-Sora?tab=readme-ov-file", "Github": "https://github.com/hpcaitech/Open-Sora", }, install_requires=fetch_requirements("requirements.txt"), python_requires=">=3.6", classifiers=[ "Programming Language :: Python :: 3", "License :: OSI Approved :: Apache Software License", "Environment :: GPU :: NVIDIA CUDA", "Topic :: Scientific/Engineering :: Artificial Intelligence", "Topic :: System :: Distributed Computing", ], )