akthangdz commited on
Commit
17a06db
·
0 Parent(s):
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +4 -0
  2. .github/workflows/pylint.yml +27 -0
  3. .gitignore +164 -0
  4. .pre-commit-config.yaml +16 -0
  5. LICENSE +201 -0
  6. README.md +49 -0
  7. app.py +71 -0
  8. docs/_static/ltx-video_example_00001.gif +3 -0
  9. docs/_static/ltx-video_example_00002.gif +3 -0
  10. docs/_static/ltx-video_example_00003.gif +3 -0
  11. docs/_static/ltx-video_example_00004.gif +3 -0
  12. docs/_static/ltx-video_example_00005.gif +3 -0
  13. docs/_static/ltx-video_example_00006.gif +3 -0
  14. docs/_static/ltx-video_example_00007.gif +3 -0
  15. docs/_static/ltx-video_example_00008.gif +3 -0
  16. docs/_static/ltx-video_example_00009.gif +3 -0
  17. docs/_static/ltx-video_example_00010.gif +3 -0
  18. docs/_static/ltx-video_example_00011.gif +3 -0
  19. docs/_static/ltx-video_example_00012.gif +3 -0
  20. docs/_static/ltx-video_example_00013.gif +3 -0
  21. docs/_static/ltx-video_example_00014.gif +3 -0
  22. docs/_static/ltx-video_example_00015.gif +3 -0
  23. docs/_static/ltx-video_example_00016.gif +3 -0
  24. inference.py +488 -0
  25. itv.py +23 -0
  26. ltx_video/__init__.py +0 -0
  27. ltx_video/models/__init__.py +0 -0
  28. ltx_video/models/autoencoders/__init__.py +0 -0
  29. ltx_video/models/autoencoders/causal_conv3d.py +62 -0
  30. ltx_video/models/autoencoders/causal_video_autoencoder.py +1263 -0
  31. ltx_video/models/autoencoders/conv_nd_factory.py +82 -0
  32. ltx_video/models/autoencoders/dual_conv3d.py +195 -0
  33. ltx_video/models/autoencoders/pixel_norm.py +12 -0
  34. ltx_video/models/autoencoders/vae.py +343 -0
  35. ltx_video/models/autoencoders/vae_encode.py +208 -0
  36. ltx_video/models/autoencoders/video_autoencoder.py +1045 -0
  37. ltx_video/models/transformers/__init__.py +0 -0
  38. ltx_video/models/transformers/attention.py +1246 -0
  39. ltx_video/models/transformers/embeddings.py +129 -0
  40. ltx_video/models/transformers/symmetric_patchifier.py +96 -0
  41. ltx_video/models/transformers/transformer3d.py +605 -0
  42. ltx_video/pipelines/__init__.py +0 -0
  43. ltx_video/pipelines/pipeline_ltx_video.py +1274 -0
  44. ltx_video/schedulers/__init__.py +0 -0
  45. ltx_video/schedulers/rf.py +331 -0
  46. ltx_video/utils/__init__.py +0 -0
  47. ltx_video/utils/conditioning_method.py +6 -0
  48. ltx_video/utils/diffusers_config_mapping.py +174 -0
  49. ltx_video/utils/skip_layer_strategy.py +6 -0
  50. ltx_video/utils/torch_utils.py +25 -0
.gitattributes ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ *.jpg filter=lfs diff=lfs merge=lfs -text
2
+ *.jpeg filter=lfs diff=lfs merge=lfs -text
3
+ *.png filter=lfs diff=lfs merge=lfs -text
4
+ *.gif filter=lfs diff=lfs merge=lfs -text
.github/workflows/pylint.yml ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Ruff
2
+
3
+ on: [push]
4
+
5
+ jobs:
6
+ build:
7
+ runs-on: ubuntu-latest
8
+ strategy:
9
+ matrix:
10
+ python-version: ["3.10"]
11
+ steps:
12
+ - name: Checkout repository and submodules
13
+ uses: actions/checkout@v3
14
+ - name: Set up Python ${{ matrix.python-version }}
15
+ uses: actions/setup-python@v3
16
+ with:
17
+ python-version: ${{ matrix.python-version }}
18
+ - name: Install dependencies
19
+ run: |
20
+ python -m pip install --upgrade pip
21
+ pip install ruff==0.2.2 black==24.2.0
22
+ - name: Analyzing the code with ruff
23
+ run: |
24
+ ruff $(git ls-files '*.py')
25
+ - name: Verify that no Black changes are required
26
+ run: |
27
+ black --check $(git ls-files '*.py')
.gitignore ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py,cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # poetry
98
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
102
+ #poetry.lock
103
+
104
+ # pdm
105
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
106
+ #pdm.lock
107
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
108
+ # in version control.
109
+ # https://pdm.fming.dev/latest/usage/project/#working-with-version-control
110
+ .pdm.toml
111
+ .pdm-python
112
+ .pdm-build/
113
+
114
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
115
+ __pypackages__/
116
+
117
+ # Celery stuff
118
+ celerybeat-schedule
119
+ celerybeat.pid
120
+
121
+ # SageMath parsed files
122
+ *.sage.py
123
+
124
+ # Environments
125
+ .env
126
+ .venv
127
+ env/
128
+ venv/
129
+ ENV/
130
+ env.bak/
131
+ venv.bak/
132
+
133
+ # Spyder project settings
134
+ .spyderproject
135
+ .spyproject
136
+
137
+ # Rope project settings
138
+ .ropeproject
139
+
140
+ # mkdocs documentation
141
+ /site
142
+
143
+ # mypy
144
+ .mypy_cache/
145
+ .dmypy.json
146
+ dmypy.json
147
+
148
+ # Pyre type checker
149
+ .pyre/
150
+
151
+ # pytype static type analyzer
152
+ .pytype/
153
+
154
+ # Cython debug symbols
155
+ cython_debug/
156
+
157
+ # PyCharm
158
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
159
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
160
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
161
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
162
+ .idea/
163
+
164
+ # From inference.py
.pre-commit-config.yaml ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ repos:
2
+ - repo: https://github.com/astral-sh/ruff-pre-commit
3
+ # Ruff version.
4
+ rev: v0.2.2
5
+ hooks:
6
+ # Run the linter.
7
+ - id: ruff
8
+ args: [--fix] # Automatically fix issues if possible.
9
+ types: [python] # Ensure it only runs on .py files.
10
+
11
+ - repo: https://github.com/psf/black
12
+ rev: 24.2.0 # Specify the version of Black you want
13
+ hooks:
14
+ - id: black
15
+ name: Black code formatter
16
+ language_version: python3 # Use the Python version you're targeting (e.g., 3.10)
LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
README.md ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Chuyển Văn Bản Thành Video AI
3
+ emoji: 🎬
4
+ colorFrom: blue
5
+ colorTo: purple
6
+ sdk: gradio
7
+ sdk_version: 4.19.2
8
+ app_file: app.py
9
+ pinned: false
10
+ ---
11
+
12
+ # Chuyển Văn Bản Thành Video AI
13
+
14
+ Ứng dụng này sử dụng mô hình LTX-Video để tạo video từ văn bản mô tả. Bạn có thể dễ dàng tạo video ngắn bằng cách nhập mô tả bằng văn bản.
15
+
16
+ ## Tính năng
17
+
18
+ - 🎯 Tạo video từ mô tả văn bản
19
+ - 🎨 Tùy chỉnh từ khóa loại trừ để cải thiện chất lượng
20
+ - 📱 Giao diện thân thiện, dễ sử dụng
21
+ - 🖼️ Xem lại các video đã tạo trước đó
22
+
23
+ ## Cách sử dụng
24
+
25
+ 1. Nhập mô tả cho video bạn muốn tạo vào ô "Nhập nội dung video"
26
+ 2. (Tùy chọn) Điều chỉnh từ khóa loại trừ nếu cần
27
+ 3. Nhấn nút "Tạo Video"
28
+ 4. Đợi trong giây lát để hệ thống tạo video
29
+ 5. Video được tạo sẽ hiển thị ở khung bên phải
30
+ 6. Xem lại các video đã tạo trước đó ở phần gallery bên dưới
31
+
32
+ ## Thông số kỹ thuật
33
+
34
+ - Model: Lightricks/LTX-Video
35
+ - Độ phân giải: 704x480
36
+ - Số frame: 161
37
+ - FPS: 24
38
+ - Số bước inference: 50
39
+
40
+ ## Lưu ý
41
+
42
+ - Thời gian tạo video có thể mất vài phút tùy thuộc vào độ phức tạp của mô tả
43
+ - Chất lượng video phụ thuộc vào độ chi tiết của mô tả văn bản
44
+ - Nên sử dụng mô tả rõ ràng, chi tiết để có kết quả tốt nhất
45
+
46
+ ## Credits
47
+
48
+ - Model: [Lightricks/LTX-Video](https://huggingface.co/Lightricks/LTX-Video)
49
+ - Framework: [Gradio](https://gradio.app/)
app.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+ import subprocess
4
+ from ttv import generate_video # We'll modify ttv.py to make it a function
5
+
6
+ def install_dependencies():
7
+ try:
8
+ # Cài đặt diffusers từ git
9
+ subprocess.run(["pip", "install", "-U", "git+https://github.com/huggingface/diffusers"],
10
+ check=True,
11
+ capture_output=True)
12
+
13
+ # Cài đặt inference-script
14
+ subprocess.run(["pip", "install", "-e", ".[inference-script]"],
15
+ check=True,
16
+ capture_output=True)
17
+
18
+ return "✅ Đã cài đặt thành công các gói phụ thuộc!"
19
+ except subprocess.CalledProcessError as e:
20
+ return f"❌ Lỗi khi cài đặt: {str(e)}"
21
+
22
+ def text_to_video(prompt, negative_prompt):
23
+ # Generate video from text
24
+ output_path = generate_video(prompt, negative_prompt)
25
+ return output_path
26
+
27
+ def list_videos():
28
+ # List all MP4 files in the current directory
29
+ videos = [f for f in os.listdir('.') if f.endswith('.mp4')]
30
+ return videos
31
+
32
+ # Create Gradio interface
33
+ with gr.Blocks() as demo:
34
+ gr.Markdown("# Chuyển Văn Bản Thành Video")
35
+
36
+ # Add installation button at the top
37
+ install_btn = gr.Button("Cài đặt Dependencies")
38
+ install_output = gr.Textbox(label="Trạng thái cài đặt", interactive=False)
39
+
40
+ with gr.Row():
41
+ with gr.Column():
42
+ # Input components
43
+ text_input = gr.Textbox(label="Nhập nội dung video", lines=3)
44
+ neg_prompt = gr.Textbox(label="Từ khóa loại trừ",
45
+ value="chất lượng kém, chuyển động không đồng nhất, mờ, giật, biến dạng")
46
+ generate_btn = gr.Button("Tạo Video")
47
+
48
+ with gr.Column():
49
+ # Output video display
50
+ video_output = gr.Video(label="Video đã tạo")
51
+
52
+ # Gallery of existing videos
53
+ gr.Markdown("### Video đã tạo trước đó")
54
+ gallery = gr.Gallery(value=list_videos(), label="Video có sẵn",
55
+ show_label=True, elem_id="gallery").style(grid=2)
56
+
57
+ # Connect components
58
+ generate_btn.click(
59
+ fn=text_to_video,
60
+ inputs=[text_input, neg_prompt],
61
+ outputs=[video_output]
62
+ )
63
+
64
+ # Connect install button
65
+ install_btn.click(
66
+ fn=install_dependencies,
67
+ inputs=[],
68
+ outputs=[install_output]
69
+ )
70
+
71
+ demo.launch()
docs/_static/ltx-video_example_00001.gif ADDED

Git LFS Details

  • SHA256: b679f14a09d2321b7e34b3ecd23bc01c2cfa75c8d4214a1e59af09826003e2ec
  • Pointer size: 132 Bytes
  • Size of remote file: 7.96 MB
docs/_static/ltx-video_example_00002.gif ADDED

Git LFS Details

  • SHA256: 336f4baec79c1bd754c7c1bf3ac0792910cc85b6a3bde15fabeb0fb0f33299ff
  • Pointer size: 132 Bytes
  • Size of remote file: 7.9 MB
docs/_static/ltx-video_example_00003.gif ADDED

Git LFS Details

  • SHA256: ab2cb063b872d487fbbab821de7fe8157e7f87af03bd780d55116cb98fc8fc45
  • Pointer size: 132 Bytes
  • Size of remote file: 4.43 MB
docs/_static/ltx-video_example_00004.gif ADDED

Git LFS Details

  • SHA256: 0a599a641cc3367fab5a6dd75fc89be63208cc708a1173b2ce7bfeac7208f831
  • Pointer size: 132 Bytes
  • Size of remote file: 6.71 MB
docs/_static/ltx-video_example_00005.gif ADDED

Git LFS Details

  • SHA256: 87fdb9556c1218db4b929994e9b807d1d63f4676defef5b418a4edb1ddaa8422
  • Pointer size: 132 Bytes
  • Size of remote file: 5.73 MB
docs/_static/ltx-video_example_00006.gif ADDED

Git LFS Details

  • SHA256: f56f3dcc84a871ab4ef1510120f7a4586c7044c5609a897d8177ae8d52eb3eae
  • Pointer size: 132 Bytes
  • Size of remote file: 4.24 MB
docs/_static/ltx-video_example_00007.gif ADDED

Git LFS Details

  • SHA256: a08a06681334856db516e969a9ae4290acfd7550f7b970331e87d0223e282bcc
  • Pointer size: 132 Bytes
  • Size of remote file: 7.83 MB
docs/_static/ltx-video_example_00008.gif ADDED

Git LFS Details

  • SHA256: 3242c65e11a40177c91b48d8ee18084dc4f907ffe5f11217c5f3e5aa2ca3fe36
  • Pointer size: 132 Bytes
  • Size of remote file: 6.23 MB
docs/_static/ltx-video_example_00009.gif ADDED

Git LFS Details

  • SHA256: aa1e0a2ba75c6bda530a798e8aaeb3edc19413970b99d2a67b79839cd14f2fe5
  • Pointer size: 132 Bytes
  • Size of remote file: 6.39 MB
docs/_static/ltx-video_example_00010.gif ADDED

Git LFS Details

  • SHA256: bcf1e084e936a75eaae73a29f60935c469b1fc34eb3f5ad89483e88b3a2eaffe
  • Pointer size: 132 Bytes
  • Size of remote file: 6.19 MB
docs/_static/ltx-video_example_00011.gif ADDED

Git LFS Details

  • SHA256: 3e3d04f5763ecb416b3b80c3488e48c49991d80661c94e8f08dddd7b890b1b75
  • Pointer size: 132 Bytes
  • Size of remote file: 5.35 MB
docs/_static/ltx-video_example_00012.gif ADDED

Git LFS Details

  • SHA256: 39790832fd9bff62c99a799eb4843cf99c9ab73c3f181656acbbd0d4ebf7f471
  • Pointer size: 132 Bytes
  • Size of remote file: 7.47 MB
docs/_static/ltx-video_example_00013.gif ADDED

Git LFS Details

  • SHA256: aa7eb790b43f8a55c01d1fbed4c7a7f657fb2ca78a9685833cf9cb558d2002c1
  • Pointer size: 132 Bytes
  • Size of remote file: 9.02 MB
docs/_static/ltx-video_example_00014.gif ADDED

Git LFS Details

  • SHA256: 4f7afc4b498a927dcc4e1492548db5c32fa76d117e0410d11e1e0b1929153e54
  • Pointer size: 132 Bytes
  • Size of remote file: 7.43 MB
docs/_static/ltx-video_example_00015.gif ADDED

Git LFS Details

  • SHA256: d897c9656e0cba89512ab9d2cbe2d2c0f2ddf907dcab5f7eadab4b96b1cb1efe
  • Pointer size: 132 Bytes
  • Size of remote file: 6.56 MB
docs/_static/ltx-video_example_00016.gif ADDED

Git LFS Details

  • SHA256: c74f35e37bba01817ca4ac01dd9195863100eb83e7cb73bbea2b53e0f69a8628
  • Pointer size: 132 Bytes
  • Size of remote file: 7.41 MB
inference.py ADDED
@@ -0,0 +1,488 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import os
3
+ import random
4
+ from datetime import datetime
5
+ from pathlib import Path
6
+ from diffusers.utils import logging
7
+
8
+ import imageio
9
+ import numpy as np
10
+ import torch
11
+ import torch.nn.functional as F
12
+ from PIL import Image
13
+ from transformers import T5EncoderModel, T5Tokenizer
14
+
15
+ from ltx_video.models.autoencoders.causal_video_autoencoder import (
16
+ CausalVideoAutoencoder,
17
+ )
18
+ from ltx_video.models.transformers.symmetric_patchifier import SymmetricPatchifier
19
+ from ltx_video.models.transformers.transformer3d import Transformer3DModel
20
+ from ltx_video.pipelines.pipeline_ltx_video import LTXVideoPipeline
21
+ from ltx_video.schedulers.rf import RectifiedFlowScheduler
22
+ from ltx_video.utils.conditioning_method import ConditioningMethod
23
+ from ltx_video.utils.skip_layer_strategy import SkipLayerStrategy
24
+
25
+ MAX_HEIGHT = 720
26
+ MAX_WIDTH = 1280
27
+ MAX_NUM_FRAMES = 257
28
+
29
+
30
+ def get_total_gpu_memory():
31
+ if torch.cuda.is_available():
32
+ total_memory = torch.cuda.get_device_properties(0).total_memory / (1024**3)
33
+ return total_memory
34
+ return None
35
+
36
+
37
+ def load_image_to_tensor_with_resize_and_crop(
38
+ image_path, target_height=512, target_width=768
39
+ ):
40
+ image = Image.open(image_path).convert("RGB")
41
+ input_width, input_height = image.size
42
+ aspect_ratio_target = target_width / target_height
43
+ aspect_ratio_frame = input_width / input_height
44
+ if aspect_ratio_frame > aspect_ratio_target:
45
+ new_width = int(input_height * aspect_ratio_target)
46
+ new_height = input_height
47
+ x_start = (input_width - new_width) // 2
48
+ y_start = 0
49
+ else:
50
+ new_width = input_width
51
+ new_height = int(input_width / aspect_ratio_target)
52
+ x_start = 0
53
+ y_start = (input_height - new_height) // 2
54
+
55
+ image = image.crop((x_start, y_start, x_start + new_width, y_start + new_height))
56
+ image = image.resize((target_width, target_height))
57
+ frame_tensor = torch.tensor(np.array(image)).permute(2, 0, 1).float()
58
+ frame_tensor = (frame_tensor / 127.5) - 1.0
59
+ # Create 5D tensor: (batch_size=1, channels=3, num_frames=1, height, width)
60
+ return frame_tensor.unsqueeze(0).unsqueeze(2)
61
+
62
+
63
+ def calculate_padding(
64
+ source_height: int, source_width: int, target_height: int, target_width: int
65
+ ) -> tuple[int, int, int, int]:
66
+
67
+ # Calculate total padding needed
68
+ pad_height = target_height - source_height
69
+ pad_width = target_width - source_width
70
+
71
+ # Calculate padding for each side
72
+ pad_top = pad_height // 2
73
+ pad_bottom = pad_height - pad_top # Handles odd padding
74
+ pad_left = pad_width // 2
75
+ pad_right = pad_width - pad_left # Handles odd padding
76
+
77
+ # Return padded tensor
78
+ # Padding format is (left, right, top, bottom)
79
+ padding = (pad_left, pad_right, pad_top, pad_bottom)
80
+ return padding
81
+
82
+
83
+ def convert_prompt_to_filename(text: str, max_len: int = 20) -> str:
84
+ # Remove non-letters and convert to lowercase
85
+ clean_text = "".join(
86
+ char.lower() for char in text if char.isalpha() or char.isspace()
87
+ )
88
+
89
+ # Split into words
90
+ words = clean_text.split()
91
+
92
+ # Build result string keeping track of length
93
+ result = []
94
+ current_length = 0
95
+
96
+ for word in words:
97
+ # Add word length plus 1 for underscore (except for first word)
98
+ new_length = current_length + len(word)
99
+
100
+ if new_length <= max_len:
101
+ result.append(word)
102
+ current_length += len(word)
103
+ else:
104
+ break
105
+
106
+ return "-".join(result)
107
+
108
+
109
+ # Generate output video name
110
+ def get_unique_filename(
111
+ base: str,
112
+ ext: str,
113
+ prompt: str,
114
+ seed: int,
115
+ resolution: tuple[int, int, int],
116
+ dir: Path,
117
+ endswith=None,
118
+ index_range=1000,
119
+ ) -> Path:
120
+ base_filename = f"{base}_{convert_prompt_to_filename(prompt, max_len=30)}_{seed}_{resolution[0]}x{resolution[1]}x{resolution[2]}"
121
+ for i in range(index_range):
122
+ filename = dir / f"{base_filename}_{i}{endswith if endswith else ''}{ext}"
123
+ if not os.path.exists(filename):
124
+ return filename
125
+ raise FileExistsError(
126
+ f"Could not find a unique filename after {index_range} attempts."
127
+ )
128
+
129
+
130
+ def seed_everething(seed: int):
131
+ random.seed(seed)
132
+ np.random.seed(seed)
133
+ torch.manual_seed(seed)
134
+ if torch.cuda.is_available():
135
+ torch.cuda.manual_seed(seed)
136
+
137
+
138
+ def main():
139
+ parser = argparse.ArgumentParser(
140
+ description="Load models from separate directories and run the pipeline."
141
+ )
142
+
143
+ # Directories
144
+ parser.add_argument(
145
+ "--ckpt_path",
146
+ type=str,
147
+ required=True,
148
+ help="Path to a safetensors file that contains all model parts.",
149
+ )
150
+ parser.add_argument(
151
+ "--input_video_path",
152
+ type=str,
153
+ help="Path to the input video file (first frame used)",
154
+ )
155
+ parser.add_argument(
156
+ "--input_image_path", type=str, help="Path to the input image file"
157
+ )
158
+ parser.add_argument(
159
+ "--output_path",
160
+ type=str,
161
+ default=None,
162
+ help="Path to the folder to save output video, if None will save in outputs/ directory.",
163
+ )
164
+ parser.add_argument("--seed", type=int, default="171198")
165
+
166
+ # Pipeline parameters
167
+ parser.add_argument(
168
+ "--num_inference_steps", type=int, default=40, help="Number of inference steps"
169
+ )
170
+ parser.add_argument(
171
+ "--num_images_per_prompt",
172
+ type=int,
173
+ default=1,
174
+ help="Number of images per prompt",
175
+ )
176
+ parser.add_argument(
177
+ "--guidance_scale",
178
+ type=float,
179
+ default=3,
180
+ help="Guidance scale for the pipeline",
181
+ )
182
+ parser.add_argument(
183
+ "--stg_scale",
184
+ type=float,
185
+ default=1,
186
+ help="Spatiotemporal guidance scale for the pipeline. 0 to disable STG.",
187
+ )
188
+ parser.add_argument(
189
+ "--stg_rescale",
190
+ type=float,
191
+ default=0.7,
192
+ help="Spatiotemporal guidance rescaling scale for the pipeline. 1 to disable rescale.",
193
+ )
194
+ parser.add_argument(
195
+ "--stg_mode",
196
+ type=str,
197
+ default="stg_a",
198
+ help="Spatiotemporal guidance mode for the pipeline. Can be either stg_a or stg_r.",
199
+ )
200
+ parser.add_argument(
201
+ "--stg_skip_layers",
202
+ type=str,
203
+ default="19",
204
+ help="Attention layers to skip for spatiotemporal guidance. Comma separated list of integers.",
205
+ )
206
+ parser.add_argument(
207
+ "--image_cond_noise_scale",
208
+ type=float,
209
+ default=0.15,
210
+ help="Amount of noise to add to the conditioned image",
211
+ )
212
+ parser.add_argument(
213
+ "--height",
214
+ type=int,
215
+ default=480,
216
+ help="Height of the output video frames. Optional if an input image provided.",
217
+ )
218
+ parser.add_argument(
219
+ "--width",
220
+ type=int,
221
+ default=704,
222
+ help="Width of the output video frames. If None will infer from input image.",
223
+ )
224
+ parser.add_argument(
225
+ "--num_frames",
226
+ type=int,
227
+ default=121,
228
+ help="Number of frames to generate in the output video",
229
+ )
230
+ parser.add_argument(
231
+ "--frame_rate", type=int, default=25, help="Frame rate for the output video"
232
+ )
233
+
234
+ parser.add_argument(
235
+ "--precision",
236
+ choices=["bfloat16", "mixed_precision"],
237
+ default="bfloat16",
238
+ help="Sets the precision for the transformer and tokenizer. Default is bfloat16. If 'mixed_precision' is enabled, it moves to mixed-precision.",
239
+ )
240
+
241
+ # VAE noise augmentation
242
+ parser.add_argument(
243
+ "--decode_timestep",
244
+ type=float,
245
+ default=0.05,
246
+ help="Timestep for decoding noise",
247
+ )
248
+ parser.add_argument(
249
+ "--decode_noise_scale",
250
+ type=float,
251
+ default=0.025,
252
+ help="Noise level for decoding noise",
253
+ )
254
+
255
+ # Prompts
256
+ parser.add_argument(
257
+ "--prompt",
258
+ type=str,
259
+ help="Text prompt to guide generation",
260
+ )
261
+ parser.add_argument(
262
+ "--negative_prompt",
263
+ type=str,
264
+ default="worst quality, inconsistent motion, blurry, jittery, distorted",
265
+ help="Negative prompt for undesired features",
266
+ )
267
+
268
+ parser.add_argument(
269
+ "--offload_to_cpu",
270
+ action="store_true",
271
+ help="Offloading unnecessary computations to CPU.",
272
+ )
273
+
274
+ logger = logging.get_logger(__name__)
275
+
276
+ args = parser.parse_args()
277
+
278
+ logger.warning(f"Running generation with arguments: {args}")
279
+
280
+ seed_everething(args.seed)
281
+
282
+ offload_to_cpu = False if not args.offload_to_cpu else get_total_gpu_memory() < 30
283
+
284
+ output_dir = (
285
+ Path(args.output_path)
286
+ if args.output_path
287
+ else Path(f"outputs/{datetime.today().strftime('%Y-%m-%d')}")
288
+ )
289
+ output_dir.mkdir(parents=True, exist_ok=True)
290
+
291
+ # Load image
292
+ if args.input_image_path:
293
+ media_items_prepad = load_image_to_tensor_with_resize_and_crop(
294
+ args.input_image_path, args.height, args.width
295
+ )
296
+ else:
297
+ media_items_prepad = None
298
+
299
+ height = args.height if args.height else media_items_prepad.shape[-2]
300
+ width = args.width if args.width else media_items_prepad.shape[-1]
301
+ num_frames = args.num_frames
302
+
303
+ if height > MAX_HEIGHT or width > MAX_WIDTH or num_frames > MAX_NUM_FRAMES:
304
+ logger.warning(
305
+ f"Input resolution or number of frames {height}x{width}x{num_frames} is too big, it is suggested to use the resolution below {MAX_HEIGHT}x{MAX_WIDTH}x{MAX_NUM_FRAMES}."
306
+ )
307
+
308
+ # Adjust dimensions to be divisible by 32 and num_frames to be (N * 8 + 1)
309
+ height_padded = ((height - 1) // 32 + 1) * 32
310
+ width_padded = ((width - 1) // 32 + 1) * 32
311
+ num_frames_padded = ((num_frames - 2) // 8 + 1) * 8 + 1
312
+
313
+ padding = calculate_padding(height, width, height_padded, width_padded)
314
+
315
+ logger.warning(
316
+ f"Padded dimensions: {height_padded}x{width_padded}x{num_frames_padded}"
317
+ )
318
+
319
+ if media_items_prepad is not None:
320
+ media_items = F.pad(
321
+ media_items_prepad, padding, mode="constant", value=-1
322
+ ) # -1 is the value for padding since the image is normalized to -1, 1
323
+ else:
324
+ media_items = None
325
+
326
+ ckpt_path = Path(args.ckpt_path)
327
+ vae = CausalVideoAutoencoder.from_pretrained(ckpt_path)
328
+ transformer = Transformer3DModel.from_pretrained(ckpt_path)
329
+ scheduler = RectifiedFlowScheduler.from_pretrained(ckpt_path)
330
+
331
+ text_encoder = T5EncoderModel.from_pretrained(
332
+ "PixArt-alpha/PixArt-XL-2-1024-MS", subfolder="text_encoder"
333
+ )
334
+ patchifier = SymmetricPatchifier(patch_size=1)
335
+ tokenizer = T5Tokenizer.from_pretrained(
336
+ "PixArt-alpha/PixArt-XL-2-1024-MS", subfolder="tokenizer"
337
+ )
338
+
339
+ if torch.cuda.is_available():
340
+ transformer = transformer.cuda()
341
+ vae = vae.cuda()
342
+ text_encoder = text_encoder.cuda()
343
+
344
+ vae = vae.to(torch.bfloat16)
345
+ if args.precision == "bfloat16" and transformer.dtype != torch.bfloat16:
346
+ transformer = transformer.to(torch.bfloat16)
347
+ text_encoder = text_encoder.to(torch.bfloat16)
348
+
349
+ # Set spatiotemporal guidance
350
+ skip_block_list = [int(x.strip()) for x in args.stg_skip_layers.split(",")]
351
+ skip_layer_strategy = (
352
+ SkipLayerStrategy.Attention
353
+ if args.stg_mode.lower() == "stg_a"
354
+ else SkipLayerStrategy.Residual
355
+ )
356
+
357
+ # Use submodels for the pipeline
358
+ submodel_dict = {
359
+ "transformer": transformer,
360
+ "patchifier": patchifier,
361
+ "text_encoder": text_encoder,
362
+ "tokenizer": tokenizer,
363
+ "scheduler": scheduler,
364
+ "vae": vae,
365
+ }
366
+
367
+ pipeline = LTXVideoPipeline(**submodel_dict)
368
+ if torch.cuda.is_available():
369
+ pipeline = pipeline.to("cuda")
370
+
371
+ # Prepare input for the pipeline
372
+ sample = {
373
+ "prompt": args.prompt,
374
+ "prompt_attention_mask": None,
375
+ "negative_prompt": args.negative_prompt,
376
+ "negative_prompt_attention_mask": None,
377
+ "media_items": media_items,
378
+ }
379
+
380
+ generator = torch.Generator(
381
+ device="cuda" if torch.cuda.is_available() else "cpu"
382
+ ).manual_seed(args.seed)
383
+
384
+ images = pipeline(
385
+ num_inference_steps=args.num_inference_steps,
386
+ num_images_per_prompt=args.num_images_per_prompt,
387
+ guidance_scale=args.guidance_scale,
388
+ skip_layer_strategy=skip_layer_strategy,
389
+ skip_block_list=skip_block_list,
390
+ stg_scale=args.stg_scale,
391
+ do_rescaling=args.stg_rescale != 1,
392
+ rescaling_scale=args.stg_rescale,
393
+ generator=generator,
394
+ output_type="pt",
395
+ callback_on_step_end=None,
396
+ height=height_padded,
397
+ width=width_padded,
398
+ num_frames=num_frames_padded,
399
+ frame_rate=args.frame_rate,
400
+ **sample,
401
+ is_video=True,
402
+ vae_per_channel_normalize=True,
403
+ conditioning_method=(
404
+ ConditioningMethod.FIRST_FRAME
405
+ if media_items is not None
406
+ else ConditioningMethod.UNCONDITIONAL
407
+ ),
408
+ image_cond_noise_scale=args.image_cond_noise_scale,
409
+ decode_timestep=args.decode_timestep,
410
+ decode_noise_scale=args.decode_noise_scale,
411
+ mixed_precision=(args.precision == "mixed_precision"),
412
+ offload_to_cpu=offload_to_cpu,
413
+ ).images
414
+
415
+ # Crop the padded images to the desired resolution and number of frames
416
+ (pad_left, pad_right, pad_top, pad_bottom) = padding
417
+ pad_bottom = -pad_bottom
418
+ pad_right = -pad_right
419
+ if pad_bottom == 0:
420
+ pad_bottom = images.shape[3]
421
+ if pad_right == 0:
422
+ pad_right = images.shape[4]
423
+ images = images[:, :, :num_frames, pad_top:pad_bottom, pad_left:pad_right]
424
+
425
+ for i in range(images.shape[0]):
426
+ # Gathering from B, C, F, H, W to C, F, H, W and then permuting to F, H, W, C
427
+ video_np = images[i].permute(1, 2, 3, 0).cpu().float().numpy()
428
+ # Unnormalizing images to [0, 255] range
429
+ video_np = (video_np * 255).astype(np.uint8)
430
+ fps = args.frame_rate
431
+ height, width = video_np.shape[1:3]
432
+ # In case a single image is generated
433
+ if video_np.shape[0] == 1:
434
+ output_filename = get_unique_filename(
435
+ f"image_output_{i}",
436
+ ".png",
437
+ prompt=args.prompt,
438
+ seed=args.seed,
439
+ resolution=(height, width, num_frames),
440
+ dir=output_dir,
441
+ )
442
+ imageio.imwrite(output_filename, video_np[0])
443
+ else:
444
+ if args.input_image_path:
445
+ base_filename = f"img_to_vid_{i}"
446
+ else:
447
+ base_filename = f"text_to_vid_{i}"
448
+ output_filename = get_unique_filename(
449
+ base_filename,
450
+ ".mp4",
451
+ prompt=args.prompt,
452
+ seed=args.seed,
453
+ resolution=(height, width, num_frames),
454
+ dir=output_dir,
455
+ )
456
+
457
+ # Write video
458
+ with imageio.get_writer(output_filename, fps=fps) as video:
459
+ for frame in video_np:
460
+ video.append_data(frame)
461
+
462
+ # Write condition image
463
+ if args.input_image_path:
464
+ reference_image = (
465
+ (
466
+ media_items_prepad[0, :, 0].permute(1, 2, 0).cpu().data.numpy()
467
+ + 1.0
468
+ )
469
+ / 2.0
470
+ * 255
471
+ )
472
+ imageio.imwrite(
473
+ get_unique_filename(
474
+ base_filename,
475
+ ".png",
476
+ prompt=args.prompt,
477
+ seed=args.seed,
478
+ resolution=(height, width, num_frames),
479
+ dir=output_dir,
480
+ endswith="_condition",
481
+ ),
482
+ reference_image.astype(np.uint8),
483
+ )
484
+ logger.warning(f"Output saved to {output_dir}")
485
+
486
+
487
+ if __name__ == "__main__":
488
+ main()
itv.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from diffusers import LTXImageToVideoPipeline
3
+ from diffusers.utils import export_to_video, load_image
4
+
5
+ pipe = LTXImageToVideoPipeline.from_pretrained("Lightricks/LTX-Video", torch_dtype=torch.bfloat16)
6
+ pipe.to("cuda")
7
+
8
+ image = load_image(
9
+ "https://huggingface.co/datasets/a-r-r-o-w/tiny-meme-dataset-captioned/resolve/main/images/8.png"
10
+ )
11
+ prompt = "A young girl stands calmly in the foreground, looking directly at the camera, as a house fire rages in the background. Flames engulf the structure, with smoke billowing into the air. Firefighters in protective gear rush to the scene, a fire truck labeled '38' visible behind them. The girl's neutral expression contrasts sharply with the chaos of the fire, creating a poignant and emotionally charged scene."
12
+ negative_prompt = "worst quality, inconsistent motion, blurry, jittery, distorted"
13
+
14
+ video = pipe(
15
+ image=image,
16
+ prompt=prompt,
17
+ negative_prompt=negative_prompt,
18
+ width=704,
19
+ height=480,
20
+ num_frames=161,
21
+ num_inference_steps=50,
22
+ ).frames[0]
23
+ export_to_video(video, "output.mp4", fps=24)
ltx_video/__init__.py ADDED
File without changes
ltx_video/models/__init__.py ADDED
File without changes
ltx_video/models/autoencoders/__init__.py ADDED
File without changes
ltx_video/models/autoencoders/causal_conv3d.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Tuple, Union
2
+
3
+ import torch
4
+ import torch.nn as nn
5
+
6
+
7
+ class CausalConv3d(nn.Module):
8
+ def __init__(
9
+ self,
10
+ in_channels,
11
+ out_channels,
12
+ kernel_size: int = 3,
13
+ stride: Union[int, Tuple[int]] = 1,
14
+ dilation: int = 1,
15
+ groups: int = 1,
16
+ **kwargs,
17
+ ):
18
+ super().__init__()
19
+
20
+ self.in_channels = in_channels
21
+ self.out_channels = out_channels
22
+
23
+ kernel_size = (kernel_size, kernel_size, kernel_size)
24
+ self.time_kernel_size = kernel_size[0]
25
+
26
+ dilation = (dilation, 1, 1)
27
+
28
+ height_pad = kernel_size[1] // 2
29
+ width_pad = kernel_size[2] // 2
30
+ padding = (0, height_pad, width_pad)
31
+
32
+ self.conv = nn.Conv3d(
33
+ in_channels,
34
+ out_channels,
35
+ kernel_size,
36
+ stride=stride,
37
+ dilation=dilation,
38
+ padding=padding,
39
+ padding_mode="zeros",
40
+ groups=groups,
41
+ )
42
+
43
+ def forward(self, x, causal: bool = True):
44
+ if causal:
45
+ first_frame_pad = x[:, :, :1, :, :].repeat(
46
+ (1, 1, self.time_kernel_size - 1, 1, 1)
47
+ )
48
+ x = torch.concatenate((first_frame_pad, x), dim=2)
49
+ else:
50
+ first_frame_pad = x[:, :, :1, :, :].repeat(
51
+ (1, 1, (self.time_kernel_size - 1) // 2, 1, 1)
52
+ )
53
+ last_frame_pad = x[:, :, -1:, :, :].repeat(
54
+ (1, 1, (self.time_kernel_size - 1) // 2, 1, 1)
55
+ )
56
+ x = torch.concatenate((first_frame_pad, x, last_frame_pad), dim=2)
57
+ x = self.conv(x)
58
+ return x
59
+
60
+ @property
61
+ def weight(self):
62
+ return self.conv.weight
ltx_video/models/autoencoders/causal_video_autoencoder.py ADDED
@@ -0,0 +1,1263 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ from functools import partial
4
+ from types import SimpleNamespace
5
+ from typing import Any, Mapping, Optional, Tuple, Union, List
6
+ from pathlib import Path
7
+
8
+ import torch
9
+ import numpy as np
10
+ from einops import rearrange
11
+ from torch import nn
12
+ from diffusers.utils import logging
13
+ import torch.nn.functional as F
14
+ from diffusers.models.embeddings import PixArtAlphaCombinedTimestepSizeEmbeddings
15
+ from safetensors import safe_open
16
+
17
+
18
+ from ltx_video.models.autoencoders.conv_nd_factory import make_conv_nd, make_linear_nd
19
+ from ltx_video.models.autoencoders.pixel_norm import PixelNorm
20
+ from ltx_video.models.autoencoders.vae import AutoencoderKLWrapper
21
+ from ltx_video.models.transformers.attention import Attention
22
+ from ltx_video.utils.diffusers_config_mapping import (
23
+ diffusers_and_ours_config_mapping,
24
+ make_hashable_key,
25
+ VAE_KEYS_RENAME_DICT,
26
+ )
27
+
28
+ PER_CHANNEL_STATISTICS_PREFIX = "per_channel_statistics."
29
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
30
+
31
+
32
+ class CausalVideoAutoencoder(AutoencoderKLWrapper):
33
+ @classmethod
34
+ def from_pretrained(
35
+ cls,
36
+ pretrained_model_name_or_path: Optional[Union[str, os.PathLike]],
37
+ *args,
38
+ **kwargs,
39
+ ):
40
+ pretrained_model_name_or_path = Path(pretrained_model_name_or_path)
41
+ if (
42
+ pretrained_model_name_or_path.is_dir()
43
+ and (pretrained_model_name_or_path / "autoencoder.pth").exists()
44
+ ):
45
+ config_local_path = pretrained_model_name_or_path / "config.json"
46
+ config = cls.load_config(config_local_path, **kwargs)
47
+
48
+ model_local_path = pretrained_model_name_or_path / "autoencoder.pth"
49
+ state_dict = torch.load(model_local_path, map_location=torch.device("cpu"))
50
+
51
+ statistics_local_path = (
52
+ pretrained_model_name_or_path / "per_channel_statistics.json"
53
+ )
54
+ if statistics_local_path.exists():
55
+ with open(statistics_local_path, "r") as file:
56
+ data = json.load(file)
57
+ transposed_data = list(zip(*data["data"]))
58
+ data_dict = {
59
+ col: torch.tensor(vals)
60
+ for col, vals in zip(data["columns"], transposed_data)
61
+ }
62
+ std_of_means = data_dict["std-of-means"]
63
+ mean_of_means = data_dict.get(
64
+ "mean-of-means", torch.zeros_like(data_dict["std-of-means"])
65
+ )
66
+ state_dict[f"{PER_CHANNEL_STATISTICS_PREFIX}std-of-means"] = (
67
+ std_of_means
68
+ )
69
+ state_dict[f"{PER_CHANNEL_STATISTICS_PREFIX}mean-of-means"] = (
70
+ mean_of_means
71
+ )
72
+
73
+ elif pretrained_model_name_or_path.is_dir():
74
+ config_path = pretrained_model_name_or_path / "vae" / "config.json"
75
+ with open(config_path, "r") as f:
76
+ config = make_hashable_key(json.load(f))
77
+
78
+ assert config in diffusers_and_ours_config_mapping, (
79
+ "Provided diffusers checkpoint config for VAE is not suppported. "
80
+ "We only support diffusers configs found in Lightricks/LTX-Video."
81
+ )
82
+
83
+ config = diffusers_and_ours_config_mapping[config]
84
+
85
+ state_dict_path = (
86
+ pretrained_model_name_or_path
87
+ / "vae"
88
+ / "diffusion_pytorch_model.safetensors"
89
+ )
90
+
91
+ state_dict = {}
92
+ with safe_open(state_dict_path, framework="pt", device="cpu") as f:
93
+ for k in f.keys():
94
+ state_dict[k] = f.get_tensor(k)
95
+ for key in list(state_dict.keys()):
96
+ new_key = key
97
+ for replace_key, rename_key in VAE_KEYS_RENAME_DICT.items():
98
+ new_key = new_key.replace(replace_key, rename_key)
99
+
100
+ state_dict[new_key] = state_dict.pop(key)
101
+
102
+ elif pretrained_model_name_or_path.is_file() and str(
103
+ pretrained_model_name_or_path
104
+ ).endswith(".safetensors"):
105
+ state_dict = {}
106
+ with safe_open(
107
+ pretrained_model_name_or_path, framework="pt", device="cpu"
108
+ ) as f:
109
+ metadata = f.metadata()
110
+ for k in f.keys():
111
+ state_dict[k] = f.get_tensor(k)
112
+ configs = json.loads(metadata["config"])
113
+ config = configs["vae"]
114
+
115
+ video_vae = cls.from_config(config)
116
+ if "torch_dtype" in kwargs:
117
+ video_vae.to(kwargs["torch_dtype"])
118
+ video_vae.load_state_dict(state_dict)
119
+ return video_vae
120
+
121
+ @staticmethod
122
+ def from_config(config):
123
+ assert (
124
+ config["_class_name"] == "CausalVideoAutoencoder"
125
+ ), "config must have _class_name=CausalVideoAutoencoder"
126
+ if isinstance(config["dims"], list):
127
+ config["dims"] = tuple(config["dims"])
128
+
129
+ assert config["dims"] in [2, 3, (2, 1)], "dims must be 2, 3 or (2, 1)"
130
+
131
+ double_z = config.get("double_z", True)
132
+ latent_log_var = config.get(
133
+ "latent_log_var", "per_channel" if double_z else "none"
134
+ )
135
+ use_quant_conv = config.get("use_quant_conv", True)
136
+
137
+ if use_quant_conv and latent_log_var == "uniform":
138
+ raise ValueError("uniform latent_log_var requires use_quant_conv=False")
139
+
140
+ encoder = Encoder(
141
+ dims=config["dims"],
142
+ in_channels=config.get("in_channels", 3),
143
+ out_channels=config["latent_channels"],
144
+ blocks=config.get("encoder_blocks", config.get("blocks")),
145
+ patch_size=config.get("patch_size", 1),
146
+ latent_log_var=latent_log_var,
147
+ norm_layer=config.get("norm_layer", "group_norm"),
148
+ )
149
+
150
+ decoder = Decoder(
151
+ dims=config["dims"],
152
+ in_channels=config["latent_channels"],
153
+ out_channels=config.get("out_channels", 3),
154
+ blocks=config.get("decoder_blocks", config.get("blocks")),
155
+ patch_size=config.get("patch_size", 1),
156
+ norm_layer=config.get("norm_layer", "group_norm"),
157
+ causal=config.get("causal_decoder", False),
158
+ timestep_conditioning=config.get("timestep_conditioning", False),
159
+ )
160
+
161
+ dims = config["dims"]
162
+ return CausalVideoAutoencoder(
163
+ encoder=encoder,
164
+ decoder=decoder,
165
+ latent_channels=config["latent_channels"],
166
+ dims=dims,
167
+ use_quant_conv=use_quant_conv,
168
+ )
169
+
170
+ @property
171
+ def config(self):
172
+ return SimpleNamespace(
173
+ _class_name="CausalVideoAutoencoder",
174
+ dims=self.dims,
175
+ in_channels=self.encoder.conv_in.in_channels // self.encoder.patch_size**2,
176
+ out_channels=self.decoder.conv_out.out_channels
177
+ // self.decoder.patch_size**2,
178
+ latent_channels=self.decoder.conv_in.in_channels,
179
+ encoder_blocks=self.encoder.blocks_desc,
180
+ decoder_blocks=self.decoder.blocks_desc,
181
+ scaling_factor=1.0,
182
+ norm_layer=self.encoder.norm_layer,
183
+ patch_size=self.encoder.patch_size,
184
+ latent_log_var=self.encoder.latent_log_var,
185
+ use_quant_conv=self.use_quant_conv,
186
+ causal_decoder=self.decoder.causal,
187
+ timestep_conditioning=self.decoder.timestep_conditioning,
188
+ )
189
+
190
+ @property
191
+ def is_video_supported(self):
192
+ """
193
+ Check if the model supports video inputs of shape (B, C, F, H, W). Otherwise, the model only supports 2D images.
194
+ """
195
+ return self.dims != 2
196
+
197
+ @property
198
+ def spatial_downscale_factor(self):
199
+ return (
200
+ 2
201
+ ** len(
202
+ [
203
+ block
204
+ for block in self.encoder.blocks_desc
205
+ if block[0] in ["compress_space", "compress_all"]
206
+ ]
207
+ )
208
+ * self.encoder.patch_size
209
+ )
210
+
211
+ @property
212
+ def temporal_downscale_factor(self):
213
+ return 2 ** len(
214
+ [
215
+ block
216
+ for block in self.encoder.blocks_desc
217
+ if block[0] in ["compress_time", "compress_all"]
218
+ ]
219
+ )
220
+
221
+ def to_json_string(self) -> str:
222
+ import json
223
+
224
+ return json.dumps(self.config.__dict__)
225
+
226
+ def load_state_dict(self, state_dict: Mapping[str, Any], strict: bool = True):
227
+ if any([key.startswith("vae.") for key in state_dict.keys()]):
228
+ state_dict = {
229
+ key.replace("vae.", ""): value
230
+ for key, value in state_dict.items()
231
+ if key.startswith("vae.")
232
+ }
233
+ ckpt_state_dict = {
234
+ key: value
235
+ for key, value in state_dict.items()
236
+ if not key.startswith(PER_CHANNEL_STATISTICS_PREFIX)
237
+ }
238
+
239
+ model_keys = set(name for name, _ in self.named_parameters())
240
+
241
+ key_mapping = {
242
+ ".resnets.": ".res_blocks.",
243
+ "downsamplers.0": "downsample",
244
+ "upsamplers.0": "upsample",
245
+ }
246
+ converted_state_dict = {}
247
+ for key, value in ckpt_state_dict.items():
248
+ for k, v in key_mapping.items():
249
+ key = key.replace(k, v)
250
+
251
+ if "norm" in key and key not in model_keys:
252
+ logger.info(
253
+ f"Removing key {key} from state_dict as it is not present in the model"
254
+ )
255
+ continue
256
+
257
+ converted_state_dict[key] = value
258
+
259
+ super().load_state_dict(converted_state_dict, strict=strict)
260
+
261
+ data_dict = {
262
+ key.removeprefix(PER_CHANNEL_STATISTICS_PREFIX): value
263
+ for key, value in state_dict.items()
264
+ if key.startswith(PER_CHANNEL_STATISTICS_PREFIX)
265
+ }
266
+ if len(data_dict) > 0:
267
+ self.register_buffer("std_of_means", data_dict["std-of-means"])
268
+ self.register_buffer(
269
+ "mean_of_means",
270
+ data_dict.get(
271
+ "mean-of-means", torch.zeros_like(data_dict["std-of-means"])
272
+ ),
273
+ )
274
+
275
+ def last_layer(self):
276
+ if hasattr(self.decoder, "conv_out"):
277
+ if isinstance(self.decoder.conv_out, nn.Sequential):
278
+ last_layer = self.decoder.conv_out[-1]
279
+ else:
280
+ last_layer = self.decoder.conv_out
281
+ else:
282
+ last_layer = self.decoder.layers[-1]
283
+ return last_layer
284
+
285
+ def set_use_tpu_flash_attention(self):
286
+ for block in self.decoder.up_blocks:
287
+ if isinstance(block, UNetMidBlock3D) and block.attention_blocks:
288
+ for attention_block in block.attention_blocks:
289
+ attention_block.set_use_tpu_flash_attention()
290
+
291
+
292
+ class Encoder(nn.Module):
293
+ r"""
294
+ The `Encoder` layer of a variational autoencoder that encodes its input into a latent representation.
295
+
296
+ Args:
297
+ dims (`int` or `Tuple[int, int]`, *optional*, defaults to 3):
298
+ The number of dimensions to use in convolutions.
299
+ in_channels (`int`, *optional*, defaults to 3):
300
+ The number of input channels.
301
+ out_channels (`int`, *optional*, defaults to 3):
302
+ The number of output channels.
303
+ blocks (`List[Tuple[str, int]]`, *optional*, defaults to `[("res_x", 1)]`):
304
+ The blocks to use. Each block is a tuple of the block name and the number of layers.
305
+ base_channels (`int`, *optional*, defaults to 128):
306
+ The number of output channels for the first convolutional layer.
307
+ norm_num_groups (`int`, *optional*, defaults to 32):
308
+ The number of groups for normalization.
309
+ patch_size (`int`, *optional*, defaults to 1):
310
+ The patch size to use. Should be a power of 2.
311
+ norm_layer (`str`, *optional*, defaults to `group_norm`):
312
+ The normalization layer to use. Can be either `group_norm` or `pixel_norm`.
313
+ latent_log_var (`str`, *optional*, defaults to `per_channel`):
314
+ The number of channels for the log variance. Can be either `per_channel`, `uniform`, or `none`.
315
+ """
316
+
317
+ def __init__(
318
+ self,
319
+ dims: Union[int, Tuple[int, int]] = 3,
320
+ in_channels: int = 3,
321
+ out_channels: int = 3,
322
+ blocks: List[Tuple[str, int | dict]] = [("res_x", 1)],
323
+ base_channels: int = 128,
324
+ norm_num_groups: int = 32,
325
+ patch_size: Union[int, Tuple[int]] = 1,
326
+ norm_layer: str = "group_norm", # group_norm, pixel_norm
327
+ latent_log_var: str = "per_channel",
328
+ ):
329
+ super().__init__()
330
+ self.patch_size = patch_size
331
+ self.norm_layer = norm_layer
332
+ self.latent_channels = out_channels
333
+ self.latent_log_var = latent_log_var
334
+ self.blocks_desc = blocks
335
+
336
+ in_channels = in_channels * patch_size**2
337
+ output_channel = base_channels
338
+
339
+ self.conv_in = make_conv_nd(
340
+ dims=dims,
341
+ in_channels=in_channels,
342
+ out_channels=output_channel,
343
+ kernel_size=3,
344
+ stride=1,
345
+ padding=1,
346
+ causal=True,
347
+ )
348
+
349
+ self.down_blocks = nn.ModuleList([])
350
+
351
+ for block_name, block_params in blocks:
352
+ input_channel = output_channel
353
+ if isinstance(block_params, int):
354
+ block_params = {"num_layers": block_params}
355
+
356
+ if block_name == "res_x":
357
+ block = UNetMidBlock3D(
358
+ dims=dims,
359
+ in_channels=input_channel,
360
+ num_layers=block_params["num_layers"],
361
+ resnet_eps=1e-6,
362
+ resnet_groups=norm_num_groups,
363
+ norm_layer=norm_layer,
364
+ )
365
+ elif block_name == "res_x_y":
366
+ output_channel = block_params.get("multiplier", 2) * output_channel
367
+ block = ResnetBlock3D(
368
+ dims=dims,
369
+ in_channels=input_channel,
370
+ out_channels=output_channel,
371
+ eps=1e-6,
372
+ groups=norm_num_groups,
373
+ norm_layer=norm_layer,
374
+ )
375
+ elif block_name == "compress_time":
376
+ block = make_conv_nd(
377
+ dims=dims,
378
+ in_channels=input_channel,
379
+ out_channels=output_channel,
380
+ kernel_size=3,
381
+ stride=(2, 1, 1),
382
+ causal=True,
383
+ )
384
+ elif block_name == "compress_space":
385
+ block = make_conv_nd(
386
+ dims=dims,
387
+ in_channels=input_channel,
388
+ out_channels=output_channel,
389
+ kernel_size=3,
390
+ stride=(1, 2, 2),
391
+ causal=True,
392
+ )
393
+ elif block_name == "compress_all":
394
+ block = make_conv_nd(
395
+ dims=dims,
396
+ in_channels=input_channel,
397
+ out_channels=output_channel,
398
+ kernel_size=3,
399
+ stride=(2, 2, 2),
400
+ causal=True,
401
+ )
402
+ elif block_name == "compress_all_x_y":
403
+ output_channel = block_params.get("multiplier", 2) * output_channel
404
+ block = make_conv_nd(
405
+ dims=dims,
406
+ in_channels=input_channel,
407
+ out_channels=output_channel,
408
+ kernel_size=3,
409
+ stride=(2, 2, 2),
410
+ causal=True,
411
+ )
412
+ else:
413
+ raise ValueError(f"unknown block: {block_name}")
414
+
415
+ self.down_blocks.append(block)
416
+
417
+ # out
418
+ if norm_layer == "group_norm":
419
+ self.conv_norm_out = nn.GroupNorm(
420
+ num_channels=output_channel, num_groups=norm_num_groups, eps=1e-6
421
+ )
422
+ elif norm_layer == "pixel_norm":
423
+ self.conv_norm_out = PixelNorm()
424
+ elif norm_layer == "layer_norm":
425
+ self.conv_norm_out = LayerNorm(output_channel, eps=1e-6)
426
+
427
+ self.conv_act = nn.SiLU()
428
+
429
+ conv_out_channels = out_channels
430
+ if latent_log_var == "per_channel":
431
+ conv_out_channels *= 2
432
+ elif latent_log_var == "uniform":
433
+ conv_out_channels += 1
434
+ elif latent_log_var != "none":
435
+ raise ValueError(f"Invalid latent_log_var: {latent_log_var}")
436
+ self.conv_out = make_conv_nd(
437
+ dims, output_channel, conv_out_channels, 3, padding=1, causal=True
438
+ )
439
+
440
+ self.gradient_checkpointing = False
441
+
442
+ def forward(self, sample: torch.FloatTensor) -> torch.FloatTensor:
443
+ r"""The forward method of the `Encoder` class."""
444
+
445
+ sample = patchify(sample, patch_size_hw=self.patch_size, patch_size_t=1)
446
+ sample = self.conv_in(sample)
447
+
448
+ checkpoint_fn = (
449
+ partial(torch.utils.checkpoint.checkpoint, use_reentrant=False)
450
+ if self.gradient_checkpointing and self.training
451
+ else lambda x: x
452
+ )
453
+
454
+ for down_block in self.down_blocks:
455
+ sample = checkpoint_fn(down_block)(sample)
456
+
457
+ sample = self.conv_norm_out(sample)
458
+ sample = self.conv_act(sample)
459
+ sample = self.conv_out(sample)
460
+
461
+ if self.latent_log_var == "uniform":
462
+ last_channel = sample[:, -1:, ...]
463
+ num_dims = sample.dim()
464
+
465
+ if num_dims == 4:
466
+ # For shape (B, C, H, W)
467
+ repeated_last_channel = last_channel.repeat(
468
+ 1, sample.shape[1] - 2, 1, 1
469
+ )
470
+ sample = torch.cat([sample, repeated_last_channel], dim=1)
471
+ elif num_dims == 5:
472
+ # For shape (B, C, F, H, W)
473
+ repeated_last_channel = last_channel.repeat(
474
+ 1, sample.shape[1] - 2, 1, 1, 1
475
+ )
476
+ sample = torch.cat([sample, repeated_last_channel], dim=1)
477
+ else:
478
+ raise ValueError(f"Invalid input shape: {sample.shape}")
479
+
480
+ return sample
481
+
482
+
483
+ class Decoder(nn.Module):
484
+ r"""
485
+ The `Decoder` layer of a variational autoencoder that decodes its latent representation into an output sample.
486
+
487
+ Args:
488
+ dims (`int` or `Tuple[int, int]`, *optional*, defaults to 3):
489
+ The number of dimensions to use in convolutions.
490
+ in_channels (`int`, *optional*, defaults to 3):
491
+ The number of input channels.
492
+ out_channels (`int`, *optional*, defaults to 3):
493
+ The number of output channels.
494
+ blocks (`List[Tuple[str, int]]`, *optional*, defaults to `[("res_x", 1)]`):
495
+ The blocks to use. Each block is a tuple of the block name and the number of layers.
496
+ base_channels (`int`, *optional*, defaults to 128):
497
+ The number of output channels for the first convolutional layer.
498
+ norm_num_groups (`int`, *optional*, defaults to 32):
499
+ The number of groups for normalization.
500
+ patch_size (`int`, *optional*, defaults to 1):
501
+ The patch size to use. Should be a power of 2.
502
+ norm_layer (`str`, *optional*, defaults to `group_norm`):
503
+ The normalization layer to use. Can be either `group_norm` or `pixel_norm`.
504
+ causal (`bool`, *optional*, defaults to `True`):
505
+ Whether to use causal convolutions or not.
506
+ """
507
+
508
+ def __init__(
509
+ self,
510
+ dims,
511
+ in_channels: int = 3,
512
+ out_channels: int = 3,
513
+ blocks: List[Tuple[str, int | dict]] = [("res_x", 1)],
514
+ base_channels: int = 128,
515
+ layers_per_block: int = 2,
516
+ norm_num_groups: int = 32,
517
+ patch_size: int = 1,
518
+ norm_layer: str = "group_norm",
519
+ causal: bool = True,
520
+ timestep_conditioning: bool = False,
521
+ ):
522
+ super().__init__()
523
+ self.patch_size = patch_size
524
+ self.layers_per_block = layers_per_block
525
+ out_channels = out_channels * patch_size**2
526
+ self.causal = causal
527
+ self.blocks_desc = blocks
528
+
529
+ # Compute output channel to be product of all channel-multiplier blocks
530
+ output_channel = base_channels
531
+ for block_name, block_params in list(reversed(blocks)):
532
+ block_params = block_params if isinstance(block_params, dict) else {}
533
+ if block_name == "res_x_y":
534
+ output_channel = output_channel * block_params.get("multiplier", 2)
535
+ if block_name == "compress_all":
536
+ output_channel = output_channel * block_params.get("multiplier", 1)
537
+
538
+ self.conv_in = make_conv_nd(
539
+ dims,
540
+ in_channels,
541
+ output_channel,
542
+ kernel_size=3,
543
+ stride=1,
544
+ padding=1,
545
+ causal=True,
546
+ )
547
+
548
+ self.up_blocks = nn.ModuleList([])
549
+
550
+ for block_name, block_params in list(reversed(blocks)):
551
+ input_channel = output_channel
552
+ if isinstance(block_params, int):
553
+ block_params = {"num_layers": block_params}
554
+
555
+ if block_name == "res_x":
556
+ block = UNetMidBlock3D(
557
+ dims=dims,
558
+ in_channels=input_channel,
559
+ num_layers=block_params["num_layers"],
560
+ resnet_eps=1e-6,
561
+ resnet_groups=norm_num_groups,
562
+ norm_layer=norm_layer,
563
+ inject_noise=block_params.get("inject_noise", False),
564
+ timestep_conditioning=timestep_conditioning,
565
+ )
566
+ elif block_name == "attn_res_x":
567
+ block = UNetMidBlock3D(
568
+ dims=dims,
569
+ in_channels=input_channel,
570
+ num_layers=block_params["num_layers"],
571
+ resnet_groups=norm_num_groups,
572
+ norm_layer=norm_layer,
573
+ inject_noise=block_params.get("inject_noise", False),
574
+ timestep_conditioning=timestep_conditioning,
575
+ attention_head_dim=block_params["attention_head_dim"],
576
+ )
577
+ elif block_name == "res_x_y":
578
+ output_channel = output_channel // block_params.get("multiplier", 2)
579
+ block = ResnetBlock3D(
580
+ dims=dims,
581
+ in_channels=input_channel,
582
+ out_channels=output_channel,
583
+ eps=1e-6,
584
+ groups=norm_num_groups,
585
+ norm_layer=norm_layer,
586
+ inject_noise=block_params.get("inject_noise", False),
587
+ timestep_conditioning=False,
588
+ )
589
+ elif block_name == "compress_time":
590
+ block = DepthToSpaceUpsample(
591
+ dims=dims, in_channels=input_channel, stride=(2, 1, 1)
592
+ )
593
+ elif block_name == "compress_space":
594
+ block = DepthToSpaceUpsample(
595
+ dims=dims, in_channels=input_channel, stride=(1, 2, 2)
596
+ )
597
+ elif block_name == "compress_all":
598
+ output_channel = output_channel // block_params.get("multiplier", 1)
599
+ block = DepthToSpaceUpsample(
600
+ dims=dims,
601
+ in_channels=input_channel,
602
+ stride=(2, 2, 2),
603
+ residual=block_params.get("residual", False),
604
+ out_channels_reduction_factor=block_params.get("multiplier", 1),
605
+ )
606
+ else:
607
+ raise ValueError(f"unknown layer: {block_name}")
608
+
609
+ self.up_blocks.append(block)
610
+
611
+ if norm_layer == "group_norm":
612
+ self.conv_norm_out = nn.GroupNorm(
613
+ num_channels=output_channel, num_groups=norm_num_groups, eps=1e-6
614
+ )
615
+ elif norm_layer == "pixel_norm":
616
+ self.conv_norm_out = PixelNorm()
617
+ elif norm_layer == "layer_norm":
618
+ self.conv_norm_out = LayerNorm(output_channel, eps=1e-6)
619
+
620
+ self.conv_act = nn.SiLU()
621
+ self.conv_out = make_conv_nd(
622
+ dims, output_channel, out_channels, 3, padding=1, causal=True
623
+ )
624
+
625
+ self.gradient_checkpointing = False
626
+
627
+ self.timestep_conditioning = timestep_conditioning
628
+
629
+ if timestep_conditioning:
630
+ self.timestep_scale_multiplier = nn.Parameter(
631
+ torch.tensor(1000.0, dtype=torch.float32)
632
+ )
633
+ self.last_time_embedder = PixArtAlphaCombinedTimestepSizeEmbeddings(
634
+ output_channel * 2, 0
635
+ )
636
+ self.last_scale_shift_table = nn.Parameter(
637
+ torch.randn(2, output_channel) / output_channel**0.5
638
+ )
639
+
640
+ def forward(
641
+ self,
642
+ sample: torch.FloatTensor,
643
+ target_shape,
644
+ timestep: Optional[torch.Tensor] = None,
645
+ ) -> torch.FloatTensor:
646
+ r"""The forward method of the `Decoder` class."""
647
+ assert target_shape is not None, "target_shape must be provided"
648
+ batch_size = sample.shape[0]
649
+
650
+ sample = self.conv_in(sample, causal=self.causal)
651
+
652
+ upscale_dtype = next(iter(self.up_blocks.parameters())).dtype
653
+
654
+ checkpoint_fn = (
655
+ partial(torch.utils.checkpoint.checkpoint, use_reentrant=False)
656
+ if self.gradient_checkpointing and self.training
657
+ else lambda x: x
658
+ )
659
+
660
+ sample = sample.to(upscale_dtype)
661
+
662
+ if self.timestep_conditioning:
663
+ assert (
664
+ timestep is not None
665
+ ), "should pass timestep with timestep_conditioning=True"
666
+ scaled_timestep = timestep * self.timestep_scale_multiplier
667
+
668
+ for up_block in self.up_blocks:
669
+ if self.timestep_conditioning and isinstance(up_block, UNetMidBlock3D):
670
+ sample = checkpoint_fn(up_block)(
671
+ sample, causal=self.causal, timestep=scaled_timestep
672
+ )
673
+ else:
674
+ sample = checkpoint_fn(up_block)(sample, causal=self.causal)
675
+
676
+ sample = self.conv_norm_out(sample)
677
+
678
+ if self.timestep_conditioning:
679
+ embedded_timestep = self.last_time_embedder(
680
+ timestep=scaled_timestep.flatten(),
681
+ resolution=None,
682
+ aspect_ratio=None,
683
+ batch_size=sample.shape[0],
684
+ hidden_dtype=sample.dtype,
685
+ )
686
+ embedded_timestep = embedded_timestep.view(
687
+ batch_size, embedded_timestep.shape[-1], 1, 1, 1
688
+ )
689
+ ada_values = self.last_scale_shift_table[
690
+ None, ..., None, None, None
691
+ ] + embedded_timestep.reshape(
692
+ batch_size,
693
+ 2,
694
+ -1,
695
+ embedded_timestep.shape[-3],
696
+ embedded_timestep.shape[-2],
697
+ embedded_timestep.shape[-1],
698
+ )
699
+ shift, scale = ada_values.unbind(dim=1)
700
+ sample = sample * (1 + scale) + shift
701
+
702
+ sample = self.conv_act(sample)
703
+ sample = self.conv_out(sample, causal=self.causal)
704
+
705
+ sample = unpatchify(sample, patch_size_hw=self.patch_size, patch_size_t=1)
706
+
707
+ return sample
708
+
709
+
710
+ class UNetMidBlock3D(nn.Module):
711
+ """
712
+ A 3D UNet mid-block [`UNetMidBlock3D`] with multiple residual blocks.
713
+
714
+ Args:
715
+ in_channels (`int`): The number of input channels.
716
+ dropout (`float`, *optional*, defaults to 0.0): The dropout rate.
717
+ num_layers (`int`, *optional*, defaults to 1): The number of residual blocks.
718
+ resnet_eps (`float`, *optional*, 1e-6 ): The epsilon value for the resnet blocks.
719
+ resnet_groups (`int`, *optional*, defaults to 32):
720
+ The number of groups to use in the group normalization layers of the resnet blocks.
721
+ norm_layer (`str`, *optional*, defaults to `group_norm`):
722
+ The normalization layer to use. Can be either `group_norm` or `pixel_norm`.
723
+ inject_noise (`bool`, *optional*, defaults to `False`):
724
+ Whether to inject noise into the hidden states.
725
+ timestep_conditioning (`bool`, *optional*, defaults to `False`):
726
+ Whether to condition the hidden states on the timestep.
727
+ attention_head_dim (`int`, *optional*, defaults to -1):
728
+ The dimension of the attention head. If -1, no attention is used.
729
+
730
+ Returns:
731
+ `torch.FloatTensor`: The output of the last residual block, which is a tensor of shape `(batch_size,
732
+ in_channels, height, width)`.
733
+
734
+ """
735
+
736
+ def __init__(
737
+ self,
738
+ dims: Union[int, Tuple[int, int]],
739
+ in_channels: int,
740
+ dropout: float = 0.0,
741
+ num_layers: int = 1,
742
+ resnet_eps: float = 1e-6,
743
+ resnet_groups: int = 32,
744
+ norm_layer: str = "group_norm",
745
+ inject_noise: bool = False,
746
+ timestep_conditioning: bool = False,
747
+ attention_head_dim: int = -1,
748
+ ):
749
+ super().__init__()
750
+ resnet_groups = (
751
+ resnet_groups if resnet_groups is not None else min(in_channels // 4, 32)
752
+ )
753
+ self.timestep_conditioning = timestep_conditioning
754
+
755
+ if timestep_conditioning:
756
+ self.time_embedder = PixArtAlphaCombinedTimestepSizeEmbeddings(
757
+ in_channels * 4, 0
758
+ )
759
+
760
+ self.res_blocks = nn.ModuleList(
761
+ [
762
+ ResnetBlock3D(
763
+ dims=dims,
764
+ in_channels=in_channels,
765
+ out_channels=in_channels,
766
+ eps=resnet_eps,
767
+ groups=resnet_groups,
768
+ dropout=dropout,
769
+ norm_layer=norm_layer,
770
+ inject_noise=inject_noise,
771
+ timestep_conditioning=timestep_conditioning,
772
+ )
773
+ for _ in range(num_layers)
774
+ ]
775
+ )
776
+
777
+ self.attention_blocks = None
778
+
779
+ if attention_head_dim > 0:
780
+ if attention_head_dim > in_channels:
781
+ raise ValueError(
782
+ "attention_head_dim must be less than or equal to in_channels"
783
+ )
784
+
785
+ self.attention_blocks = nn.ModuleList(
786
+ [
787
+ Attention(
788
+ query_dim=in_channels,
789
+ heads=in_channels // attention_head_dim,
790
+ dim_head=attention_head_dim,
791
+ bias=True,
792
+ out_bias=True,
793
+ qk_norm="rms_norm",
794
+ residual_connection=True,
795
+ )
796
+ for _ in range(num_layers)
797
+ ]
798
+ )
799
+
800
+ def forward(
801
+ self,
802
+ hidden_states: torch.FloatTensor,
803
+ causal: bool = True,
804
+ timestep: Optional[torch.Tensor] = None,
805
+ ) -> torch.FloatTensor:
806
+ timestep_embed = None
807
+ if self.timestep_conditioning:
808
+ assert (
809
+ timestep is not None
810
+ ), "should pass timestep with timestep_conditioning=True"
811
+ batch_size = hidden_states.shape[0]
812
+ timestep_embed = self.time_embedder(
813
+ timestep=timestep.flatten(),
814
+ resolution=None,
815
+ aspect_ratio=None,
816
+ batch_size=batch_size,
817
+ hidden_dtype=hidden_states.dtype,
818
+ )
819
+ timestep_embed = timestep_embed.view(
820
+ batch_size, timestep_embed.shape[-1], 1, 1, 1
821
+ )
822
+
823
+ if self.attention_blocks:
824
+ for resnet, attention in zip(self.res_blocks, self.attention_blocks):
825
+ hidden_states = resnet(
826
+ hidden_states, causal=causal, timestep=timestep_embed
827
+ )
828
+
829
+ # Reshape the hidden states to be (batch_size, frames * height * width, channel)
830
+ batch_size, channel, frames, height, width = hidden_states.shape
831
+ hidden_states = hidden_states.view(
832
+ batch_size, channel, frames * height * width
833
+ ).transpose(1, 2)
834
+
835
+ if attention.use_tpu_flash_attention:
836
+ # Pad the second dimension to be divisible by block_k_major (block in flash attention)
837
+ seq_len = hidden_states.shape[1]
838
+ block_k_major = 512
839
+ pad_len = (block_k_major - seq_len % block_k_major) % block_k_major
840
+ if pad_len > 0:
841
+ hidden_states = F.pad(
842
+ hidden_states, (0, 0, 0, pad_len), "constant", 0
843
+ )
844
+
845
+ # Create a mask with ones for the original sequence length and zeros for the padded indexes
846
+ mask = torch.ones(
847
+ (hidden_states.shape[0], seq_len),
848
+ device=hidden_states.device,
849
+ dtype=hidden_states.dtype,
850
+ )
851
+ if pad_len > 0:
852
+ mask = F.pad(mask, (0, pad_len), "constant", 0)
853
+
854
+ hidden_states = attention(
855
+ hidden_states,
856
+ attention_mask=(
857
+ None if not attention.use_tpu_flash_attention else mask
858
+ ),
859
+ )
860
+
861
+ if attention.use_tpu_flash_attention:
862
+ # Remove the padding
863
+ if pad_len > 0:
864
+ hidden_states = hidden_states[:, :-pad_len, :]
865
+
866
+ # Reshape the hidden states back to (batch_size, channel, frames, height, width, channel)
867
+ hidden_states = hidden_states.transpose(-1, -2).reshape(
868
+ batch_size, channel, frames, height, width
869
+ )
870
+ else:
871
+ for resnet in self.res_blocks:
872
+ hidden_states = resnet(
873
+ hidden_states, causal=causal, timestep=timestep_embed
874
+ )
875
+
876
+ return hidden_states
877
+
878
+
879
+ class DepthToSpaceUpsample(nn.Module):
880
+ def __init__(
881
+ self, dims, in_channels, stride, residual=False, out_channels_reduction_factor=1
882
+ ):
883
+ super().__init__()
884
+ self.stride = stride
885
+ self.out_channels = (
886
+ np.prod(stride) * in_channels // out_channels_reduction_factor
887
+ )
888
+ self.conv = make_conv_nd(
889
+ dims=dims,
890
+ in_channels=in_channels,
891
+ out_channels=self.out_channels,
892
+ kernel_size=3,
893
+ stride=1,
894
+ causal=True,
895
+ )
896
+ self.residual = residual
897
+ self.out_channels_reduction_factor = out_channels_reduction_factor
898
+
899
+ def forward(self, x, causal: bool = True):
900
+ if self.residual:
901
+ # Reshape and duplicate the input to match the output shape
902
+ x_in = rearrange(
903
+ x,
904
+ "b (c p1 p2 p3) d h w -> b c (d p1) (h p2) (w p3)",
905
+ p1=self.stride[0],
906
+ p2=self.stride[1],
907
+ p3=self.stride[2],
908
+ )
909
+ num_repeat = np.prod(self.stride) // self.out_channels_reduction_factor
910
+ x_in = x_in.repeat(1, num_repeat, 1, 1, 1)
911
+ if self.stride[0] == 2:
912
+ x_in = x_in[:, :, 1:, :, :]
913
+ x = self.conv(x, causal=causal)
914
+ x = rearrange(
915
+ x,
916
+ "b (c p1 p2 p3) d h w -> b c (d p1) (h p2) (w p3)",
917
+ p1=self.stride[0],
918
+ p2=self.stride[1],
919
+ p3=self.stride[2],
920
+ )
921
+ if self.stride[0] == 2:
922
+ x = x[:, :, 1:, :, :]
923
+ if self.residual:
924
+ x = x + x_in
925
+ return x
926
+
927
+
928
+ class LayerNorm(nn.Module):
929
+ def __init__(self, dim, eps, elementwise_affine=True) -> None:
930
+ super().__init__()
931
+ self.norm = nn.LayerNorm(dim, eps=eps, elementwise_affine=elementwise_affine)
932
+
933
+ def forward(self, x):
934
+ x = rearrange(x, "b c d h w -> b d h w c")
935
+ x = self.norm(x)
936
+ x = rearrange(x, "b d h w c -> b c d h w")
937
+ return x
938
+
939
+
940
+ class ResnetBlock3D(nn.Module):
941
+ r"""
942
+ A Resnet block.
943
+
944
+ Parameters:
945
+ in_channels (`int`): The number of channels in the input.
946
+ out_channels (`int`, *optional*, default to be `None`):
947
+ The number of output channels for the first conv layer. If None, same as `in_channels`.
948
+ dropout (`float`, *optional*, defaults to `0.0`): The dropout probability to use.
949
+ groups (`int`, *optional*, default to `32`): The number of groups to use for the first normalization layer.
950
+ eps (`float`, *optional*, defaults to `1e-6`): The epsilon to use for the normalization.
951
+ """
952
+
953
+ def __init__(
954
+ self,
955
+ dims: Union[int, Tuple[int, int]],
956
+ in_channels: int,
957
+ out_channels: Optional[int] = None,
958
+ dropout: float = 0.0,
959
+ groups: int = 32,
960
+ eps: float = 1e-6,
961
+ norm_layer: str = "group_norm",
962
+ inject_noise: bool = False,
963
+ timestep_conditioning: bool = False,
964
+ ):
965
+ super().__init__()
966
+ self.in_channels = in_channels
967
+ out_channels = in_channels if out_channels is None else out_channels
968
+ self.out_channels = out_channels
969
+ self.inject_noise = inject_noise
970
+
971
+ if norm_layer == "group_norm":
972
+ self.norm1 = nn.GroupNorm(
973
+ num_groups=groups, num_channels=in_channels, eps=eps, affine=True
974
+ )
975
+ elif norm_layer == "pixel_norm":
976
+ self.norm1 = PixelNorm()
977
+ elif norm_layer == "layer_norm":
978
+ self.norm1 = LayerNorm(in_channels, eps=eps, elementwise_affine=True)
979
+
980
+ self.non_linearity = nn.SiLU()
981
+
982
+ self.conv1 = make_conv_nd(
983
+ dims,
984
+ in_channels,
985
+ out_channels,
986
+ kernel_size=3,
987
+ stride=1,
988
+ padding=1,
989
+ causal=True,
990
+ )
991
+
992
+ if inject_noise:
993
+ self.per_channel_scale1 = nn.Parameter(torch.zeros((in_channels, 1, 1)))
994
+
995
+ if norm_layer == "group_norm":
996
+ self.norm2 = nn.GroupNorm(
997
+ num_groups=groups, num_channels=out_channels, eps=eps, affine=True
998
+ )
999
+ elif norm_layer == "pixel_norm":
1000
+ self.norm2 = PixelNorm()
1001
+ elif norm_layer == "layer_norm":
1002
+ self.norm2 = LayerNorm(out_channels, eps=eps, elementwise_affine=True)
1003
+
1004
+ self.dropout = torch.nn.Dropout(dropout)
1005
+
1006
+ self.conv2 = make_conv_nd(
1007
+ dims,
1008
+ out_channels,
1009
+ out_channels,
1010
+ kernel_size=3,
1011
+ stride=1,
1012
+ padding=1,
1013
+ causal=True,
1014
+ )
1015
+
1016
+ if inject_noise:
1017
+ self.per_channel_scale2 = nn.Parameter(torch.zeros((in_channels, 1, 1)))
1018
+
1019
+ self.conv_shortcut = (
1020
+ make_linear_nd(
1021
+ dims=dims, in_channels=in_channels, out_channels=out_channels
1022
+ )
1023
+ if in_channels != out_channels
1024
+ else nn.Identity()
1025
+ )
1026
+
1027
+ self.norm3 = (
1028
+ LayerNorm(in_channels, eps=eps, elementwise_affine=True)
1029
+ if in_channels != out_channels
1030
+ else nn.Identity()
1031
+ )
1032
+
1033
+ self.timestep_conditioning = timestep_conditioning
1034
+
1035
+ if timestep_conditioning:
1036
+ self.scale_shift_table = nn.Parameter(
1037
+ torch.randn(4, in_channels) / in_channels**0.5
1038
+ )
1039
+
1040
+ def _feed_spatial_noise(
1041
+ self, hidden_states: torch.FloatTensor, per_channel_scale: torch.FloatTensor
1042
+ ) -> torch.FloatTensor:
1043
+ spatial_shape = hidden_states.shape[-2:]
1044
+ device = hidden_states.device
1045
+ dtype = hidden_states.dtype
1046
+
1047
+ # similar to the "explicit noise inputs" method in style-gan
1048
+ spatial_noise = torch.randn(spatial_shape, device=device, dtype=dtype)[None]
1049
+ scaled_noise = (spatial_noise * per_channel_scale)[None, :, None, ...]
1050
+ hidden_states = hidden_states + scaled_noise
1051
+
1052
+ return hidden_states
1053
+
1054
+ def forward(
1055
+ self,
1056
+ input_tensor: torch.FloatTensor,
1057
+ causal: bool = True,
1058
+ timestep: Optional[torch.Tensor] = None,
1059
+ ) -> torch.FloatTensor:
1060
+ hidden_states = input_tensor
1061
+ batch_size = hidden_states.shape[0]
1062
+
1063
+ hidden_states = self.norm1(hidden_states)
1064
+ if self.timestep_conditioning:
1065
+ assert (
1066
+ timestep is not None
1067
+ ), "should pass timestep with timestep_conditioning=True"
1068
+ ada_values = self.scale_shift_table[
1069
+ None, ..., None, None, None
1070
+ ] + timestep.reshape(
1071
+ batch_size,
1072
+ 4,
1073
+ -1,
1074
+ timestep.shape[-3],
1075
+ timestep.shape[-2],
1076
+ timestep.shape[-1],
1077
+ )
1078
+ shift1, scale1, shift2, scale2 = ada_values.unbind(dim=1)
1079
+
1080
+ hidden_states = hidden_states * (1 + scale1) + shift1
1081
+
1082
+ hidden_states = self.non_linearity(hidden_states)
1083
+
1084
+ hidden_states = self.conv1(hidden_states, causal=causal)
1085
+
1086
+ if self.inject_noise:
1087
+ hidden_states = self._feed_spatial_noise(
1088
+ hidden_states, self.per_channel_scale1
1089
+ )
1090
+
1091
+ hidden_states = self.norm2(hidden_states)
1092
+
1093
+ if self.timestep_conditioning:
1094
+ hidden_states = hidden_states * (1 + scale2) + shift2
1095
+
1096
+ hidden_states = self.non_linearity(hidden_states)
1097
+
1098
+ hidden_states = self.dropout(hidden_states)
1099
+
1100
+ hidden_states = self.conv2(hidden_states, causal=causal)
1101
+
1102
+ if self.inject_noise:
1103
+ hidden_states = self._feed_spatial_noise(
1104
+ hidden_states, self.per_channel_scale2
1105
+ )
1106
+
1107
+ input_tensor = self.norm3(input_tensor)
1108
+
1109
+ batch_size = input_tensor.shape[0]
1110
+
1111
+ input_tensor = self.conv_shortcut(input_tensor)
1112
+
1113
+ output_tensor = input_tensor + hidden_states
1114
+
1115
+ return output_tensor
1116
+
1117
+
1118
+ def patchify(x, patch_size_hw, patch_size_t=1):
1119
+ if patch_size_hw == 1 and patch_size_t == 1:
1120
+ return x
1121
+ if x.dim() == 4:
1122
+ x = rearrange(
1123
+ x, "b c (h q) (w r) -> b (c r q) h w", q=patch_size_hw, r=patch_size_hw
1124
+ )
1125
+ elif x.dim() == 5:
1126
+ x = rearrange(
1127
+ x,
1128
+ "b c (f p) (h q) (w r) -> b (c p r q) f h w",
1129
+ p=patch_size_t,
1130
+ q=patch_size_hw,
1131
+ r=patch_size_hw,
1132
+ )
1133
+ else:
1134
+ raise ValueError(f"Invalid input shape: {x.shape}")
1135
+
1136
+ return x
1137
+
1138
+
1139
+ def unpatchify(x, patch_size_hw, patch_size_t=1):
1140
+ if patch_size_hw == 1 and patch_size_t == 1:
1141
+ return x
1142
+
1143
+ if x.dim() == 4:
1144
+ x = rearrange(
1145
+ x, "b (c r q) h w -> b c (h q) (w r)", q=patch_size_hw, r=patch_size_hw
1146
+ )
1147
+ elif x.dim() == 5:
1148
+ x = rearrange(
1149
+ x,
1150
+ "b (c p r q) f h w -> b c (f p) (h q) (w r)",
1151
+ p=patch_size_t,
1152
+ q=patch_size_hw,
1153
+ r=patch_size_hw,
1154
+ )
1155
+
1156
+ return x
1157
+
1158
+
1159
+ def create_video_autoencoder_config(
1160
+ latent_channels: int = 64,
1161
+ ):
1162
+ encoder_blocks = [
1163
+ ("res_x", {"num_layers": 4}),
1164
+ ("compress_all_x_y", {"multiplier": 3}),
1165
+ ("res_x", {"num_layers": 4}),
1166
+ ("compress_all_x_y", {"multiplier": 2}),
1167
+ ("res_x", {"num_layers": 4}),
1168
+ ("compress_all", {}),
1169
+ ("res_x", {"num_layers": 3}),
1170
+ ("res_x", {"num_layers": 4}),
1171
+ ]
1172
+ decoder_blocks = [
1173
+ ("res_x", {"num_layers": 4}),
1174
+ ("compress_all", {"residual": True}),
1175
+ ("res_x_y", {"multiplier": 3}),
1176
+ ("res_x", {"num_layers": 3}),
1177
+ ("compress_all", {"residual": True}),
1178
+ ("res_x_y", {"multiplier": 2}),
1179
+ ("res_x", {"num_layers": 3}),
1180
+ ("compress_all", {"residual": True}),
1181
+ ("res_x", {"num_layers": 3}),
1182
+ ("res_x", {"num_layers": 4}),
1183
+ ]
1184
+ return {
1185
+ "_class_name": "CausalVideoAutoencoder",
1186
+ "dims": 3,
1187
+ "encoder_blocks": encoder_blocks,
1188
+ "decoder_blocks": decoder_blocks,
1189
+ "latent_channels": latent_channels,
1190
+ "norm_layer": "pixel_norm",
1191
+ "patch_size": 4,
1192
+ "latent_log_var": "uniform",
1193
+ "use_quant_conv": False,
1194
+ "causal_decoder": False,
1195
+ "timestep_conditioning": True,
1196
+ }
1197
+
1198
+
1199
+ def test_vae_patchify_unpatchify():
1200
+ import torch
1201
+
1202
+ x = torch.randn(2, 3, 8, 64, 64)
1203
+ x_patched = patchify(x, patch_size_hw=4, patch_size_t=4)
1204
+ x_unpatched = unpatchify(x_patched, patch_size_hw=4, patch_size_t=4)
1205
+ assert torch.allclose(x, x_unpatched)
1206
+
1207
+
1208
+ def demo_video_autoencoder_forward_backward():
1209
+ # Configuration for the VideoAutoencoder
1210
+ config = create_video_autoencoder_config()
1211
+
1212
+ # Instantiate the VideoAutoencoder with the specified configuration
1213
+ video_autoencoder = CausalVideoAutoencoder.from_config(config)
1214
+
1215
+ print(video_autoencoder)
1216
+ video_autoencoder.eval()
1217
+ # Print the total number of parameters in the video autoencoder
1218
+ total_params = sum(p.numel() for p in video_autoencoder.parameters())
1219
+ print(f"Total number of parameters in VideoAutoencoder: {total_params:,}")
1220
+
1221
+ # Create a mock input tensor simulating a batch of videos
1222
+ # Shape: (batch_size, channels, depth, height, width)
1223
+ # E.g., 4 videos, each with 3 color channels, 16 frames, and 64x64 pixels per frame
1224
+ input_videos = torch.randn(2, 3, 17, 64, 64)
1225
+
1226
+ # Forward pass: encode and decode the input videos
1227
+ latent = video_autoencoder.encode(input_videos).latent_dist.mode()
1228
+ print(f"input shape={input_videos.shape}")
1229
+ print(f"latent shape={latent.shape}")
1230
+
1231
+ timestep = torch.ones(input_videos.shape[0]) * 0.1
1232
+ reconstructed_videos = video_autoencoder.decode(
1233
+ latent, target_shape=input_videos.shape, timestep=timestep
1234
+ ).sample
1235
+
1236
+ print(f"reconstructed shape={reconstructed_videos.shape}")
1237
+
1238
+ # Validate that single image gets treated the same way as first frame
1239
+ input_image = input_videos[:, :, :1, :, :]
1240
+ image_latent = video_autoencoder.encode(input_image).latent_dist.mode()
1241
+ _ = video_autoencoder.decode(
1242
+ image_latent, target_shape=image_latent.shape, timestep=timestep
1243
+ ).sample
1244
+
1245
+ # first_frame_latent = latent[:, :, :1, :, :]
1246
+
1247
+ # assert torch.allclose(image_latent, first_frame_latent, atol=1e-6)
1248
+ # assert torch.allclose(reconstructed_image, reconstructed_videos[:, :, :1, :, :], atol=1e-6)
1249
+ # assert (image_latent == first_frame_latent).all()
1250
+ # assert (reconstructed_image == reconstructed_videos[:, :, :1, :, :]).all()
1251
+
1252
+ # Calculate the loss (e.g., mean squared error)
1253
+ loss = torch.nn.functional.mse_loss(input_videos, reconstructed_videos)
1254
+
1255
+ # Perform backward pass
1256
+ loss.backward()
1257
+
1258
+ print(f"Demo completed with loss: {loss.item()}")
1259
+
1260
+
1261
+ # Ensure to call the demo function to execute the forward and backward pass
1262
+ if __name__ == "__main__":
1263
+ demo_video_autoencoder_forward_backward()
ltx_video/models/autoencoders/conv_nd_factory.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Tuple, Union
2
+
3
+ import torch
4
+
5
+ from ltx_video.models.autoencoders.dual_conv3d import DualConv3d
6
+ from ltx_video.models.autoencoders.causal_conv3d import CausalConv3d
7
+
8
+
9
+ def make_conv_nd(
10
+ dims: Union[int, Tuple[int, int]],
11
+ in_channels: int,
12
+ out_channels: int,
13
+ kernel_size: int,
14
+ stride=1,
15
+ padding=0,
16
+ dilation=1,
17
+ groups=1,
18
+ bias=True,
19
+ causal=False,
20
+ ):
21
+ if dims == 2:
22
+ return torch.nn.Conv2d(
23
+ in_channels=in_channels,
24
+ out_channels=out_channels,
25
+ kernel_size=kernel_size,
26
+ stride=stride,
27
+ padding=padding,
28
+ dilation=dilation,
29
+ groups=groups,
30
+ bias=bias,
31
+ )
32
+ elif dims == 3:
33
+ if causal:
34
+ return CausalConv3d(
35
+ in_channels=in_channels,
36
+ out_channels=out_channels,
37
+ kernel_size=kernel_size,
38
+ stride=stride,
39
+ padding=padding,
40
+ dilation=dilation,
41
+ groups=groups,
42
+ bias=bias,
43
+ )
44
+ return torch.nn.Conv3d(
45
+ in_channels=in_channels,
46
+ out_channels=out_channels,
47
+ kernel_size=kernel_size,
48
+ stride=stride,
49
+ padding=padding,
50
+ dilation=dilation,
51
+ groups=groups,
52
+ bias=bias,
53
+ )
54
+ elif dims == (2, 1):
55
+ return DualConv3d(
56
+ in_channels=in_channels,
57
+ out_channels=out_channels,
58
+ kernel_size=kernel_size,
59
+ stride=stride,
60
+ padding=padding,
61
+ bias=bias,
62
+ )
63
+ else:
64
+ raise ValueError(f"unsupported dimensions: {dims}")
65
+
66
+
67
+ def make_linear_nd(
68
+ dims: int,
69
+ in_channels: int,
70
+ out_channels: int,
71
+ bias=True,
72
+ ):
73
+ if dims == 2:
74
+ return torch.nn.Conv2d(
75
+ in_channels=in_channels, out_channels=out_channels, kernel_size=1, bias=bias
76
+ )
77
+ elif dims == 3 or dims == (2, 1):
78
+ return torch.nn.Conv3d(
79
+ in_channels=in_channels, out_channels=out_channels, kernel_size=1, bias=bias
80
+ )
81
+ else:
82
+ raise ValueError(f"unsupported dimensions: {dims}")
ltx_video/models/autoencoders/dual_conv3d.py ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from typing import Tuple, Union
3
+
4
+ import torch
5
+ import torch.nn as nn
6
+ import torch.nn.functional as F
7
+ from einops import rearrange
8
+
9
+
10
+ class DualConv3d(nn.Module):
11
+ def __init__(
12
+ self,
13
+ in_channels,
14
+ out_channels,
15
+ kernel_size,
16
+ stride: Union[int, Tuple[int, int, int]] = 1,
17
+ padding: Union[int, Tuple[int, int, int]] = 0,
18
+ dilation: Union[int, Tuple[int, int, int]] = 1,
19
+ groups=1,
20
+ bias=True,
21
+ ):
22
+ super(DualConv3d, self).__init__()
23
+
24
+ self.in_channels = in_channels
25
+ self.out_channels = out_channels
26
+ # Ensure kernel_size, stride, padding, and dilation are tuples of length 3
27
+ if isinstance(kernel_size, int):
28
+ kernel_size = (kernel_size, kernel_size, kernel_size)
29
+ if kernel_size == (1, 1, 1):
30
+ raise ValueError(
31
+ "kernel_size must be greater than 1. Use make_linear_nd instead."
32
+ )
33
+ if isinstance(stride, int):
34
+ stride = (stride, stride, stride)
35
+ if isinstance(padding, int):
36
+ padding = (padding, padding, padding)
37
+ if isinstance(dilation, int):
38
+ dilation = (dilation, dilation, dilation)
39
+
40
+ # Set parameters for convolutions
41
+ self.groups = groups
42
+ self.bias = bias
43
+
44
+ # Define the size of the channels after the first convolution
45
+ intermediate_channels = (
46
+ out_channels if in_channels < out_channels else in_channels
47
+ )
48
+
49
+ # Define parameters for the first convolution
50
+ self.weight1 = nn.Parameter(
51
+ torch.Tensor(
52
+ intermediate_channels,
53
+ in_channels // groups,
54
+ 1,
55
+ kernel_size[1],
56
+ kernel_size[2],
57
+ )
58
+ )
59
+ self.stride1 = (1, stride[1], stride[2])
60
+ self.padding1 = (0, padding[1], padding[2])
61
+ self.dilation1 = (1, dilation[1], dilation[2])
62
+ if bias:
63
+ self.bias1 = nn.Parameter(torch.Tensor(intermediate_channels))
64
+ else:
65
+ self.register_parameter("bias1", None)
66
+
67
+ # Define parameters for the second convolution
68
+ self.weight2 = nn.Parameter(
69
+ torch.Tensor(
70
+ out_channels, intermediate_channels // groups, kernel_size[0], 1, 1
71
+ )
72
+ )
73
+ self.stride2 = (stride[0], 1, 1)
74
+ self.padding2 = (padding[0], 0, 0)
75
+ self.dilation2 = (dilation[0], 1, 1)
76
+ if bias:
77
+ self.bias2 = nn.Parameter(torch.Tensor(out_channels))
78
+ else:
79
+ self.register_parameter("bias2", None)
80
+
81
+ # Initialize weights and biases
82
+ self.reset_parameters()
83
+
84
+ def reset_parameters(self):
85
+ nn.init.kaiming_uniform_(self.weight1, a=math.sqrt(5))
86
+ nn.init.kaiming_uniform_(self.weight2, a=math.sqrt(5))
87
+ if self.bias:
88
+ fan_in1, _ = nn.init._calculate_fan_in_and_fan_out(self.weight1)
89
+ bound1 = 1 / math.sqrt(fan_in1)
90
+ nn.init.uniform_(self.bias1, -bound1, bound1)
91
+ fan_in2, _ = nn.init._calculate_fan_in_and_fan_out(self.weight2)
92
+ bound2 = 1 / math.sqrt(fan_in2)
93
+ nn.init.uniform_(self.bias2, -bound2, bound2)
94
+
95
+ def forward(self, x, use_conv3d=False, skip_time_conv=False):
96
+ if use_conv3d:
97
+ return self.forward_with_3d(x=x, skip_time_conv=skip_time_conv)
98
+ else:
99
+ return self.forward_with_2d(x=x, skip_time_conv=skip_time_conv)
100
+
101
+ def forward_with_3d(self, x, skip_time_conv):
102
+ # First convolution
103
+ x = F.conv3d(
104
+ x,
105
+ self.weight1,
106
+ self.bias1,
107
+ self.stride1,
108
+ self.padding1,
109
+ self.dilation1,
110
+ self.groups,
111
+ )
112
+
113
+ if skip_time_conv:
114
+ return x
115
+
116
+ # Second convolution
117
+ x = F.conv3d(
118
+ x,
119
+ self.weight2,
120
+ self.bias2,
121
+ self.stride2,
122
+ self.padding2,
123
+ self.dilation2,
124
+ self.groups,
125
+ )
126
+
127
+ return x
128
+
129
+ def forward_with_2d(self, x, skip_time_conv):
130
+ b, c, d, h, w = x.shape
131
+
132
+ # First 2D convolution
133
+ x = rearrange(x, "b c d h w -> (b d) c h w")
134
+ # Squeeze the depth dimension out of weight1 since it's 1
135
+ weight1 = self.weight1.squeeze(2)
136
+ # Select stride, padding, and dilation for the 2D convolution
137
+ stride1 = (self.stride1[1], self.stride1[2])
138
+ padding1 = (self.padding1[1], self.padding1[2])
139
+ dilation1 = (self.dilation1[1], self.dilation1[2])
140
+ x = F.conv2d(x, weight1, self.bias1, stride1, padding1, dilation1, self.groups)
141
+
142
+ _, _, h, w = x.shape
143
+
144
+ if skip_time_conv:
145
+ x = rearrange(x, "(b d) c h w -> b c d h w", b=b)
146
+ return x
147
+
148
+ # Second convolution which is essentially treated as a 1D convolution across the 'd' dimension
149
+ x = rearrange(x, "(b d) c h w -> (b h w) c d", b=b)
150
+
151
+ # Reshape weight2 to match the expected dimensions for conv1d
152
+ weight2 = self.weight2.squeeze(-1).squeeze(-1)
153
+ # Use only the relevant dimension for stride, padding, and dilation for the 1D convolution
154
+ stride2 = self.stride2[0]
155
+ padding2 = self.padding2[0]
156
+ dilation2 = self.dilation2[0]
157
+ x = F.conv1d(x, weight2, self.bias2, stride2, padding2, dilation2, self.groups)
158
+ x = rearrange(x, "(b h w) c d -> b c d h w", b=b, h=h, w=w)
159
+
160
+ return x
161
+
162
+ @property
163
+ def weight(self):
164
+ return self.weight2
165
+
166
+
167
+ def test_dual_conv3d_consistency():
168
+ # Initialize parameters
169
+ in_channels = 3
170
+ out_channels = 5
171
+ kernel_size = (3, 3, 3)
172
+ stride = (2, 2, 2)
173
+ padding = (1, 1, 1)
174
+
175
+ # Create an instance of the DualConv3d class
176
+ dual_conv3d = DualConv3d(
177
+ in_channels=in_channels,
178
+ out_channels=out_channels,
179
+ kernel_size=kernel_size,
180
+ stride=stride,
181
+ padding=padding,
182
+ bias=True,
183
+ )
184
+
185
+ # Example input tensor
186
+ test_input = torch.randn(1, 3, 10, 10, 10)
187
+
188
+ # Perform forward passes with both 3D and 2D settings
189
+ output_conv3d = dual_conv3d(test_input, use_conv3d=True)
190
+ output_2d = dual_conv3d(test_input, use_conv3d=False)
191
+
192
+ # Assert that the outputs from both methods are sufficiently close
193
+ assert torch.allclose(
194
+ output_conv3d, output_2d, atol=1e-6
195
+ ), "Outputs are not consistent between 3D and 2D convolutions."
ltx_video/models/autoencoders/pixel_norm.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch import nn
3
+
4
+
5
+ class PixelNorm(nn.Module):
6
+ def __init__(self, dim=1, eps=1e-8):
7
+ super(PixelNorm, self).__init__()
8
+ self.dim = dim
9
+ self.eps = eps
10
+
11
+ def forward(self, x):
12
+ return x / torch.sqrt(torch.mean(x**2, dim=self.dim, keepdim=True) + self.eps)
ltx_video/models/autoencoders/vae.py ADDED
@@ -0,0 +1,343 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional, Union
2
+
3
+ import torch
4
+ import inspect
5
+ import math
6
+ import torch.nn as nn
7
+ from diffusers import ConfigMixin, ModelMixin
8
+ from diffusers.models.autoencoders.vae import (
9
+ DecoderOutput,
10
+ DiagonalGaussianDistribution,
11
+ )
12
+ from diffusers.models.modeling_outputs import AutoencoderKLOutput
13
+ from ltx_video.models.autoencoders.conv_nd_factory import make_conv_nd
14
+
15
+
16
+ class AutoencoderKLWrapper(ModelMixin, ConfigMixin):
17
+ """Variational Autoencoder (VAE) model with KL loss.
18
+
19
+ VAE from the paper Auto-Encoding Variational Bayes by Diederik P. Kingma and Max Welling.
20
+ This model is a wrapper around an encoder and a decoder, and it adds a KL loss term to the reconstruction loss.
21
+
22
+ Args:
23
+ encoder (`nn.Module`):
24
+ Encoder module.
25
+ decoder (`nn.Module`):
26
+ Decoder module.
27
+ latent_channels (`int`, *optional*, defaults to 4):
28
+ Number of latent channels.
29
+ """
30
+
31
+ def __init__(
32
+ self,
33
+ encoder: nn.Module,
34
+ decoder: nn.Module,
35
+ latent_channels: int = 4,
36
+ dims: int = 2,
37
+ sample_size=512,
38
+ use_quant_conv: bool = True,
39
+ ):
40
+ super().__init__()
41
+
42
+ # pass init params to Encoder
43
+ self.encoder = encoder
44
+ self.use_quant_conv = use_quant_conv
45
+
46
+ # pass init params to Decoder
47
+ quant_dims = 2 if dims == 2 else 3
48
+ self.decoder = decoder
49
+ if use_quant_conv:
50
+ self.quant_conv = make_conv_nd(
51
+ quant_dims, 2 * latent_channels, 2 * latent_channels, 1
52
+ )
53
+ self.post_quant_conv = make_conv_nd(
54
+ quant_dims, latent_channels, latent_channels, 1
55
+ )
56
+ else:
57
+ self.quant_conv = nn.Identity()
58
+ self.post_quant_conv = nn.Identity()
59
+ self.use_z_tiling = False
60
+ self.use_hw_tiling = False
61
+ self.dims = dims
62
+ self.z_sample_size = 1
63
+
64
+ self.decoder_params = inspect.signature(self.decoder.forward).parameters
65
+
66
+ # only relevant if vae tiling is enabled
67
+ self.set_tiling_params(sample_size=sample_size, overlap_factor=0.25)
68
+
69
+ def set_tiling_params(self, sample_size: int = 512, overlap_factor: float = 0.25):
70
+ self.tile_sample_min_size = sample_size
71
+ num_blocks = len(self.encoder.down_blocks)
72
+ self.tile_latent_min_size = int(sample_size / (2 ** (num_blocks - 1)))
73
+ self.tile_overlap_factor = overlap_factor
74
+
75
+ def enable_z_tiling(self, z_sample_size: int = 8):
76
+ r"""
77
+ Enable tiling during VAE decoding.
78
+
79
+ When this option is enabled, the VAE will split the input tensor in tiles to compute decoding in several
80
+ steps. This is useful to save some memory and allow larger batch sizes.
81
+ """
82
+ self.use_z_tiling = z_sample_size > 1
83
+ self.z_sample_size = z_sample_size
84
+ assert (
85
+ z_sample_size % 8 == 0 or z_sample_size == 1
86
+ ), f"z_sample_size must be a multiple of 8 or 1. Got {z_sample_size}."
87
+
88
+ def disable_z_tiling(self):
89
+ r"""
90
+ Disable tiling during VAE decoding. If `use_tiling` was previously invoked, this method will go back to computing
91
+ decoding in one step.
92
+ """
93
+ self.use_z_tiling = False
94
+
95
+ def enable_hw_tiling(self):
96
+ r"""
97
+ Enable tiling during VAE decoding along the height and width dimension.
98
+ """
99
+ self.use_hw_tiling = True
100
+
101
+ def disable_hw_tiling(self):
102
+ r"""
103
+ Disable tiling during VAE decoding along the height and width dimension.
104
+ """
105
+ self.use_hw_tiling = False
106
+
107
+ def _hw_tiled_encode(self, x: torch.FloatTensor, return_dict: bool = True):
108
+ overlap_size = int(self.tile_sample_min_size * (1 - self.tile_overlap_factor))
109
+ blend_extent = int(self.tile_latent_min_size * self.tile_overlap_factor)
110
+ row_limit = self.tile_latent_min_size - blend_extent
111
+
112
+ # Split the image into 512x512 tiles and encode them separately.
113
+ rows = []
114
+ for i in range(0, x.shape[3], overlap_size):
115
+ row = []
116
+ for j in range(0, x.shape[4], overlap_size):
117
+ tile = x[
118
+ :,
119
+ :,
120
+ :,
121
+ i : i + self.tile_sample_min_size,
122
+ j : j + self.tile_sample_min_size,
123
+ ]
124
+ tile = self.encoder(tile)
125
+ tile = self.quant_conv(tile)
126
+ row.append(tile)
127
+ rows.append(row)
128
+ result_rows = []
129
+ for i, row in enumerate(rows):
130
+ result_row = []
131
+ for j, tile in enumerate(row):
132
+ # blend the above tile and the left tile
133
+ # to the current tile and add the current tile to the result row
134
+ if i > 0:
135
+ tile = self.blend_v(rows[i - 1][j], tile, blend_extent)
136
+ if j > 0:
137
+ tile = self.blend_h(row[j - 1], tile, blend_extent)
138
+ result_row.append(tile[:, :, :, :row_limit, :row_limit])
139
+ result_rows.append(torch.cat(result_row, dim=4))
140
+
141
+ moments = torch.cat(result_rows, dim=3)
142
+ return moments
143
+
144
+ def blend_z(
145
+ self, a: torch.Tensor, b: torch.Tensor, blend_extent: int
146
+ ) -> torch.Tensor:
147
+ blend_extent = min(a.shape[2], b.shape[2], blend_extent)
148
+ for z in range(blend_extent):
149
+ b[:, :, z, :, :] = a[:, :, -blend_extent + z, :, :] * (
150
+ 1 - z / blend_extent
151
+ ) + b[:, :, z, :, :] * (z / blend_extent)
152
+ return b
153
+
154
+ def blend_v(
155
+ self, a: torch.Tensor, b: torch.Tensor, blend_extent: int
156
+ ) -> torch.Tensor:
157
+ blend_extent = min(a.shape[3], b.shape[3], blend_extent)
158
+ for y in range(blend_extent):
159
+ b[:, :, :, y, :] = a[:, :, :, -blend_extent + y, :] * (
160
+ 1 - y / blend_extent
161
+ ) + b[:, :, :, y, :] * (y / blend_extent)
162
+ return b
163
+
164
+ def blend_h(
165
+ self, a: torch.Tensor, b: torch.Tensor, blend_extent: int
166
+ ) -> torch.Tensor:
167
+ blend_extent = min(a.shape[4], b.shape[4], blend_extent)
168
+ for x in range(blend_extent):
169
+ b[:, :, :, :, x] = a[:, :, :, :, -blend_extent + x] * (
170
+ 1 - x / blend_extent
171
+ ) + b[:, :, :, :, x] * (x / blend_extent)
172
+ return b
173
+
174
+ def _hw_tiled_decode(self, z: torch.FloatTensor, target_shape):
175
+ overlap_size = int(self.tile_latent_min_size * (1 - self.tile_overlap_factor))
176
+ blend_extent = int(self.tile_sample_min_size * self.tile_overlap_factor)
177
+ row_limit = self.tile_sample_min_size - blend_extent
178
+ tile_target_shape = (
179
+ *target_shape[:3],
180
+ self.tile_sample_min_size,
181
+ self.tile_sample_min_size,
182
+ )
183
+ # Split z into overlapping 64x64 tiles and decode them separately.
184
+ # The tiles have an overlap to avoid seams between tiles.
185
+ rows = []
186
+ for i in range(0, z.shape[3], overlap_size):
187
+ row = []
188
+ for j in range(0, z.shape[4], overlap_size):
189
+ tile = z[
190
+ :,
191
+ :,
192
+ :,
193
+ i : i + self.tile_latent_min_size,
194
+ j : j + self.tile_latent_min_size,
195
+ ]
196
+ tile = self.post_quant_conv(tile)
197
+ decoded = self.decoder(tile, target_shape=tile_target_shape)
198
+ row.append(decoded)
199
+ rows.append(row)
200
+ result_rows = []
201
+ for i, row in enumerate(rows):
202
+ result_row = []
203
+ for j, tile in enumerate(row):
204
+ # blend the above tile and the left tile
205
+ # to the current tile and add the current tile to the result row
206
+ if i > 0:
207
+ tile = self.blend_v(rows[i - 1][j], tile, blend_extent)
208
+ if j > 0:
209
+ tile = self.blend_h(row[j - 1], tile, blend_extent)
210
+ result_row.append(tile[:, :, :, :row_limit, :row_limit])
211
+ result_rows.append(torch.cat(result_row, dim=4))
212
+
213
+ dec = torch.cat(result_rows, dim=3)
214
+ return dec
215
+
216
+ def encode(
217
+ self, z: torch.FloatTensor, return_dict: bool = True
218
+ ) -> Union[DecoderOutput, torch.FloatTensor]:
219
+ if self.use_z_tiling and z.shape[2] > self.z_sample_size > 1:
220
+ num_splits = z.shape[2] // self.z_sample_size
221
+ sizes = [self.z_sample_size] * num_splits
222
+ sizes = (
223
+ sizes + [z.shape[2] - sum(sizes)]
224
+ if z.shape[2] - sum(sizes) > 0
225
+ else sizes
226
+ )
227
+ tiles = z.split(sizes, dim=2)
228
+ moments_tiles = [
229
+ (
230
+ self._hw_tiled_encode(z_tile, return_dict)
231
+ if self.use_hw_tiling
232
+ else self._encode(z_tile)
233
+ )
234
+ for z_tile in tiles
235
+ ]
236
+ moments = torch.cat(moments_tiles, dim=2)
237
+
238
+ else:
239
+ moments = (
240
+ self._hw_tiled_encode(z, return_dict)
241
+ if self.use_hw_tiling
242
+ else self._encode(z)
243
+ )
244
+
245
+ posterior = DiagonalGaussianDistribution(moments)
246
+ if not return_dict:
247
+ return (posterior,)
248
+
249
+ return AutoencoderKLOutput(latent_dist=posterior)
250
+
251
+ def _encode(self, x: torch.FloatTensor) -> AutoencoderKLOutput:
252
+ h = self.encoder(x)
253
+ moments = self.quant_conv(h)
254
+ return moments
255
+
256
+ def _decode(
257
+ self,
258
+ z: torch.FloatTensor,
259
+ target_shape=None,
260
+ timestep: Optional[torch.Tensor] = None,
261
+ ) -> Union[DecoderOutput, torch.FloatTensor]:
262
+ z = self.post_quant_conv(z)
263
+ if "timestep" in self.decoder_params:
264
+ dec = self.decoder(z, target_shape=target_shape, timestep=timestep)
265
+ else:
266
+ dec = self.decoder(z, target_shape=target_shape)
267
+ return dec
268
+
269
+ def decode(
270
+ self,
271
+ z: torch.FloatTensor,
272
+ return_dict: bool = True,
273
+ target_shape=None,
274
+ timestep: Optional[torch.Tensor] = None,
275
+ ) -> Union[DecoderOutput, torch.FloatTensor]:
276
+ assert target_shape is not None, "target_shape must be provided for decoding"
277
+ if self.use_z_tiling and z.shape[2] > self.z_sample_size > 1:
278
+ reduction_factor = int(
279
+ self.encoder.patch_size_t
280
+ * 2
281
+ ** (
282
+ len(self.encoder.down_blocks)
283
+ - 1
284
+ - math.sqrt(self.encoder.patch_size)
285
+ )
286
+ )
287
+ split_size = self.z_sample_size // reduction_factor
288
+ num_splits = z.shape[2] // split_size
289
+
290
+ # copy target shape, and divide frame dimension (=2) by the context size
291
+ target_shape_split = list(target_shape)
292
+ target_shape_split[2] = target_shape[2] // num_splits
293
+
294
+ decoded_tiles = [
295
+ (
296
+ self._hw_tiled_decode(z_tile, target_shape_split)
297
+ if self.use_hw_tiling
298
+ else self._decode(z_tile, target_shape=target_shape_split)
299
+ )
300
+ for z_tile in torch.tensor_split(z, num_splits, dim=2)
301
+ ]
302
+ decoded = torch.cat(decoded_tiles, dim=2)
303
+ else:
304
+ decoded = (
305
+ self._hw_tiled_decode(z, target_shape)
306
+ if self.use_hw_tiling
307
+ else self._decode(z, target_shape=target_shape, timestep=timestep)
308
+ )
309
+
310
+ if not return_dict:
311
+ return (decoded,)
312
+
313
+ return DecoderOutput(sample=decoded)
314
+
315
+ def forward(
316
+ self,
317
+ sample: torch.FloatTensor,
318
+ sample_posterior: bool = False,
319
+ return_dict: bool = True,
320
+ generator: Optional[torch.Generator] = None,
321
+ ) -> Union[DecoderOutput, torch.FloatTensor]:
322
+ r"""
323
+ Args:
324
+ sample (`torch.FloatTensor`): Input sample.
325
+ sample_posterior (`bool`, *optional*, defaults to `False`):
326
+ Whether to sample from the posterior.
327
+ return_dict (`bool`, *optional*, defaults to `True`):
328
+ Whether to return a [`DecoderOutput`] instead of a plain tuple.
329
+ generator (`torch.Generator`, *optional*):
330
+ Generator used to sample from the posterior.
331
+ """
332
+ x = sample
333
+ posterior = self.encode(x).latent_dist
334
+ if sample_posterior:
335
+ z = posterior.sample(generator=generator)
336
+ else:
337
+ z = posterior.mode()
338
+ dec = self.decode(z, target_shape=sample.shape).sample
339
+
340
+ if not return_dict:
341
+ return (dec,)
342
+
343
+ return DecoderOutput(sample=dec)
ltx_video/models/autoencoders/vae_encode.py ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from diffusers import AutoencoderKL
3
+ from einops import rearrange
4
+ from torch import Tensor
5
+
6
+
7
+ from ltx_video.models.autoencoders.causal_video_autoencoder import (
8
+ CausalVideoAutoencoder,
9
+ )
10
+ from ltx_video.models.autoencoders.video_autoencoder import (
11
+ Downsample3D,
12
+ VideoAutoencoder,
13
+ )
14
+
15
+ try:
16
+ import torch_xla.core.xla_model as xm
17
+ except ImportError:
18
+ xm = None
19
+
20
+
21
+ def vae_encode(
22
+ media_items: Tensor,
23
+ vae: AutoencoderKL,
24
+ split_size: int = 1,
25
+ vae_per_channel_normalize=False,
26
+ ) -> Tensor:
27
+ """
28
+ Encodes media items (images or videos) into latent representations using a specified VAE model.
29
+ The function supports processing batches of images or video frames and can handle the processing
30
+ in smaller sub-batches if needed.
31
+
32
+ Args:
33
+ media_items (Tensor): A torch Tensor containing the media items to encode. The expected
34
+ shape is (batch_size, channels, height, width) for images or (batch_size, channels,
35
+ frames, height, width) for videos.
36
+ vae (AutoencoderKL): An instance of the `AutoencoderKL` class from the `diffusers` library,
37
+ pre-configured and loaded with the appropriate model weights.
38
+ split_size (int, optional): The number of sub-batches to split the input batch into for encoding.
39
+ If set to more than 1, the input media items are processed in smaller batches according to
40
+ this value. Defaults to 1, which processes all items in a single batch.
41
+
42
+ Returns:
43
+ Tensor: A torch Tensor of the encoded latent representations. The shape of the tensor is adjusted
44
+ to match the input shape, scaled by the model's configuration.
45
+
46
+ Examples:
47
+ >>> import torch
48
+ >>> from diffusers import AutoencoderKL
49
+ >>> vae = AutoencoderKL.from_pretrained('your-model-name')
50
+ >>> images = torch.rand(10, 3, 8 256, 256) # Example tensor with 10 videos of 8 frames.
51
+ >>> latents = vae_encode(images, vae)
52
+ >>> print(latents.shape) # Output shape will depend on the model's latent configuration.
53
+
54
+ Note:
55
+ In case of a video, the function encodes the media item frame-by frame.
56
+ """
57
+ is_video_shaped = media_items.dim() == 5
58
+ batch_size, channels = media_items.shape[0:2]
59
+
60
+ if channels != 3:
61
+ raise ValueError(f"Expects tensors with 3 channels, got {channels}.")
62
+
63
+ if is_video_shaped and not isinstance(
64
+ vae, (VideoAutoencoder, CausalVideoAutoencoder)
65
+ ):
66
+ media_items = rearrange(media_items, "b c n h w -> (b n) c h w")
67
+ if split_size > 1:
68
+ if len(media_items) % split_size != 0:
69
+ raise ValueError(
70
+ "Error: The batch size must be divisible by 'train.vae_bs_split"
71
+ )
72
+ encode_bs = len(media_items) // split_size
73
+ # latents = [vae.encode(image_batch).latent_dist.sample() for image_batch in media_items.split(encode_bs)]
74
+ latents = []
75
+ if media_items.device.type == "xla":
76
+ xm.mark_step()
77
+ for image_batch in media_items.split(encode_bs):
78
+ latents.append(vae.encode(image_batch).latent_dist.sample())
79
+ if media_items.device.type == "xla":
80
+ xm.mark_step()
81
+ latents = torch.cat(latents, dim=0)
82
+ else:
83
+ latents = vae.encode(media_items).latent_dist.sample()
84
+
85
+ latents = normalize_latents(latents, vae, vae_per_channel_normalize)
86
+ if is_video_shaped and not isinstance(
87
+ vae, (VideoAutoencoder, CausalVideoAutoencoder)
88
+ ):
89
+ latents = rearrange(latents, "(b n) c h w -> b c n h w", b=batch_size)
90
+ return latents
91
+
92
+
93
+ def vae_decode(
94
+ latents: Tensor,
95
+ vae: AutoencoderKL,
96
+ is_video: bool = True,
97
+ split_size: int = 1,
98
+ vae_per_channel_normalize=False,
99
+ timestep=None,
100
+ ) -> Tensor:
101
+ is_video_shaped = latents.dim() == 5
102
+ batch_size = latents.shape[0]
103
+
104
+ if is_video_shaped and not isinstance(
105
+ vae, (VideoAutoencoder, CausalVideoAutoencoder)
106
+ ):
107
+ latents = rearrange(latents, "b c n h w -> (b n) c h w")
108
+ if split_size > 1:
109
+ if len(latents) % split_size != 0:
110
+ raise ValueError(
111
+ "Error: The batch size must be divisible by 'train.vae_bs_split"
112
+ )
113
+ encode_bs = len(latents) // split_size
114
+ image_batch = [
115
+ _run_decoder(
116
+ latent_batch, vae, is_video, vae_per_channel_normalize, timestep
117
+ )
118
+ for latent_batch in latents.split(encode_bs)
119
+ ]
120
+ images = torch.cat(image_batch, dim=0)
121
+ else:
122
+ images = _run_decoder(
123
+ latents, vae, is_video, vae_per_channel_normalize, timestep
124
+ )
125
+
126
+ if is_video_shaped and not isinstance(
127
+ vae, (VideoAutoencoder, CausalVideoAutoencoder)
128
+ ):
129
+ images = rearrange(images, "(b n) c h w -> b c n h w", b=batch_size)
130
+ return images
131
+
132
+
133
+ def _run_decoder(
134
+ latents: Tensor,
135
+ vae: AutoencoderKL,
136
+ is_video: bool,
137
+ vae_per_channel_normalize=False,
138
+ timestep=None,
139
+ ) -> Tensor:
140
+ if isinstance(vae, (VideoAutoencoder, CausalVideoAutoencoder)):
141
+ *_, fl, hl, wl = latents.shape
142
+ temporal_scale, spatial_scale, _ = get_vae_size_scale_factor(vae)
143
+ latents = latents.to(vae.dtype)
144
+ vae_decode_kwargs = {}
145
+ if timestep is not None:
146
+ vae_decode_kwargs["timestep"] = timestep
147
+ image = vae.decode(
148
+ un_normalize_latents(latents, vae, vae_per_channel_normalize),
149
+ return_dict=False,
150
+ target_shape=(
151
+ 1,
152
+ 3,
153
+ fl * temporal_scale if is_video else 1,
154
+ hl * spatial_scale,
155
+ wl * spatial_scale,
156
+ ),
157
+ **vae_decode_kwargs,
158
+ )[0]
159
+ else:
160
+ image = vae.decode(
161
+ un_normalize_latents(latents, vae, vae_per_channel_normalize),
162
+ return_dict=False,
163
+ )[0]
164
+ return image
165
+
166
+
167
+ def get_vae_size_scale_factor(vae: AutoencoderKL) -> float:
168
+ if isinstance(vae, CausalVideoAutoencoder):
169
+ spatial = vae.spatial_downscale_factor
170
+ temporal = vae.temporal_downscale_factor
171
+ else:
172
+ down_blocks = len(
173
+ [
174
+ block
175
+ for block in vae.encoder.down_blocks
176
+ if isinstance(block.downsample, Downsample3D)
177
+ ]
178
+ )
179
+ spatial = vae.config.patch_size * 2**down_blocks
180
+ temporal = (
181
+ vae.config.patch_size_t * 2**down_blocks
182
+ if isinstance(vae, VideoAutoencoder)
183
+ else 1
184
+ )
185
+
186
+ return (temporal, spatial, spatial)
187
+
188
+
189
+ def normalize_latents(
190
+ latents: Tensor, vae: AutoencoderKL, vae_per_channel_normalize: bool = False
191
+ ) -> Tensor:
192
+ return (
193
+ (latents - vae.mean_of_means.to(latents.dtype).view(1, -1, 1, 1, 1))
194
+ / vae.std_of_means.to(latents.dtype).view(1, -1, 1, 1, 1)
195
+ if vae_per_channel_normalize
196
+ else latents * vae.config.scaling_factor
197
+ )
198
+
199
+
200
+ def un_normalize_latents(
201
+ latents: Tensor, vae: AutoencoderKL, vae_per_channel_normalize: bool = False
202
+ ) -> Tensor:
203
+ return (
204
+ latents * vae.std_of_means.to(latents.dtype).view(1, -1, 1, 1, 1)
205
+ + vae.mean_of_means.to(latents.dtype).view(1, -1, 1, 1, 1)
206
+ if vae_per_channel_normalize
207
+ else latents / vae.config.scaling_factor
208
+ )
ltx_video/models/autoencoders/video_autoencoder.py ADDED
@@ -0,0 +1,1045 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import os
3
+ from functools import partial
4
+ from types import SimpleNamespace
5
+ from typing import Any, Mapping, Optional, Tuple, Union
6
+
7
+ import torch
8
+ from einops import rearrange
9
+ from torch import nn
10
+ from torch.nn import functional
11
+
12
+ from diffusers.utils import logging
13
+
14
+ from ltx_video.utils.torch_utils import Identity
15
+ from ltx_video.models.autoencoders.conv_nd_factory import make_conv_nd, make_linear_nd
16
+ from ltx_video.models.autoencoders.pixel_norm import PixelNorm
17
+ from ltx_video.models.autoencoders.vae import AutoencoderKLWrapper
18
+
19
+ logger = logging.get_logger(__name__)
20
+
21
+
22
+ class VideoAutoencoder(AutoencoderKLWrapper):
23
+ @classmethod
24
+ def from_pretrained(
25
+ cls,
26
+ pretrained_model_name_or_path: Optional[Union[str, os.PathLike]],
27
+ *args,
28
+ **kwargs,
29
+ ):
30
+ config_local_path = pretrained_model_name_or_path / "config.json"
31
+ config = cls.load_config(config_local_path, **kwargs)
32
+ video_vae = cls.from_config(config)
33
+ video_vae.to(kwargs["torch_dtype"])
34
+
35
+ model_local_path = pretrained_model_name_or_path / "autoencoder.pth"
36
+ ckpt_state_dict = torch.load(model_local_path)
37
+ video_vae.load_state_dict(ckpt_state_dict)
38
+
39
+ statistics_local_path = (
40
+ pretrained_model_name_or_path / "per_channel_statistics.json"
41
+ )
42
+ if statistics_local_path.exists():
43
+ with open(statistics_local_path, "r") as file:
44
+ data = json.load(file)
45
+ transposed_data = list(zip(*data["data"]))
46
+ data_dict = {
47
+ col: torch.tensor(vals)
48
+ for col, vals in zip(data["columns"], transposed_data)
49
+ }
50
+ video_vae.register_buffer("std_of_means", data_dict["std-of-means"])
51
+ video_vae.register_buffer(
52
+ "mean_of_means",
53
+ data_dict.get(
54
+ "mean-of-means", torch.zeros_like(data_dict["std-of-means"])
55
+ ),
56
+ )
57
+
58
+ return video_vae
59
+
60
+ @staticmethod
61
+ def from_config(config):
62
+ assert (
63
+ config["_class_name"] == "VideoAutoencoder"
64
+ ), "config must have _class_name=VideoAutoencoder"
65
+ if isinstance(config["dims"], list):
66
+ config["dims"] = tuple(config["dims"])
67
+
68
+ assert config["dims"] in [2, 3, (2, 1)], "dims must be 2, 3 or (2, 1)"
69
+
70
+ double_z = config.get("double_z", True)
71
+ latent_log_var = config.get(
72
+ "latent_log_var", "per_channel" if double_z else "none"
73
+ )
74
+ use_quant_conv = config.get("use_quant_conv", True)
75
+
76
+ if use_quant_conv and latent_log_var == "uniform":
77
+ raise ValueError("uniform latent_log_var requires use_quant_conv=False")
78
+
79
+ encoder = Encoder(
80
+ dims=config["dims"],
81
+ in_channels=config.get("in_channels", 3),
82
+ out_channels=config["latent_channels"],
83
+ block_out_channels=config["block_out_channels"],
84
+ patch_size=config.get("patch_size", 1),
85
+ latent_log_var=latent_log_var,
86
+ norm_layer=config.get("norm_layer", "group_norm"),
87
+ patch_size_t=config.get("patch_size_t", config.get("patch_size", 1)),
88
+ add_channel_padding=config.get("add_channel_padding", False),
89
+ )
90
+
91
+ decoder = Decoder(
92
+ dims=config["dims"],
93
+ in_channels=config["latent_channels"],
94
+ out_channels=config.get("out_channels", 3),
95
+ block_out_channels=config["block_out_channels"],
96
+ patch_size=config.get("patch_size", 1),
97
+ norm_layer=config.get("norm_layer", "group_norm"),
98
+ patch_size_t=config.get("patch_size_t", config.get("patch_size", 1)),
99
+ add_channel_padding=config.get("add_channel_padding", False),
100
+ )
101
+
102
+ dims = config["dims"]
103
+ return VideoAutoencoder(
104
+ encoder=encoder,
105
+ decoder=decoder,
106
+ latent_channels=config["latent_channels"],
107
+ dims=dims,
108
+ use_quant_conv=use_quant_conv,
109
+ )
110
+
111
+ @property
112
+ def config(self):
113
+ return SimpleNamespace(
114
+ _class_name="VideoAutoencoder",
115
+ dims=self.dims,
116
+ in_channels=self.encoder.conv_in.in_channels
117
+ // (self.encoder.patch_size_t * self.encoder.patch_size**2),
118
+ out_channels=self.decoder.conv_out.out_channels
119
+ // (self.decoder.patch_size_t * self.decoder.patch_size**2),
120
+ latent_channels=self.decoder.conv_in.in_channels,
121
+ block_out_channels=[
122
+ self.encoder.down_blocks[i].res_blocks[-1].conv1.out_channels
123
+ for i in range(len(self.encoder.down_blocks))
124
+ ],
125
+ scaling_factor=1.0,
126
+ norm_layer=self.encoder.norm_layer,
127
+ patch_size=self.encoder.patch_size,
128
+ latent_log_var=self.encoder.latent_log_var,
129
+ use_quant_conv=self.use_quant_conv,
130
+ patch_size_t=self.encoder.patch_size_t,
131
+ add_channel_padding=self.encoder.add_channel_padding,
132
+ )
133
+
134
+ @property
135
+ def is_video_supported(self):
136
+ """
137
+ Check if the model supports video inputs of shape (B, C, F, H, W). Otherwise, the model only supports 2D images.
138
+ """
139
+ return self.dims != 2
140
+
141
+ @property
142
+ def downscale_factor(self):
143
+ return self.encoder.downsample_factor
144
+
145
+ def to_json_string(self) -> str:
146
+ import json
147
+
148
+ return json.dumps(self.config.__dict__)
149
+
150
+ def load_state_dict(self, state_dict: Mapping[str, Any], strict: bool = True):
151
+ model_keys = set(name for name, _ in self.named_parameters())
152
+
153
+ key_mapping = {
154
+ ".resnets.": ".res_blocks.",
155
+ "downsamplers.0": "downsample",
156
+ "upsamplers.0": "upsample",
157
+ }
158
+
159
+ converted_state_dict = {}
160
+ for key, value in state_dict.items():
161
+ for k, v in key_mapping.items():
162
+ key = key.replace(k, v)
163
+
164
+ if "norm" in key and key not in model_keys:
165
+ logger.info(
166
+ f"Removing key {key} from state_dict as it is not present in the model"
167
+ )
168
+ continue
169
+
170
+ converted_state_dict[key] = value
171
+
172
+ super().load_state_dict(converted_state_dict, strict=strict)
173
+
174
+ def last_layer(self):
175
+ if hasattr(self.decoder, "conv_out"):
176
+ if isinstance(self.decoder.conv_out, nn.Sequential):
177
+ last_layer = self.decoder.conv_out[-1]
178
+ else:
179
+ last_layer = self.decoder.conv_out
180
+ else:
181
+ last_layer = self.decoder.layers[-1]
182
+ return last_layer
183
+
184
+
185
+ class Encoder(nn.Module):
186
+ r"""
187
+ The `Encoder` layer of a variational autoencoder that encodes its input into a latent representation.
188
+
189
+ Args:
190
+ in_channels (`int`, *optional*, defaults to 3):
191
+ The number of input channels.
192
+ out_channels (`int`, *optional*, defaults to 3):
193
+ The number of output channels.
194
+ block_out_channels (`Tuple[int, ...]`, *optional*, defaults to `(64,)`):
195
+ The number of output channels for each block.
196
+ layers_per_block (`int`, *optional*, defaults to 2):
197
+ The number of layers per block.
198
+ norm_num_groups (`int`, *optional*, defaults to 32):
199
+ The number of groups for normalization.
200
+ patch_size (`int`, *optional*, defaults to 1):
201
+ The patch size to use. Should be a power of 2.
202
+ norm_layer (`str`, *optional*, defaults to `group_norm`):
203
+ The normalization layer to use. Can be either `group_norm` or `pixel_norm`.
204
+ latent_log_var (`str`, *optional*, defaults to `per_channel`):
205
+ The number of channels for the log variance. Can be either `per_channel`, `uniform`, or `none`.
206
+ """
207
+
208
+ def __init__(
209
+ self,
210
+ dims: Union[int, Tuple[int, int]] = 3,
211
+ in_channels: int = 3,
212
+ out_channels: int = 3,
213
+ block_out_channels: Tuple[int, ...] = (64,),
214
+ layers_per_block: int = 2,
215
+ norm_num_groups: int = 32,
216
+ patch_size: Union[int, Tuple[int]] = 1,
217
+ norm_layer: str = "group_norm", # group_norm, pixel_norm
218
+ latent_log_var: str = "per_channel",
219
+ patch_size_t: Optional[int] = None,
220
+ add_channel_padding: Optional[bool] = False,
221
+ ):
222
+ super().__init__()
223
+ self.patch_size = patch_size
224
+ self.patch_size_t = patch_size_t if patch_size_t is not None else patch_size
225
+ self.add_channel_padding = add_channel_padding
226
+ self.layers_per_block = layers_per_block
227
+ self.norm_layer = norm_layer
228
+ self.latent_channels = out_channels
229
+ self.latent_log_var = latent_log_var
230
+ if add_channel_padding:
231
+ in_channels = in_channels * self.patch_size**3
232
+ else:
233
+ in_channels = in_channels * self.patch_size_t * self.patch_size**2
234
+ self.in_channels = in_channels
235
+ output_channel = block_out_channels[0]
236
+
237
+ self.conv_in = make_conv_nd(
238
+ dims=dims,
239
+ in_channels=in_channels,
240
+ out_channels=output_channel,
241
+ kernel_size=3,
242
+ stride=1,
243
+ padding=1,
244
+ )
245
+
246
+ self.down_blocks = nn.ModuleList([])
247
+
248
+ for i in range(len(block_out_channels)):
249
+ input_channel = output_channel
250
+ output_channel = block_out_channels[i]
251
+ is_final_block = i == len(block_out_channels) - 1
252
+
253
+ down_block = DownEncoderBlock3D(
254
+ dims=dims,
255
+ in_channels=input_channel,
256
+ out_channels=output_channel,
257
+ num_layers=self.layers_per_block,
258
+ add_downsample=not is_final_block and 2**i >= patch_size,
259
+ resnet_eps=1e-6,
260
+ downsample_padding=0,
261
+ resnet_groups=norm_num_groups,
262
+ norm_layer=norm_layer,
263
+ )
264
+ self.down_blocks.append(down_block)
265
+
266
+ self.mid_block = UNetMidBlock3D(
267
+ dims=dims,
268
+ in_channels=block_out_channels[-1],
269
+ num_layers=self.layers_per_block,
270
+ resnet_eps=1e-6,
271
+ resnet_groups=norm_num_groups,
272
+ norm_layer=norm_layer,
273
+ )
274
+
275
+ # out
276
+ if norm_layer == "group_norm":
277
+ self.conv_norm_out = nn.GroupNorm(
278
+ num_channels=block_out_channels[-1],
279
+ num_groups=norm_num_groups,
280
+ eps=1e-6,
281
+ )
282
+ elif norm_layer == "pixel_norm":
283
+ self.conv_norm_out = PixelNorm()
284
+ self.conv_act = nn.SiLU()
285
+
286
+ conv_out_channels = out_channels
287
+ if latent_log_var == "per_channel":
288
+ conv_out_channels *= 2
289
+ elif latent_log_var == "uniform":
290
+ conv_out_channels += 1
291
+ elif latent_log_var != "none":
292
+ raise ValueError(f"Invalid latent_log_var: {latent_log_var}")
293
+ self.conv_out = make_conv_nd(
294
+ dims, block_out_channels[-1], conv_out_channels, 3, padding=1
295
+ )
296
+
297
+ self.gradient_checkpointing = False
298
+
299
+ @property
300
+ def downscale_factor(self):
301
+ return (
302
+ 2
303
+ ** len(
304
+ [
305
+ block
306
+ for block in self.down_blocks
307
+ if isinstance(block.downsample, Downsample3D)
308
+ ]
309
+ )
310
+ * self.patch_size
311
+ )
312
+
313
+ def forward(
314
+ self, sample: torch.FloatTensor, return_features=False
315
+ ) -> torch.FloatTensor:
316
+ r"""The forward method of the `Encoder` class."""
317
+
318
+ downsample_in_time = sample.shape[2] != 1
319
+
320
+ # patchify
321
+ patch_size_t = self.patch_size_t if downsample_in_time else 1
322
+ sample = patchify(
323
+ sample,
324
+ patch_size_hw=self.patch_size,
325
+ patch_size_t=patch_size_t,
326
+ add_channel_padding=self.add_channel_padding,
327
+ )
328
+
329
+ sample = self.conv_in(sample)
330
+
331
+ checkpoint_fn = (
332
+ partial(torch.utils.checkpoint.checkpoint, use_reentrant=False)
333
+ if self.gradient_checkpointing and self.training
334
+ else lambda x: x
335
+ )
336
+
337
+ if return_features:
338
+ features = []
339
+ for down_block in self.down_blocks:
340
+ sample = checkpoint_fn(down_block)(
341
+ sample, downsample_in_time=downsample_in_time
342
+ )
343
+ if return_features:
344
+ features.append(sample)
345
+
346
+ sample = checkpoint_fn(self.mid_block)(sample)
347
+
348
+ # post-process
349
+ sample = self.conv_norm_out(sample)
350
+ sample = self.conv_act(sample)
351
+ sample = self.conv_out(sample)
352
+
353
+ if self.latent_log_var == "uniform":
354
+ last_channel = sample[:, -1:, ...]
355
+ num_dims = sample.dim()
356
+
357
+ if num_dims == 4:
358
+ # For shape (B, C, H, W)
359
+ repeated_last_channel = last_channel.repeat(
360
+ 1, sample.shape[1] - 2, 1, 1
361
+ )
362
+ sample = torch.cat([sample, repeated_last_channel], dim=1)
363
+ elif num_dims == 5:
364
+ # For shape (B, C, F, H, W)
365
+ repeated_last_channel = last_channel.repeat(
366
+ 1, sample.shape[1] - 2, 1, 1, 1
367
+ )
368
+ sample = torch.cat([sample, repeated_last_channel], dim=1)
369
+ else:
370
+ raise ValueError(f"Invalid input shape: {sample.shape}")
371
+
372
+ if return_features:
373
+ features.append(sample[:, : self.latent_channels, ...])
374
+ return sample, features
375
+ return sample
376
+
377
+
378
+ class Decoder(nn.Module):
379
+ r"""
380
+ The `Decoder` layer of a variational autoencoder that decodes its latent representation into an output sample.
381
+
382
+ Args:
383
+ in_channels (`int`, *optional*, defaults to 3):
384
+ The number of input channels.
385
+ out_channels (`int`, *optional*, defaults to 3):
386
+ The number of output channels.
387
+ block_out_channels (`Tuple[int, ...]`, *optional*, defaults to `(64,)`):
388
+ The number of output channels for each block.
389
+ layers_per_block (`int`, *optional*, defaults to 2):
390
+ The number of layers per block.
391
+ norm_num_groups (`int`, *optional*, defaults to 32):
392
+ The number of groups for normalization.
393
+ patch_size (`int`, *optional*, defaults to 1):
394
+ The patch size to use. Should be a power of 2.
395
+ norm_layer (`str`, *optional*, defaults to `group_norm`):
396
+ The normalization layer to use. Can be either `group_norm` or `pixel_norm`.
397
+ """
398
+
399
+ def __init__(
400
+ self,
401
+ dims,
402
+ in_channels: int = 3,
403
+ out_channels: int = 3,
404
+ block_out_channels: Tuple[int, ...] = (64,),
405
+ layers_per_block: int = 2,
406
+ norm_num_groups: int = 32,
407
+ patch_size: int = 1,
408
+ norm_layer: str = "group_norm",
409
+ patch_size_t: Optional[int] = None,
410
+ add_channel_padding: Optional[bool] = False,
411
+ ):
412
+ super().__init__()
413
+ self.patch_size = patch_size
414
+ self.patch_size_t = patch_size_t if patch_size_t is not None else patch_size
415
+ self.add_channel_padding = add_channel_padding
416
+ self.layers_per_block = layers_per_block
417
+ if add_channel_padding:
418
+ out_channels = out_channels * self.patch_size**3
419
+ else:
420
+ out_channels = out_channels * self.patch_size_t * self.patch_size**2
421
+ self.out_channels = out_channels
422
+
423
+ self.conv_in = make_conv_nd(
424
+ dims,
425
+ in_channels,
426
+ block_out_channels[-1],
427
+ kernel_size=3,
428
+ stride=1,
429
+ padding=1,
430
+ )
431
+
432
+ self.mid_block = None
433
+ self.up_blocks = nn.ModuleList([])
434
+
435
+ self.mid_block = UNetMidBlock3D(
436
+ dims=dims,
437
+ in_channels=block_out_channels[-1],
438
+ num_layers=self.layers_per_block,
439
+ resnet_eps=1e-6,
440
+ resnet_groups=norm_num_groups,
441
+ norm_layer=norm_layer,
442
+ )
443
+
444
+ reversed_block_out_channels = list(reversed(block_out_channels))
445
+ output_channel = reversed_block_out_channels[0]
446
+ for i in range(len(reversed_block_out_channels)):
447
+ prev_output_channel = output_channel
448
+ output_channel = reversed_block_out_channels[i]
449
+
450
+ is_final_block = i == len(block_out_channels) - 1
451
+
452
+ up_block = UpDecoderBlock3D(
453
+ dims=dims,
454
+ num_layers=self.layers_per_block + 1,
455
+ in_channels=prev_output_channel,
456
+ out_channels=output_channel,
457
+ add_upsample=not is_final_block
458
+ and 2 ** (len(block_out_channels) - i - 1) > patch_size,
459
+ resnet_eps=1e-6,
460
+ resnet_groups=norm_num_groups,
461
+ norm_layer=norm_layer,
462
+ )
463
+ self.up_blocks.append(up_block)
464
+
465
+ if norm_layer == "group_norm":
466
+ self.conv_norm_out = nn.GroupNorm(
467
+ num_channels=block_out_channels[0], num_groups=norm_num_groups, eps=1e-6
468
+ )
469
+ elif norm_layer == "pixel_norm":
470
+ self.conv_norm_out = PixelNorm()
471
+
472
+ self.conv_act = nn.SiLU()
473
+ self.conv_out = make_conv_nd(
474
+ dims, block_out_channels[0], out_channels, 3, padding=1
475
+ )
476
+
477
+ self.gradient_checkpointing = False
478
+
479
+ def forward(self, sample: torch.FloatTensor, target_shape) -> torch.FloatTensor:
480
+ r"""The forward method of the `Decoder` class."""
481
+ assert target_shape is not None, "target_shape must be provided"
482
+ upsample_in_time = sample.shape[2] < target_shape[2]
483
+
484
+ sample = self.conv_in(sample)
485
+
486
+ upscale_dtype = next(iter(self.up_blocks.parameters())).dtype
487
+
488
+ checkpoint_fn = (
489
+ partial(torch.utils.checkpoint.checkpoint, use_reentrant=False)
490
+ if self.gradient_checkpointing and self.training
491
+ else lambda x: x
492
+ )
493
+
494
+ sample = checkpoint_fn(self.mid_block)(sample)
495
+ sample = sample.to(upscale_dtype)
496
+
497
+ for up_block in self.up_blocks:
498
+ sample = checkpoint_fn(up_block)(sample, upsample_in_time=upsample_in_time)
499
+
500
+ # post-process
501
+ sample = self.conv_norm_out(sample)
502
+ sample = self.conv_act(sample)
503
+ sample = self.conv_out(sample)
504
+
505
+ # un-patchify
506
+ patch_size_t = self.patch_size_t if upsample_in_time else 1
507
+ sample = unpatchify(
508
+ sample,
509
+ patch_size_hw=self.patch_size,
510
+ patch_size_t=patch_size_t,
511
+ add_channel_padding=self.add_channel_padding,
512
+ )
513
+
514
+ return sample
515
+
516
+
517
+ class DownEncoderBlock3D(nn.Module):
518
+ def __init__(
519
+ self,
520
+ dims: Union[int, Tuple[int, int]],
521
+ in_channels: int,
522
+ out_channels: int,
523
+ dropout: float = 0.0,
524
+ num_layers: int = 1,
525
+ resnet_eps: float = 1e-6,
526
+ resnet_groups: int = 32,
527
+ add_downsample: bool = True,
528
+ downsample_padding: int = 1,
529
+ norm_layer: str = "group_norm",
530
+ ):
531
+ super().__init__()
532
+ res_blocks = []
533
+
534
+ for i in range(num_layers):
535
+ in_channels = in_channels if i == 0 else out_channels
536
+ res_blocks.append(
537
+ ResnetBlock3D(
538
+ dims=dims,
539
+ in_channels=in_channels,
540
+ out_channels=out_channels,
541
+ eps=resnet_eps,
542
+ groups=resnet_groups,
543
+ dropout=dropout,
544
+ norm_layer=norm_layer,
545
+ )
546
+ )
547
+
548
+ self.res_blocks = nn.ModuleList(res_blocks)
549
+
550
+ if add_downsample:
551
+ self.downsample = Downsample3D(
552
+ dims,
553
+ out_channels,
554
+ out_channels=out_channels,
555
+ padding=downsample_padding,
556
+ )
557
+ else:
558
+ self.downsample = Identity()
559
+
560
+ def forward(
561
+ self, hidden_states: torch.FloatTensor, downsample_in_time
562
+ ) -> torch.FloatTensor:
563
+ for resnet in self.res_blocks:
564
+ hidden_states = resnet(hidden_states)
565
+
566
+ hidden_states = self.downsample(
567
+ hidden_states, downsample_in_time=downsample_in_time
568
+ )
569
+
570
+ return hidden_states
571
+
572
+
573
+ class UNetMidBlock3D(nn.Module):
574
+ """
575
+ A 3D UNet mid-block [`UNetMidBlock3D`] with multiple residual blocks.
576
+
577
+ Args:
578
+ in_channels (`int`): The number of input channels.
579
+ dropout (`float`, *optional*, defaults to 0.0): The dropout rate.
580
+ num_layers (`int`, *optional*, defaults to 1): The number of residual blocks.
581
+ resnet_eps (`float`, *optional*, 1e-6 ): The epsilon value for the resnet blocks.
582
+ resnet_groups (`int`, *optional*, defaults to 32):
583
+ The number of groups to use in the group normalization layers of the resnet blocks.
584
+
585
+ Returns:
586
+ `torch.FloatTensor`: The output of the last residual block, which is a tensor of shape `(batch_size,
587
+ in_channels, height, width)`.
588
+
589
+ """
590
+
591
+ def __init__(
592
+ self,
593
+ dims: Union[int, Tuple[int, int]],
594
+ in_channels: int,
595
+ dropout: float = 0.0,
596
+ num_layers: int = 1,
597
+ resnet_eps: float = 1e-6,
598
+ resnet_groups: int = 32,
599
+ norm_layer: str = "group_norm",
600
+ ):
601
+ super().__init__()
602
+ resnet_groups = (
603
+ resnet_groups if resnet_groups is not None else min(in_channels // 4, 32)
604
+ )
605
+
606
+ self.res_blocks = nn.ModuleList(
607
+ [
608
+ ResnetBlock3D(
609
+ dims=dims,
610
+ in_channels=in_channels,
611
+ out_channels=in_channels,
612
+ eps=resnet_eps,
613
+ groups=resnet_groups,
614
+ dropout=dropout,
615
+ norm_layer=norm_layer,
616
+ )
617
+ for _ in range(num_layers)
618
+ ]
619
+ )
620
+
621
+ def forward(self, hidden_states: torch.FloatTensor) -> torch.FloatTensor:
622
+ for resnet in self.res_blocks:
623
+ hidden_states = resnet(hidden_states)
624
+
625
+ return hidden_states
626
+
627
+
628
+ class UpDecoderBlock3D(nn.Module):
629
+ def __init__(
630
+ self,
631
+ dims: Union[int, Tuple[int, int]],
632
+ in_channels: int,
633
+ out_channels: int,
634
+ resolution_idx: Optional[int] = None,
635
+ dropout: float = 0.0,
636
+ num_layers: int = 1,
637
+ resnet_eps: float = 1e-6,
638
+ resnet_groups: int = 32,
639
+ add_upsample: bool = True,
640
+ norm_layer: str = "group_norm",
641
+ ):
642
+ super().__init__()
643
+ res_blocks = []
644
+
645
+ for i in range(num_layers):
646
+ input_channels = in_channels if i == 0 else out_channels
647
+
648
+ res_blocks.append(
649
+ ResnetBlock3D(
650
+ dims=dims,
651
+ in_channels=input_channels,
652
+ out_channels=out_channels,
653
+ eps=resnet_eps,
654
+ groups=resnet_groups,
655
+ dropout=dropout,
656
+ norm_layer=norm_layer,
657
+ )
658
+ )
659
+
660
+ self.res_blocks = nn.ModuleList(res_blocks)
661
+
662
+ if add_upsample:
663
+ self.upsample = Upsample3D(
664
+ dims=dims, channels=out_channels, out_channels=out_channels
665
+ )
666
+ else:
667
+ self.upsample = Identity()
668
+
669
+ self.resolution_idx = resolution_idx
670
+
671
+ def forward(
672
+ self, hidden_states: torch.FloatTensor, upsample_in_time=True
673
+ ) -> torch.FloatTensor:
674
+ for resnet in self.res_blocks:
675
+ hidden_states = resnet(hidden_states)
676
+
677
+ hidden_states = self.upsample(hidden_states, upsample_in_time=upsample_in_time)
678
+
679
+ return hidden_states
680
+
681
+
682
+ class ResnetBlock3D(nn.Module):
683
+ r"""
684
+ A Resnet block.
685
+
686
+ Parameters:
687
+ in_channels (`int`): The number of channels in the input.
688
+ out_channels (`int`, *optional*, default to be `None`):
689
+ The number of output channels for the first conv layer. If None, same as `in_channels`.
690
+ dropout (`float`, *optional*, defaults to `0.0`): The dropout probability to use.
691
+ groups (`int`, *optional*, default to `32`): The number of groups to use for the first normalization layer.
692
+ eps (`float`, *optional*, defaults to `1e-6`): The epsilon to use for the normalization.
693
+ """
694
+
695
+ def __init__(
696
+ self,
697
+ dims: Union[int, Tuple[int, int]],
698
+ in_channels: int,
699
+ out_channels: Optional[int] = None,
700
+ conv_shortcut: bool = False,
701
+ dropout: float = 0.0,
702
+ groups: int = 32,
703
+ eps: float = 1e-6,
704
+ norm_layer: str = "group_norm",
705
+ ):
706
+ super().__init__()
707
+ self.in_channels = in_channels
708
+ out_channels = in_channels if out_channels is None else out_channels
709
+ self.out_channels = out_channels
710
+ self.use_conv_shortcut = conv_shortcut
711
+
712
+ if norm_layer == "group_norm":
713
+ self.norm1 = torch.nn.GroupNorm(
714
+ num_groups=groups, num_channels=in_channels, eps=eps, affine=True
715
+ )
716
+ elif norm_layer == "pixel_norm":
717
+ self.norm1 = PixelNorm()
718
+
719
+ self.non_linearity = nn.SiLU()
720
+
721
+ self.conv1 = make_conv_nd(
722
+ dims, in_channels, out_channels, kernel_size=3, stride=1, padding=1
723
+ )
724
+
725
+ if norm_layer == "group_norm":
726
+ self.norm2 = torch.nn.GroupNorm(
727
+ num_groups=groups, num_channels=out_channels, eps=eps, affine=True
728
+ )
729
+ elif norm_layer == "pixel_norm":
730
+ self.norm2 = PixelNorm()
731
+
732
+ self.dropout = torch.nn.Dropout(dropout)
733
+
734
+ self.conv2 = make_conv_nd(
735
+ dims, out_channels, out_channels, kernel_size=3, stride=1, padding=1
736
+ )
737
+
738
+ self.conv_shortcut = (
739
+ make_linear_nd(
740
+ dims=dims, in_channels=in_channels, out_channels=out_channels
741
+ )
742
+ if in_channels != out_channels
743
+ else nn.Identity()
744
+ )
745
+
746
+ def forward(
747
+ self,
748
+ input_tensor: torch.FloatTensor,
749
+ ) -> torch.FloatTensor:
750
+ hidden_states = input_tensor
751
+
752
+ hidden_states = self.norm1(hidden_states)
753
+
754
+ hidden_states = self.non_linearity(hidden_states)
755
+
756
+ hidden_states = self.conv1(hidden_states)
757
+
758
+ hidden_states = self.norm2(hidden_states)
759
+
760
+ hidden_states = self.non_linearity(hidden_states)
761
+
762
+ hidden_states = self.dropout(hidden_states)
763
+
764
+ hidden_states = self.conv2(hidden_states)
765
+
766
+ input_tensor = self.conv_shortcut(input_tensor)
767
+
768
+ output_tensor = input_tensor + hidden_states
769
+
770
+ return output_tensor
771
+
772
+
773
+ class Downsample3D(nn.Module):
774
+ def __init__(
775
+ self,
776
+ dims,
777
+ in_channels: int,
778
+ out_channels: int,
779
+ kernel_size: int = 3,
780
+ padding: int = 1,
781
+ ):
782
+ super().__init__()
783
+ stride: int = 2
784
+ self.padding = padding
785
+ self.in_channels = in_channels
786
+ self.dims = dims
787
+ self.conv = make_conv_nd(
788
+ dims=dims,
789
+ in_channels=in_channels,
790
+ out_channels=out_channels,
791
+ kernel_size=kernel_size,
792
+ stride=stride,
793
+ padding=padding,
794
+ )
795
+
796
+ def forward(self, x, downsample_in_time=True):
797
+ conv = self.conv
798
+ if self.padding == 0:
799
+ if self.dims == 2:
800
+ padding = (0, 1, 0, 1)
801
+ else:
802
+ padding = (0, 1, 0, 1, 0, 1 if downsample_in_time else 0)
803
+
804
+ x = functional.pad(x, padding, mode="constant", value=0)
805
+
806
+ if self.dims == (2, 1) and not downsample_in_time:
807
+ return conv(x, skip_time_conv=True)
808
+
809
+ return conv(x)
810
+
811
+
812
+ class Upsample3D(nn.Module):
813
+ """
814
+ An upsampling layer for 3D tensors of shape (B, C, D, H, W).
815
+
816
+ :param channels: channels in the inputs and outputs.
817
+ """
818
+
819
+ def __init__(self, dims, channels, out_channels=None):
820
+ super().__init__()
821
+ self.dims = dims
822
+ self.channels = channels
823
+ self.out_channels = out_channels or channels
824
+ self.conv = make_conv_nd(
825
+ dims, channels, out_channels, kernel_size=3, padding=1, bias=True
826
+ )
827
+
828
+ def forward(self, x, upsample_in_time):
829
+ if self.dims == 2:
830
+ x = functional.interpolate(
831
+ x, (x.shape[2] * 2, x.shape[3] * 2), mode="nearest"
832
+ )
833
+ else:
834
+ time_scale_factor = 2 if upsample_in_time else 1
835
+ # print("before:", x.shape)
836
+ b, c, d, h, w = x.shape
837
+ x = rearrange(x, "b c d h w -> (b d) c h w")
838
+ # height and width interpolate
839
+ x = functional.interpolate(
840
+ x, (x.shape[2] * 2, x.shape[3] * 2), mode="nearest"
841
+ )
842
+ _, _, h, w = x.shape
843
+
844
+ if not upsample_in_time and self.dims == (2, 1):
845
+ x = rearrange(x, "(b d) c h w -> b c d h w ", b=b, h=h, w=w)
846
+ return self.conv(x, skip_time_conv=True)
847
+
848
+ # Second ** upsampling ** which is essentially treated as a 1D convolution across the 'd' dimension
849
+ x = rearrange(x, "(b d) c h w -> (b h w) c 1 d", b=b)
850
+
851
+ # (b h w) c 1 d
852
+ new_d = x.shape[-1] * time_scale_factor
853
+ x = functional.interpolate(x, (1, new_d), mode="nearest")
854
+ # (b h w) c 1 new_d
855
+ x = rearrange(
856
+ x, "(b h w) c 1 new_d -> b c new_d h w", b=b, h=h, w=w, new_d=new_d
857
+ )
858
+ # b c d h w
859
+
860
+ # x = functional.interpolate(
861
+ # x, (x.shape[2] * time_scale_factor, x.shape[3] * 2, x.shape[4] * 2), mode="nearest"
862
+ # )
863
+ # print("after:", x.shape)
864
+
865
+ return self.conv(x)
866
+
867
+
868
+ def patchify(x, patch_size_hw, patch_size_t=1, add_channel_padding=False):
869
+ if patch_size_hw == 1 and patch_size_t == 1:
870
+ return x
871
+ if x.dim() == 4:
872
+ x = rearrange(
873
+ x, "b c (h q) (w r) -> b (c r q) h w", q=patch_size_hw, r=patch_size_hw
874
+ )
875
+ elif x.dim() == 5:
876
+ x = rearrange(
877
+ x,
878
+ "b c (f p) (h q) (w r) -> b (c p r q) f h w",
879
+ p=patch_size_t,
880
+ q=patch_size_hw,
881
+ r=patch_size_hw,
882
+ )
883
+ else:
884
+ raise ValueError(f"Invalid input shape: {x.shape}")
885
+
886
+ if (
887
+ (x.dim() == 5)
888
+ and (patch_size_hw > patch_size_t)
889
+ and (patch_size_t > 1 or add_channel_padding)
890
+ ):
891
+ channels_to_pad = x.shape[1] * (patch_size_hw // patch_size_t) - x.shape[1]
892
+ padding_zeros = torch.zeros(
893
+ x.shape[0],
894
+ channels_to_pad,
895
+ x.shape[2],
896
+ x.shape[3],
897
+ x.shape[4],
898
+ device=x.device,
899
+ dtype=x.dtype,
900
+ )
901
+ x = torch.cat([padding_zeros, x], dim=1)
902
+
903
+ return x
904
+
905
+
906
+ def unpatchify(x, patch_size_hw, patch_size_t=1, add_channel_padding=False):
907
+ if patch_size_hw == 1 and patch_size_t == 1:
908
+ return x
909
+
910
+ if (
911
+ (x.dim() == 5)
912
+ and (patch_size_hw > patch_size_t)
913
+ and (patch_size_t > 1 or add_channel_padding)
914
+ ):
915
+ channels_to_keep = int(x.shape[1] * (patch_size_t / patch_size_hw))
916
+ x = x[:, :channels_to_keep, :, :, :]
917
+
918
+ if x.dim() == 4:
919
+ x = rearrange(
920
+ x, "b (c r q) h w -> b c (h q) (w r)", q=patch_size_hw, r=patch_size_hw
921
+ )
922
+ elif x.dim() == 5:
923
+ x = rearrange(
924
+ x,
925
+ "b (c p r q) f h w -> b c (f p) (h q) (w r)",
926
+ p=patch_size_t,
927
+ q=patch_size_hw,
928
+ r=patch_size_hw,
929
+ )
930
+
931
+ return x
932
+
933
+
934
+ def create_video_autoencoder_config(
935
+ latent_channels: int = 4,
936
+ ):
937
+ config = {
938
+ "_class_name": "VideoAutoencoder",
939
+ "dims": (
940
+ 2,
941
+ 1,
942
+ ), # 2 for Conv2, 3 for Conv3d, (2, 1) for Conv2d followed by Conv1d
943
+ "in_channels": 3, # Number of input color channels (e.g., RGB)
944
+ "out_channels": 3, # Number of output color channels
945
+ "latent_channels": latent_channels, # Number of channels in the latent space representation
946
+ "block_out_channels": [
947
+ 128,
948
+ 256,
949
+ 512,
950
+ 512,
951
+ ], # Number of output channels of each encoder / decoder inner block
952
+ "patch_size": 1,
953
+ }
954
+
955
+ return config
956
+
957
+
958
+ def create_video_autoencoder_pathify4x4x4_config(
959
+ latent_channels: int = 4,
960
+ ):
961
+ config = {
962
+ "_class_name": "VideoAutoencoder",
963
+ "dims": (
964
+ 2,
965
+ 1,
966
+ ), # 2 for Conv2, 3 for Conv3d, (2, 1) for Conv2d followed by Conv1d
967
+ "in_channels": 3, # Number of input color channels (e.g., RGB)
968
+ "out_channels": 3, # Number of output color channels
969
+ "latent_channels": latent_channels, # Number of channels in the latent space representation
970
+ "block_out_channels": [512]
971
+ * 4, # Number of output channels of each encoder / decoder inner block
972
+ "patch_size": 4,
973
+ "latent_log_var": "uniform",
974
+ }
975
+
976
+ return config
977
+
978
+
979
+ def create_video_autoencoder_pathify4x4_config(
980
+ latent_channels: int = 4,
981
+ ):
982
+ config = {
983
+ "_class_name": "VideoAutoencoder",
984
+ "dims": 2, # 2 for Conv2, 3 for Conv3d, (2, 1) for Conv2d followed by Conv1d
985
+ "in_channels": 3, # Number of input color channels (e.g., RGB)
986
+ "out_channels": 3, # Number of output color channels
987
+ "latent_channels": latent_channels, # Number of channels in the latent space representation
988
+ "block_out_channels": [512]
989
+ * 4, # Number of output channels of each encoder / decoder inner block
990
+ "patch_size": 4,
991
+ "norm_layer": "pixel_norm",
992
+ }
993
+
994
+ return config
995
+
996
+
997
+ def test_vae_patchify_unpatchify():
998
+ import torch
999
+
1000
+ x = torch.randn(2, 3, 8, 64, 64)
1001
+ x_patched = patchify(x, patch_size_hw=4, patch_size_t=4)
1002
+ x_unpatched = unpatchify(x_patched, patch_size_hw=4, patch_size_t=4)
1003
+ assert torch.allclose(x, x_unpatched)
1004
+
1005
+
1006
+ def demo_video_autoencoder_forward_backward():
1007
+ # Configuration for the VideoAutoencoder
1008
+ config = create_video_autoencoder_pathify4x4x4_config()
1009
+
1010
+ # Instantiate the VideoAutoencoder with the specified configuration
1011
+ video_autoencoder = VideoAutoencoder.from_config(config)
1012
+
1013
+ print(video_autoencoder)
1014
+
1015
+ # Print the total number of parameters in the video autoencoder
1016
+ total_params = sum(p.numel() for p in video_autoencoder.parameters())
1017
+ print(f"Total number of parameters in VideoAutoencoder: {total_params:,}")
1018
+
1019
+ # Create a mock input tensor simulating a batch of videos
1020
+ # Shape: (batch_size, channels, depth, height, width)
1021
+ # E.g., 4 videos, each with 3 color channels, 16 frames, and 64x64 pixels per frame
1022
+ input_videos = torch.randn(2, 3, 8, 64, 64)
1023
+
1024
+ # Forward pass: encode and decode the input videos
1025
+ latent = video_autoencoder.encode(input_videos).latent_dist.mode()
1026
+ print(f"input shape={input_videos.shape}")
1027
+ print(f"latent shape={latent.shape}")
1028
+ reconstructed_videos = video_autoencoder.decode(
1029
+ latent, target_shape=input_videos.shape
1030
+ ).sample
1031
+
1032
+ print(f"reconstructed shape={reconstructed_videos.shape}")
1033
+
1034
+ # Calculate the loss (e.g., mean squared error)
1035
+ loss = torch.nn.functional.mse_loss(input_videos, reconstructed_videos)
1036
+
1037
+ # Perform backward pass
1038
+ loss.backward()
1039
+
1040
+ print(f"Demo completed with loss: {loss.item()}")
1041
+
1042
+
1043
+ # Ensure to call the demo function to execute the forward and backward pass
1044
+ if __name__ == "__main__":
1045
+ demo_video_autoencoder_forward_backward()
ltx_video/models/transformers/__init__.py ADDED
File without changes
ltx_video/models/transformers/attention.py ADDED
@@ -0,0 +1,1246 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import inspect
2
+ from importlib import import_module
3
+ from typing import Any, Dict, Optional, Tuple
4
+
5
+ import torch
6
+ import torch.nn.functional as F
7
+ from diffusers.models.activations import GEGLU, GELU, ApproximateGELU
8
+ from diffusers.models.attention import _chunked_feed_forward
9
+ from diffusers.models.attention_processor import (
10
+ LoRAAttnAddedKVProcessor,
11
+ LoRAAttnProcessor,
12
+ LoRAAttnProcessor2_0,
13
+ LoRAXFormersAttnProcessor,
14
+ SpatialNorm,
15
+ )
16
+ from diffusers.models.lora import LoRACompatibleLinear
17
+ from diffusers.models.normalization import RMSNorm
18
+ from diffusers.utils import deprecate, logging
19
+ from diffusers.utils.torch_utils import maybe_allow_in_graph
20
+ from einops import rearrange
21
+ from torch import nn
22
+
23
+ from ltx_video.utils.skip_layer_strategy import SkipLayerStrategy
24
+
25
+ try:
26
+ from torch_xla.experimental.custom_kernel import flash_attention
27
+ except ImportError:
28
+ # workaround for automatic tests. Currently this function is manually patched
29
+ # to the torch_xla lib on setup of container
30
+ pass
31
+
32
+ # code adapted from https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention.py
33
+
34
+ logger = logging.get_logger(__name__)
35
+
36
+
37
+ @maybe_allow_in_graph
38
+ class BasicTransformerBlock(nn.Module):
39
+ r"""
40
+ A basic Transformer block.
41
+
42
+ Parameters:
43
+ dim (`int`): The number of channels in the input and output.
44
+ num_attention_heads (`int`): The number of heads to use for multi-head attention.
45
+ attention_head_dim (`int`): The number of channels in each head.
46
+ dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
47
+ cross_attention_dim (`int`, *optional*): The size of the encoder_hidden_states vector for cross attention.
48
+ activation_fn (`str`, *optional*, defaults to `"geglu"`): Activation function to be used in feed-forward.
49
+ num_embeds_ada_norm (:
50
+ obj: `int`, *optional*): The number of diffusion steps used during training. See `Transformer2DModel`.
51
+ attention_bias (:
52
+ obj: `bool`, *optional*, defaults to `False`): Configure if the attentions should contain a bias parameter.
53
+ only_cross_attention (`bool`, *optional*):
54
+ Whether to use only cross-attention layers. In this case two cross attention layers are used.
55
+ double_self_attention (`bool`, *optional*):
56
+ Whether to use two self-attention layers. In this case no cross attention layers are used.
57
+ upcast_attention (`bool`, *optional*):
58
+ Whether to upcast the attention computation to float32. This is useful for mixed precision training.
59
+ norm_elementwise_affine (`bool`, *optional*, defaults to `True`):
60
+ Whether to use learnable elementwise affine parameters for normalization.
61
+ qk_norm (`str`, *optional*, defaults to None):
62
+ Set to 'layer_norm' or `rms_norm` to perform query and key normalization.
63
+ adaptive_norm (`str`, *optional*, defaults to `"single_scale_shift"`):
64
+ The type of adaptive norm to use. Can be `"single_scale_shift"`, `"single_scale"` or "none".
65
+ standardization_norm (`str`, *optional*, defaults to `"layer_norm"`):
66
+ The type of pre-normalization to use. Can be `"layer_norm"` or `"rms_norm"`.
67
+ final_dropout (`bool` *optional*, defaults to False):
68
+ Whether to apply a final dropout after the last feed-forward layer.
69
+ attention_type (`str`, *optional*, defaults to `"default"`):
70
+ The type of attention to use. Can be `"default"` or `"gated"` or `"gated-text-image"`.
71
+ positional_embeddings (`str`, *optional*, defaults to `None`):
72
+ The type of positional embeddings to apply to.
73
+ num_positional_embeddings (`int`, *optional*, defaults to `None`):
74
+ The maximum number of positional embeddings to apply.
75
+ """
76
+
77
+ def __init__(
78
+ self,
79
+ dim: int,
80
+ num_attention_heads: int,
81
+ attention_head_dim: int,
82
+ dropout=0.0,
83
+ cross_attention_dim: Optional[int] = None,
84
+ activation_fn: str = "geglu",
85
+ num_embeds_ada_norm: Optional[int] = None, # pylint: disable=unused-argument
86
+ attention_bias: bool = False,
87
+ only_cross_attention: bool = False,
88
+ double_self_attention: bool = False,
89
+ upcast_attention: bool = False,
90
+ norm_elementwise_affine: bool = True,
91
+ adaptive_norm: str = "single_scale_shift", # 'single_scale_shift', 'single_scale' or 'none'
92
+ standardization_norm: str = "layer_norm", # 'layer_norm' or 'rms_norm'
93
+ norm_eps: float = 1e-5,
94
+ qk_norm: Optional[str] = None,
95
+ final_dropout: bool = False,
96
+ attention_type: str = "default", # pylint: disable=unused-argument
97
+ ff_inner_dim: Optional[int] = None,
98
+ ff_bias: bool = True,
99
+ attention_out_bias: bool = True,
100
+ use_tpu_flash_attention: bool = False,
101
+ use_rope: bool = False,
102
+ ):
103
+ super().__init__()
104
+ self.only_cross_attention = only_cross_attention
105
+ self.use_tpu_flash_attention = use_tpu_flash_attention
106
+ self.adaptive_norm = adaptive_norm
107
+
108
+ assert standardization_norm in ["layer_norm", "rms_norm"]
109
+ assert adaptive_norm in ["single_scale_shift", "single_scale", "none"]
110
+
111
+ make_norm_layer = (
112
+ nn.LayerNorm if standardization_norm == "layer_norm" else RMSNorm
113
+ )
114
+
115
+ # Define 3 blocks. Each block has its own normalization layer.
116
+ # 1. Self-Attn
117
+ self.norm1 = make_norm_layer(
118
+ dim, elementwise_affine=norm_elementwise_affine, eps=norm_eps
119
+ )
120
+
121
+ self.attn1 = Attention(
122
+ query_dim=dim,
123
+ heads=num_attention_heads,
124
+ dim_head=attention_head_dim,
125
+ dropout=dropout,
126
+ bias=attention_bias,
127
+ cross_attention_dim=cross_attention_dim if only_cross_attention else None,
128
+ upcast_attention=upcast_attention,
129
+ out_bias=attention_out_bias,
130
+ use_tpu_flash_attention=use_tpu_flash_attention,
131
+ qk_norm=qk_norm,
132
+ use_rope=use_rope,
133
+ )
134
+
135
+ # 2. Cross-Attn
136
+ if cross_attention_dim is not None or double_self_attention:
137
+ self.attn2 = Attention(
138
+ query_dim=dim,
139
+ cross_attention_dim=(
140
+ cross_attention_dim if not double_self_attention else None
141
+ ),
142
+ heads=num_attention_heads,
143
+ dim_head=attention_head_dim,
144
+ dropout=dropout,
145
+ bias=attention_bias,
146
+ upcast_attention=upcast_attention,
147
+ out_bias=attention_out_bias,
148
+ use_tpu_flash_attention=use_tpu_flash_attention,
149
+ qk_norm=qk_norm,
150
+ use_rope=use_rope,
151
+ ) # is self-attn if encoder_hidden_states is none
152
+
153
+ if adaptive_norm == "none":
154
+ self.attn2_norm = make_norm_layer(
155
+ dim, norm_eps, norm_elementwise_affine
156
+ )
157
+ else:
158
+ self.attn2 = None
159
+ self.attn2_norm = None
160
+
161
+ self.norm2 = make_norm_layer(dim, norm_eps, norm_elementwise_affine)
162
+
163
+ # 3. Feed-forward
164
+ self.ff = FeedForward(
165
+ dim,
166
+ dropout=dropout,
167
+ activation_fn=activation_fn,
168
+ final_dropout=final_dropout,
169
+ inner_dim=ff_inner_dim,
170
+ bias=ff_bias,
171
+ )
172
+
173
+ # 5. Scale-shift for PixArt-Alpha.
174
+ if adaptive_norm != "none":
175
+ num_ada_params = 4 if adaptive_norm == "single_scale" else 6
176
+ self.scale_shift_table = nn.Parameter(
177
+ torch.randn(num_ada_params, dim) / dim**0.5
178
+ )
179
+
180
+ # let chunk size default to None
181
+ self._chunk_size = None
182
+ self._chunk_dim = 0
183
+
184
+ def set_use_tpu_flash_attention(self):
185
+ r"""
186
+ Function sets the flag in this object and propagates down the children. The flag will enforce the usage of TPU
187
+ attention kernel.
188
+ """
189
+ self.use_tpu_flash_attention = True
190
+ self.attn1.set_use_tpu_flash_attention()
191
+ self.attn2.set_use_tpu_flash_attention()
192
+
193
+ def set_chunk_feed_forward(self, chunk_size: Optional[int], dim: int = 0):
194
+ # Sets chunk feed-forward
195
+ self._chunk_size = chunk_size
196
+ self._chunk_dim = dim
197
+
198
+ def forward(
199
+ self,
200
+ hidden_states: torch.FloatTensor,
201
+ freqs_cis: Optional[Tuple[torch.FloatTensor, torch.FloatTensor]] = None,
202
+ attention_mask: Optional[torch.FloatTensor] = None,
203
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
204
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
205
+ timestep: Optional[torch.LongTensor] = None,
206
+ cross_attention_kwargs: Dict[str, Any] = None,
207
+ class_labels: Optional[torch.LongTensor] = None,
208
+ added_cond_kwargs: Optional[Dict[str, torch.Tensor]] = None,
209
+ skip_layer_mask: Optional[torch.Tensor] = None,
210
+ skip_layer_strategy: Optional[SkipLayerStrategy] = None,
211
+ ) -> torch.FloatTensor:
212
+ if cross_attention_kwargs is not None:
213
+ if cross_attention_kwargs.get("scale", None) is not None:
214
+ logger.warning(
215
+ "Passing `scale` to `cross_attention_kwargs` is depcrecated. `scale` will be ignored."
216
+ )
217
+
218
+ # Notice that normalization is always applied before the real computation in the following blocks.
219
+ # 0. Self-Attention
220
+ batch_size = hidden_states.shape[0]
221
+
222
+ norm_hidden_states = self.norm1(hidden_states)
223
+
224
+ # Apply ada_norm_single
225
+ if self.adaptive_norm in ["single_scale_shift", "single_scale"]:
226
+ assert timestep.ndim == 3 # [batch, 1 or num_tokens, embedding_dim]
227
+ num_ada_params = self.scale_shift_table.shape[0]
228
+ ada_values = self.scale_shift_table[None, None] + timestep.reshape(
229
+ batch_size, timestep.shape[1], num_ada_params, -1
230
+ )
231
+ if self.adaptive_norm == "single_scale_shift":
232
+ shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = (
233
+ ada_values.unbind(dim=2)
234
+ )
235
+ norm_hidden_states = norm_hidden_states * (1 + scale_msa) + shift_msa
236
+ else:
237
+ scale_msa, gate_msa, scale_mlp, gate_mlp = ada_values.unbind(dim=2)
238
+ norm_hidden_states = norm_hidden_states * (1 + scale_msa)
239
+ elif self.adaptive_norm == "none":
240
+ scale_msa, gate_msa, scale_mlp, gate_mlp = None, None, None, None
241
+ else:
242
+ raise ValueError(f"Unknown adaptive norm type: {self.adaptive_norm}")
243
+
244
+ norm_hidden_states = norm_hidden_states.squeeze(
245
+ 1
246
+ ) # TODO: Check if this is needed
247
+
248
+ # 1. Prepare GLIGEN inputs
249
+ cross_attention_kwargs = (
250
+ cross_attention_kwargs.copy() if cross_attention_kwargs is not None else {}
251
+ )
252
+
253
+ attn_output = self.attn1(
254
+ norm_hidden_states,
255
+ freqs_cis=freqs_cis,
256
+ encoder_hidden_states=(
257
+ encoder_hidden_states if self.only_cross_attention else None
258
+ ),
259
+ attention_mask=attention_mask,
260
+ skip_layer_mask=skip_layer_mask,
261
+ skip_layer_strategy=skip_layer_strategy,
262
+ **cross_attention_kwargs,
263
+ )
264
+ if gate_msa is not None:
265
+ attn_output = gate_msa * attn_output
266
+
267
+ hidden_states = attn_output + hidden_states
268
+ if hidden_states.ndim == 4:
269
+ hidden_states = hidden_states.squeeze(1)
270
+
271
+ # 3. Cross-Attention
272
+ if self.attn2 is not None:
273
+ if self.adaptive_norm == "none":
274
+ attn_input = self.attn2_norm(hidden_states)
275
+ else:
276
+ attn_input = hidden_states
277
+ attn_output = self.attn2(
278
+ attn_input,
279
+ freqs_cis=freqs_cis,
280
+ encoder_hidden_states=encoder_hidden_states,
281
+ attention_mask=encoder_attention_mask,
282
+ **cross_attention_kwargs,
283
+ )
284
+ hidden_states = attn_output + hidden_states
285
+
286
+ # 4. Feed-forward
287
+ norm_hidden_states = self.norm2(hidden_states)
288
+ if self.adaptive_norm == "single_scale_shift":
289
+ norm_hidden_states = norm_hidden_states * (1 + scale_mlp) + shift_mlp
290
+ elif self.adaptive_norm == "single_scale":
291
+ norm_hidden_states = norm_hidden_states * (1 + scale_mlp)
292
+ elif self.adaptive_norm == "none":
293
+ pass
294
+ else:
295
+ raise ValueError(f"Unknown adaptive norm type: {self.adaptive_norm}")
296
+
297
+ if self._chunk_size is not None:
298
+ # "feed_forward_chunk_size" can be used to save memory
299
+ ff_output = _chunked_feed_forward(
300
+ self.ff, norm_hidden_states, self._chunk_dim, self._chunk_size
301
+ )
302
+ else:
303
+ ff_output = self.ff(norm_hidden_states)
304
+ if gate_mlp is not None:
305
+ ff_output = gate_mlp * ff_output
306
+
307
+ hidden_states = ff_output + hidden_states
308
+ if hidden_states.ndim == 4:
309
+ hidden_states = hidden_states.squeeze(1)
310
+
311
+ return hidden_states
312
+
313
+
314
+ @maybe_allow_in_graph
315
+ class Attention(nn.Module):
316
+ r"""
317
+ A cross attention layer.
318
+
319
+ Parameters:
320
+ query_dim (`int`):
321
+ The number of channels in the query.
322
+ cross_attention_dim (`int`, *optional*):
323
+ The number of channels in the encoder_hidden_states. If not given, defaults to `query_dim`.
324
+ heads (`int`, *optional*, defaults to 8):
325
+ The number of heads to use for multi-head attention.
326
+ dim_head (`int`, *optional*, defaults to 64):
327
+ The number of channels in each head.
328
+ dropout (`float`, *optional*, defaults to 0.0):
329
+ The dropout probability to use.
330
+ bias (`bool`, *optional*, defaults to False):
331
+ Set to `True` for the query, key, and value linear layers to contain a bias parameter.
332
+ upcast_attention (`bool`, *optional*, defaults to False):
333
+ Set to `True` to upcast the attention computation to `float32`.
334
+ upcast_softmax (`bool`, *optional*, defaults to False):
335
+ Set to `True` to upcast the softmax computation to `float32`.
336
+ cross_attention_norm (`str`, *optional*, defaults to `None`):
337
+ The type of normalization to use for the cross attention. Can be `None`, `layer_norm`, or `group_norm`.
338
+ cross_attention_norm_num_groups (`int`, *optional*, defaults to 32):
339
+ The number of groups to use for the group norm in the cross attention.
340
+ added_kv_proj_dim (`int`, *optional*, defaults to `None`):
341
+ The number of channels to use for the added key and value projections. If `None`, no projection is used.
342
+ norm_num_groups (`int`, *optional*, defaults to `None`):
343
+ The number of groups to use for the group norm in the attention.
344
+ spatial_norm_dim (`int`, *optional*, defaults to `None`):
345
+ The number of channels to use for the spatial normalization.
346
+ out_bias (`bool`, *optional*, defaults to `True`):
347
+ Set to `True` to use a bias in the output linear layer.
348
+ scale_qk (`bool`, *optional*, defaults to `True`):
349
+ Set to `True` to scale the query and key by `1 / sqrt(dim_head)`.
350
+ qk_norm (`str`, *optional*, defaults to None):
351
+ Set to 'layer_norm' or `rms_norm` to perform query and key normalization.
352
+ only_cross_attention (`bool`, *optional*, defaults to `False`):
353
+ Set to `True` to only use cross attention and not added_kv_proj_dim. Can only be set to `True` if
354
+ `added_kv_proj_dim` is not `None`.
355
+ eps (`float`, *optional*, defaults to 1e-5):
356
+ An additional value added to the denominator in group normalization that is used for numerical stability.
357
+ rescale_output_factor (`float`, *optional*, defaults to 1.0):
358
+ A factor to rescale the output by dividing it with this value.
359
+ residual_connection (`bool`, *optional*, defaults to `False`):
360
+ Set to `True` to add the residual connection to the output.
361
+ _from_deprecated_attn_block (`bool`, *optional*, defaults to `False`):
362
+ Set to `True` if the attention block is loaded from a deprecated state dict.
363
+ processor (`AttnProcessor`, *optional*, defaults to `None`):
364
+ The attention processor to use. If `None`, defaults to `AttnProcessor2_0` if `torch 2.x` is used and
365
+ `AttnProcessor` otherwise.
366
+ """
367
+
368
+ def __init__(
369
+ self,
370
+ query_dim: int,
371
+ cross_attention_dim: Optional[int] = None,
372
+ heads: int = 8,
373
+ dim_head: int = 64,
374
+ dropout: float = 0.0,
375
+ bias: bool = False,
376
+ upcast_attention: bool = False,
377
+ upcast_softmax: bool = False,
378
+ cross_attention_norm: Optional[str] = None,
379
+ cross_attention_norm_num_groups: int = 32,
380
+ added_kv_proj_dim: Optional[int] = None,
381
+ norm_num_groups: Optional[int] = None,
382
+ spatial_norm_dim: Optional[int] = None,
383
+ out_bias: bool = True,
384
+ scale_qk: bool = True,
385
+ qk_norm: Optional[str] = None,
386
+ only_cross_attention: bool = False,
387
+ eps: float = 1e-5,
388
+ rescale_output_factor: float = 1.0,
389
+ residual_connection: bool = False,
390
+ _from_deprecated_attn_block: bool = False,
391
+ processor: Optional["AttnProcessor"] = None,
392
+ out_dim: int = None,
393
+ use_tpu_flash_attention: bool = False,
394
+ use_rope: bool = False,
395
+ ):
396
+ super().__init__()
397
+ self.inner_dim = out_dim if out_dim is not None else dim_head * heads
398
+ self.query_dim = query_dim
399
+ self.use_bias = bias
400
+ self.is_cross_attention = cross_attention_dim is not None
401
+ self.cross_attention_dim = (
402
+ cross_attention_dim if cross_attention_dim is not None else query_dim
403
+ )
404
+ self.upcast_attention = upcast_attention
405
+ self.upcast_softmax = upcast_softmax
406
+ self.rescale_output_factor = rescale_output_factor
407
+ self.residual_connection = residual_connection
408
+ self.dropout = dropout
409
+ self.fused_projections = False
410
+ self.out_dim = out_dim if out_dim is not None else query_dim
411
+ self.use_tpu_flash_attention = use_tpu_flash_attention
412
+ self.use_rope = use_rope
413
+
414
+ # we make use of this private variable to know whether this class is loaded
415
+ # with an deprecated state dict so that we can convert it on the fly
416
+ self._from_deprecated_attn_block = _from_deprecated_attn_block
417
+
418
+ self.scale_qk = scale_qk
419
+ self.scale = dim_head**-0.5 if self.scale_qk else 1.0
420
+
421
+ if qk_norm is None:
422
+ self.q_norm = nn.Identity()
423
+ self.k_norm = nn.Identity()
424
+ elif qk_norm == "rms_norm":
425
+ self.q_norm = RMSNorm(dim_head * heads, eps=1e-5)
426
+ self.k_norm = RMSNorm(dim_head * heads, eps=1e-5)
427
+ elif qk_norm == "layer_norm":
428
+ self.q_norm = nn.LayerNorm(dim_head * heads, eps=1e-5)
429
+ self.k_norm = nn.LayerNorm(dim_head * heads, eps=1e-5)
430
+ else:
431
+ raise ValueError(f"Unsupported qk_norm method: {qk_norm}")
432
+
433
+ self.heads = out_dim // dim_head if out_dim is not None else heads
434
+ # for slice_size > 0 the attention score computation
435
+ # is split across the batch axis to save memory
436
+ # You can set slice_size with `set_attention_slice`
437
+ self.sliceable_head_dim = heads
438
+
439
+ self.added_kv_proj_dim = added_kv_proj_dim
440
+ self.only_cross_attention = only_cross_attention
441
+
442
+ if self.added_kv_proj_dim is None and self.only_cross_attention:
443
+ raise ValueError(
444
+ "`only_cross_attention` can only be set to True if `added_kv_proj_dim` is not None. Make sure to set either `only_cross_attention=False` or define `added_kv_proj_dim`."
445
+ )
446
+
447
+ if norm_num_groups is not None:
448
+ self.group_norm = nn.GroupNorm(
449
+ num_channels=query_dim, num_groups=norm_num_groups, eps=eps, affine=True
450
+ )
451
+ else:
452
+ self.group_norm = None
453
+
454
+ if spatial_norm_dim is not None:
455
+ self.spatial_norm = SpatialNorm(
456
+ f_channels=query_dim, zq_channels=spatial_norm_dim
457
+ )
458
+ else:
459
+ self.spatial_norm = None
460
+
461
+ if cross_attention_norm is None:
462
+ self.norm_cross = None
463
+ elif cross_attention_norm == "layer_norm":
464
+ self.norm_cross = nn.LayerNorm(self.cross_attention_dim)
465
+ elif cross_attention_norm == "group_norm":
466
+ if self.added_kv_proj_dim is not None:
467
+ # The given `encoder_hidden_states` are initially of shape
468
+ # (batch_size, seq_len, added_kv_proj_dim) before being projected
469
+ # to (batch_size, seq_len, cross_attention_dim). The norm is applied
470
+ # before the projection, so we need to use `added_kv_proj_dim` as
471
+ # the number of channels for the group norm.
472
+ norm_cross_num_channels = added_kv_proj_dim
473
+ else:
474
+ norm_cross_num_channels = self.cross_attention_dim
475
+
476
+ self.norm_cross = nn.GroupNorm(
477
+ num_channels=norm_cross_num_channels,
478
+ num_groups=cross_attention_norm_num_groups,
479
+ eps=1e-5,
480
+ affine=True,
481
+ )
482
+ else:
483
+ raise ValueError(
484
+ f"unknown cross_attention_norm: {cross_attention_norm}. Should be None, 'layer_norm' or 'group_norm'"
485
+ )
486
+
487
+ linear_cls = nn.Linear
488
+
489
+ self.linear_cls = linear_cls
490
+ self.to_q = linear_cls(query_dim, self.inner_dim, bias=bias)
491
+
492
+ if not self.only_cross_attention:
493
+ # only relevant for the `AddedKVProcessor` classes
494
+ self.to_k = linear_cls(self.cross_attention_dim, self.inner_dim, bias=bias)
495
+ self.to_v = linear_cls(self.cross_attention_dim, self.inner_dim, bias=bias)
496
+ else:
497
+ self.to_k = None
498
+ self.to_v = None
499
+
500
+ if self.added_kv_proj_dim is not None:
501
+ self.add_k_proj = linear_cls(added_kv_proj_dim, self.inner_dim)
502
+ self.add_v_proj = linear_cls(added_kv_proj_dim, self.inner_dim)
503
+
504
+ self.to_out = nn.ModuleList([])
505
+ self.to_out.append(linear_cls(self.inner_dim, self.out_dim, bias=out_bias))
506
+ self.to_out.append(nn.Dropout(dropout))
507
+
508
+ # set attention processor
509
+ # We use the AttnProcessor2_0 by default when torch 2.x is used which uses
510
+ # torch.nn.functional.scaled_dot_product_attention for native Flash/memory_efficient_attention
511
+ # but only if it has the default `scale` argument. TODO remove scale_qk check when we move to torch 2.1
512
+ if processor is None:
513
+ processor = AttnProcessor2_0()
514
+ self.set_processor(processor)
515
+
516
+ def set_use_tpu_flash_attention(self):
517
+ r"""
518
+ Function sets the flag in this object. The flag will enforce the usage of TPU attention kernel.
519
+ """
520
+ self.use_tpu_flash_attention = True
521
+
522
+ def set_processor(self, processor: "AttnProcessor") -> None:
523
+ r"""
524
+ Set the attention processor to use.
525
+
526
+ Args:
527
+ processor (`AttnProcessor`):
528
+ The attention processor to use.
529
+ """
530
+ # if current processor is in `self._modules` and if passed `processor` is not, we need to
531
+ # pop `processor` from `self._modules`
532
+ if (
533
+ hasattr(self, "processor")
534
+ and isinstance(self.processor, torch.nn.Module)
535
+ and not isinstance(processor, torch.nn.Module)
536
+ ):
537
+ logger.info(
538
+ f"You are removing possibly trained weights of {self.processor} with {processor}"
539
+ )
540
+ self._modules.pop("processor")
541
+
542
+ self.processor = processor
543
+
544
+ def get_processor(
545
+ self, return_deprecated_lora: bool = False
546
+ ) -> "AttentionProcessor": # noqa: F821
547
+ r"""
548
+ Get the attention processor in use.
549
+
550
+ Args:
551
+ return_deprecated_lora (`bool`, *optional*, defaults to `False`):
552
+ Set to `True` to return the deprecated LoRA attention processor.
553
+
554
+ Returns:
555
+ "AttentionProcessor": The attention processor in use.
556
+ """
557
+ if not return_deprecated_lora:
558
+ return self.processor
559
+
560
+ # TODO(Sayak, Patrick). The rest of the function is needed to ensure backwards compatible
561
+ # serialization format for LoRA Attention Processors. It should be deleted once the integration
562
+ # with PEFT is completed.
563
+ is_lora_activated = {
564
+ name: module.lora_layer is not None
565
+ for name, module in self.named_modules()
566
+ if hasattr(module, "lora_layer")
567
+ }
568
+
569
+ # 1. if no layer has a LoRA activated we can return the processor as usual
570
+ if not any(is_lora_activated.values()):
571
+ return self.processor
572
+
573
+ # If doesn't apply LoRA do `add_k_proj` or `add_v_proj`
574
+ is_lora_activated.pop("add_k_proj", None)
575
+ is_lora_activated.pop("add_v_proj", None)
576
+ # 2. else it is not posssible that only some layers have LoRA activated
577
+ if not all(is_lora_activated.values()):
578
+ raise ValueError(
579
+ f"Make sure that either all layers or no layers have LoRA activated, but have {is_lora_activated}"
580
+ )
581
+
582
+ # 3. And we need to merge the current LoRA layers into the corresponding LoRA attention processor
583
+ non_lora_processor_cls_name = self.processor.__class__.__name__
584
+ lora_processor_cls = getattr(
585
+ import_module(__name__), "LoRA" + non_lora_processor_cls_name
586
+ )
587
+
588
+ hidden_size = self.inner_dim
589
+
590
+ # now create a LoRA attention processor from the LoRA layers
591
+ if lora_processor_cls in [
592
+ LoRAAttnProcessor,
593
+ LoRAAttnProcessor2_0,
594
+ LoRAXFormersAttnProcessor,
595
+ ]:
596
+ kwargs = {
597
+ "cross_attention_dim": self.cross_attention_dim,
598
+ "rank": self.to_q.lora_layer.rank,
599
+ "network_alpha": self.to_q.lora_layer.network_alpha,
600
+ "q_rank": self.to_q.lora_layer.rank,
601
+ "q_hidden_size": self.to_q.lora_layer.out_features,
602
+ "k_rank": self.to_k.lora_layer.rank,
603
+ "k_hidden_size": self.to_k.lora_layer.out_features,
604
+ "v_rank": self.to_v.lora_layer.rank,
605
+ "v_hidden_size": self.to_v.lora_layer.out_features,
606
+ "out_rank": self.to_out[0].lora_layer.rank,
607
+ "out_hidden_size": self.to_out[0].lora_layer.out_features,
608
+ }
609
+
610
+ if hasattr(self.processor, "attention_op"):
611
+ kwargs["attention_op"] = self.processor.attention_op
612
+
613
+ lora_processor = lora_processor_cls(hidden_size, **kwargs)
614
+ lora_processor.to_q_lora.load_state_dict(self.to_q.lora_layer.state_dict())
615
+ lora_processor.to_k_lora.load_state_dict(self.to_k.lora_layer.state_dict())
616
+ lora_processor.to_v_lora.load_state_dict(self.to_v.lora_layer.state_dict())
617
+ lora_processor.to_out_lora.load_state_dict(
618
+ self.to_out[0].lora_layer.state_dict()
619
+ )
620
+ elif lora_processor_cls == LoRAAttnAddedKVProcessor:
621
+ lora_processor = lora_processor_cls(
622
+ hidden_size,
623
+ cross_attention_dim=self.add_k_proj.weight.shape[0],
624
+ rank=self.to_q.lora_layer.rank,
625
+ network_alpha=self.to_q.lora_layer.network_alpha,
626
+ )
627
+ lora_processor.to_q_lora.load_state_dict(self.to_q.lora_layer.state_dict())
628
+ lora_processor.to_k_lora.load_state_dict(self.to_k.lora_layer.state_dict())
629
+ lora_processor.to_v_lora.load_state_dict(self.to_v.lora_layer.state_dict())
630
+ lora_processor.to_out_lora.load_state_dict(
631
+ self.to_out[0].lora_layer.state_dict()
632
+ )
633
+
634
+ # only save if used
635
+ if self.add_k_proj.lora_layer is not None:
636
+ lora_processor.add_k_proj_lora.load_state_dict(
637
+ self.add_k_proj.lora_layer.state_dict()
638
+ )
639
+ lora_processor.add_v_proj_lora.load_state_dict(
640
+ self.add_v_proj.lora_layer.state_dict()
641
+ )
642
+ else:
643
+ lora_processor.add_k_proj_lora = None
644
+ lora_processor.add_v_proj_lora = None
645
+ else:
646
+ raise ValueError(f"{lora_processor_cls} does not exist.")
647
+
648
+ return lora_processor
649
+
650
+ def forward(
651
+ self,
652
+ hidden_states: torch.FloatTensor,
653
+ freqs_cis: Optional[Tuple[torch.FloatTensor, torch.FloatTensor]] = None,
654
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
655
+ attention_mask: Optional[torch.FloatTensor] = None,
656
+ skip_layer_mask: Optional[torch.Tensor] = None,
657
+ skip_layer_strategy: Optional[SkipLayerStrategy] = None,
658
+ **cross_attention_kwargs,
659
+ ) -> torch.Tensor:
660
+ r"""
661
+ The forward method of the `Attention` class.
662
+
663
+ Args:
664
+ hidden_states (`torch.Tensor`):
665
+ The hidden states of the query.
666
+ encoder_hidden_states (`torch.Tensor`, *optional*):
667
+ The hidden states of the encoder.
668
+ attention_mask (`torch.Tensor`, *optional*):
669
+ The attention mask to use. If `None`, no mask is applied.
670
+ skip_layer_mask (`torch.Tensor`, *optional*):
671
+ The skip layer mask to use. If `None`, no mask is applied.
672
+ skip_layer_strategy (`SkipLayerStrategy`, *optional*, defaults to `None`):
673
+ Controls which layers to skip for spatiotemporal guidance.
674
+ **cross_attention_kwargs:
675
+ Additional keyword arguments to pass along to the cross attention.
676
+
677
+ Returns:
678
+ `torch.Tensor`: The output of the attention layer.
679
+ """
680
+ # The `Attention` class can call different attention processors / attention functions
681
+ # here we simply pass along all tensors to the selected processor class
682
+ # For standard processors that are defined here, `**cross_attention_kwargs` is empty
683
+
684
+ attn_parameters = set(
685
+ inspect.signature(self.processor.__call__).parameters.keys()
686
+ )
687
+ unused_kwargs = [
688
+ k for k, _ in cross_attention_kwargs.items() if k not in attn_parameters
689
+ ]
690
+ if len(unused_kwargs) > 0:
691
+ logger.warning(
692
+ f"cross_attention_kwargs {unused_kwargs} are not expected by"
693
+ f" {self.processor.__class__.__name__} and will be ignored."
694
+ )
695
+ cross_attention_kwargs = {
696
+ k: w for k, w in cross_attention_kwargs.items() if k in attn_parameters
697
+ }
698
+
699
+ return self.processor(
700
+ self,
701
+ hidden_states,
702
+ freqs_cis=freqs_cis,
703
+ encoder_hidden_states=encoder_hidden_states,
704
+ attention_mask=attention_mask,
705
+ skip_layer_mask=skip_layer_mask,
706
+ skip_layer_strategy=skip_layer_strategy,
707
+ **cross_attention_kwargs,
708
+ )
709
+
710
+ def batch_to_head_dim(self, tensor: torch.Tensor) -> torch.Tensor:
711
+ r"""
712
+ Reshape the tensor from `[batch_size, seq_len, dim]` to `[batch_size // heads, seq_len, dim * heads]`. `heads`
713
+ is the number of heads initialized while constructing the `Attention` class.
714
+
715
+ Args:
716
+ tensor (`torch.Tensor`): The tensor to reshape.
717
+
718
+ Returns:
719
+ `torch.Tensor`: The reshaped tensor.
720
+ """
721
+ head_size = self.heads
722
+ batch_size, seq_len, dim = tensor.shape
723
+ tensor = tensor.reshape(batch_size // head_size, head_size, seq_len, dim)
724
+ tensor = tensor.permute(0, 2, 1, 3).reshape(
725
+ batch_size // head_size, seq_len, dim * head_size
726
+ )
727
+ return tensor
728
+
729
+ def head_to_batch_dim(self, tensor: torch.Tensor, out_dim: int = 3) -> torch.Tensor:
730
+ r"""
731
+ Reshape the tensor from `[batch_size, seq_len, dim]` to `[batch_size, seq_len, heads, dim // heads]` `heads` is
732
+ the number of heads initialized while constructing the `Attention` class.
733
+
734
+ Args:
735
+ tensor (`torch.Tensor`): The tensor to reshape.
736
+ out_dim (`int`, *optional*, defaults to `3`): The output dimension of the tensor. If `3`, the tensor is
737
+ reshaped to `[batch_size * heads, seq_len, dim // heads]`.
738
+
739
+ Returns:
740
+ `torch.Tensor`: The reshaped tensor.
741
+ """
742
+
743
+ head_size = self.heads
744
+ if tensor.ndim == 3:
745
+ batch_size, seq_len, dim = tensor.shape
746
+ extra_dim = 1
747
+ else:
748
+ batch_size, extra_dim, seq_len, dim = tensor.shape
749
+ tensor = tensor.reshape(
750
+ batch_size, seq_len * extra_dim, head_size, dim // head_size
751
+ )
752
+ tensor = tensor.permute(0, 2, 1, 3)
753
+
754
+ if out_dim == 3:
755
+ tensor = tensor.reshape(
756
+ batch_size * head_size, seq_len * extra_dim, dim // head_size
757
+ )
758
+
759
+ return tensor
760
+
761
+ def get_attention_scores(
762
+ self,
763
+ query: torch.Tensor,
764
+ key: torch.Tensor,
765
+ attention_mask: torch.Tensor = None,
766
+ ) -> torch.Tensor:
767
+ r"""
768
+ Compute the attention scores.
769
+
770
+ Args:
771
+ query (`torch.Tensor`): The query tensor.
772
+ key (`torch.Tensor`): The key tensor.
773
+ attention_mask (`torch.Tensor`, *optional*): The attention mask to use. If `None`, no mask is applied.
774
+
775
+ Returns:
776
+ `torch.Tensor`: The attention probabilities/scores.
777
+ """
778
+ dtype = query.dtype
779
+ if self.upcast_attention:
780
+ query = query.float()
781
+ key = key.float()
782
+
783
+ if attention_mask is None:
784
+ baddbmm_input = torch.empty(
785
+ query.shape[0],
786
+ query.shape[1],
787
+ key.shape[1],
788
+ dtype=query.dtype,
789
+ device=query.device,
790
+ )
791
+ beta = 0
792
+ else:
793
+ baddbmm_input = attention_mask
794
+ beta = 1
795
+
796
+ attention_scores = torch.baddbmm(
797
+ baddbmm_input,
798
+ query,
799
+ key.transpose(-1, -2),
800
+ beta=beta,
801
+ alpha=self.scale,
802
+ )
803
+ del baddbmm_input
804
+
805
+ if self.upcast_softmax:
806
+ attention_scores = attention_scores.float()
807
+
808
+ attention_probs = attention_scores.softmax(dim=-1)
809
+ del attention_scores
810
+
811
+ attention_probs = attention_probs.to(dtype)
812
+
813
+ return attention_probs
814
+
815
+ def prepare_attention_mask(
816
+ self,
817
+ attention_mask: torch.Tensor,
818
+ target_length: int,
819
+ batch_size: int,
820
+ out_dim: int = 3,
821
+ ) -> torch.Tensor:
822
+ r"""
823
+ Prepare the attention mask for the attention computation.
824
+
825
+ Args:
826
+ attention_mask (`torch.Tensor`):
827
+ The attention mask to prepare.
828
+ target_length (`int`):
829
+ The target length of the attention mask. This is the length of the attention mask after padding.
830
+ batch_size (`int`):
831
+ The batch size, which is used to repeat the attention mask.
832
+ out_dim (`int`, *optional*, defaults to `3`):
833
+ The output dimension of the attention mask. Can be either `3` or `4`.
834
+
835
+ Returns:
836
+ `torch.Tensor`: The prepared attention mask.
837
+ """
838
+ head_size = self.heads
839
+ if attention_mask is None:
840
+ return attention_mask
841
+
842
+ current_length: int = attention_mask.shape[-1]
843
+ if current_length != target_length:
844
+ if attention_mask.device.type == "mps":
845
+ # HACK: MPS: Does not support padding by greater than dimension of input tensor.
846
+ # Instead, we can manually construct the padding tensor.
847
+ padding_shape = (
848
+ attention_mask.shape[0],
849
+ attention_mask.shape[1],
850
+ target_length,
851
+ )
852
+ padding = torch.zeros(
853
+ padding_shape,
854
+ dtype=attention_mask.dtype,
855
+ device=attention_mask.device,
856
+ )
857
+ attention_mask = torch.cat([attention_mask, padding], dim=2)
858
+ else:
859
+ # TODO: for pipelines such as stable-diffusion, padding cross-attn mask:
860
+ # we want to instead pad by (0, remaining_length), where remaining_length is:
861
+ # remaining_length: int = target_length - current_length
862
+ # TODO: re-enable tests/models/test_models_unet_2d_condition.py#test_model_xattn_padding
863
+ attention_mask = F.pad(attention_mask, (0, target_length), value=0.0)
864
+
865
+ if out_dim == 3:
866
+ if attention_mask.shape[0] < batch_size * head_size:
867
+ attention_mask = attention_mask.repeat_interleave(head_size, dim=0)
868
+ elif out_dim == 4:
869
+ attention_mask = attention_mask.unsqueeze(1)
870
+ attention_mask = attention_mask.repeat_interleave(head_size, dim=1)
871
+
872
+ return attention_mask
873
+
874
+ def norm_encoder_hidden_states(
875
+ self, encoder_hidden_states: torch.Tensor
876
+ ) -> torch.Tensor:
877
+ r"""
878
+ Normalize the encoder hidden states. Requires `self.norm_cross` to be specified when constructing the
879
+ `Attention` class.
880
+
881
+ Args:
882
+ encoder_hidden_states (`torch.Tensor`): Hidden states of the encoder.
883
+
884
+ Returns:
885
+ `torch.Tensor`: The normalized encoder hidden states.
886
+ """
887
+ assert (
888
+ self.norm_cross is not None
889
+ ), "self.norm_cross must be defined to call self.norm_encoder_hidden_states"
890
+
891
+ if isinstance(self.norm_cross, nn.LayerNorm):
892
+ encoder_hidden_states = self.norm_cross(encoder_hidden_states)
893
+ elif isinstance(self.norm_cross, nn.GroupNorm):
894
+ # Group norm norms along the channels dimension and expects
895
+ # input to be in the shape of (N, C, *). In this case, we want
896
+ # to norm along the hidden dimension, so we need to move
897
+ # (batch_size, sequence_length, hidden_size) ->
898
+ # (batch_size, hidden_size, sequence_length)
899
+ encoder_hidden_states = encoder_hidden_states.transpose(1, 2)
900
+ encoder_hidden_states = self.norm_cross(encoder_hidden_states)
901
+ encoder_hidden_states = encoder_hidden_states.transpose(1, 2)
902
+ else:
903
+ assert False
904
+
905
+ return encoder_hidden_states
906
+
907
+ @staticmethod
908
+ def apply_rotary_emb(
909
+ input_tensor: torch.Tensor,
910
+ freqs_cis: Tuple[torch.FloatTensor, torch.FloatTensor],
911
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
912
+ cos_freqs = freqs_cis[0]
913
+ sin_freqs = freqs_cis[1]
914
+
915
+ t_dup = rearrange(input_tensor, "... (d r) -> ... d r", r=2)
916
+ t1, t2 = t_dup.unbind(dim=-1)
917
+ t_dup = torch.stack((-t2, t1), dim=-1)
918
+ input_tensor_rot = rearrange(t_dup, "... d r -> ... (d r)")
919
+
920
+ out = input_tensor * cos_freqs + input_tensor_rot * sin_freqs
921
+
922
+ return out
923
+
924
+
925
+ class AttnProcessor2_0:
926
+ r"""
927
+ Processor for implementing scaled dot-product attention (enabled by default if you're using PyTorch 2.0).
928
+ """
929
+
930
+ def __init__(self):
931
+ pass
932
+
933
+ def __call__(
934
+ self,
935
+ attn: Attention,
936
+ hidden_states: torch.FloatTensor,
937
+ freqs_cis: Tuple[torch.FloatTensor, torch.FloatTensor],
938
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
939
+ attention_mask: Optional[torch.FloatTensor] = None,
940
+ temb: Optional[torch.FloatTensor] = None,
941
+ skip_layer_mask: Optional[torch.FloatTensor] = None,
942
+ skip_layer_strategy: Optional[SkipLayerStrategy] = None,
943
+ *args,
944
+ **kwargs,
945
+ ) -> torch.FloatTensor:
946
+ if len(args) > 0 or kwargs.get("scale", None) is not None:
947
+ deprecation_message = "The `scale` argument is deprecated and will be ignored. Please remove it, as passing it will raise an error in the future. `scale` should directly be passed while calling the underlying pipeline component i.e., via `cross_attention_kwargs`."
948
+ deprecate("scale", "1.0.0", deprecation_message)
949
+
950
+ residual = hidden_states
951
+ if attn.spatial_norm is not None:
952
+ hidden_states = attn.spatial_norm(hidden_states, temb)
953
+
954
+ input_ndim = hidden_states.ndim
955
+
956
+ if input_ndim == 4:
957
+ batch_size, channel, height, width = hidden_states.shape
958
+ hidden_states = hidden_states.view(
959
+ batch_size, channel, height * width
960
+ ).transpose(1, 2)
961
+
962
+ batch_size, sequence_length, _ = (
963
+ hidden_states.shape
964
+ if encoder_hidden_states is None
965
+ else encoder_hidden_states.shape
966
+ )
967
+
968
+ if skip_layer_mask is not None:
969
+ skip_layer_mask = skip_layer_mask.reshape(batch_size, 1, 1)
970
+
971
+ if (attention_mask is not None) and (not attn.use_tpu_flash_attention):
972
+ attention_mask = attn.prepare_attention_mask(
973
+ attention_mask, sequence_length, batch_size
974
+ )
975
+ # scaled_dot_product_attention expects attention_mask shape to be
976
+ # (batch, heads, source_length, target_length)
977
+ attention_mask = attention_mask.view(
978
+ batch_size, attn.heads, -1, attention_mask.shape[-1]
979
+ )
980
+
981
+ if attn.group_norm is not None:
982
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(
983
+ 1, 2
984
+ )
985
+
986
+ query = attn.to_q(hidden_states)
987
+ query = attn.q_norm(query)
988
+
989
+ if encoder_hidden_states is not None:
990
+ if attn.norm_cross:
991
+ encoder_hidden_states = attn.norm_encoder_hidden_states(
992
+ encoder_hidden_states
993
+ )
994
+ key = attn.to_k(encoder_hidden_states)
995
+ key = attn.k_norm(key)
996
+ else: # if no context provided do self-attention
997
+ encoder_hidden_states = hidden_states
998
+ key = attn.to_k(hidden_states)
999
+ key = attn.k_norm(key)
1000
+ if attn.use_rope:
1001
+ key = attn.apply_rotary_emb(key, freqs_cis)
1002
+ query = attn.apply_rotary_emb(query, freqs_cis)
1003
+
1004
+ value = attn.to_v(encoder_hidden_states)
1005
+
1006
+ inner_dim = key.shape[-1]
1007
+ head_dim = inner_dim // attn.heads
1008
+
1009
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
1010
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
1011
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
1012
+
1013
+ # the output of sdp = (batch, num_heads, seq_len, head_dim)
1014
+
1015
+ if attn.use_tpu_flash_attention: # use tpu attention offload 'flash attention'
1016
+ q_segment_indexes = None
1017
+ if (
1018
+ attention_mask is not None
1019
+ ): # if mask is required need to tune both segmenIds fields
1020
+ # attention_mask = torch.squeeze(attention_mask).to(torch.float32)
1021
+ attention_mask = attention_mask.to(torch.float32)
1022
+ q_segment_indexes = torch.ones(
1023
+ batch_size, query.shape[2], device=query.device, dtype=torch.float32
1024
+ )
1025
+ assert (
1026
+ attention_mask.shape[1] == key.shape[2]
1027
+ ), f"ERROR: KEY SHAPE must be same as attention mask [{key.shape[2]}, {attention_mask.shape[1]}]"
1028
+
1029
+ assert (
1030
+ query.shape[2] % 128 == 0
1031
+ ), f"ERROR: QUERY SHAPE must be divisible by 128 (TPU limitation) [{query.shape[2]}]"
1032
+ assert (
1033
+ key.shape[2] % 128 == 0
1034
+ ), f"ERROR: KEY SHAPE must be divisible by 128 (TPU limitation) [{key.shape[2]}]"
1035
+
1036
+ # run the TPU kernel implemented in jax with pallas
1037
+ hidden_states_a = flash_attention(
1038
+ q=query,
1039
+ k=key,
1040
+ v=value,
1041
+ q_segment_ids=q_segment_indexes,
1042
+ kv_segment_ids=attention_mask,
1043
+ sm_scale=attn.scale,
1044
+ )
1045
+ else:
1046
+ hidden_states_a = F.scaled_dot_product_attention(
1047
+ query,
1048
+ key,
1049
+ value,
1050
+ attn_mask=attention_mask,
1051
+ dropout_p=0.0,
1052
+ is_causal=False,
1053
+ )
1054
+
1055
+ hidden_states_a = hidden_states_a.transpose(1, 2).reshape(
1056
+ batch_size, -1, attn.heads * head_dim
1057
+ )
1058
+ hidden_states_a = hidden_states_a.to(query.dtype)
1059
+
1060
+ if (
1061
+ skip_layer_mask is not None
1062
+ and skip_layer_strategy == SkipLayerStrategy.Attention
1063
+ ):
1064
+ hidden_states = hidden_states_a * skip_layer_mask + hidden_states * (
1065
+ 1.0 - skip_layer_mask
1066
+ )
1067
+ else:
1068
+ hidden_states = hidden_states_a
1069
+
1070
+ # linear proj
1071
+ hidden_states = attn.to_out[0](hidden_states)
1072
+ # dropout
1073
+ hidden_states = attn.to_out[1](hidden_states)
1074
+
1075
+ if input_ndim == 4:
1076
+ hidden_states = hidden_states.transpose(-1, -2).reshape(
1077
+ batch_size, channel, height, width
1078
+ )
1079
+ if (
1080
+ skip_layer_mask is not None
1081
+ and skip_layer_strategy == SkipLayerStrategy.Residual
1082
+ ):
1083
+ skip_layer_mask = skip_layer_mask.reshape(batch_size, 1, 1, 1)
1084
+
1085
+ if attn.residual_connection:
1086
+ if (
1087
+ skip_layer_mask is not None
1088
+ and skip_layer_strategy == SkipLayerStrategy.Residual
1089
+ ):
1090
+ hidden_states = hidden_states + residual * skip_layer_mask
1091
+ else:
1092
+ hidden_states = hidden_states + residual
1093
+
1094
+ hidden_states = hidden_states / attn.rescale_output_factor
1095
+
1096
+ return hidden_states
1097
+
1098
+
1099
+ class AttnProcessor:
1100
+ r"""
1101
+ Default processor for performing attention-related computations.
1102
+ """
1103
+
1104
+ def __call__(
1105
+ self,
1106
+ attn: Attention,
1107
+ hidden_states: torch.FloatTensor,
1108
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
1109
+ attention_mask: Optional[torch.FloatTensor] = None,
1110
+ temb: Optional[torch.FloatTensor] = None,
1111
+ *args,
1112
+ **kwargs,
1113
+ ) -> torch.Tensor:
1114
+ if len(args) > 0 or kwargs.get("scale", None) is not None:
1115
+ deprecation_message = "The `scale` argument is deprecated and will be ignored. Please remove it, as passing it will raise an error in the future. `scale` should directly be passed while calling the underlying pipeline component i.e., via `cross_attention_kwargs`."
1116
+ deprecate("scale", "1.0.0", deprecation_message)
1117
+
1118
+ residual = hidden_states
1119
+
1120
+ if attn.spatial_norm is not None:
1121
+ hidden_states = attn.spatial_norm(hidden_states, temb)
1122
+
1123
+ input_ndim = hidden_states.ndim
1124
+
1125
+ if input_ndim == 4:
1126
+ batch_size, channel, height, width = hidden_states.shape
1127
+ hidden_states = hidden_states.view(
1128
+ batch_size, channel, height * width
1129
+ ).transpose(1, 2)
1130
+
1131
+ batch_size, sequence_length, _ = (
1132
+ hidden_states.shape
1133
+ if encoder_hidden_states is None
1134
+ else encoder_hidden_states.shape
1135
+ )
1136
+ attention_mask = attn.prepare_attention_mask(
1137
+ attention_mask, sequence_length, batch_size
1138
+ )
1139
+
1140
+ if attn.group_norm is not None:
1141
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(
1142
+ 1, 2
1143
+ )
1144
+
1145
+ query = attn.to_q(hidden_states)
1146
+
1147
+ if encoder_hidden_states is None:
1148
+ encoder_hidden_states = hidden_states
1149
+ elif attn.norm_cross:
1150
+ encoder_hidden_states = attn.norm_encoder_hidden_states(
1151
+ encoder_hidden_states
1152
+ )
1153
+
1154
+ key = attn.to_k(encoder_hidden_states)
1155
+ value = attn.to_v(encoder_hidden_states)
1156
+
1157
+ query = attn.head_to_batch_dim(query)
1158
+ key = attn.head_to_batch_dim(key)
1159
+ value = attn.head_to_batch_dim(value)
1160
+
1161
+ query = attn.q_norm(query)
1162
+ key = attn.k_norm(key)
1163
+
1164
+ attention_probs = attn.get_attention_scores(query, key, attention_mask)
1165
+ hidden_states = torch.bmm(attention_probs, value)
1166
+ hidden_states = attn.batch_to_head_dim(hidden_states)
1167
+
1168
+ # linear proj
1169
+ hidden_states = attn.to_out[0](hidden_states)
1170
+ # dropout
1171
+ hidden_states = attn.to_out[1](hidden_states)
1172
+
1173
+ if input_ndim == 4:
1174
+ hidden_states = hidden_states.transpose(-1, -2).reshape(
1175
+ batch_size, channel, height, width
1176
+ )
1177
+
1178
+ if attn.residual_connection:
1179
+ hidden_states = hidden_states + residual
1180
+
1181
+ hidden_states = hidden_states / attn.rescale_output_factor
1182
+
1183
+ return hidden_states
1184
+
1185
+
1186
+ class FeedForward(nn.Module):
1187
+ r"""
1188
+ A feed-forward layer.
1189
+
1190
+ Parameters:
1191
+ dim (`int`): The number of channels in the input.
1192
+ dim_out (`int`, *optional*): The number of channels in the output. If not given, defaults to `dim`.
1193
+ mult (`int`, *optional*, defaults to 4): The multiplier to use for the hidden dimension.
1194
+ dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
1195
+ activation_fn (`str`, *optional*, defaults to `"geglu"`): Activation function to be used in feed-forward.
1196
+ final_dropout (`bool` *optional*, defaults to False): Apply a final dropout.
1197
+ bias (`bool`, defaults to True): Whether to use a bias in the linear layer.
1198
+ """
1199
+
1200
+ def __init__(
1201
+ self,
1202
+ dim: int,
1203
+ dim_out: Optional[int] = None,
1204
+ mult: int = 4,
1205
+ dropout: float = 0.0,
1206
+ activation_fn: str = "geglu",
1207
+ final_dropout: bool = False,
1208
+ inner_dim=None,
1209
+ bias: bool = True,
1210
+ ):
1211
+ super().__init__()
1212
+ if inner_dim is None:
1213
+ inner_dim = int(dim * mult)
1214
+ dim_out = dim_out if dim_out is not None else dim
1215
+ linear_cls = nn.Linear
1216
+
1217
+ if activation_fn == "gelu":
1218
+ act_fn = GELU(dim, inner_dim, bias=bias)
1219
+ elif activation_fn == "gelu-approximate":
1220
+ act_fn = GELU(dim, inner_dim, approximate="tanh", bias=bias)
1221
+ elif activation_fn == "geglu":
1222
+ act_fn = GEGLU(dim, inner_dim, bias=bias)
1223
+ elif activation_fn == "geglu-approximate":
1224
+ act_fn = ApproximateGELU(dim, inner_dim, bias=bias)
1225
+ else:
1226
+ raise ValueError(f"Unsupported activation function: {activation_fn}")
1227
+
1228
+ self.net = nn.ModuleList([])
1229
+ # project in
1230
+ self.net.append(act_fn)
1231
+ # project dropout
1232
+ self.net.append(nn.Dropout(dropout))
1233
+ # project out
1234
+ self.net.append(linear_cls(inner_dim, dim_out, bias=bias))
1235
+ # FF as used in Vision Transformer, MLP-Mixer, etc. have a final dropout
1236
+ if final_dropout:
1237
+ self.net.append(nn.Dropout(dropout))
1238
+
1239
+ def forward(self, hidden_states: torch.Tensor, scale: float = 1.0) -> torch.Tensor:
1240
+ compatible_cls = (GEGLU, LoRACompatibleLinear)
1241
+ for module in self.net:
1242
+ if isinstance(module, compatible_cls):
1243
+ hidden_states = module(hidden_states, scale)
1244
+ else:
1245
+ hidden_states = module(hidden_states)
1246
+ return hidden_states
ltx_video/models/transformers/embeddings.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Adapted from: https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/embeddings.py
2
+ import math
3
+
4
+ import numpy as np
5
+ import torch
6
+ from einops import rearrange
7
+ from torch import nn
8
+
9
+
10
+ def get_timestep_embedding(
11
+ timesteps: torch.Tensor,
12
+ embedding_dim: int,
13
+ flip_sin_to_cos: bool = False,
14
+ downscale_freq_shift: float = 1,
15
+ scale: float = 1,
16
+ max_period: int = 10000,
17
+ ):
18
+ """
19
+ This matches the implementation in Denoising Diffusion Probabilistic Models: Create sinusoidal timestep embeddings.
20
+
21
+ :param timesteps: a 1-D Tensor of N indices, one per batch element.
22
+ These may be fractional.
23
+ :param embedding_dim: the dimension of the output. :param max_period: controls the minimum frequency of the
24
+ embeddings. :return: an [N x dim] Tensor of positional embeddings.
25
+ """
26
+ assert len(timesteps.shape) == 1, "Timesteps should be a 1d-array"
27
+
28
+ half_dim = embedding_dim // 2
29
+ exponent = -math.log(max_period) * torch.arange(
30
+ start=0, end=half_dim, dtype=torch.float32, device=timesteps.device
31
+ )
32
+ exponent = exponent / (half_dim - downscale_freq_shift)
33
+
34
+ emb = torch.exp(exponent)
35
+ emb = timesteps[:, None].float() * emb[None, :]
36
+
37
+ # scale embeddings
38
+ emb = scale * emb
39
+
40
+ # concat sine and cosine embeddings
41
+ emb = torch.cat([torch.sin(emb), torch.cos(emb)], dim=-1)
42
+
43
+ # flip sine and cosine embeddings
44
+ if flip_sin_to_cos:
45
+ emb = torch.cat([emb[:, half_dim:], emb[:, :half_dim]], dim=-1)
46
+
47
+ # zero pad
48
+ if embedding_dim % 2 == 1:
49
+ emb = torch.nn.functional.pad(emb, (0, 1, 0, 0))
50
+ return emb
51
+
52
+
53
+ def get_3d_sincos_pos_embed(embed_dim, grid, w, h, f):
54
+ """
55
+ grid_size: int of the grid height and width return: pos_embed: [grid_size*grid_size, embed_dim] or
56
+ [1+grid_size*grid_size, embed_dim] (w/ or w/o cls_token)
57
+ """
58
+ grid = rearrange(grid, "c (f h w) -> c f h w", h=h, w=w)
59
+ grid = rearrange(grid, "c f h w -> c h w f", h=h, w=w)
60
+ grid = grid.reshape([3, 1, w, h, f])
61
+ pos_embed = get_3d_sincos_pos_embed_from_grid(embed_dim, grid)
62
+ pos_embed = pos_embed.transpose(1, 0, 2, 3)
63
+ return rearrange(pos_embed, "h w f c -> (f h w) c")
64
+
65
+
66
+ def get_3d_sincos_pos_embed_from_grid(embed_dim, grid):
67
+ if embed_dim % 3 != 0:
68
+ raise ValueError("embed_dim must be divisible by 3")
69
+
70
+ # use half of dimensions to encode grid_h
71
+ emb_f = get_1d_sincos_pos_embed_from_grid(embed_dim // 3, grid[0]) # (H*W*T, D/3)
72
+ emb_h = get_1d_sincos_pos_embed_from_grid(embed_dim // 3, grid[1]) # (H*W*T, D/3)
73
+ emb_w = get_1d_sincos_pos_embed_from_grid(embed_dim // 3, grid[2]) # (H*W*T, D/3)
74
+
75
+ emb = np.concatenate([emb_h, emb_w, emb_f], axis=-1) # (H*W*T, D)
76
+ return emb
77
+
78
+
79
+ def get_1d_sincos_pos_embed_from_grid(embed_dim, pos):
80
+ """
81
+ embed_dim: output dimension for each position pos: a list of positions to be encoded: size (M,) out: (M, D)
82
+ """
83
+ if embed_dim % 2 != 0:
84
+ raise ValueError("embed_dim must be divisible by 2")
85
+
86
+ omega = np.arange(embed_dim // 2, dtype=np.float64)
87
+ omega /= embed_dim / 2.0
88
+ omega = 1.0 / 10000**omega # (D/2,)
89
+
90
+ pos_shape = pos.shape
91
+
92
+ pos = pos.reshape(-1)
93
+ out = np.einsum("m,d->md", pos, omega) # (M, D/2), outer product
94
+ out = out.reshape([*pos_shape, -1])[0]
95
+
96
+ emb_sin = np.sin(out) # (M, D/2)
97
+ emb_cos = np.cos(out) # (M, D/2)
98
+
99
+ emb = np.concatenate([emb_sin, emb_cos], axis=-1) # (M, D)
100
+ return emb
101
+
102
+
103
+ class SinusoidalPositionalEmbedding(nn.Module):
104
+ """Apply positional information to a sequence of embeddings.
105
+
106
+ Takes in a sequence of embeddings with shape (batch_size, seq_length, embed_dim) and adds positional embeddings to
107
+ them
108
+
109
+ Args:
110
+ embed_dim: (int): Dimension of the positional embedding.
111
+ max_seq_length: Maximum sequence length to apply positional embeddings
112
+
113
+ """
114
+
115
+ def __init__(self, embed_dim: int, max_seq_length: int = 32):
116
+ super().__init__()
117
+ position = torch.arange(max_seq_length).unsqueeze(1)
118
+ div_term = torch.exp(
119
+ torch.arange(0, embed_dim, 2) * (-math.log(10000.0) / embed_dim)
120
+ )
121
+ pe = torch.zeros(1, max_seq_length, embed_dim)
122
+ pe[0, :, 0::2] = torch.sin(position * div_term)
123
+ pe[0, :, 1::2] = torch.cos(position * div_term)
124
+ self.register_buffer("pe", pe)
125
+
126
+ def forward(self, x):
127
+ _, seq_length, _ = x.shape
128
+ x = x + self.pe[:, :seq_length]
129
+ return x
ltx_video/models/transformers/symmetric_patchifier.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from abc import ABC, abstractmethod
2
+ from typing import Tuple
3
+
4
+ import torch
5
+ from diffusers.configuration_utils import ConfigMixin
6
+ from einops import rearrange
7
+ from torch import Tensor
8
+
9
+ from ltx_video.utils.torch_utils import append_dims
10
+
11
+
12
+ class Patchifier(ConfigMixin, ABC):
13
+ def __init__(self, patch_size: int):
14
+ super().__init__()
15
+ self._patch_size = (1, patch_size, patch_size)
16
+
17
+ @abstractmethod
18
+ def patchify(
19
+ self, latents: Tensor, frame_rates: Tensor, scale_grid: bool
20
+ ) -> Tuple[Tensor, Tensor]:
21
+ pass
22
+
23
+ @abstractmethod
24
+ def unpatchify(
25
+ self,
26
+ latents: Tensor,
27
+ output_height: int,
28
+ output_width: int,
29
+ output_num_frames: int,
30
+ out_channels: int,
31
+ ) -> Tuple[Tensor, Tensor]:
32
+ pass
33
+
34
+ @property
35
+ def patch_size(self):
36
+ return self._patch_size
37
+
38
+ def get_grid(
39
+ self, orig_num_frames, orig_height, orig_width, batch_size, scale_grid, device
40
+ ):
41
+ f = orig_num_frames // self._patch_size[0]
42
+ h = orig_height // self._patch_size[1]
43
+ w = orig_width // self._patch_size[2]
44
+ grid_h = torch.arange(h, dtype=torch.float32, device=device)
45
+ grid_w = torch.arange(w, dtype=torch.float32, device=device)
46
+ grid_f = torch.arange(f, dtype=torch.float32, device=device)
47
+ grid = torch.meshgrid(grid_f, grid_h, grid_w)
48
+ grid = torch.stack(grid, dim=0)
49
+ grid = grid.unsqueeze(0).repeat(batch_size, 1, 1, 1, 1)
50
+
51
+ if scale_grid is not None:
52
+ for i in range(3):
53
+ if isinstance(scale_grid[i], Tensor):
54
+ scale = append_dims(scale_grid[i], grid.ndim - 1)
55
+ else:
56
+ scale = scale_grid[i]
57
+ grid[:, i, ...] = grid[:, i, ...] * scale * self._patch_size[i]
58
+
59
+ grid = rearrange(grid, "b c f h w -> b c (f h w)", b=batch_size)
60
+ return grid
61
+
62
+
63
+ class SymmetricPatchifier(Patchifier):
64
+ def patchify(
65
+ self,
66
+ latents: Tensor,
67
+ ) -> Tuple[Tensor, Tensor]:
68
+ latents = rearrange(
69
+ latents,
70
+ "b c (f p1) (h p2) (w p3) -> b (f h w) (c p1 p2 p3)",
71
+ p1=self._patch_size[0],
72
+ p2=self._patch_size[1],
73
+ p3=self._patch_size[2],
74
+ )
75
+ return latents
76
+
77
+ def unpatchify(
78
+ self,
79
+ latents: Tensor,
80
+ output_height: int,
81
+ output_width: int,
82
+ output_num_frames: int,
83
+ out_channels: int,
84
+ ) -> Tuple[Tensor, Tensor]:
85
+ output_height = output_height // self._patch_size[1]
86
+ output_width = output_width // self._patch_size[2]
87
+ latents = rearrange(
88
+ latents,
89
+ "b (f h w) (c p q) -> b c f (h p) (w q) ",
90
+ f=output_num_frames,
91
+ h=output_height,
92
+ w=output_width,
93
+ p=self._patch_size[1],
94
+ q=self._patch_size[2],
95
+ )
96
+ return latents
ltx_video/models/transformers/transformer3d.py ADDED
@@ -0,0 +1,605 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Adapted from: https://github.com/huggingface/diffusers/blob/v0.26.3/src/diffusers/models/transformers/transformer_2d.py
2
+ import math
3
+ from dataclasses import dataclass
4
+ from typing import Any, Dict, List, Optional, Literal, Union
5
+ import os
6
+ import json
7
+ import glob
8
+ from pathlib import Path
9
+
10
+ import torch
11
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
12
+ from diffusers.models.embeddings import PixArtAlphaTextProjection
13
+ from diffusers.models.modeling_utils import ModelMixin
14
+ from diffusers.models.normalization import AdaLayerNormSingle
15
+ from diffusers.utils import BaseOutput, is_torch_version
16
+ from diffusers.utils import logging
17
+ from torch import nn
18
+ from safetensors import safe_open
19
+
20
+
21
+ from ltx_video.models.transformers.attention import BasicTransformerBlock
22
+ from ltx_video.models.transformers.embeddings import get_3d_sincos_pos_embed
23
+ from ltx_video.utils.skip_layer_strategy import SkipLayerStrategy
24
+
25
+ from ltx_video.utils.diffusers_config_mapping import (
26
+ diffusers_and_ours_config_mapping,
27
+ make_hashable_key,
28
+ TRANSFORMER_KEYS_RENAME_DICT,
29
+ )
30
+
31
+
32
+ logger = logging.get_logger(__name__)
33
+
34
+
35
+ @dataclass
36
+ class Transformer3DModelOutput(BaseOutput):
37
+ """
38
+ The output of [`Transformer2DModel`].
39
+
40
+ Args:
41
+ sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` or `(batch size, num_vector_embeds - 1, num_latent_pixels)` if [`Transformer2DModel`] is discrete):
42
+ The hidden states output conditioned on the `encoder_hidden_states` input. If discrete, returns probability
43
+ distributions for the unnoised latent pixels.
44
+ """
45
+
46
+ sample: torch.FloatTensor
47
+
48
+
49
+ class Transformer3DModel(ModelMixin, ConfigMixin):
50
+ _supports_gradient_checkpointing = True
51
+
52
+ @register_to_config
53
+ def __init__(
54
+ self,
55
+ num_attention_heads: int = 16,
56
+ attention_head_dim: int = 88,
57
+ in_channels: Optional[int] = None,
58
+ out_channels: Optional[int] = None,
59
+ num_layers: int = 1,
60
+ dropout: float = 0.0,
61
+ norm_num_groups: int = 32,
62
+ cross_attention_dim: Optional[int] = None,
63
+ attention_bias: bool = False,
64
+ num_vector_embeds: Optional[int] = None,
65
+ activation_fn: str = "geglu",
66
+ num_embeds_ada_norm: Optional[int] = None,
67
+ use_linear_projection: bool = False,
68
+ only_cross_attention: bool = False,
69
+ double_self_attention: bool = False,
70
+ upcast_attention: bool = False,
71
+ adaptive_norm: str = "single_scale_shift", # 'single_scale_shift' or 'single_scale'
72
+ standardization_norm: str = "layer_norm", # 'layer_norm' or 'rms_norm'
73
+ norm_elementwise_affine: bool = True,
74
+ norm_eps: float = 1e-5,
75
+ attention_type: str = "default",
76
+ caption_channels: int = None,
77
+ project_to_2d_pos: bool = False,
78
+ use_tpu_flash_attention: bool = False, # if True uses the TPU attention offload ('flash attention')
79
+ qk_norm: Optional[str] = None,
80
+ positional_embedding_type: str = "absolute",
81
+ positional_embedding_theta: Optional[float] = None,
82
+ positional_embedding_max_pos: Optional[List[int]] = None,
83
+ timestep_scale_multiplier: Optional[float] = None,
84
+ ):
85
+ super().__init__()
86
+ self.use_tpu_flash_attention = (
87
+ use_tpu_flash_attention # FIXME: push config down to the attention modules
88
+ )
89
+ self.use_linear_projection = use_linear_projection
90
+ self.num_attention_heads = num_attention_heads
91
+ self.attention_head_dim = attention_head_dim
92
+ inner_dim = num_attention_heads * attention_head_dim
93
+ self.inner_dim = inner_dim
94
+
95
+ self.project_to_2d_pos = project_to_2d_pos
96
+
97
+ self.patchify_proj = nn.Linear(in_channels, inner_dim, bias=True)
98
+
99
+ self.positional_embedding_type = positional_embedding_type
100
+ self.positional_embedding_theta = positional_embedding_theta
101
+ self.positional_embedding_max_pos = positional_embedding_max_pos
102
+ self.use_rope = self.positional_embedding_type == "rope"
103
+ self.timestep_scale_multiplier = timestep_scale_multiplier
104
+
105
+ if self.positional_embedding_type == "absolute":
106
+ embed_dim_3d = (
107
+ math.ceil((inner_dim / 2) * 3) if project_to_2d_pos else inner_dim
108
+ )
109
+ if self.project_to_2d_pos:
110
+ self.to_2d_proj = torch.nn.Linear(embed_dim_3d, inner_dim, bias=False)
111
+ self._init_to_2d_proj_weights(self.to_2d_proj)
112
+ elif self.positional_embedding_type == "rope":
113
+ if positional_embedding_theta is None:
114
+ raise ValueError(
115
+ "If `positional_embedding_type` type is rope, `positional_embedding_theta` must also be defined"
116
+ )
117
+ if positional_embedding_max_pos is None:
118
+ raise ValueError(
119
+ "If `positional_embedding_type` type is rope, `positional_embedding_max_pos` must also be defined"
120
+ )
121
+
122
+ # 3. Define transformers blocks
123
+ self.transformer_blocks = nn.ModuleList(
124
+ [
125
+ BasicTransformerBlock(
126
+ inner_dim,
127
+ num_attention_heads,
128
+ attention_head_dim,
129
+ dropout=dropout,
130
+ cross_attention_dim=cross_attention_dim,
131
+ activation_fn=activation_fn,
132
+ num_embeds_ada_norm=num_embeds_ada_norm,
133
+ attention_bias=attention_bias,
134
+ only_cross_attention=only_cross_attention,
135
+ double_self_attention=double_self_attention,
136
+ upcast_attention=upcast_attention,
137
+ adaptive_norm=adaptive_norm,
138
+ standardization_norm=standardization_norm,
139
+ norm_elementwise_affine=norm_elementwise_affine,
140
+ norm_eps=norm_eps,
141
+ attention_type=attention_type,
142
+ use_tpu_flash_attention=use_tpu_flash_attention,
143
+ qk_norm=qk_norm,
144
+ use_rope=self.use_rope,
145
+ )
146
+ for d in range(num_layers)
147
+ ]
148
+ )
149
+
150
+ # 4. Define output layers
151
+ self.out_channels = in_channels if out_channels is None else out_channels
152
+ self.norm_out = nn.LayerNorm(inner_dim, elementwise_affine=False, eps=1e-6)
153
+ self.scale_shift_table = nn.Parameter(
154
+ torch.randn(2, inner_dim) / inner_dim**0.5
155
+ )
156
+ self.proj_out = nn.Linear(inner_dim, self.out_channels)
157
+
158
+ self.adaln_single = AdaLayerNormSingle(
159
+ inner_dim, use_additional_conditions=False
160
+ )
161
+ if adaptive_norm == "single_scale":
162
+ self.adaln_single.linear = nn.Linear(inner_dim, 4 * inner_dim, bias=True)
163
+
164
+ self.caption_projection = None
165
+ if caption_channels is not None:
166
+ self.caption_projection = PixArtAlphaTextProjection(
167
+ in_features=caption_channels, hidden_size=inner_dim
168
+ )
169
+
170
+ self.gradient_checkpointing = False
171
+
172
+ def set_use_tpu_flash_attention(self):
173
+ r"""
174
+ Function sets the flag in this object and propagates down the children. The flag will enforce the usage of TPU
175
+ attention kernel.
176
+ """
177
+ logger.info("ENABLE TPU FLASH ATTENTION -> TRUE")
178
+ self.use_tpu_flash_attention = True
179
+ # push config down to the attention modules
180
+ for block in self.transformer_blocks:
181
+ block.set_use_tpu_flash_attention()
182
+
183
+ def create_skip_layer_mask(
184
+ self,
185
+ skip_block_list: List[int],
186
+ batch_size: int,
187
+ num_conds: int,
188
+ ptb_index: int,
189
+ ):
190
+ num_layers = len(self.transformer_blocks)
191
+ mask = torch.ones(
192
+ (num_layers, batch_size * num_conds), device=self.device, dtype=self.dtype
193
+ )
194
+ for block_idx in skip_block_list:
195
+ mask[block_idx, ptb_index::num_conds] = 0
196
+ return mask
197
+
198
+ def initialize(self, embedding_std: float, mode: Literal["ltx_video", "legacy"]):
199
+ def _basic_init(module):
200
+ if isinstance(module, nn.Linear):
201
+ torch.nn.init.xavier_uniform_(module.weight)
202
+ if module.bias is not None:
203
+ nn.init.constant_(module.bias, 0)
204
+
205
+ self.apply(_basic_init)
206
+
207
+ # Initialize timestep embedding MLP:
208
+ nn.init.normal_(
209
+ self.adaln_single.emb.timestep_embedder.linear_1.weight, std=embedding_std
210
+ )
211
+ nn.init.normal_(
212
+ self.adaln_single.emb.timestep_embedder.linear_2.weight, std=embedding_std
213
+ )
214
+ nn.init.normal_(self.adaln_single.linear.weight, std=embedding_std)
215
+
216
+ if hasattr(self.adaln_single.emb, "resolution_embedder"):
217
+ nn.init.normal_(
218
+ self.adaln_single.emb.resolution_embedder.linear_1.weight,
219
+ std=embedding_std,
220
+ )
221
+ nn.init.normal_(
222
+ self.adaln_single.emb.resolution_embedder.linear_2.weight,
223
+ std=embedding_std,
224
+ )
225
+ if hasattr(self.adaln_single.emb, "aspect_ratio_embedder"):
226
+ nn.init.normal_(
227
+ self.adaln_single.emb.aspect_ratio_embedder.linear_1.weight,
228
+ std=embedding_std,
229
+ )
230
+ nn.init.normal_(
231
+ self.adaln_single.emb.aspect_ratio_embedder.linear_2.weight,
232
+ std=embedding_std,
233
+ )
234
+
235
+ # Initialize caption embedding MLP:
236
+ nn.init.normal_(self.caption_projection.linear_1.weight, std=embedding_std)
237
+ nn.init.normal_(self.caption_projection.linear_1.weight, std=embedding_std)
238
+
239
+ for block in self.transformer_blocks:
240
+ if mode.lower() == "ltx_video":
241
+ nn.init.constant_(block.attn1.to_out[0].weight, 0)
242
+ nn.init.constant_(block.attn1.to_out[0].bias, 0)
243
+
244
+ nn.init.constant_(block.attn2.to_out[0].weight, 0)
245
+ nn.init.constant_(block.attn2.to_out[0].bias, 0)
246
+
247
+ if mode.lower() == "ltx_video":
248
+ nn.init.constant_(block.ff.net[2].weight, 0)
249
+ nn.init.constant_(block.ff.net[2].bias, 0)
250
+
251
+ # Zero-out output layers:
252
+ nn.init.constant_(self.proj_out.weight, 0)
253
+ nn.init.constant_(self.proj_out.bias, 0)
254
+
255
+ def _set_gradient_checkpointing(self, module, value=False):
256
+ if hasattr(module, "gradient_checkpointing"):
257
+ module.gradient_checkpointing = value
258
+
259
+ @staticmethod
260
+ def _init_to_2d_proj_weights(linear_layer):
261
+ input_features = linear_layer.weight.data.size(1)
262
+ output_features = linear_layer.weight.data.size(0)
263
+
264
+ # Start with a zero matrix
265
+ identity_like = torch.zeros((output_features, input_features))
266
+
267
+ # Fill the diagonal with 1's as much as possible
268
+ min_features = min(output_features, input_features)
269
+ identity_like[:min_features, :min_features] = torch.eye(min_features)
270
+ linear_layer.weight.data = identity_like.to(linear_layer.weight.data.device)
271
+
272
+ def get_fractional_positions(self, indices_grid):
273
+ fractional_positions = torch.stack(
274
+ [
275
+ indices_grid[:, i] / self.positional_embedding_max_pos[i]
276
+ for i in range(3)
277
+ ],
278
+ dim=-1,
279
+ )
280
+ return fractional_positions
281
+
282
+ def precompute_freqs_cis(self, indices_grid, spacing="exp"):
283
+ dtype = torch.float32 # We need full precision in the freqs_cis computation.
284
+ dim = self.inner_dim
285
+ theta = self.positional_embedding_theta
286
+
287
+ fractional_positions = self.get_fractional_positions(indices_grid)
288
+
289
+ start = 1
290
+ end = theta
291
+ device = fractional_positions.device
292
+ if spacing == "exp":
293
+ indices = theta ** (
294
+ torch.linspace(
295
+ math.log(start, theta),
296
+ math.log(end, theta),
297
+ dim // 6,
298
+ device=device,
299
+ dtype=dtype,
300
+ )
301
+ )
302
+ indices = indices.to(dtype=dtype)
303
+ elif spacing == "exp_2":
304
+ indices = 1.0 / theta ** (torch.arange(0, dim, 6, device=device) / dim)
305
+ indices = indices.to(dtype=dtype)
306
+ elif spacing == "linear":
307
+ indices = torch.linspace(start, end, dim // 6, device=device, dtype=dtype)
308
+ elif spacing == "sqrt":
309
+ indices = torch.linspace(
310
+ start**2, end**2, dim // 6, device=device, dtype=dtype
311
+ ).sqrt()
312
+
313
+ indices = indices * math.pi / 2
314
+
315
+ if spacing == "exp_2":
316
+ freqs = (
317
+ (indices * fractional_positions.unsqueeze(-1))
318
+ .transpose(-1, -2)
319
+ .flatten(2)
320
+ )
321
+ else:
322
+ freqs = (
323
+ (indices * (fractional_positions.unsqueeze(-1) * 2 - 1))
324
+ .transpose(-1, -2)
325
+ .flatten(2)
326
+ )
327
+
328
+ cos_freq = freqs.cos().repeat_interleave(2, dim=-1)
329
+ sin_freq = freqs.sin().repeat_interleave(2, dim=-1)
330
+ if dim % 6 != 0:
331
+ cos_padding = torch.ones_like(cos_freq[:, :, : dim % 6])
332
+ sin_padding = torch.zeros_like(cos_freq[:, :, : dim % 6])
333
+ cos_freq = torch.cat([cos_padding, cos_freq], dim=-1)
334
+ sin_freq = torch.cat([sin_padding, sin_freq], dim=-1)
335
+ return cos_freq.to(self.dtype), sin_freq.to(self.dtype)
336
+
337
+ def load_state_dict(
338
+ self,
339
+ state_dict: Dict,
340
+ *args,
341
+ **kwargs,
342
+ ):
343
+ if any([key.startswith("model.diffusion_model.") for key in state_dict.keys()]):
344
+ state_dict = {
345
+ key.replace("model.diffusion_model.", ""): value
346
+ for key, value in state_dict.items()
347
+ if key.startswith("model.diffusion_model.")
348
+ }
349
+ super().load_state_dict(state_dict, **kwargs)
350
+
351
+ @classmethod
352
+ def from_pretrained(
353
+ cls,
354
+ pretrained_model_path: Optional[Union[str, os.PathLike]],
355
+ *args,
356
+ **kwargs,
357
+ ):
358
+ pretrained_model_path = Path(pretrained_model_path)
359
+ if pretrained_model_path.is_dir():
360
+ config_path = pretrained_model_path / "transformer" / "config.json"
361
+ with open(config_path, "r") as f:
362
+ config = make_hashable_key(json.load(f))
363
+
364
+ assert config in diffusers_and_ours_config_mapping, (
365
+ "Provided diffusers checkpoint config for transformer is not suppported. "
366
+ "We only support diffusers configs found in Lightricks/LTX-Video."
367
+ )
368
+
369
+ config = diffusers_and_ours_config_mapping[config]
370
+ state_dict = {}
371
+ ckpt_paths = (
372
+ pretrained_model_path
373
+ / "transformer"
374
+ / "diffusion_pytorch_model*.safetensors"
375
+ )
376
+ dict_list = glob.glob(str(ckpt_paths))
377
+ for dict_path in dict_list:
378
+ part_dict = {}
379
+ with safe_open(dict_path, framework="pt", device="cpu") as f:
380
+ for k in f.keys():
381
+ part_dict[k] = f.get_tensor(k)
382
+ state_dict.update(part_dict)
383
+
384
+ for key in list(state_dict.keys()):
385
+ new_key = key
386
+ for replace_key, rename_key in TRANSFORMER_KEYS_RENAME_DICT.items():
387
+ new_key = new_key.replace(replace_key, rename_key)
388
+ state_dict[new_key] = state_dict.pop(key)
389
+
390
+ transformer = cls.from_config(config)
391
+ transformer.load_state_dict(state_dict, strict=True)
392
+ elif pretrained_model_path.is_file() and str(pretrained_model_path).endswith(
393
+ ".safetensors"
394
+ ):
395
+ comfy_single_file_state_dict = {}
396
+ with safe_open(pretrained_model_path, framework="pt", device="cpu") as f:
397
+ metadata = f.metadata()
398
+ for k in f.keys():
399
+ comfy_single_file_state_dict[k] = f.get_tensor(k)
400
+ configs = json.loads(metadata["config"])
401
+ transformer_config = configs["transformer"]
402
+ transformer = Transformer3DModel.from_config(transformer_config)
403
+ transformer.load_state_dict(comfy_single_file_state_dict)
404
+ return transformer
405
+
406
+ def forward(
407
+ self,
408
+ hidden_states: torch.Tensor,
409
+ indices_grid: torch.Tensor,
410
+ encoder_hidden_states: Optional[torch.Tensor] = None,
411
+ timestep: Optional[torch.LongTensor] = None,
412
+ class_labels: Optional[torch.LongTensor] = None,
413
+ cross_attention_kwargs: Dict[str, Any] = None,
414
+ attention_mask: Optional[torch.Tensor] = None,
415
+ encoder_attention_mask: Optional[torch.Tensor] = None,
416
+ skip_layer_mask: Optional[torch.Tensor] = None,
417
+ skip_layer_strategy: Optional[SkipLayerStrategy] = None,
418
+ return_dict: bool = True,
419
+ ):
420
+ """
421
+ The [`Transformer2DModel`] forward method.
422
+
423
+ Args:
424
+ hidden_states (`torch.LongTensor` of shape `(batch size, num latent pixels)` if discrete, `torch.FloatTensor` of shape `(batch size, channel, height, width)` if continuous):
425
+ Input `hidden_states`.
426
+ indices_grid (`torch.LongTensor` of shape `(batch size, 3, num latent pixels)`):
427
+ encoder_hidden_states ( `torch.FloatTensor` of shape `(batch size, sequence len, embed dims)`, *optional*):
428
+ Conditional embeddings for cross attention layer. If not given, cross-attention defaults to
429
+ self-attention.
430
+ timestep ( `torch.LongTensor`, *optional*):
431
+ Used to indicate denoising step. Optional timestep to be applied as an embedding in `AdaLayerNorm`.
432
+ class_labels ( `torch.LongTensor` of shape `(batch size, num classes)`, *optional*):
433
+ Used to indicate class labels conditioning. Optional class labels to be applied as an embedding in
434
+ `AdaLayerZeroNorm`.
435
+ cross_attention_kwargs ( `Dict[str, Any]`, *optional*):
436
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
437
+ `self.processor` in
438
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
439
+ attention_mask ( `torch.Tensor`, *optional*):
440
+ An attention mask of shape `(batch, key_tokens)` is applied to `encoder_hidden_states`. If `1` the mask
441
+ is kept, otherwise if `0` it is discarded. Mask will be converted into a bias, which adds large
442
+ negative values to the attention scores corresponding to "discard" tokens.
443
+ encoder_attention_mask ( `torch.Tensor`, *optional*):
444
+ Cross-attention mask applied to `encoder_hidden_states`. Two formats supported:
445
+
446
+ * Mask `(batch, sequence_length)` True = keep, False = discard.
447
+ * Bias `(batch, 1, sequence_length)` 0 = keep, -10000 = discard.
448
+
449
+ If `ndim == 2`: will be interpreted as a mask, then converted into a bias consistent with the format
450
+ above. This bias will be added to the cross-attention scores.
451
+ skip_layer_mask ( `torch.Tensor`, *optional*):
452
+ A mask of shape `(num_layers, batch)` that indicates which layers to skip. `0` at position
453
+ `layer, batch_idx` indicates that the layer should be skipped for the corresponding batch index.
454
+ skip_layer_strategy ( `SkipLayerStrategy`, *optional*, defaults to `None`):
455
+ Controls which layers are skipped when calculating a perturbed latent for spatiotemporal guidance.
456
+ return_dict (`bool`, *optional*, defaults to `True`):
457
+ Whether or not to return a [`~models.unets.unet_2d_condition.UNet2DConditionOutput`] instead of a plain
458
+ tuple.
459
+
460
+ Returns:
461
+ If `return_dict` is True, an [`~models.transformer_2d.Transformer2DModelOutput`] is returned, otherwise a
462
+ `tuple` where the first element is the sample tensor.
463
+ """
464
+ # for tpu attention offload 2d token masks are used. No need to transform.
465
+ if not self.use_tpu_flash_attention:
466
+ # ensure attention_mask is a bias, and give it a singleton query_tokens dimension.
467
+ # we may have done this conversion already, e.g. if we came here via UNet2DConditionModel#forward.
468
+ # we can tell by counting dims; if ndim == 2: it's a mask rather than a bias.
469
+ # expects mask of shape:
470
+ # [batch, key_tokens]
471
+ # adds singleton query_tokens dimension:
472
+ # [batch, 1, key_tokens]
473
+ # this helps to broadcast it as a bias over attention scores, which will be in one of the following shapes:
474
+ # [batch, heads, query_tokens, key_tokens] (e.g. torch sdp attn)
475
+ # [batch * heads, query_tokens, key_tokens] (e.g. xformers or classic attn)
476
+ if attention_mask is not None and attention_mask.ndim == 2:
477
+ # assume that mask is expressed as:
478
+ # (1 = keep, 0 = discard)
479
+ # convert mask into a bias that can be added to attention scores:
480
+ # (keep = +0, discard = -10000.0)
481
+ attention_mask = (1 - attention_mask.to(hidden_states.dtype)) * -10000.0
482
+ attention_mask = attention_mask.unsqueeze(1)
483
+
484
+ # convert encoder_attention_mask to a bias the same way we do for attention_mask
485
+ if encoder_attention_mask is not None and encoder_attention_mask.ndim == 2:
486
+ encoder_attention_mask = (
487
+ 1 - encoder_attention_mask.to(hidden_states.dtype)
488
+ ) * -10000.0
489
+ encoder_attention_mask = encoder_attention_mask.unsqueeze(1)
490
+
491
+ # 1. Input
492
+ hidden_states = self.patchify_proj(hidden_states)
493
+
494
+ if self.timestep_scale_multiplier:
495
+ timestep = self.timestep_scale_multiplier * timestep
496
+
497
+ if self.positional_embedding_type == "absolute":
498
+ pos_embed_3d = self.get_absolute_pos_embed(indices_grid).to(
499
+ hidden_states.device
500
+ )
501
+ if self.project_to_2d_pos:
502
+ pos_embed = self.to_2d_proj(pos_embed_3d)
503
+ hidden_states = (hidden_states + pos_embed).to(hidden_states.dtype)
504
+ freqs_cis = None
505
+ elif self.positional_embedding_type == "rope":
506
+ freqs_cis = self.precompute_freqs_cis(indices_grid)
507
+
508
+ batch_size = hidden_states.shape[0]
509
+ timestep, embedded_timestep = self.adaln_single(
510
+ timestep.flatten(),
511
+ {"resolution": None, "aspect_ratio": None},
512
+ batch_size=batch_size,
513
+ hidden_dtype=hidden_states.dtype,
514
+ )
515
+ # Second dimension is 1 or number of tokens (if timestep_per_token)
516
+ timestep = timestep.view(batch_size, -1, timestep.shape[-1])
517
+ embedded_timestep = embedded_timestep.view(
518
+ batch_size, -1, embedded_timestep.shape[-1]
519
+ )
520
+
521
+ if skip_layer_mask is None:
522
+ skip_layer_mask = torch.ones(
523
+ len(self.transformer_blocks), batch_size, device=hidden_states.device
524
+ )
525
+
526
+ # 2. Blocks
527
+ if self.caption_projection is not None:
528
+ batch_size = hidden_states.shape[0]
529
+ encoder_hidden_states = self.caption_projection(encoder_hidden_states)
530
+ encoder_hidden_states = encoder_hidden_states.view(
531
+ batch_size, -1, hidden_states.shape[-1]
532
+ )
533
+
534
+ for block_idx, block in enumerate(self.transformer_blocks):
535
+ if self.training and self.gradient_checkpointing:
536
+
537
+ def create_custom_forward(module, return_dict=None):
538
+ def custom_forward(*inputs):
539
+ if return_dict is not None:
540
+ return module(*inputs, return_dict=return_dict)
541
+ else:
542
+ return module(*inputs)
543
+
544
+ return custom_forward
545
+
546
+ ckpt_kwargs: Dict[str, Any] = (
547
+ {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
548
+ )
549
+ hidden_states = torch.utils.checkpoint.checkpoint(
550
+ create_custom_forward(block),
551
+ hidden_states,
552
+ freqs_cis,
553
+ attention_mask,
554
+ encoder_hidden_states,
555
+ encoder_attention_mask,
556
+ timestep,
557
+ cross_attention_kwargs,
558
+ class_labels,
559
+ skip_layer_mask[block_idx],
560
+ skip_layer_strategy,
561
+ **ckpt_kwargs,
562
+ )
563
+ else:
564
+ hidden_states = block(
565
+ hidden_states,
566
+ freqs_cis=freqs_cis,
567
+ attention_mask=attention_mask,
568
+ encoder_hidden_states=encoder_hidden_states,
569
+ encoder_attention_mask=encoder_attention_mask,
570
+ timestep=timestep,
571
+ cross_attention_kwargs=cross_attention_kwargs,
572
+ class_labels=class_labels,
573
+ skip_layer_mask=skip_layer_mask[block_idx],
574
+ skip_layer_strategy=skip_layer_strategy,
575
+ )
576
+
577
+ # 3. Output
578
+ scale_shift_values = (
579
+ self.scale_shift_table[None, None] + embedded_timestep[:, :, None]
580
+ )
581
+ shift, scale = scale_shift_values[:, :, 0], scale_shift_values[:, :, 1]
582
+ hidden_states = self.norm_out(hidden_states)
583
+ # Modulation
584
+ hidden_states = hidden_states * (1 + scale) + shift
585
+ hidden_states = self.proj_out(hidden_states)
586
+ if not return_dict:
587
+ return (hidden_states,)
588
+
589
+ return Transformer3DModelOutput(sample=hidden_states)
590
+
591
+ def get_absolute_pos_embed(self, grid):
592
+ grid_np = grid[0].cpu().numpy()
593
+ embed_dim_3d = (
594
+ math.ceil((self.inner_dim / 2) * 3)
595
+ if self.project_to_2d_pos
596
+ else self.inner_dim
597
+ )
598
+ pos_embed = get_3d_sincos_pos_embed( # (f h w)
599
+ embed_dim_3d,
600
+ grid_np,
601
+ h=int(max(grid_np[1]) + 1),
602
+ w=int(max(grid_np[2]) + 1),
603
+ f=int(max(grid_np[0] + 1)),
604
+ )
605
+ return torch.from_numpy(pos_embed).float().unsqueeze(0)
ltx_video/pipelines/__init__.py ADDED
File without changes
ltx_video/pipelines/pipeline_ltx_video.py ADDED
@@ -0,0 +1,1274 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Adapted from: https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/pixart_alpha/pipeline_pixart_alpha.py
2
+ import html
3
+ import inspect
4
+ import math
5
+ import re
6
+ import urllib.parse as ul
7
+ from typing import Callable, Dict, List, Optional, Tuple, Union
8
+
9
+
10
+ import torch
11
+ import torch.nn.functional as F
12
+ from contextlib import nullcontext
13
+ from diffusers.image_processor import VaeImageProcessor
14
+ from diffusers.models import AutoencoderKL
15
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline, ImagePipelineOutput
16
+ from diffusers.schedulers import DPMSolverMultistepScheduler
17
+ from diffusers.utils import (
18
+ BACKENDS_MAPPING,
19
+ deprecate,
20
+ is_bs4_available,
21
+ is_ftfy_available,
22
+ logging,
23
+ )
24
+ from diffusers.utils.torch_utils import randn_tensor
25
+ from einops import rearrange
26
+ from transformers import T5EncoderModel, T5Tokenizer
27
+
28
+ from ltx_video.models.transformers.transformer3d import Transformer3DModel
29
+ from ltx_video.models.transformers.symmetric_patchifier import Patchifier
30
+ from ltx_video.models.autoencoders.vae_encode import (
31
+ get_vae_size_scale_factor,
32
+ vae_decode,
33
+ vae_encode,
34
+ )
35
+ from ltx_video.models.autoencoders.causal_video_autoencoder import (
36
+ CausalVideoAutoencoder,
37
+ )
38
+ from ltx_video.schedulers.rf import TimestepShifter
39
+ from ltx_video.utils.conditioning_method import ConditioningMethod
40
+ from ltx_video.utils.skip_layer_strategy import SkipLayerStrategy
41
+
42
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
43
+
44
+ if is_bs4_available():
45
+ from bs4 import BeautifulSoup
46
+
47
+ if is_ftfy_available():
48
+ import ftfy
49
+
50
+ ASPECT_RATIO_1024_BIN = {
51
+ "0.25": [512.0, 2048.0],
52
+ "0.28": [512.0, 1856.0],
53
+ "0.32": [576.0, 1792.0],
54
+ "0.33": [576.0, 1728.0],
55
+ "0.35": [576.0, 1664.0],
56
+ "0.4": [640.0, 1600.0],
57
+ "0.42": [640.0, 1536.0],
58
+ "0.48": [704.0, 1472.0],
59
+ "0.5": [704.0, 1408.0],
60
+ "0.52": [704.0, 1344.0],
61
+ "0.57": [768.0, 1344.0],
62
+ "0.6": [768.0, 1280.0],
63
+ "0.68": [832.0, 1216.0],
64
+ "0.72": [832.0, 1152.0],
65
+ "0.78": [896.0, 1152.0],
66
+ "0.82": [896.0, 1088.0],
67
+ "0.88": [960.0, 1088.0],
68
+ "0.94": [960.0, 1024.0],
69
+ "1.0": [1024.0, 1024.0],
70
+ "1.07": [1024.0, 960.0],
71
+ "1.13": [1088.0, 960.0],
72
+ "1.21": [1088.0, 896.0],
73
+ "1.29": [1152.0, 896.0],
74
+ "1.38": [1152.0, 832.0],
75
+ "1.46": [1216.0, 832.0],
76
+ "1.67": [1280.0, 768.0],
77
+ "1.75": [1344.0, 768.0],
78
+ "2.0": [1408.0, 704.0],
79
+ "2.09": [1472.0, 704.0],
80
+ "2.4": [1536.0, 640.0],
81
+ "2.5": [1600.0, 640.0],
82
+ "3.0": [1728.0, 576.0],
83
+ "4.0": [2048.0, 512.0],
84
+ }
85
+
86
+ ASPECT_RATIO_512_BIN = {
87
+ "0.25": [256.0, 1024.0],
88
+ "0.28": [256.0, 928.0],
89
+ "0.32": [288.0, 896.0],
90
+ "0.33": [288.0, 864.0],
91
+ "0.35": [288.0, 832.0],
92
+ "0.4": [320.0, 800.0],
93
+ "0.42": [320.0, 768.0],
94
+ "0.48": [352.0, 736.0],
95
+ "0.5": [352.0, 704.0],
96
+ "0.52": [352.0, 672.0],
97
+ "0.57": [384.0, 672.0],
98
+ "0.6": [384.0, 640.0],
99
+ "0.68": [416.0, 608.0],
100
+ "0.72": [416.0, 576.0],
101
+ "0.78": [448.0, 576.0],
102
+ "0.82": [448.0, 544.0],
103
+ "0.88": [480.0, 544.0],
104
+ "0.94": [480.0, 512.0],
105
+ "1.0": [512.0, 512.0],
106
+ "1.07": [512.0, 480.0],
107
+ "1.13": [544.0, 480.0],
108
+ "1.21": [544.0, 448.0],
109
+ "1.29": [576.0, 448.0],
110
+ "1.38": [576.0, 416.0],
111
+ "1.46": [608.0, 416.0],
112
+ "1.67": [640.0, 384.0],
113
+ "1.75": [672.0, 384.0],
114
+ "2.0": [704.0, 352.0],
115
+ "2.09": [736.0, 352.0],
116
+ "2.4": [768.0, 320.0],
117
+ "2.5": [800.0, 320.0],
118
+ "3.0": [864.0, 288.0],
119
+ "4.0": [1024.0, 256.0],
120
+ }
121
+
122
+
123
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
124
+ def retrieve_timesteps(
125
+ scheduler,
126
+ num_inference_steps: Optional[int] = None,
127
+ device: Optional[Union[str, torch.device]] = None,
128
+ timesteps: Optional[List[int]] = None,
129
+ **kwargs,
130
+ ):
131
+ """
132
+ Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
133
+ custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
134
+
135
+ Args:
136
+ scheduler (`SchedulerMixin`):
137
+ The scheduler to get timesteps from.
138
+ num_inference_steps (`int`):
139
+ The number of diffusion steps used when generating samples with a pre-trained model. If used,
140
+ `timesteps` must be `None`.
141
+ device (`str` or `torch.device`, *optional*):
142
+ The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
143
+ timesteps (`List[int]`, *optional*):
144
+ Custom timesteps used to support arbitrary spacing between timesteps. If `None`, then the default
145
+ timestep spacing strategy of the scheduler is used. If `timesteps` is passed, `num_inference_steps`
146
+ must be `None`.
147
+
148
+ Returns:
149
+ `Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
150
+ second element is the number of inference steps.
151
+ """
152
+ if timesteps is not None:
153
+ accepts_timesteps = "timesteps" in set(
154
+ inspect.signature(scheduler.set_timesteps).parameters.keys()
155
+ )
156
+ if not accepts_timesteps:
157
+ raise ValueError(
158
+ f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
159
+ f" timestep schedules. Please check whether you are using the correct scheduler."
160
+ )
161
+ scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
162
+ timesteps = scheduler.timesteps
163
+ num_inference_steps = len(timesteps)
164
+ else:
165
+ scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
166
+ timesteps = scheduler.timesteps
167
+ return timesteps, num_inference_steps
168
+
169
+
170
+ class LTXVideoPipeline(DiffusionPipeline):
171
+ r"""
172
+ Pipeline for text-to-image generation using LTX-Video.
173
+
174
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
175
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
176
+
177
+ Args:
178
+ vae ([`AutoencoderKL`]):
179
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
180
+ text_encoder ([`T5EncoderModel`]):
181
+ Frozen text-encoder. This uses
182
+ [T5](https://huggingface.co/docs/transformers/model_doc/t5#transformers.T5EncoderModel), specifically the
183
+ [t5-v1_1-xxl](https://huggingface.co/PixArt-alpha/PixArt-alpha/tree/main/t5-v1_1-xxl) variant.
184
+ tokenizer (`T5Tokenizer`):
185
+ Tokenizer of class
186
+ [T5Tokenizer](https://huggingface.co/docs/transformers/model_doc/t5#transformers.T5Tokenizer).
187
+ transformer ([`Transformer2DModel`]):
188
+ A text conditioned `Transformer2DModel` to denoise the encoded image latents.
189
+ scheduler ([`SchedulerMixin`]):
190
+ A scheduler to be used in combination with `transformer` to denoise the encoded image latents.
191
+ """
192
+
193
+ bad_punct_regex = re.compile(
194
+ r"["
195
+ + "#®•©™&@·º½¾¿¡§~"
196
+ + r"\)"
197
+ + r"\("
198
+ + r"\]"
199
+ + r"\["
200
+ + r"\}"
201
+ + r"\{"
202
+ + r"\|"
203
+ + "\\"
204
+ + r"\/"
205
+ + r"\*"
206
+ + r"]{1,}"
207
+ ) # noqa
208
+
209
+ _optional_components = ["tokenizer", "text_encoder"]
210
+ model_cpu_offload_seq = "text_encoder->transformer->vae"
211
+
212
+ def __init__(
213
+ self,
214
+ tokenizer: T5Tokenizer,
215
+ text_encoder: T5EncoderModel,
216
+ vae: AutoencoderKL,
217
+ transformer: Transformer3DModel,
218
+ scheduler: DPMSolverMultistepScheduler,
219
+ patchifier: Patchifier,
220
+ ):
221
+ super().__init__()
222
+
223
+ self.register_modules(
224
+ tokenizer=tokenizer,
225
+ text_encoder=text_encoder,
226
+ vae=vae,
227
+ transformer=transformer,
228
+ scheduler=scheduler,
229
+ patchifier=patchifier,
230
+ )
231
+
232
+ self.video_scale_factor, self.vae_scale_factor, _ = get_vae_size_scale_factor(
233
+ self.vae
234
+ )
235
+ self.image_processor = VaeImageProcessor(vae_scale_factor=self.vae_scale_factor)
236
+
237
+ def mask_text_embeddings(self, emb, mask):
238
+ if emb.shape[0] == 1:
239
+ keep_index = mask.sum().item()
240
+ return emb[:, :, :keep_index, :], keep_index
241
+ else:
242
+ masked_feature = emb * mask[:, None, :, None]
243
+ return masked_feature, emb.shape[2]
244
+
245
+ # Adapted from diffusers.pipelines.deepfloyd_if.pipeline_if.encode_prompt
246
+ def encode_prompt(
247
+ self,
248
+ prompt: Union[str, List[str]],
249
+ do_classifier_free_guidance: bool = True,
250
+ negative_prompt: str = "",
251
+ num_images_per_prompt: int = 1,
252
+ device: Optional[torch.device] = None,
253
+ prompt_embeds: Optional[torch.FloatTensor] = None,
254
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
255
+ prompt_attention_mask: Optional[torch.FloatTensor] = None,
256
+ negative_prompt_attention_mask: Optional[torch.FloatTensor] = None,
257
+ clean_caption: bool = False,
258
+ **kwargs,
259
+ ):
260
+ r"""
261
+ Encodes the prompt into text encoder hidden states.
262
+
263
+ Args:
264
+ prompt (`str` or `List[str]`, *optional*):
265
+ prompt to be encoded
266
+ negative_prompt (`str` or `List[str]`, *optional*):
267
+ The prompt not to guide the image generation. If not defined, one has to pass `negative_prompt_embeds`
268
+ instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is less than `1`). For
269
+ This should be "".
270
+ do_classifier_free_guidance (`bool`, *optional*, defaults to `True`):
271
+ whether to use classifier free guidance or not
272
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
273
+ number of images that should be generated per prompt
274
+ device: (`torch.device`, *optional*):
275
+ torch device to place the resulting embeddings on
276
+ prompt_embeds (`torch.FloatTensor`, *optional*):
277
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
278
+ provided, text embeddings will be generated from `prompt` input argument.
279
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
280
+ Pre-generated negative text embeddings.
281
+ clean_caption (bool, defaults to `False`):
282
+ If `True`, the function will preprocess and clean the provided caption before encoding.
283
+ """
284
+
285
+ if "mask_feature" in kwargs:
286
+ deprecation_message = "The use of `mask_feature` is deprecated. It is no longer used in any computation and that doesn't affect the end results. It will be removed in a future version."
287
+ deprecate("mask_feature", "1.0.0", deprecation_message, standard_warn=False)
288
+
289
+ if device is None:
290
+ device = self._execution_device
291
+
292
+ if prompt is not None and isinstance(prompt, str):
293
+ batch_size = 1
294
+ elif prompt is not None and isinstance(prompt, list):
295
+ batch_size = len(prompt)
296
+ else:
297
+ batch_size = prompt_embeds.shape[0]
298
+
299
+ # See Section 3.1. of the paper.
300
+ # FIXME: to be configured in config not hardecoded. Fix in separate PR with rest of config
301
+ max_length = 128 # TPU supports only lengths multiple of 128
302
+ text_enc_device = next(self.text_encoder.parameters()).device
303
+ if prompt_embeds is None:
304
+ prompt = self._text_preprocessing(prompt, clean_caption=clean_caption)
305
+ text_inputs = self.tokenizer(
306
+ prompt,
307
+ padding="max_length",
308
+ max_length=max_length,
309
+ truncation=True,
310
+ add_special_tokens=True,
311
+ return_tensors="pt",
312
+ )
313
+ text_input_ids = text_inputs.input_ids
314
+ untruncated_ids = self.tokenizer(
315
+ prompt, padding="longest", return_tensors="pt"
316
+ ).input_ids
317
+
318
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[
319
+ -1
320
+ ] and not torch.equal(text_input_ids, untruncated_ids):
321
+ removed_text = self.tokenizer.batch_decode(
322
+ untruncated_ids[:, max_length - 1 : -1]
323
+ )
324
+ logger.warning(
325
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
326
+ f" {max_length} tokens: {removed_text}"
327
+ )
328
+
329
+ prompt_attention_mask = text_inputs.attention_mask
330
+ prompt_attention_mask = prompt_attention_mask.to(text_enc_device)
331
+ prompt_attention_mask = prompt_attention_mask.to(device)
332
+
333
+ prompt_embeds = self.text_encoder(
334
+ text_input_ids.to(text_enc_device), attention_mask=prompt_attention_mask
335
+ )
336
+ prompt_embeds = prompt_embeds[0]
337
+
338
+ if self.text_encoder is not None:
339
+ dtype = self.text_encoder.dtype
340
+ elif self.transformer is not None:
341
+ dtype = self.transformer.dtype
342
+ else:
343
+ dtype = None
344
+
345
+ prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
346
+
347
+ bs_embed, seq_len, _ = prompt_embeds.shape
348
+ # duplicate text embeddings and attention mask for each generation per prompt, using mps friendly method
349
+ prompt_embeds = prompt_embeds.repeat(1, num_images_per_prompt, 1)
350
+ prompt_embeds = prompt_embeds.view(
351
+ bs_embed * num_images_per_prompt, seq_len, -1
352
+ )
353
+ prompt_attention_mask = prompt_attention_mask.repeat(1, num_images_per_prompt)
354
+ prompt_attention_mask = prompt_attention_mask.view(
355
+ bs_embed * num_images_per_prompt, -1
356
+ )
357
+
358
+ # get unconditional embeddings for classifier free guidance
359
+ if do_classifier_free_guidance and negative_prompt_embeds is None:
360
+ uncond_tokens = [negative_prompt] * batch_size
361
+ uncond_tokens = self._text_preprocessing(
362
+ uncond_tokens, clean_caption=clean_caption
363
+ )
364
+ max_length = prompt_embeds.shape[1]
365
+ uncond_input = self.tokenizer(
366
+ uncond_tokens,
367
+ padding="max_length",
368
+ max_length=max_length,
369
+ truncation=True,
370
+ return_attention_mask=True,
371
+ add_special_tokens=True,
372
+ return_tensors="pt",
373
+ )
374
+ negative_prompt_attention_mask = uncond_input.attention_mask
375
+ negative_prompt_attention_mask = negative_prompt_attention_mask.to(
376
+ text_enc_device
377
+ )
378
+
379
+ negative_prompt_embeds = self.text_encoder(
380
+ uncond_input.input_ids.to(text_enc_device),
381
+ attention_mask=negative_prompt_attention_mask,
382
+ )
383
+ negative_prompt_embeds = negative_prompt_embeds[0]
384
+
385
+ if do_classifier_free_guidance:
386
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
387
+ seq_len = negative_prompt_embeds.shape[1]
388
+
389
+ negative_prompt_embeds = negative_prompt_embeds.to(
390
+ dtype=dtype, device=device
391
+ )
392
+
393
+ negative_prompt_embeds = negative_prompt_embeds.repeat(
394
+ 1, num_images_per_prompt, 1
395
+ )
396
+ negative_prompt_embeds = negative_prompt_embeds.view(
397
+ batch_size * num_images_per_prompt, seq_len, -1
398
+ )
399
+
400
+ negative_prompt_attention_mask = negative_prompt_attention_mask.repeat(
401
+ 1, num_images_per_prompt
402
+ )
403
+ negative_prompt_attention_mask = negative_prompt_attention_mask.view(
404
+ bs_embed * num_images_per_prompt, -1
405
+ )
406
+ else:
407
+ negative_prompt_embeds = None
408
+ negative_prompt_attention_mask = None
409
+
410
+ return (
411
+ prompt_embeds,
412
+ prompt_attention_mask,
413
+ negative_prompt_embeds,
414
+ negative_prompt_attention_mask,
415
+ )
416
+
417
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
418
+ def prepare_extra_step_kwargs(self, generator, eta):
419
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
420
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
421
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
422
+ # and should be between [0, 1]
423
+
424
+ accepts_eta = "eta" in set(
425
+ inspect.signature(self.scheduler.step).parameters.keys()
426
+ )
427
+ extra_step_kwargs = {}
428
+ if accepts_eta:
429
+ extra_step_kwargs["eta"] = eta
430
+
431
+ # check if the scheduler accepts generator
432
+ accepts_generator = "generator" in set(
433
+ inspect.signature(self.scheduler.step).parameters.keys()
434
+ )
435
+ if accepts_generator:
436
+ extra_step_kwargs["generator"] = generator
437
+ return extra_step_kwargs
438
+
439
+ def check_inputs(
440
+ self,
441
+ prompt,
442
+ height,
443
+ width,
444
+ negative_prompt,
445
+ prompt_embeds=None,
446
+ negative_prompt_embeds=None,
447
+ prompt_attention_mask=None,
448
+ negative_prompt_attention_mask=None,
449
+ ):
450
+ if height % 8 != 0 or width % 8 != 0:
451
+ raise ValueError(
452
+ f"`height` and `width` have to be divisible by 8 but are {height} and {width}."
453
+ )
454
+
455
+ if prompt is not None and prompt_embeds is not None:
456
+ raise ValueError(
457
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
458
+ " only forward one of the two."
459
+ )
460
+ elif prompt is None and prompt_embeds is None:
461
+ raise ValueError(
462
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
463
+ )
464
+ elif prompt is not None and (
465
+ not isinstance(prompt, str) and not isinstance(prompt, list)
466
+ ):
467
+ raise ValueError(
468
+ f"`prompt` has to be of type `str` or `list` but is {type(prompt)}"
469
+ )
470
+
471
+ if prompt is not None and negative_prompt_embeds is not None:
472
+ raise ValueError(
473
+ f"Cannot forward both `prompt`: {prompt} and `negative_prompt_embeds`:"
474
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
475
+ )
476
+
477
+ if negative_prompt is not None and negative_prompt_embeds is not None:
478
+ raise ValueError(
479
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
480
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
481
+ )
482
+
483
+ if prompt_embeds is not None and prompt_attention_mask is None:
484
+ raise ValueError(
485
+ "Must provide `prompt_attention_mask` when specifying `prompt_embeds`."
486
+ )
487
+
488
+ if (
489
+ negative_prompt_embeds is not None
490
+ and negative_prompt_attention_mask is None
491
+ ):
492
+ raise ValueError(
493
+ "Must provide `negative_prompt_attention_mask` when specifying `negative_prompt_embeds`."
494
+ )
495
+
496
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
497
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
498
+ raise ValueError(
499
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
500
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
501
+ f" {negative_prompt_embeds.shape}."
502
+ )
503
+ if prompt_attention_mask.shape != negative_prompt_attention_mask.shape:
504
+ raise ValueError(
505
+ "`prompt_attention_mask` and `negative_prompt_attention_mask` must have the same shape when passed directly, but"
506
+ f" got: `prompt_attention_mask` {prompt_attention_mask.shape} != `negative_prompt_attention_mask`"
507
+ f" {negative_prompt_attention_mask.shape}."
508
+ )
509
+
510
+ # Copied from diffusers.pipelines.deepfloyd_if.pipeline_if.IFPipeline._text_preprocessing
511
+ def _text_preprocessing(self, text, clean_caption=False):
512
+ if clean_caption and not is_bs4_available():
513
+ logger.warn(
514
+ BACKENDS_MAPPING["bs4"][-1].format("Setting `clean_caption=True`")
515
+ )
516
+ logger.warn("Setting `clean_caption` to False...")
517
+ clean_caption = False
518
+
519
+ if clean_caption and not is_ftfy_available():
520
+ logger.warn(
521
+ BACKENDS_MAPPING["ftfy"][-1].format("Setting `clean_caption=True`")
522
+ )
523
+ logger.warn("Setting `clean_caption` to False...")
524
+ clean_caption = False
525
+
526
+ if not isinstance(text, (tuple, list)):
527
+ text = [text]
528
+
529
+ def process(text: str):
530
+ if clean_caption:
531
+ text = self._clean_caption(text)
532
+ text = self._clean_caption(text)
533
+ else:
534
+ text = text.lower().strip()
535
+ return text
536
+
537
+ return [process(t) for t in text]
538
+
539
+ # Copied from diffusers.pipelines.deepfloyd_if.pipeline_if.IFPipeline._clean_caption
540
+ def _clean_caption(self, caption):
541
+ caption = str(caption)
542
+ caption = ul.unquote_plus(caption)
543
+ caption = caption.strip().lower()
544
+ caption = re.sub("<person>", "person", caption)
545
+ # urls:
546
+ caption = re.sub(
547
+ r"\b((?:https?:(?:\/{1,3}|[a-zA-Z0-9%])|[a-zA-Z0-9.\-]+[.](?:com|co|ru|net|org|edu|gov|it)[\w/-]*\b\/?(?!@)))", # noqa
548
+ "",
549
+ caption,
550
+ ) # regex for urls
551
+ caption = re.sub(
552
+ r"\b((?:www:(?:\/{1,3}|[a-zA-Z0-9%])|[a-zA-Z0-9.\-]+[.](?:com|co|ru|net|org|edu|gov|it)[\w/-]*\b\/?(?!@)))", # noqa
553
+ "",
554
+ caption,
555
+ ) # regex for urls
556
+ # html:
557
+ caption = BeautifulSoup(caption, features="html.parser").text
558
+
559
+ # @<nickname>
560
+ caption = re.sub(r"@[\w\d]+\b", "", caption)
561
+
562
+ # 31C0—31EF CJK Strokes
563
+ # 31F0—31FF Katakana Phonetic Extensions
564
+ # 3200—32FF Enclosed CJK Letters and Months
565
+ # 3300—33FF CJK Compatibility
566
+ # 3400—4DBF CJK Unified Ideographs Extension A
567
+ # 4DC0—4DFF Yijing Hexagram Symbols
568
+ # 4E00—9FFF CJK Unified Ideographs
569
+ caption = re.sub(r"[\u31c0-\u31ef]+", "", caption)
570
+ caption = re.sub(r"[\u31f0-\u31ff]+", "", caption)
571
+ caption = re.sub(r"[\u3200-\u32ff]+", "", caption)
572
+ caption = re.sub(r"[\u3300-\u33ff]+", "", caption)
573
+ caption = re.sub(r"[\u3400-\u4dbf]+", "", caption)
574
+ caption = re.sub(r"[\u4dc0-\u4dff]+", "", caption)
575
+ caption = re.sub(r"[\u4e00-\u9fff]+", "", caption)
576
+ #######################################################
577
+
578
+ # все виды тире / all types of dash --> "-"
579
+ caption = re.sub(
580
+ r"[\u002D\u058A\u05BE\u1400\u1806\u2010-\u2015\u2E17\u2E1A\u2E3A\u2E3B\u2E40\u301C\u3030\u30A0\uFE31\uFE32\uFE58\uFE63\uFF0D]+", # noqa
581
+ "-",
582
+ caption,
583
+ )
584
+
585
+ # кавычки к одному стандарту
586
+ caption = re.sub(r"[`´«»“”¨]", '"', caption)
587
+ caption = re.sub(r"[‘’]", "'", caption)
588
+
589
+ # &quot;
590
+ caption = re.sub(r"&quot;?", "", caption)
591
+ # &amp
592
+ caption = re.sub(r"&amp", "", caption)
593
+
594
+ # ip adresses:
595
+ caption = re.sub(r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}", " ", caption)
596
+
597
+ # article ids:
598
+ caption = re.sub(r"\d:\d\d\s+$", "", caption)
599
+
600
+ # \n
601
+ caption = re.sub(r"\\n", " ", caption)
602
+
603
+ # "#123"
604
+ caption = re.sub(r"#\d{1,3}\b", "", caption)
605
+ # "#12345.."
606
+ caption = re.sub(r"#\d{5,}\b", "", caption)
607
+ # "123456.."
608
+ caption = re.sub(r"\b\d{6,}\b", "", caption)
609
+ # filenames:
610
+ caption = re.sub(
611
+ r"[\S]+\.(?:png|jpg|jpeg|bmp|webp|eps|pdf|apk|mp4)", "", caption
612
+ )
613
+
614
+ #
615
+ caption = re.sub(r"[\"\']{2,}", r'"', caption) # """AUSVERKAUFT"""
616
+ caption = re.sub(r"[\.]{2,}", r" ", caption) # """AUSVERKAUFT"""
617
+
618
+ caption = re.sub(
619
+ self.bad_punct_regex, r" ", caption
620
+ ) # ***AUSVERKAUFT***, #AUSVERKAUFT
621
+ caption = re.sub(r"\s+\.\s+", r" ", caption) # " . "
622
+
623
+ # this-is-my-cute-cat / this_is_my_cute_cat
624
+ regex2 = re.compile(r"(?:\-|\_)")
625
+ if len(re.findall(regex2, caption)) > 3:
626
+ caption = re.sub(regex2, " ", caption)
627
+
628
+ caption = ftfy.fix_text(caption)
629
+ caption = html.unescape(html.unescape(caption))
630
+
631
+ caption = re.sub(r"\b[a-zA-Z]{1,3}\d{3,15}\b", "", caption) # jc6640
632
+ caption = re.sub(r"\b[a-zA-Z]+\d+[a-zA-Z]+\b", "", caption) # jc6640vc
633
+ caption = re.sub(r"\b\d+[a-zA-Z]+\d+\b", "", caption) # 6640vc231
634
+
635
+ caption = re.sub(r"(worldwide\s+)?(free\s+)?shipping", "", caption)
636
+ caption = re.sub(r"(free\s)?download(\sfree)?", "", caption)
637
+ caption = re.sub(r"\bclick\b\s(?:for|on)\s\w+", "", caption)
638
+ caption = re.sub(
639
+ r"\b(?:png|jpg|jpeg|bmp|webp|eps|pdf|apk|mp4)(\simage[s]?)?", "", caption
640
+ )
641
+ caption = re.sub(r"\bpage\s+\d+\b", "", caption)
642
+
643
+ caption = re.sub(
644
+ r"\b\d*[a-zA-Z]+\d+[a-zA-Z]+\d+[a-zA-Z\d]*\b", r" ", caption
645
+ ) # j2d1a2a...
646
+
647
+ caption = re.sub(r"\b\d+\.?\d*[xх×]\d+\.?\d*\b", "", caption)
648
+
649
+ caption = re.sub(r"\b\s+\:\s+", r": ", caption)
650
+ caption = re.sub(r"(\D[,\./])\b", r"\1 ", caption)
651
+ caption = re.sub(r"\s+", " ", caption)
652
+
653
+ caption.strip()
654
+
655
+ caption = re.sub(r"^[\"\']([\w\W]+)[\"\']$", r"\1", caption)
656
+ caption = re.sub(r"^[\'\_,\-\:;]", r"", caption)
657
+ caption = re.sub(r"[\'\_,\-\:\-\+]$", r"", caption)
658
+ caption = re.sub(r"^\.\S+$", "", caption)
659
+
660
+ return caption.strip()
661
+
662
+ def image_cond_noise_update(
663
+ self,
664
+ t,
665
+ init_latents,
666
+ latents,
667
+ noise_scale,
668
+ conditiong_mask,
669
+ generator,
670
+ ):
671
+ noise = randn_tensor(
672
+ latents.shape,
673
+ generator=generator,
674
+ device=latents.device,
675
+ dtype=latents.dtype,
676
+ )
677
+ latents = (init_latents + noise_scale * noise * (t**2)) * conditiong_mask[
678
+ ..., None
679
+ ] + latents * (1 - conditiong_mask[..., None])
680
+ return latents
681
+
682
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_latents
683
+ def prepare_latents(
684
+ self,
685
+ batch_size,
686
+ num_latent_channels,
687
+ num_patches,
688
+ dtype,
689
+ device,
690
+ generator,
691
+ latents=None,
692
+ latents_mask=None,
693
+ ):
694
+ shape = (
695
+ batch_size,
696
+ num_patches // math.prod(self.patchifier.patch_size),
697
+ num_latent_channels,
698
+ )
699
+
700
+ if isinstance(generator, list) and len(generator) != batch_size:
701
+ raise ValueError(
702
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
703
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
704
+ )
705
+
706
+ if latents is None:
707
+ latents = randn_tensor(
708
+ shape, generator=generator, device=generator.device, dtype=dtype
709
+ )
710
+ elif latents_mask is not None:
711
+ noise = randn_tensor(
712
+ shape, generator=generator, device=generator.device, dtype=dtype
713
+ )
714
+ latents = latents * latents_mask[..., None] + noise * (
715
+ 1 - latents_mask[..., None]
716
+ )
717
+ else:
718
+ latents = latents.to(device)
719
+
720
+ # scale the initial noise by the standard deviation required by the scheduler
721
+ latents = latents * self.scheduler.init_noise_sigma
722
+ return latents
723
+
724
+ @staticmethod
725
+ def classify_height_width_bin(
726
+ height: int, width: int, ratios: dict
727
+ ) -> Tuple[int, int]:
728
+ """Returns binned height and width."""
729
+ ar = float(height / width)
730
+ closest_ratio = min(ratios.keys(), key=lambda ratio: abs(float(ratio) - ar))
731
+ default_hw = ratios[closest_ratio]
732
+ return int(default_hw[0]), int(default_hw[1])
733
+
734
+ @staticmethod
735
+ def resize_and_crop_tensor(
736
+ samples: torch.Tensor, new_width: int, new_height: int
737
+ ) -> torch.Tensor:
738
+ n_frames, orig_height, orig_width = samples.shape[-3:]
739
+
740
+ # Check if resizing is needed
741
+ if orig_height != new_height or orig_width != new_width:
742
+ ratio = max(new_height / orig_height, new_width / orig_width)
743
+ resized_width = int(orig_width * ratio)
744
+ resized_height = int(orig_height * ratio)
745
+
746
+ # Resize
747
+ samples = rearrange(samples, "b c n h w -> (b n) c h w")
748
+ samples = F.interpolate(
749
+ samples,
750
+ size=(resized_height, resized_width),
751
+ mode="bilinear",
752
+ align_corners=False,
753
+ )
754
+ samples = rearrange(samples, "(b n) c h w -> b c n h w", n=n_frames)
755
+
756
+ # Center Crop
757
+ start_x = (resized_width - new_width) // 2
758
+ end_x = start_x + new_width
759
+ start_y = (resized_height - new_height) // 2
760
+ end_y = start_y + new_height
761
+ samples = samples[..., start_y:end_y, start_x:end_x]
762
+
763
+ return samples
764
+
765
+ @torch.no_grad()
766
+ def __call__(
767
+ self,
768
+ height: int,
769
+ width: int,
770
+ num_frames: int,
771
+ frame_rate: float,
772
+ prompt: Union[str, List[str]] = None,
773
+ negative_prompt: str = "",
774
+ num_inference_steps: int = 20,
775
+ timesteps: List[int] = None,
776
+ guidance_scale: float = 4.5,
777
+ skip_layer_strategy: Optional[SkipLayerStrategy] = None,
778
+ skip_block_list: List[int] = None,
779
+ stg_scale: float = 1.0,
780
+ do_rescaling: bool = True,
781
+ rescaling_scale: float = 0.7,
782
+ num_images_per_prompt: Optional[int] = 1,
783
+ eta: float = 0.0,
784
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
785
+ latents: Optional[torch.FloatTensor] = None,
786
+ prompt_embeds: Optional[torch.FloatTensor] = None,
787
+ prompt_attention_mask: Optional[torch.FloatTensor] = None,
788
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
789
+ negative_prompt_attention_mask: Optional[torch.FloatTensor] = None,
790
+ output_type: Optional[str] = "pil",
791
+ return_dict: bool = True,
792
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
793
+ clean_caption: bool = True,
794
+ media_items: Optional[torch.FloatTensor] = None,
795
+ decode_timestep: Union[List[float], float] = 0.0,
796
+ decode_noise_scale: Optional[List[float]] = None,
797
+ mixed_precision: bool = False,
798
+ offload_to_cpu: bool = False,
799
+ **kwargs,
800
+ ) -> Union[ImagePipelineOutput, Tuple]:
801
+ """
802
+ Function invoked when calling the pipeline for generation.
803
+
804
+ Args:
805
+ prompt (`str` or `List[str]`, *optional*):
806
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
807
+ instead.
808
+ negative_prompt (`str` or `List[str]`, *optional*):
809
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
810
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
811
+ less than `1`).
812
+ num_inference_steps (`int`, *optional*, defaults to 100):
813
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
814
+ expense of slower inference.
815
+ timesteps (`List[int]`, *optional*):
816
+ Custom timesteps to use for the denoising process. If not defined, equal spaced `num_inference_steps`
817
+ timesteps are used. Must be in descending order.
818
+ guidance_scale (`float`, *optional*, defaults to 4.5):
819
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
820
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
821
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
822
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
823
+ usually at the expense of lower image quality.
824
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
825
+ The number of images to generate per prompt.
826
+ height (`int`, *optional*, defaults to self.unet.config.sample_size):
827
+ The height in pixels of the generated image.
828
+ width (`int`, *optional*, defaults to self.unet.config.sample_size):
829
+ The width in pixels of the generated image.
830
+ eta (`float`, *optional*, defaults to 0.0):
831
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
832
+ [`schedulers.DDIMScheduler`], will be ignored for others.
833
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
834
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
835
+ to make generation deterministic.
836
+ latents (`torch.FloatTensor`, *optional*):
837
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
838
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
839
+ tensor will ge generated by sampling using the supplied random `generator`.
840
+ prompt_embeds (`torch.FloatTensor`, *optional*):
841
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
842
+ provided, text embeddings will be generated from `prompt` input argument.
843
+ prompt_attention_mask (`torch.FloatTensor`, *optional*): Pre-generated attention mask for text embeddings.
844
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
845
+ Pre-generated negative text embeddings. This negative prompt should be "". If not
846
+ provided, negative_prompt_embeds will be generated from `negative_prompt` input argument.
847
+ negative_prompt_attention_mask (`torch.FloatTensor`, *optional*):
848
+ Pre-generated attention mask for negative text embeddings.
849
+ output_type (`str`, *optional*, defaults to `"pil"`):
850
+ The output format of the generate image. Choose between
851
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
852
+ return_dict (`bool`, *optional*, defaults to `True`):
853
+ Whether or not to return a [`~pipelines.stable_diffusion.IFPipelineOutput`] instead of a plain tuple.
854
+ callback_on_step_end (`Callable`, *optional*):
855
+ A function that calls at the end of each denoising steps during the inference. The function is called
856
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
857
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
858
+ `callback_on_step_end_tensor_inputs`.
859
+ clean_caption (`bool`, *optional*, defaults to `True`):
860
+ Whether or not to clean the caption before creating embeddings. Requires `beautifulsoup4` and `ftfy` to
861
+ be installed. If the dependencies are not installed, the embeddings will be created from the raw
862
+ prompt.
863
+ use_resolution_binning (`bool` defaults to `True`):
864
+ If set to `True`, the requested height and width are first mapped to the closest resolutions using
865
+ `ASPECT_RATIO_1024_BIN`. After the produced latents are decoded into images, they are resized back to
866
+ the requested resolution. Useful for generating non-square images.
867
+
868
+ Examples:
869
+
870
+ Returns:
871
+ [`~pipelines.ImagePipelineOutput`] or `tuple`:
872
+ If `return_dict` is `True`, [`~pipelines.ImagePipelineOutput`] is returned, otherwise a `tuple` is
873
+ returned where the first element is a list with the generated images
874
+ """
875
+ if "mask_feature" in kwargs:
876
+ deprecation_message = "The use of `mask_feature` is deprecated. It is no longer used in any computation and that doesn't affect the end results. It will be removed in a future version."
877
+ deprecate("mask_feature", "1.0.0", deprecation_message, standard_warn=False)
878
+
879
+ is_video = kwargs.get("is_video", False)
880
+ self.check_inputs(
881
+ prompt,
882
+ height,
883
+ width,
884
+ negative_prompt,
885
+ prompt_embeds,
886
+ negative_prompt_embeds,
887
+ prompt_attention_mask,
888
+ negative_prompt_attention_mask,
889
+ )
890
+
891
+ # 2. Default height and width to transformer
892
+ if prompt is not None and isinstance(prompt, str):
893
+ batch_size = 1
894
+ elif prompt is not None and isinstance(prompt, list):
895
+ batch_size = len(prompt)
896
+ else:
897
+ batch_size = prompt_embeds.shape[0]
898
+
899
+ device = self._execution_device
900
+
901
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
902
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
903
+ # corresponds to doing no classifier free guidance.
904
+ do_classifier_free_guidance = guidance_scale > 1.0
905
+ do_spatio_temporal_guidance = stg_scale > 0.0
906
+
907
+ num_conds = 1
908
+ if do_classifier_free_guidance:
909
+ num_conds += 1
910
+ if do_spatio_temporal_guidance:
911
+ num_conds += 1
912
+
913
+ skip_layer_mask = None
914
+ if do_spatio_temporal_guidance:
915
+ skip_layer_mask = self.transformer.create_skip_layer_mask(
916
+ skip_block_list, batch_size, num_conds, 2
917
+ )
918
+
919
+ # 3. Encode input prompt
920
+ self.text_encoder = self.text_encoder.to(self._execution_device)
921
+
922
+ (
923
+ prompt_embeds,
924
+ prompt_attention_mask,
925
+ negative_prompt_embeds,
926
+ negative_prompt_attention_mask,
927
+ ) = self.encode_prompt(
928
+ prompt,
929
+ do_classifier_free_guidance,
930
+ negative_prompt=negative_prompt,
931
+ num_images_per_prompt=num_images_per_prompt,
932
+ device=device,
933
+ prompt_embeds=prompt_embeds,
934
+ negative_prompt_embeds=negative_prompt_embeds,
935
+ prompt_attention_mask=prompt_attention_mask,
936
+ negative_prompt_attention_mask=negative_prompt_attention_mask,
937
+ clean_caption=clean_caption,
938
+ )
939
+
940
+ if offload_to_cpu:
941
+ self.text_encoder = self.text_encoder.cpu()
942
+
943
+ self.transformer = self.transformer.to(self._execution_device)
944
+
945
+ prompt_embeds_batch = prompt_embeds
946
+ prompt_attention_mask_batch = prompt_attention_mask
947
+ if do_classifier_free_guidance:
948
+ prompt_embeds_batch = torch.cat(
949
+ [negative_prompt_embeds, prompt_embeds], dim=0
950
+ )
951
+ prompt_attention_mask_batch = torch.cat(
952
+ [negative_prompt_attention_mask, prompt_attention_mask], dim=0
953
+ )
954
+ if do_spatio_temporal_guidance:
955
+ prompt_embeds_batch = torch.cat([prompt_embeds_batch, prompt_embeds], dim=0)
956
+ prompt_attention_mask_batch = torch.cat(
957
+ [
958
+ prompt_attention_mask_batch,
959
+ prompt_attention_mask,
960
+ ],
961
+ dim=0,
962
+ )
963
+
964
+ # 3b. Encode and prepare conditioning data
965
+ self.video_scale_factor = self.video_scale_factor if is_video else 1
966
+ conditioning_method = kwargs.get("conditioning_method", None)
967
+ vae_per_channel_normalize = kwargs.get("vae_per_channel_normalize", False)
968
+ image_cond_noise_scale = kwargs.get("image_cond_noise_scale", 0.0)
969
+ init_latents, conditioning_mask = self.prepare_conditioning(
970
+ media_items,
971
+ num_frames,
972
+ height,
973
+ width,
974
+ conditioning_method,
975
+ vae_per_channel_normalize,
976
+ )
977
+
978
+ # 4. Prepare latents.
979
+ latent_height = height // self.vae_scale_factor
980
+ latent_width = width // self.vae_scale_factor
981
+ latent_num_frames = num_frames // self.video_scale_factor
982
+ if isinstance(self.vae, CausalVideoAutoencoder) and is_video:
983
+ latent_num_frames += 1
984
+ latent_frame_rate = frame_rate / self.video_scale_factor
985
+ num_latent_patches = latent_height * latent_width * latent_num_frames
986
+ latents = self.prepare_latents(
987
+ batch_size=batch_size * num_images_per_prompt,
988
+ num_latent_channels=self.transformer.config.in_channels,
989
+ num_patches=num_latent_patches,
990
+ dtype=prompt_embeds_batch.dtype,
991
+ device=device,
992
+ generator=generator,
993
+ latents=init_latents,
994
+ latents_mask=conditioning_mask,
995
+ )
996
+ orig_conditiong_mask = conditioning_mask
997
+ if conditioning_mask is not None and is_video:
998
+ assert num_images_per_prompt == 1
999
+ conditioning_mask = (
1000
+ torch.cat([conditioning_mask] * num_conds)
1001
+ if num_conds > 1
1002
+ else conditioning_mask
1003
+ )
1004
+
1005
+ # 5. Prepare timesteps
1006
+ retrieve_timesteps_kwargs = {}
1007
+ if isinstance(self.scheduler, TimestepShifter):
1008
+ retrieve_timesteps_kwargs["samples"] = latents
1009
+ timesteps, num_inference_steps = retrieve_timesteps(
1010
+ self.scheduler,
1011
+ num_inference_steps,
1012
+ device,
1013
+ timesteps,
1014
+ **retrieve_timesteps_kwargs,
1015
+ )
1016
+
1017
+ # 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
1018
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
1019
+
1020
+ # 7. Denoising loop
1021
+ num_warmup_steps = max(
1022
+ len(timesteps) - num_inference_steps * self.scheduler.order, 0
1023
+ )
1024
+
1025
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
1026
+ for i, t in enumerate(timesteps):
1027
+ if conditioning_method == ConditioningMethod.FIRST_FRAME:
1028
+ latents = self.image_cond_noise_update(
1029
+ t,
1030
+ init_latents,
1031
+ latents,
1032
+ image_cond_noise_scale,
1033
+ orig_conditiong_mask,
1034
+ generator,
1035
+ )
1036
+
1037
+ latent_model_input = (
1038
+ torch.cat([latents] * num_conds) if num_conds > 1 else latents
1039
+ )
1040
+ latent_model_input = self.scheduler.scale_model_input(
1041
+ latent_model_input, t
1042
+ )
1043
+
1044
+ latent_frame_rates = (
1045
+ torch.ones(
1046
+ latent_model_input.shape[0], 1, device=latent_model_input.device
1047
+ )
1048
+ * latent_frame_rate
1049
+ )
1050
+
1051
+ current_timestep = t
1052
+ if not torch.is_tensor(current_timestep):
1053
+ # TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can
1054
+ # This would be a good case for the `match` statement (Python 3.10+)
1055
+ is_mps = latent_model_input.device.type == "mps"
1056
+ if isinstance(current_timestep, float):
1057
+ dtype = torch.float32 if is_mps else torch.float64
1058
+ else:
1059
+ dtype = torch.int32 if is_mps else torch.int64
1060
+ current_timestep = torch.tensor(
1061
+ [current_timestep],
1062
+ dtype=dtype,
1063
+ device=latent_model_input.device,
1064
+ )
1065
+ elif len(current_timestep.shape) == 0:
1066
+ current_timestep = current_timestep[None].to(
1067
+ latent_model_input.device
1068
+ )
1069
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
1070
+ current_timestep = current_timestep.expand(
1071
+ latent_model_input.shape[0]
1072
+ ).unsqueeze(-1)
1073
+ scale_grid = (
1074
+ (
1075
+ 1 / latent_frame_rates,
1076
+ self.vae_scale_factor,
1077
+ self.vae_scale_factor,
1078
+ )
1079
+ if self.transformer.use_rope
1080
+ else None
1081
+ )
1082
+ indices_grid = self.patchifier.get_grid(
1083
+ orig_num_frames=latent_num_frames,
1084
+ orig_height=latent_height,
1085
+ orig_width=latent_width,
1086
+ batch_size=latent_model_input.shape[0],
1087
+ scale_grid=scale_grid,
1088
+ device=latents.device,
1089
+ )
1090
+
1091
+ if conditioning_mask is not None:
1092
+ current_timestep = current_timestep * (1 - conditioning_mask)
1093
+ # Choose the appropriate context manager based on `mixed_precision`
1094
+ if mixed_precision:
1095
+ if "xla" in device.type:
1096
+ raise NotImplementedError(
1097
+ "Mixed precision is not supported yet on XLA devices."
1098
+ )
1099
+
1100
+ context_manager = torch.autocast(device.type, dtype=torch.bfloat16)
1101
+ else:
1102
+ context_manager = nullcontext() # Dummy context manager
1103
+
1104
+ # predict noise model_output
1105
+ with context_manager:
1106
+ noise_pred = self.transformer(
1107
+ latent_model_input.to(self.transformer.dtype),
1108
+ indices_grid,
1109
+ encoder_hidden_states=prompt_embeds_batch.to(
1110
+ self.transformer.dtype
1111
+ ),
1112
+ encoder_attention_mask=prompt_attention_mask_batch,
1113
+ timestep=current_timestep,
1114
+ skip_layer_mask=skip_layer_mask,
1115
+ skip_layer_strategy=skip_layer_strategy,
1116
+ return_dict=False,
1117
+ )[0]
1118
+
1119
+ # perform guidance
1120
+ if do_spatio_temporal_guidance:
1121
+ noise_pred_text_perturb = noise_pred[-1:]
1122
+ if do_classifier_free_guidance:
1123
+ noise_pred_uncond, noise_pred_text = noise_pred[:2].chunk(2)
1124
+ noise_pred = noise_pred_uncond + guidance_scale * (
1125
+ noise_pred_text - noise_pred_uncond
1126
+ )
1127
+ if do_spatio_temporal_guidance:
1128
+ noise_pred = noise_pred + stg_scale * (
1129
+ noise_pred_text - noise_pred_text_perturb
1130
+ )
1131
+ if do_rescaling:
1132
+ factor = noise_pred_text.std() / noise_pred.std()
1133
+ factor = rescaling_scale * factor + (1 - rescaling_scale)
1134
+ noise_pred = noise_pred * factor
1135
+
1136
+ current_timestep = current_timestep[:1]
1137
+ # learned sigma
1138
+ if (
1139
+ self.transformer.config.out_channels // 2
1140
+ == self.transformer.config.in_channels
1141
+ ):
1142
+ noise_pred = noise_pred.chunk(2, dim=1)[0]
1143
+
1144
+ # compute previous image: x_t -> x_t-1
1145
+ latents = self.scheduler.step(
1146
+ noise_pred,
1147
+ t if current_timestep is None else current_timestep,
1148
+ latents,
1149
+ **extra_step_kwargs,
1150
+ return_dict=False,
1151
+ )[0]
1152
+
1153
+ # call the callback, if provided
1154
+ if i == len(timesteps) - 1 or (
1155
+ (i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0
1156
+ ):
1157
+ progress_bar.update()
1158
+
1159
+ if callback_on_step_end is not None:
1160
+ callback_on_step_end(self, i, t, {})
1161
+
1162
+ if offload_to_cpu:
1163
+ self.transformer = self.transformer.cpu()
1164
+ if self._execution_device == "cuda":
1165
+ torch.cuda.empty_cache()
1166
+
1167
+ latents = self.patchifier.unpatchify(
1168
+ latents=latents,
1169
+ output_height=latent_height,
1170
+ output_width=latent_width,
1171
+ output_num_frames=latent_num_frames,
1172
+ out_channels=self.transformer.in_channels
1173
+ // math.prod(self.patchifier.patch_size),
1174
+ )
1175
+ if output_type != "latent":
1176
+ if self.vae.decoder.timestep_conditioning:
1177
+ noise = torch.randn_like(latents)
1178
+ if not isinstance(decode_timestep, list):
1179
+ decode_timestep = [decode_timestep] * latents.shape[0]
1180
+ if decode_noise_scale is None:
1181
+ decode_noise_scale = decode_timestep
1182
+ elif not isinstance(decode_noise_scale, list):
1183
+ decode_noise_scale = [decode_noise_scale] * latents.shape[0]
1184
+
1185
+ decode_timestep = torch.tensor(decode_timestep).to(latents.device)
1186
+ decode_noise_scale = torch.tensor(decode_noise_scale).to(
1187
+ latents.device
1188
+ )[:, None, None, None, None]
1189
+ latents = (
1190
+ latents * (1 - decode_noise_scale) + noise * decode_noise_scale
1191
+ )
1192
+ else:
1193
+ decode_timestep = None
1194
+ image = vae_decode(
1195
+ latents,
1196
+ self.vae,
1197
+ is_video,
1198
+ vae_per_channel_normalize=kwargs["vae_per_channel_normalize"],
1199
+ timestep=decode_timestep,
1200
+ )
1201
+ image = self.image_processor.postprocess(image, output_type=output_type)
1202
+
1203
+ else:
1204
+ image = latents
1205
+
1206
+ # Offload all models
1207
+ self.maybe_free_model_hooks()
1208
+
1209
+ if not return_dict:
1210
+ return (image,)
1211
+
1212
+ return ImagePipelineOutput(images=image)
1213
+
1214
+ def prepare_conditioning(
1215
+ self,
1216
+ media_items: torch.Tensor,
1217
+ num_frames: int,
1218
+ height: int,
1219
+ width: int,
1220
+ method: ConditioningMethod = ConditioningMethod.UNCONDITIONAL,
1221
+ vae_per_channel_normalize: bool = False,
1222
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
1223
+ """
1224
+ Prepare the conditioning data for the video generation. If an input media item is provided, encode it
1225
+ and set the conditioning_mask to indicate which tokens to condition on. Input media item should have
1226
+ the same height and width as the generated video.
1227
+
1228
+ Args:
1229
+ media_items (torch.Tensor): media items to condition on (images or videos)
1230
+ num_frames (int): number of frames to generate
1231
+ height (int): height of the generated video
1232
+ width (int): width of the generated video
1233
+ method (ConditioningMethod, optional): conditioning method to use. Defaults to ConditioningMethod.UNCONDITIONAL.
1234
+ vae_per_channel_normalize (bool, optional): whether to normalize the input to the VAE per channel. Defaults to False.
1235
+
1236
+ Returns:
1237
+ Tuple[torch.Tensor, torch.Tensor]: the conditioning latents and the conditioning mask
1238
+ """
1239
+ if media_items is None or method == ConditioningMethod.UNCONDITIONAL:
1240
+ return None, None
1241
+
1242
+ assert media_items.ndim == 5
1243
+ assert height == media_items.shape[-2] and width == media_items.shape[-1]
1244
+
1245
+ # Encode the input video and repeat to the required number of frame-tokens
1246
+ init_latents = vae_encode(
1247
+ media_items.to(dtype=self.vae.dtype, device=self.vae.device),
1248
+ self.vae,
1249
+ vae_per_channel_normalize=vae_per_channel_normalize,
1250
+ ).float()
1251
+
1252
+ init_len, target_len = (
1253
+ init_latents.shape[2],
1254
+ num_frames // self.video_scale_factor,
1255
+ )
1256
+ if isinstance(self.vae, CausalVideoAutoencoder):
1257
+ target_len += 1
1258
+ init_latents = init_latents[:, :, :target_len]
1259
+ if target_len > init_len:
1260
+ repeat_factor = (target_len + init_len - 1) // init_len # Ceiling division
1261
+ init_latents = init_latents.repeat(1, 1, repeat_factor, 1, 1)[
1262
+ :, :, :target_len
1263
+ ]
1264
+
1265
+ # Prepare the conditioning mask (1.0 = condition on this token)
1266
+ b, n, f, h, w = init_latents.shape
1267
+ conditioning_mask = torch.zeros([b, 1, f, h, w], device=init_latents.device)
1268
+ if method == ConditioningMethod.FIRST_FRAME:
1269
+ conditioning_mask[:, :, 0] = 1.0
1270
+
1271
+ # Patchify the init latents and the mask
1272
+ conditioning_mask = self.patchifier.patchify(conditioning_mask).squeeze(-1)
1273
+ init_latents = self.patchifier.patchify(latents=init_latents)
1274
+ return init_latents, conditioning_mask
ltx_video/schedulers/__init__.py ADDED
File without changes
ltx_video/schedulers/rf.py ADDED
@@ -0,0 +1,331 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from abc import ABC, abstractmethod
3
+ from dataclasses import dataclass
4
+ from typing import Callable, Optional, Tuple, Union
5
+ import json
6
+ import os
7
+ from pathlib import Path
8
+
9
+ import torch
10
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
11
+ from diffusers.schedulers.scheduling_utils import SchedulerMixin
12
+ from diffusers.utils import BaseOutput
13
+ from torch import Tensor
14
+ from safetensors import safe_open
15
+
16
+
17
+ from ltx_video.utils.torch_utils import append_dims
18
+
19
+ from ltx_video.utils.diffusers_config_mapping import (
20
+ diffusers_and_ours_config_mapping,
21
+ make_hashable_key,
22
+ )
23
+
24
+
25
+ def simple_diffusion_resolution_dependent_timestep_shift(
26
+ samples: Tensor,
27
+ timesteps: Tensor,
28
+ n: int = 32 * 32,
29
+ ) -> Tensor:
30
+ if len(samples.shape) == 3:
31
+ _, m, _ = samples.shape
32
+ elif len(samples.shape) in [4, 5]:
33
+ m = math.prod(samples.shape[2:])
34
+ else:
35
+ raise ValueError(
36
+ "Samples must have shape (b, t, c), (b, c, h, w) or (b, c, f, h, w)"
37
+ )
38
+ snr = (timesteps / (1 - timesteps)) ** 2
39
+ shift_snr = torch.log(snr) + 2 * math.log(m / n)
40
+ shifted_timesteps = torch.sigmoid(0.5 * shift_snr)
41
+
42
+ return shifted_timesteps
43
+
44
+
45
+ def time_shift(mu: float, sigma: float, t: Tensor):
46
+ return math.exp(mu) / (math.exp(mu) + (1 / t - 1) ** sigma)
47
+
48
+
49
+ def get_normal_shift(
50
+ n_tokens: int,
51
+ min_tokens: int = 1024,
52
+ max_tokens: int = 4096,
53
+ min_shift: float = 0.95,
54
+ max_shift: float = 2.05,
55
+ ) -> Callable[[float], float]:
56
+ m = (max_shift - min_shift) / (max_tokens - min_tokens)
57
+ b = min_shift - m * min_tokens
58
+ return m * n_tokens + b
59
+
60
+
61
+ def strech_shifts_to_terminal(shifts: Tensor, terminal=0.1):
62
+ """
63
+ Stretch a function (given as sampled shifts) so that its final value matches the given terminal value
64
+ using the provided formula.
65
+
66
+ Parameters:
67
+ - shifts (Tensor): The samples of the function to be stretched (PyTorch Tensor).
68
+ - terminal (float): The desired terminal value (value at the last sample).
69
+
70
+ Returns:
71
+ - Tensor: The stretched shifts such that the final value equals `terminal`.
72
+ """
73
+ if shifts.numel() == 0:
74
+ raise ValueError("The 'shifts' tensor must not be empty.")
75
+
76
+ # Ensure terminal value is valid
77
+ if terminal <= 0 or terminal >= 1:
78
+ raise ValueError("The terminal value must be between 0 and 1 (exclusive).")
79
+
80
+ # Transform the shifts using the given formula
81
+ one_minus_z = 1 - shifts
82
+ scale_factor = one_minus_z[-1] / (1 - terminal)
83
+ stretched_shifts = 1 - (one_minus_z / scale_factor)
84
+
85
+ return stretched_shifts
86
+
87
+
88
+ def sd3_resolution_dependent_timestep_shift(
89
+ samples: Tensor, timesteps: Tensor, target_shift_terminal: Optional[float] = None
90
+ ) -> Tensor:
91
+ """
92
+ Shifts the timestep schedule as a function of the generated resolution.
93
+
94
+ In the SD3 paper, the authors empirically how to shift the timesteps based on the resolution of the target images.
95
+ For more details: https://arxiv.org/pdf/2403.03206
96
+
97
+ In Flux they later propose a more dynamic resolution dependent timestep shift, see:
98
+ https://github.com/black-forest-labs/flux/blob/87f6fff727a377ea1c378af692afb41ae84cbe04/src/flux/sampling.py#L66
99
+
100
+
101
+ Args:
102
+ samples (Tensor): A batch of samples with shape (batch_size, channels, height, width) or
103
+ (batch_size, channels, frame, height, width).
104
+ timesteps (Tensor): A batch of timesteps with shape (batch_size,).
105
+ target_shift_terminal (float): The target terminal value for the shifted timesteps.
106
+
107
+ Returns:
108
+ Tensor: The shifted timesteps.
109
+ """
110
+ if len(samples.shape) == 3:
111
+ _, m, _ = samples.shape
112
+ elif len(samples.shape) in [4, 5]:
113
+ m = math.prod(samples.shape[2:])
114
+ else:
115
+ raise ValueError(
116
+ "Samples must have shape (b, t, c), (b, c, h, w) or (b, c, f, h, w)"
117
+ )
118
+
119
+ shift = get_normal_shift(m)
120
+ time_shifts = time_shift(shift, 1, timesteps)
121
+ if target_shift_terminal is not None: # Stretch the shifts to the target terminal
122
+ time_shifts = strech_shifts_to_terminal(time_shifts, target_shift_terminal)
123
+ return time_shifts
124
+
125
+
126
+ class TimestepShifter(ABC):
127
+ @abstractmethod
128
+ def shift_timesteps(self, samples: Tensor, timesteps: Tensor) -> Tensor:
129
+ pass
130
+
131
+
132
+ @dataclass
133
+ class RectifiedFlowSchedulerOutput(BaseOutput):
134
+ """
135
+ Output class for the scheduler's step function output.
136
+
137
+ Args:
138
+ prev_sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` for images):
139
+ Computed sample (x_{t-1}) of previous timestep. `prev_sample` should be used as next model input in the
140
+ denoising loop.
141
+ pred_original_sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` for images):
142
+ The predicted denoised sample (x_{0}) based on the model output from the current timestep.
143
+ `pred_original_sample` can be used to preview progress or for guidance.
144
+ """
145
+
146
+ prev_sample: torch.FloatTensor
147
+ pred_original_sample: Optional[torch.FloatTensor] = None
148
+
149
+
150
+ class RectifiedFlowScheduler(SchedulerMixin, ConfigMixin, TimestepShifter):
151
+ order = 1
152
+
153
+ @register_to_config
154
+ def __init__(
155
+ self,
156
+ num_train_timesteps=1000,
157
+ shifting: Optional[str] = None,
158
+ base_resolution: int = 32**2,
159
+ target_shift_terminal: Optional[float] = None,
160
+ ):
161
+ super().__init__()
162
+ self.init_noise_sigma = 1.0
163
+ self.num_inference_steps = None
164
+ self.timesteps = self.sigmas = torch.linspace(
165
+ 1, 1 / num_train_timesteps, num_train_timesteps
166
+ )
167
+ self.delta_timesteps = self.timesteps - torch.cat(
168
+ [self.timesteps[1:], torch.zeros_like(self.timesteps[-1:])]
169
+ )
170
+ self.shifting = shifting
171
+ self.base_resolution = base_resolution
172
+ self.target_shift_terminal = target_shift_terminal
173
+
174
+ def shift_timesteps(self, samples: Tensor, timesteps: Tensor) -> Tensor:
175
+ if self.shifting == "SD3":
176
+ return sd3_resolution_dependent_timestep_shift(
177
+ samples, timesteps, self.target_shift_terminal
178
+ )
179
+ elif self.shifting == "SimpleDiffusion":
180
+ return simple_diffusion_resolution_dependent_timestep_shift(
181
+ samples, timesteps, self.base_resolution
182
+ )
183
+ return timesteps
184
+
185
+ def set_timesteps(
186
+ self,
187
+ num_inference_steps: int,
188
+ samples: Tensor,
189
+ device: Union[str, torch.device] = None,
190
+ ):
191
+ """
192
+ Sets the discrete timesteps used for the diffusion chain. Supporting function to be run before inference.
193
+
194
+ Args:
195
+ num_inference_steps (`int`): The number of diffusion steps used when generating samples.
196
+ samples (`Tensor`): A batch of samples with shape.
197
+ device (`Union[str, torch.device]`, *optional*): The device to which the timesteps tensor will be moved.
198
+ """
199
+ num_inference_steps = min(self.config.num_train_timesteps, num_inference_steps)
200
+ timesteps = torch.linspace(1, 1 / num_inference_steps, num_inference_steps).to(
201
+ device
202
+ )
203
+ self.timesteps = self.shift_timesteps(samples, timesteps)
204
+ self.delta_timesteps = self.timesteps - torch.cat(
205
+ [self.timesteps[1:], torch.zeros_like(self.timesteps[-1:])]
206
+ )
207
+ self.num_inference_steps = num_inference_steps
208
+ self.sigmas = self.timesteps
209
+
210
+ @staticmethod
211
+ def from_pretrained(pretrained_model_path: Union[str, os.PathLike]):
212
+ pretrained_model_path = Path(pretrained_model_path)
213
+ if pretrained_model_path.is_file():
214
+ comfy_single_file_state_dict = {}
215
+ with safe_open(pretrained_model_path, framework="pt", device="cpu") as f:
216
+ metadata = f.metadata()
217
+ for k in f.keys():
218
+ comfy_single_file_state_dict[k] = f.get_tensor(k)
219
+ configs = json.loads(metadata["config"])
220
+ config = configs["scheduler"]
221
+ del comfy_single_file_state_dict
222
+
223
+ elif pretrained_model_path.is_dir():
224
+ diffusers_noise_scheduler_config_path = (
225
+ pretrained_model_path / "scheduler" / "scheduler_config.json"
226
+ )
227
+
228
+ with open(diffusers_noise_scheduler_config_path, "r") as f:
229
+ scheduler_config = json.load(f)
230
+ hashable_config = make_hashable_key(scheduler_config)
231
+ if hashable_config in diffusers_and_ours_config_mapping:
232
+ config = diffusers_and_ours_config_mapping[hashable_config]
233
+ return RectifiedFlowScheduler.from_config(config)
234
+
235
+ def scale_model_input(
236
+ self, sample: torch.FloatTensor, timestep: Optional[int] = None
237
+ ) -> torch.FloatTensor:
238
+ # pylint: disable=unused-argument
239
+ """
240
+ Ensures interchangeability with schedulers that need to scale the denoising model input depending on the
241
+ current timestep.
242
+
243
+ Args:
244
+ sample (`torch.FloatTensor`): input sample
245
+ timestep (`int`, optional): current timestep
246
+
247
+ Returns:
248
+ `torch.FloatTensor`: scaled input sample
249
+ """
250
+ return sample
251
+
252
+ def step(
253
+ self,
254
+ model_output: torch.FloatTensor,
255
+ timestep: torch.FloatTensor,
256
+ sample: torch.FloatTensor,
257
+ eta: float = 0.0,
258
+ use_clipped_model_output: bool = False,
259
+ generator=None,
260
+ variance_noise: Optional[torch.FloatTensor] = None,
261
+ return_dict: bool = True,
262
+ ) -> Union[RectifiedFlowSchedulerOutput, Tuple]:
263
+ # pylint: disable=unused-argument
264
+ """
265
+ Predict the sample from the previous timestep by reversing the SDE. This function propagates the diffusion
266
+ process from the learned model outputs (most often the predicted noise).
267
+
268
+ Args:
269
+ model_output (`torch.FloatTensor`):
270
+ The direct output from learned diffusion model.
271
+ timestep (`float`):
272
+ The current discrete timestep in the diffusion chain.
273
+ sample (`torch.FloatTensor`):
274
+ A current instance of a sample created by the diffusion process.
275
+ eta (`float`):
276
+ The weight of noise for added noise in diffusion step.
277
+ use_clipped_model_output (`bool`, defaults to `False`):
278
+ If `True`, computes "corrected" `model_output` from the clipped predicted original sample. Necessary
279
+ because predicted original sample is clipped to [-1, 1] when `self.config.clip_sample` is `True`. If no
280
+ clipping has happened, "corrected" `model_output` would coincide with the one provided as input and
281
+ `use_clipped_model_output` has no effect.
282
+ generator (`torch.Generator`, *optional*):
283
+ A random number generator.
284
+ variance_noise (`torch.FloatTensor`):
285
+ Alternative to generating noise with `generator` by directly providing the noise for the variance
286
+ itself. Useful for methods such as [`CycleDiffusion`].
287
+ return_dict (`bool`, *optional*, defaults to `True`):
288
+ Whether or not to return a [`~schedulers.scheduling_ddim.DDIMSchedulerOutput`] or `tuple`.
289
+
290
+ Returns:
291
+ [`~schedulers.scheduling_utils.RectifiedFlowSchedulerOutput`] or `tuple`:
292
+ If return_dict is `True`, [`~schedulers.rf_scheduler.RectifiedFlowSchedulerOutput`] is returned,
293
+ otherwise a tuple is returned where the first element is the sample tensor.
294
+ """
295
+ if self.num_inference_steps is None:
296
+ raise ValueError(
297
+ "Number of inference steps is 'None', you need to run 'set_timesteps' after creating the scheduler"
298
+ )
299
+
300
+ if timestep.ndim == 0:
301
+ # Global timestep
302
+ current_index = (self.timesteps - timestep).abs().argmin()
303
+ dt = self.delta_timesteps.gather(0, current_index.unsqueeze(0))
304
+ else:
305
+ # Timestep per token
306
+ assert timestep.ndim == 2
307
+ current_index = (
308
+ (self.timesteps[:, None, None] - timestep[None]).abs().argmin(dim=0)
309
+ )
310
+ dt = self.delta_timesteps[current_index]
311
+ # Special treatment for zero timestep tokens - set dt to 0 so prev_sample = sample
312
+ dt = torch.where(timestep == 0.0, torch.zeros_like(dt), dt)[..., None]
313
+
314
+ prev_sample = sample - dt * model_output
315
+
316
+ if not return_dict:
317
+ return (prev_sample,)
318
+
319
+ return RectifiedFlowSchedulerOutput(prev_sample=prev_sample)
320
+
321
+ def add_noise(
322
+ self,
323
+ original_samples: torch.FloatTensor,
324
+ noise: torch.FloatTensor,
325
+ timesteps: torch.FloatTensor,
326
+ ) -> torch.FloatTensor:
327
+ sigmas = timesteps
328
+ sigmas = append_dims(sigmas, original_samples.ndim)
329
+ alphas = 1 - sigmas
330
+ noisy_samples = alphas * original_samples + sigmas * noise
331
+ return noisy_samples
ltx_video/utils/__init__.py ADDED
File without changes
ltx_video/utils/conditioning_method.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ from enum import Enum
2
+
3
+
4
+ class ConditioningMethod(Enum):
5
+ UNCONDITIONAL = "unconditional"
6
+ FIRST_FRAME = "first_frame"
ltx_video/utils/diffusers_config_mapping.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ def make_hashable_key(dict_key):
2
+ def convert_value(value):
3
+ if isinstance(value, list):
4
+ return tuple(value)
5
+ elif isinstance(value, dict):
6
+ return tuple(sorted((k, convert_value(v)) for k, v in value.items()))
7
+ else:
8
+ return value
9
+
10
+ return tuple(sorted((k, convert_value(v)) for k, v in dict_key.items()))
11
+
12
+
13
+ DIFFUSERS_SCHEDULER_CONFIG = {
14
+ "_class_name": "FlowMatchEulerDiscreteScheduler",
15
+ "_diffusers_version": "0.32.0.dev0",
16
+ "base_image_seq_len": 1024,
17
+ "base_shift": 0.95,
18
+ "invert_sigmas": False,
19
+ "max_image_seq_len": 4096,
20
+ "max_shift": 2.05,
21
+ "num_train_timesteps": 1000,
22
+ "shift": 1.0,
23
+ "shift_terminal": 0.1,
24
+ "use_beta_sigmas": False,
25
+ "use_dynamic_shifting": True,
26
+ "use_exponential_sigmas": False,
27
+ "use_karras_sigmas": False,
28
+ }
29
+ DIFFUSERS_TRANSFORMER_CONFIG = {
30
+ "_class_name": "LTXVideoTransformer3DModel",
31
+ "_diffusers_version": "0.32.0.dev0",
32
+ "activation_fn": "gelu-approximate",
33
+ "attention_bias": True,
34
+ "attention_head_dim": 64,
35
+ "attention_out_bias": True,
36
+ "caption_channels": 4096,
37
+ "cross_attention_dim": 2048,
38
+ "in_channels": 128,
39
+ "norm_elementwise_affine": False,
40
+ "norm_eps": 1e-06,
41
+ "num_attention_heads": 32,
42
+ "num_layers": 28,
43
+ "out_channels": 128,
44
+ "patch_size": 1,
45
+ "patch_size_t": 1,
46
+ "qk_norm": "rms_norm_across_heads",
47
+ }
48
+ DIFFUSERS_VAE_CONFIG = {
49
+ "_class_name": "AutoencoderKLLTXVideo",
50
+ "_diffusers_version": "0.32.0.dev0",
51
+ "block_out_channels": [128, 256, 512, 512],
52
+ "decoder_causal": False,
53
+ "encoder_causal": True,
54
+ "in_channels": 3,
55
+ "latent_channels": 128,
56
+ "layers_per_block": [4, 3, 3, 3, 4],
57
+ "out_channels": 3,
58
+ "patch_size": 4,
59
+ "patch_size_t": 1,
60
+ "resnet_norm_eps": 1e-06,
61
+ "scaling_factor": 1.0,
62
+ "spatio_temporal_scaling": [True, True, True, False],
63
+ }
64
+
65
+ OURS_SCHEDULER_CONFIG = {
66
+ "_class_name": "RectifiedFlowScheduler",
67
+ "_diffusers_version": "0.25.1",
68
+ "num_train_timesteps": 1000,
69
+ "shifting": "SD3",
70
+ "base_resolution": None,
71
+ "target_shift_terminal": 0.1,
72
+ }
73
+
74
+ OURS_TRANSFORMER_CONFIG = {
75
+ "_class_name": "Transformer3DModel",
76
+ "_diffusers_version": "0.25.1",
77
+ "_name_or_path": "PixArt-alpha/PixArt-XL-2-256x256",
78
+ "activation_fn": "gelu-approximate",
79
+ "attention_bias": True,
80
+ "attention_head_dim": 64,
81
+ "attention_type": "default",
82
+ "caption_channels": 4096,
83
+ "cross_attention_dim": 2048,
84
+ "double_self_attention": False,
85
+ "dropout": 0.0,
86
+ "in_channels": 128,
87
+ "norm_elementwise_affine": False,
88
+ "norm_eps": 1e-06,
89
+ "norm_num_groups": 32,
90
+ "num_attention_heads": 32,
91
+ "num_embeds_ada_norm": 1000,
92
+ "num_layers": 28,
93
+ "num_vector_embeds": None,
94
+ "only_cross_attention": False,
95
+ "out_channels": 128,
96
+ "project_to_2d_pos": True,
97
+ "upcast_attention": False,
98
+ "use_linear_projection": False,
99
+ "qk_norm": "rms_norm",
100
+ "standardization_norm": "rms_norm",
101
+ "positional_embedding_type": "rope",
102
+ "positional_embedding_theta": 10000.0,
103
+ "positional_embedding_max_pos": [20, 2048, 2048],
104
+ "timestep_scale_multiplier": 1000,
105
+ }
106
+ OURS_VAE_CONFIG = {
107
+ "_class_name": "CausalVideoAutoencoder",
108
+ "dims": 3,
109
+ "in_channels": 3,
110
+ "out_channels": 3,
111
+ "latent_channels": 128,
112
+ "blocks": [
113
+ ["res_x", 4],
114
+ ["compress_all", 1],
115
+ ["res_x_y", 1],
116
+ ["res_x", 3],
117
+ ["compress_all", 1],
118
+ ["res_x_y", 1],
119
+ ["res_x", 3],
120
+ ["compress_all", 1],
121
+ ["res_x", 3],
122
+ ["res_x", 4],
123
+ ],
124
+ "scaling_factor": 1.0,
125
+ "norm_layer": "pixel_norm",
126
+ "patch_size": 4,
127
+ "latent_log_var": "uniform",
128
+ "use_quant_conv": False,
129
+ "causal_decoder": False,
130
+ }
131
+
132
+
133
+ diffusers_and_ours_config_mapping = {
134
+ make_hashable_key(DIFFUSERS_SCHEDULER_CONFIG): OURS_SCHEDULER_CONFIG,
135
+ make_hashable_key(DIFFUSERS_TRANSFORMER_CONFIG): OURS_TRANSFORMER_CONFIG,
136
+ make_hashable_key(DIFFUSERS_VAE_CONFIG): OURS_VAE_CONFIG,
137
+ }
138
+
139
+
140
+ TRANSFORMER_KEYS_RENAME_DICT = {
141
+ "proj_in": "patchify_proj",
142
+ "time_embed": "adaln_single",
143
+ "norm_q": "q_norm",
144
+ "norm_k": "k_norm",
145
+ }
146
+
147
+
148
+ VAE_KEYS_RENAME_DICT = {
149
+ "decoder.up_blocks.3.conv_in": "decoder.up_blocks.7",
150
+ "decoder.up_blocks.3.upsamplers.0": "decoder.up_blocks.8",
151
+ "decoder.up_blocks.3": "decoder.up_blocks.9",
152
+ "decoder.up_blocks.2.upsamplers.0": "decoder.up_blocks.5",
153
+ "decoder.up_blocks.2.conv_in": "decoder.up_blocks.4",
154
+ "decoder.up_blocks.2": "decoder.up_blocks.6",
155
+ "decoder.up_blocks.1.upsamplers.0": "decoder.up_blocks.2",
156
+ "decoder.up_blocks.1": "decoder.up_blocks.3",
157
+ "decoder.up_blocks.0": "decoder.up_blocks.1",
158
+ "decoder.mid_block": "decoder.up_blocks.0",
159
+ "encoder.down_blocks.3": "encoder.down_blocks.8",
160
+ "encoder.down_blocks.2.downsamplers.0": "encoder.down_blocks.7",
161
+ "encoder.down_blocks.2": "encoder.down_blocks.6",
162
+ "encoder.down_blocks.1.downsamplers.0": "encoder.down_blocks.4",
163
+ "encoder.down_blocks.1.conv_out": "encoder.down_blocks.5",
164
+ "encoder.down_blocks.1": "encoder.down_blocks.3",
165
+ "encoder.down_blocks.0.conv_out": "encoder.down_blocks.2",
166
+ "encoder.down_blocks.0.downsamplers.0": "encoder.down_blocks.1",
167
+ "encoder.down_blocks.0": "encoder.down_blocks.0",
168
+ "encoder.mid_block": "encoder.down_blocks.9",
169
+ "conv_shortcut.conv": "conv_shortcut",
170
+ "resnets": "res_blocks",
171
+ "norm3": "norm3.norm",
172
+ "latents_mean": "per_channel_statistics.mean-of-means",
173
+ "latents_std": "per_channel_statistics.std-of-means",
174
+ }
ltx_video/utils/skip_layer_strategy.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ from enum import Enum, auto
2
+
3
+
4
+ class SkipLayerStrategy(Enum):
5
+ Attention = auto()
6
+ Residual = auto()
ltx_video/utils/torch_utils.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch import nn
3
+
4
+
5
+ def append_dims(x: torch.Tensor, target_dims: int) -> torch.Tensor:
6
+ """Appends dimensions to the end of a tensor until it has target_dims dimensions."""
7
+ dims_to_append = target_dims - x.ndim
8
+ if dims_to_append < 0:
9
+ raise ValueError(
10
+ f"input has {x.ndim} dims but target_dims is {target_dims}, which is less"
11
+ )
12
+ elif dims_to_append == 0:
13
+ return x
14
+ return x[(...,) + (None,) * dims_to_append]
15
+
16
+
17
+ class Identity(nn.Module):
18
+ """A placeholder identity operator that is argument-insensitive."""
19
+
20
+ def __init__(self, *args, **kwargs) -> None: # pylint: disable=unused-argument
21
+ super().__init__()
22
+
23
+ # pylint: disable=unused-argument
24
+ def forward(self, x: torch.Tensor, *args, **kwargs) -> torch.Tensor:
25
+ return x