Spaces:
Running on Zero
Running on Zero
diagnostics bootstrap: vendored worldcrafter package, deps, examples
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +7 -0
- LICENSE.txt +500 -0
- README.md +61 -7
- app.py +119 -0
- examples/I2V/00_cat_vac/actions.txt +9 -0
- examples/I2V/00_cat_vac/camera.npy +3 -0
- examples/I2V/00_cat_vac/image.png +3 -0
- examples/I2V/00_cat_vac/prompt.txt +1 -0
- examples/I2V/01_socrates/actions.txt +15 -0
- examples/I2V/01_socrates/camera.npy +3 -0
- examples/I2V/01_socrates/image.png +3 -0
- examples/I2V/01_socrates/prompt.txt +1 -0
- examples/I2V/02_chestnut/actions.txt +9 -0
- examples/I2V/02_chestnut/camera.npy +3 -0
- examples/I2V/02_chestnut/image.png +3 -0
- examples/I2V/02_chestnut/prompt.txt +1 -0
- examples/I2V/06_waterfall/actions.txt +6 -0
- examples/I2V/06_waterfall/camera.npy +3 -0
- examples/I2V/06_waterfall/image.png +3 -0
- examples/I2V/06_waterfall/prompt.txt +1 -0
- examples/I2V/10_case061/actions.txt +8 -0
- examples/I2V/10_case061/camera.npy +3 -0
- examples/I2V/10_case061/image.png +3 -0
- examples/I2V/10_case061/prompt.txt +1 -0
- examples/I2V/13_burrow/actions.txt +12 -0
- examples/I2V/13_burrow/camera.npy +3 -0
- examples/I2V/13_burrow/image.png +3 -0
- examples/I2V/13_burrow/prompt.txt +1 -0
- examples/I2V/15_case104/actions.txt +4 -0
- examples/I2V/15_case104/camera.npy +3 -0
- examples/I2V/15_case104/image.png +3 -0
- examples/I2V/15_case104/prompt.txt +1 -0
- examples/README.md +148 -0
- examples/T2V/00_red_balloon/actions.txt +12 -0
- examples/T2V/00_red_balloon/camera.npy +3 -0
- examples/T2V/00_red_balloon/prompt.txt +1 -0
- examples/T2V/01_t2v-mind131-00/actions.txt +8 -0
- examples/T2V/01_t2v-mind131-00/camera.npy +3 -0
- examples/T2V/01_t2v-mind131-00/prompt.txt +1 -0
- examples/T2V/02_tokyo_street/actions.txt +6 -0
- examples/T2V/02_tokyo_street/camera.npy +3 -0
- examples/T2V/02_tokyo_street/negative_prompt.txt +1 -0
- examples/T2V/02_tokyo_street/prompt.txt +1 -0
- examples/negative_prompt.txt +1 -0
- requirements.txt +18 -0
- worldcrafter/__init__.py +27 -0
- worldcrafter/camera.py +349 -0
- worldcrafter/cli.py +166 -0
- worldcrafter/diffusers/__init__.py +5 -0
- worldcrafter/diffusers/pipeline.py +1628 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,10 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
examples/I2V/00_cat_vac/image.png filter=lfs diff=lfs merge=lfs -text
|
| 37 |
+
examples/I2V/01_socrates/image.png filter=lfs diff=lfs merge=lfs -text
|
| 38 |
+
examples/I2V/02_chestnut/image.png filter=lfs diff=lfs merge=lfs -text
|
| 39 |
+
examples/I2V/06_waterfall/image.png filter=lfs diff=lfs merge=lfs -text
|
| 40 |
+
examples/I2V/10_case061/image.png filter=lfs diff=lfs merge=lfs -text
|
| 41 |
+
examples/I2V/13_burrow/image.png filter=lfs diff=lfs merge=lfs -text
|
| 42 |
+
examples/I2V/15_case104/image.png filter=lfs diff=lfs merge=lfs -text
|
LICENSE.txt
ADDED
|
@@ -0,0 +1,500 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Tencent is pleased to support the community by making WorldCrafter available.
|
| 2 |
+
|
| 3 |
+
Copyright (C) 2026 Tencent. All rights reserved.
|
| 4 |
+
|
| 5 |
+
The open-source software and/or model(s) included in this distribution may have been modified by Tencent ("Tencent Modifications"). All Tencent Modifications are Copyright (C) Tencent.
|
| 6 |
+
|
| 7 |
+
WorldCrafter is licensed under License Term of WorldCrafter, except for the third-party components listed below, which remain licensed under their respective original terms. WorldCrafter does not impose any additional restrictions beyond those specified in the original licenses of these third-party components. Users are required to comply with all applicable terms and conditions of the original licenses and to ensure that the use of these third-party components conforms to all relevant laws and regulations.
|
| 8 |
+
|
| 9 |
+
For the avoidance of doubt, WorldCrafter refers solely to code, parameters, and weights made publicly available by Tencent in accordance with License Term of WorldCrafter.
|
| 10 |
+
|
| 11 |
+
Terms of License Term of WorldCrafter:
|
| 12 |
+
--------------------------------------------------------------------
|
| 13 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, and /or sublicense copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
| 14 |
+
|
| 15 |
+
- You agree to use the WorldCrafter only for academic purposes, and refrain from using it for any commercial or production purposes under any circumstances.
|
| 16 |
+
|
| 17 |
+
- The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
| 18 |
+
|
| 19 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
Dependencies and Licenses:
|
| 23 |
+
|
| 24 |
+
This open-source project builds upon the following open-source model(s) and/or software, each of which remains licensed under its original license(s). Certain component(s) may include modifications made by Tencent ("Tencent Modifications"), which are Copyright (C) Tencent.
|
| 25 |
+
|
| 26 |
+
In case you believe there have been errors in the attribution below, you may submit the concerns to us for review and correction.
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
Open Source Model(s)/Software Licensed under the Apache-2.0:
|
| 30 |
+
--------------------------------------------------------------------
|
| 31 |
+
1. Helios-Base
|
| 32 |
+
Copyright (c) Helios-Base Original author and authors
|
| 33 |
+
Terms of the Apache-2.0:
|
| 34 |
+
--------------------------------------------------------------------
|
| 35 |
+
Apache License
|
| 36 |
+
Version 2.0, January 2004
|
| 37 |
+
http://www.apache.org/licenses/
|
| 38 |
+
|
| 39 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
| 40 |
+
|
| 41 |
+
1. Definitions.
|
| 42 |
+
|
| 43 |
+
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
|
| 44 |
+
|
| 45 |
+
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
|
| 46 |
+
|
| 47 |
+
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
|
| 48 |
+
|
| 49 |
+
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
|
| 50 |
+
|
| 51 |
+
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
|
| 52 |
+
|
| 53 |
+
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
|
| 54 |
+
|
| 55 |
+
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
|
| 56 |
+
|
| 57 |
+
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
|
| 58 |
+
|
| 59 |
+
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
|
| 60 |
+
|
| 61 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
|
| 62 |
+
|
| 63 |
+
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
|
| 64 |
+
|
| 65 |
+
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
|
| 66 |
+
|
| 67 |
+
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
|
| 68 |
+
|
| 69 |
+
You must give any other recipients of the Work or Derivative Works a copy of this License; and
|
| 70 |
+
You must cause any modified files to carry prominent notices stating that You changed the files; and
|
| 71 |
+
You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
|
| 72 |
+
If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
|
| 73 |
+
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
|
| 74 |
+
|
| 75 |
+
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
|
| 76 |
+
|
| 77 |
+
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
|
| 78 |
+
|
| 79 |
+
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
|
| 80 |
+
|
| 81 |
+
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
|
| 82 |
+
|
| 83 |
+
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
|
| 84 |
+
|
| 85 |
+
END OF TERMS AND CONDITIONS
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
Open Source Model(s)/Software Licensed under the CC-BY-NC-4.0:
|
| 92 |
+
--------------------------------------------------------------------
|
| 93 |
+
1. VGGT
|
| 94 |
+
Copyright (c) VGGT Original author and authors
|
| 95 |
+
Please note this software has been modified by Tencent in this distribution.
|
| 96 |
+
You may find the original code here: https://huggingface.co/facebook/VGGT-1B
|
| 97 |
+
Terms of the CC-BY-NC-4.0:
|
| 98 |
+
--------------------------------------------------------------------
|
| 99 |
+
Attribution-NonCommercial 4.0 International
|
| 100 |
+
|
| 101 |
+
=======================================================================
|
| 102 |
+
|
| 103 |
+
Creative Commons Corporation ("Creative Commons") is not a law firm and
|
| 104 |
+
does not provide legal services or legal advice. Distribution of
|
| 105 |
+
Creative Commons public licenses does not create a lawyer-client or
|
| 106 |
+
other relationship. Creative Commons makes its licenses and related
|
| 107 |
+
information available on an "as-is" basis. Creative Commons gives no
|
| 108 |
+
warranties regarding its licenses, any material licensed under their
|
| 109 |
+
terms and conditions, or any related information. Creative Commons
|
| 110 |
+
disclaims all liability for damages resulting from their use to the
|
| 111 |
+
fullest extent possible.
|
| 112 |
+
|
| 113 |
+
Using Creative Commons Public Licenses
|
| 114 |
+
|
| 115 |
+
Creative Commons public licenses provide a standard set of terms and
|
| 116 |
+
conditions that creators and other rights holders may use to share
|
| 117 |
+
original works of authorship and other material subject to copyright
|
| 118 |
+
and certain other rights specified in the public license below. The
|
| 119 |
+
following considerations are for informational purposes only, are not
|
| 120 |
+
exhaustive, and do not form part of our licenses.
|
| 121 |
+
|
| 122 |
+
Considerations for licensors: Our public licenses are
|
| 123 |
+
intended for use by those authorized to give the public
|
| 124 |
+
permission to use material in ways otherwise restricted by
|
| 125 |
+
copyright and certain other rights. Our licenses are
|
| 126 |
+
irrevocable. Licensors should read and understand the terms
|
| 127 |
+
and conditions of the license they choose before applying it.
|
| 128 |
+
Licensors should also secure all rights necessary before
|
| 129 |
+
applying our licenses so that the public can reuse the
|
| 130 |
+
material as expected. Licensors should clearly mark any
|
| 131 |
+
material not subject to the license. This includes other CC-
|
| 132 |
+
licensed material, or material used under an exception or
|
| 133 |
+
limitation to copyright. More considerations for licensors:
|
| 134 |
+
wiki.creativecommons.org/Considerations_for_licensors
|
| 135 |
+
|
| 136 |
+
Considerations for the public: By using one of our public
|
| 137 |
+
licenses, a licensor grants the public permission to use the
|
| 138 |
+
licensed material under specified terms and conditions. If
|
| 139 |
+
the licensor's permission is not necessary for any reason--for
|
| 140 |
+
example, because of any applicable exception or limitation to
|
| 141 |
+
copyright--then that use is not regulated by the license. Our
|
| 142 |
+
licenses grant only permissions under copyright and certain
|
| 143 |
+
other rights that a licensor has authority to grant. Use of
|
| 144 |
+
the licensed material may still be restricted for other
|
| 145 |
+
reasons, including because others have copyright or other
|
| 146 |
+
rights in the material. A licensor may make special requests,
|
| 147 |
+
such as asking that all changes be marked or described.
|
| 148 |
+
Although not required by our licenses, you are encouraged to
|
| 149 |
+
respect those requests where reasonable. More_considerations
|
| 150 |
+
for the public:
|
| 151 |
+
wiki.creativecommons.org/Considerations_for_licensees
|
| 152 |
+
|
| 153 |
+
=======================================================================
|
| 154 |
+
|
| 155 |
+
Creative Commons Attribution-NonCommercial 4.0 International Public
|
| 156 |
+
License
|
| 157 |
+
|
| 158 |
+
By exercising the Licensed Rights (defined below), You accept and agree
|
| 159 |
+
to be bound by the terms and conditions of this Creative Commons
|
| 160 |
+
Attribution-NonCommercial 4.0 International Public License ("Public
|
| 161 |
+
License"). To the extent this Public License may be interpreted as a
|
| 162 |
+
contract, You are granted the Licensed Rights in consideration of Your
|
| 163 |
+
acceptance of these terms and conditions, and the Licensor grants You
|
| 164 |
+
such rights in consideration of benefits the Licensor receives from
|
| 165 |
+
making the Licensed Material available under these terms and
|
| 166 |
+
conditions.
|
| 167 |
+
|
| 168 |
+
Section 1 -- Definitions.
|
| 169 |
+
|
| 170 |
+
a. Adapted Material means material subject to Copyright and Similar
|
| 171 |
+
Rights that is derived from or based upon the Licensed Material
|
| 172 |
+
and in which the Licensed Material is translated, altered,
|
| 173 |
+
arranged, transformed, or otherwise modified in a manner requiring
|
| 174 |
+
permission under the Copyright and Similar Rights held by the
|
| 175 |
+
Licensor. For purposes of this Public License, where the Licensed
|
| 176 |
+
Material is a musical work, performance, or sound recording,
|
| 177 |
+
Adapted Material is always produced where the Licensed Material is
|
| 178 |
+
synched in timed relation with a moving image.
|
| 179 |
+
|
| 180 |
+
b. Adapter's License means the license You apply to Your Copyright
|
| 181 |
+
and Similar Rights in Your contributions to Adapted Material in
|
| 182 |
+
accordance with the terms and conditions of this Public License.
|
| 183 |
+
|
| 184 |
+
c. Copyright and Similar Rights means copyright and/or similar rights
|
| 185 |
+
closely related to copyright including, without limitation,
|
| 186 |
+
performance, broadcast, sound recording, and Sui Generis Database
|
| 187 |
+
Rights, without regard to how the rights are labeled or
|
| 188 |
+
categorized. For purposes of this Public License, the rights
|
| 189 |
+
specified in Section 2(b)(1)-(2) are not Copyright and Similar
|
| 190 |
+
Rights.
|
| 191 |
+
d. Effective Technological Measures means those measures that, in the
|
| 192 |
+
absence of proper authority, may not be circumvented under laws
|
| 193 |
+
fulfilling obligations under Article 11 of the WIPO Copyright
|
| 194 |
+
Treaty adopted on December 20, 1996, and/or similar international
|
| 195 |
+
agreements.
|
| 196 |
+
|
| 197 |
+
e. Exceptions and Limitations means fair use, fair dealing, and/or
|
| 198 |
+
any other exception or limitation to Copyright and Similar Rights
|
| 199 |
+
that applies to Your use of the Licensed Material.
|
| 200 |
+
|
| 201 |
+
f. Licensed Material means the artistic or literary work, database,
|
| 202 |
+
or other material to which the Licensor applied this Public
|
| 203 |
+
License.
|
| 204 |
+
|
| 205 |
+
g. Licensed Rights means the rights granted to You subject to the
|
| 206 |
+
terms and conditions of this Public License, which are limited to
|
| 207 |
+
all Copyright and Similar Rights that apply to Your use of the
|
| 208 |
+
Licensed Material and that the Licensor has authority to license.
|
| 209 |
+
|
| 210 |
+
h. Licensor means the individual(s) or entity(ies) granting rights
|
| 211 |
+
under this Public License.
|
| 212 |
+
|
| 213 |
+
i. NonCommercial means not primarily intended for or directed towards
|
| 214 |
+
commercial advantage or monetary compensation. For purposes of
|
| 215 |
+
this Public License, the exchange of the Licensed Material for
|
| 216 |
+
other material subject to Copyright and Similar Rights by digital
|
| 217 |
+
file-sharing or similar means is NonCommercial provided there is
|
| 218 |
+
no payment of monetary compensation in connection with the
|
| 219 |
+
exchange.
|
| 220 |
+
|
| 221 |
+
j. Share means to provide material to the public by any means or
|
| 222 |
+
process that requires permission under the Licensed Rights, such
|
| 223 |
+
as reproduction, public display, public performance, distribution,
|
| 224 |
+
dissemination, communication, or importation, and to make material
|
| 225 |
+
available to the public including in ways that members of the
|
| 226 |
+
public may access the material from a place and at a time
|
| 227 |
+
individually chosen by them.
|
| 228 |
+
|
| 229 |
+
k. Sui Generis Database Rights means rights other than copyright
|
| 230 |
+
resulting from Directive 96/9/EC of the European Parliament and of
|
| 231 |
+
the Council of 11 March 1996 on the legal protection of databases,
|
| 232 |
+
as amended and/or succeeded, as well as other essentially
|
| 233 |
+
equivalent rights anywhere in the world.
|
| 234 |
+
|
| 235 |
+
l. You means the individual or entity exercising the Licensed Rights
|
| 236 |
+
under this Public License. Your has a corresponding meaning.
|
| 237 |
+
|
| 238 |
+
Section 2 -- Scope.
|
| 239 |
+
|
| 240 |
+
a. License grant.
|
| 241 |
+
|
| 242 |
+
1. Subject to the terms and conditions of this Public License,
|
| 243 |
+
the Licensor hereby grants You a worldwide, royalty-free,
|
| 244 |
+
non-sublicensable, non-exclusive, irrevocable license to
|
| 245 |
+
exercise the Licensed Rights in the Licensed Material to:
|
| 246 |
+
|
| 247 |
+
a. reproduce and Share the Licensed Material, in whole or
|
| 248 |
+
in part, for NonCommercial purposes only; and
|
| 249 |
+
|
| 250 |
+
b. produce, reproduce, and Share Adapted Material for
|
| 251 |
+
NonCommercial purposes only.
|
| 252 |
+
|
| 253 |
+
2. Exceptions and Limitations. For the avoidance of doubt, where
|
| 254 |
+
Exceptions and Limitations apply to Your use, this Public
|
| 255 |
+
License does not apply, and You do not need to comply with
|
| 256 |
+
its terms and conditions.
|
| 257 |
+
|
| 258 |
+
3. Term. The term of this Public License is specified in Section
|
| 259 |
+
6(a).
|
| 260 |
+
|
| 261 |
+
4. Media and formats; technical modifications allowed. The
|
| 262 |
+
Licensor authorizes You to exercise the Licensed Rights in
|
| 263 |
+
all media and formats whether now known or hereafter created,
|
| 264 |
+
and to make technical modifications necessary to do so. The
|
| 265 |
+
Licensor waives and/or agrees not to assert any right or
|
| 266 |
+
authority to forbid You from making technical modifications
|
| 267 |
+
necessary to exercise the Licensed Rights, including
|
| 268 |
+
technical modifications necessary to circumvent Effective
|
| 269 |
+
Technological Measures. For purposes of this Public License,
|
| 270 |
+
simply making modifications authorized by this Section 2(a)
|
| 271 |
+
(4) never produces Adapted Material.
|
| 272 |
+
|
| 273 |
+
5. Downstream recipients.
|
| 274 |
+
|
| 275 |
+
a. Offer from the Licensor -- Licensed Material. Every
|
| 276 |
+
recipient of the Licensed Material automatically
|
| 277 |
+
receives an offer from the Licensor to exercise the
|
| 278 |
+
Licensed Rights under the terms and conditions of this
|
| 279 |
+
Public License.
|
| 280 |
+
|
| 281 |
+
b. No downstream restrictions. You may not offer or impose
|
| 282 |
+
any additional or different terms or conditions on, or
|
| 283 |
+
apply any Effective Technological Measures to, the
|
| 284 |
+
Licensed Material if doing so restricts exercise of the
|
| 285 |
+
Licensed Rights by any recipient of the Licensed
|
| 286 |
+
Material.
|
| 287 |
+
|
| 288 |
+
6. No endorsement. Nothing in this Public License constitutes or
|
| 289 |
+
may be construed as permission to assert or imply that You
|
| 290 |
+
are, or that Your use of the Licensed Material is, connected
|
| 291 |
+
with, or sponsored, endorsed, or granted official status by,
|
| 292 |
+
the Licensor or others designated to receive attribution as
|
| 293 |
+
provided in Section 3(a)(1)(A)(i).
|
| 294 |
+
|
| 295 |
+
b. Other rights.
|
| 296 |
+
|
| 297 |
+
1. Moral rights, such as the right of integrity, are not
|
| 298 |
+
licensed under this Public License, nor are publicity,
|
| 299 |
+
privacy, and/or other similar personality rights; however, to
|
| 300 |
+
the extent possible, the Licensor waives and/or agrees not to
|
| 301 |
+
assert any such rights held by the Licensor to the limited
|
| 302 |
+
extent necessary to allow You to exercise the Licensed
|
| 303 |
+
Rights, but not otherwise.
|
| 304 |
+
|
| 305 |
+
2. Patent and trademark rights are not licensed under this
|
| 306 |
+
Public License.
|
| 307 |
+
|
| 308 |
+
3. To the extent possible, the Licensor waives any right to
|
| 309 |
+
collect royalties from You for the exercise of the Licensed
|
| 310 |
+
Rights, whether directly or through a collecting society
|
| 311 |
+
under any voluntary or waivable statutory or compulsory
|
| 312 |
+
licensing scheme. In all other cases the Licensor expressly
|
| 313 |
+
reserves any right to collect such royalties, including when
|
| 314 |
+
the Licensed Material is used other than for NonCommercial
|
| 315 |
+
purposes.
|
| 316 |
+
|
| 317 |
+
Section 3 -- License Conditions.
|
| 318 |
+
|
| 319 |
+
Your exercise of the Licensed Rights is expressly made subject to the
|
| 320 |
+
following conditions.
|
| 321 |
+
|
| 322 |
+
a. Attribution.
|
| 323 |
+
|
| 324 |
+
1. If You Share the Licensed Material (including in modified
|
| 325 |
+
form), You must:
|
| 326 |
+
|
| 327 |
+
a. retain the following if it is supplied by the Licensor
|
| 328 |
+
with the Licensed Material:
|
| 329 |
+
|
| 330 |
+
i. identification of the creator(s) of the Licensed
|
| 331 |
+
Material and any others designated to receive
|
| 332 |
+
attribution, in any reasonable manner requested by
|
| 333 |
+
the Licensor (including by pseudonym if
|
| 334 |
+
designated);
|
| 335 |
+
|
| 336 |
+
ii. a copyright notice;
|
| 337 |
+
|
| 338 |
+
iii. a notice that refers to this Public License;
|
| 339 |
+
|
| 340 |
+
iv. a notice that refers to the disclaimer of
|
| 341 |
+
warranties;
|
| 342 |
+
|
| 343 |
+
v. a URI or hyperlink to the Licensed Material to the
|
| 344 |
+
extent reasonably practicable;
|
| 345 |
+
|
| 346 |
+
b. indicate if You modified the Licensed Material and
|
| 347 |
+
retain an indication of any previous modifications; and
|
| 348 |
+
|
| 349 |
+
c. indicate the Licensed Material is licensed under this
|
| 350 |
+
Public License, and include the text of, or the URI or
|
| 351 |
+
hyperlink to, this Public License.
|
| 352 |
+
|
| 353 |
+
2. You may satisfy the conditions in Section 3(a)(1) in any
|
| 354 |
+
reasonable manner based on the medium, means, and context in
|
| 355 |
+
which You Share the Licensed Material. For example, it may be
|
| 356 |
+
reasonable to satisfy the conditions by providing a URI or
|
| 357 |
+
hyperlink to a resource that includes the required
|
| 358 |
+
information.
|
| 359 |
+
|
| 360 |
+
3. If requested by the Licensor, You must remove any of the
|
| 361 |
+
information required by Section 3(a)(1)(A) to the extent
|
| 362 |
+
reasonably practicable.
|
| 363 |
+
|
| 364 |
+
4. If You Share Adapted Material You produce, the Adapter's
|
| 365 |
+
License You apply must not prevent recipients of the Adapted
|
| 366 |
+
Material from complying with this Public License.
|
| 367 |
+
|
| 368 |
+
Section 4 -- Sui Generis Database Rights.
|
| 369 |
+
|
| 370 |
+
Where the Licensed Rights include Sui Generis Database Rights that
|
| 371 |
+
apply to Your use of the Licensed Material:
|
| 372 |
+
|
| 373 |
+
a. for the avoidance of doubt, Section 2(a)(1) grants You the right
|
| 374 |
+
to extract, reuse, reproduce, and Share all or a substantial
|
| 375 |
+
portion of the contents of the database for NonCommercial purposes
|
| 376 |
+
only;
|
| 377 |
+
|
| 378 |
+
b. if You include all or a substantial portion of the database
|
| 379 |
+
contents in a database in which You have Sui Generis Database
|
| 380 |
+
Rights, then the database in which You have Sui Generis Database
|
| 381 |
+
Rights (but not its individual contents) is Adapted Material; and
|
| 382 |
+
|
| 383 |
+
c. You must comply with the conditions in Section 3(a) if You Share
|
| 384 |
+
all or a substantial portion of the contents of the database.
|
| 385 |
+
|
| 386 |
+
For the avoidance of doubt, this Section 4 supplements and does not
|
| 387 |
+
replace Your obligations under this Public License where the Licensed
|
| 388 |
+
Rights include other Copyright and Similar Rights.
|
| 389 |
+
|
| 390 |
+
Section 5 -- Disclaimer of Warranties and Limitation of Liability.
|
| 391 |
+
|
| 392 |
+
a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
|
| 393 |
+
EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
|
| 394 |
+
AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
|
| 395 |
+
ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
|
| 396 |
+
IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
|
| 397 |
+
WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
|
| 398 |
+
PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
|
| 399 |
+
ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
|
| 400 |
+
KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
|
| 401 |
+
ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
|
| 402 |
+
|
| 403 |
+
b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
|
| 404 |
+
TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
|
| 405 |
+
NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
|
| 406 |
+
INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
|
| 407 |
+
COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
|
| 408 |
+
USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
|
| 409 |
+
ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
|
| 410 |
+
DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
|
| 411 |
+
IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
|
| 412 |
+
|
| 413 |
+
c. The disclaimer of warranties and limitation of liability provided
|
| 414 |
+
above shall be interpreted in a manner that, to the extent
|
| 415 |
+
possible, most closely approximates an absolute disclaimer and
|
| 416 |
+
waiver of all liability.
|
| 417 |
+
|
| 418 |
+
Section 6 -- Term and Termination.
|
| 419 |
+
|
| 420 |
+
a. This Public License applies for the term of the Copyright and
|
| 421 |
+
Similar Rights licensed here. However, if You fail to comply with
|
| 422 |
+
this Public License, then Your rights under this Public License
|
| 423 |
+
terminate automatically.
|
| 424 |
+
|
| 425 |
+
b. Where Your right to use the Licensed Material has terminated under
|
| 426 |
+
Section 6(a), it reinstates:
|
| 427 |
+
|
| 428 |
+
1. automatically as of the date the violation is cured, provided
|
| 429 |
+
it is cured within 30 days of Your discovery of the
|
| 430 |
+
violation; or
|
| 431 |
+
|
| 432 |
+
2. upon express reinstatement by the Licensor.
|
| 433 |
+
|
| 434 |
+
For the avoidance of doubt, this Section 6(b) does not affect any
|
| 435 |
+
right the Licensor may have to seek remedies for Your violations
|
| 436 |
+
of this Public License.
|
| 437 |
+
|
| 438 |
+
c. For the avoidance of doubt, the Licensor may also offer the
|
| 439 |
+
Licensed Material under separate terms or conditions or stop
|
| 440 |
+
distributing the Licensed Material at any time; however, doing so
|
| 441 |
+
will not terminate this Public License.
|
| 442 |
+
|
| 443 |
+
d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
|
| 444 |
+
License.
|
| 445 |
+
|
| 446 |
+
Section 7 -- Other Terms and Conditions.
|
| 447 |
+
|
| 448 |
+
a. The Licensor shall not be bound by any additional or different
|
| 449 |
+
terms or conditions communicated by You unless expressly agreed.
|
| 450 |
+
|
| 451 |
+
b. Any arrangements, understandings, or agreements regarding the
|
| 452 |
+
Licensed Material not stated herein are separate from and
|
| 453 |
+
independent of the terms and conditions of this Public License.
|
| 454 |
+
|
| 455 |
+
Section 8 -- Interpretation.
|
| 456 |
+
|
| 457 |
+
a. For the avoidance of doubt, this Public License does not, and
|
| 458 |
+
shall not be interpreted to, reduce, limit, restrict, or impose
|
| 459 |
+
conditions on any use of the Licensed Material that could lawfully
|
| 460 |
+
be made without permission under this Public License.
|
| 461 |
+
|
| 462 |
+
b. To the extent possible, if any provision of this Public License is
|
| 463 |
+
deemed unenforceable, it shall be automatically reformed to the
|
| 464 |
+
minimum extent necessary to make it enforceable. If the provision
|
| 465 |
+
cannot be reformed, it shall be severed from this Public License
|
| 466 |
+
without affecting the enforceability of the remaining terms and
|
| 467 |
+
conditions.
|
| 468 |
+
|
| 469 |
+
c. No term or condition of this Public License will be waived and no
|
| 470 |
+
failure to comply consented to unless expressly agreed to by the
|
| 471 |
+
Licensor.
|
| 472 |
+
|
| 473 |
+
d. Nothing in this Public License constitutes or may be interpreted
|
| 474 |
+
as a limitation upon, or waiver of, any privileges and immunities
|
| 475 |
+
that apply to the Licensor or You, including from the legal
|
| 476 |
+
processes of any jurisdiction or authority.
|
| 477 |
+
|
| 478 |
+
=======================================================================
|
| 479 |
+
|
| 480 |
+
Creative Commons is not a party to its public
|
| 481 |
+
licenses. Notwithstanding, Creative Commons may elect to apply one of
|
| 482 |
+
its public licenses to material it publishes and in those instances
|
| 483 |
+
will be considered the “Licensor.” The text of the Creative Commons
|
| 484 |
+
public licenses is dedicated to the public domain under the CC0 Public
|
| 485 |
+
Domain Dedication. Except for the limited purpose of indicating that
|
| 486 |
+
material is shared under a Creative Commons public license or as
|
| 487 |
+
otherwise permitted by the Creative Commons policies published at
|
| 488 |
+
creativecommons.org/policies, Creative Commons does not authorize the
|
| 489 |
+
use of the trademark "Creative Commons" or any other trademark or logo
|
| 490 |
+
of Creative Commons without its prior written consent including,
|
| 491 |
+
without limitation, in connection with any unauthorized modifications
|
| 492 |
+
to any of its public licenses or any other arrangements,
|
| 493 |
+
understandings, or agreements concerning use of licensed material. For
|
| 494 |
+
the avoidance of doubt, this paragraph does not form part of the
|
| 495 |
+
public licenses.
|
| 496 |
+
|
| 497 |
+
Creative Commons may be contacted at creativecommons.org.
|
| 498 |
+
|
| 499 |
+
==================================================
|
| 500 |
+
End of the Attribution Notice of this project.
|
README.md
CHANGED
|
@@ -1,13 +1,67 @@
|
|
| 1 |
---
|
| 2 |
-
title:
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
-
colorTo:
|
| 6 |
sdk: gradio
|
| 7 |
sdk_version: 6.28.0
|
| 8 |
-
python_version: '3.12'
|
| 9 |
app_file: app.py
|
| 10 |
-
|
|
|
|
|
|
|
| 11 |
---
|
| 12 |
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
+
title: WorldCrafter
|
| 3 |
+
emoji: 🌍
|
| 4 |
+
colorFrom: gray
|
| 5 |
+
colorTo: red
|
| 6 |
sdk: gradio
|
| 7 |
sdk_version: 6.28.0
|
|
|
|
| 8 |
app_file: app.py
|
| 9 |
+
python_version: "3.12"
|
| 10 |
+
startup_duration_timeout: 1h
|
| 11 |
+
short_description: Camera-controlled video world model with 3D-aware memory
|
| 12 |
---
|
| 13 |
|
| 14 |
+
# WorldCrafter: Consistent Video World Model with Implicit 3D-aware Memory
|
| 15 |
+
|
| 16 |
+
Interactive demo of [`TencentARC/WorldCrafter-Fast`](https://huggingface.co/TencentARC/WorldCrafter-Fast) —
|
| 17 |
+
the distilled 6-step variant of WorldCrafter. Give it a start image (or just a prompt) plus a
|
| 18 |
+
camera action script, and it explores the scene, keeping geometry consistent across chunks
|
| 19 |
+
through a camera-queryable implicit 3D-aware memory.
|
| 20 |
+
|
| 21 |
+
- Paper: https://huggingface.co/papers/2609.24984
|
| 22 |
+
- Code: https://github.com/TencentARC/WorldCrafter
|
| 23 |
+
- Weights: [`WorldCrafter-Fast`](https://huggingface.co/TencentARC/WorldCrafter-Fast) (distilled, 6 steps, CFG 1.0)
|
| 24 |
+
|
| 25 |
+
Output is 384×640 at 16 fps, generated in 33-frame chunks.
|
| 26 |
+
|
| 27 |
+
## Camera actions
|
| 28 |
+
|
| 29 |
+
One action per chunk, e.g.
|
| 30 |
+
|
| 31 |
+
```
|
| 32 |
+
forward1x2
|
| 33 |
+
yaw_left30x3
|
| 34 |
+
backward1
|
| 35 |
+
```
|
| 36 |
+
|
| 37 |
+
| Movement | Actions | Short forms |
|
| 38 |
+
| --- | --- | --- |
|
| 39 |
+
| Forward / backward | `forward1`, `backward1` | `f1`, `b1` |
|
| 40 |
+
| Left / right | `left1`, `right1` | `l1`, `r1` |
|
| 41 |
+
| Up / down | `up1`, `down1` | same |
|
| 42 |
+
| Turn left / right | `yaw_left30`, `yaw_right30` | `yl30`, `yr30` |
|
| 43 |
+
| Look up / down | `pitch_up15`, `pitch_down15` | `pu15`, `pd15` |
|
| 44 |
+
|
| 45 |
+
`xN` repeats an action, `&` combines movement and rotation in one chunk
|
| 46 |
+
(`forward2&right2&yaw_left45`), `reverseN` retraces the previous N chunks. Keep total
|
| 47 |
+
translation per chunk at or below 5. Optional headers `@dtype`, `@sampling`, `@last_frame`
|
| 48 |
+
must precede the actions.
|
| 49 |
+
|
| 50 |
+
## Credits and license
|
| 51 |
+
|
| 52 |
+
Model, example images, prompts and camera scripts are from the official
|
| 53 |
+
[WorldCrafter repository](https://github.com/TencentARC/WorldCrafter) and are redistributed
|
| 54 |
+
here under the WorldCrafter license (see `LICENSE.txt`), which permits copying and
|
| 55 |
+
distribution **for academic purposes only**. The underlying Helios-Base components are
|
| 56 |
+
Apache-2.0. Copyright (C) 2026 THL A29 Limited, a Tencent company.
|
| 57 |
+
|
| 58 |
+
```bibtex
|
| 59 |
+
@article{yu2026worldcrafter,
|
| 60 |
+
title = {WorldCrafter: Consistent Video World Model with Implicit 3D-aware Memory},
|
| 61 |
+
author = {Yu, Wangbo and Liu, Kunhao and Hu, Wenbo and Yuan, Shenghai and Feng, Chaoran
|
| 62 |
+
and Zhou, Haiyang and Huang, Yukun and Wang, Yiran and Zhao, Wang
|
| 63 |
+
and Luo, Yingmin and Shan, Ying},
|
| 64 |
+
journal = {arXiv preprint arXiv:2609.24984},
|
| 65 |
+
year = {2026}
|
| 66 |
+
}
|
| 67 |
+
```
|
app.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
|
| 3 |
+
os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")
|
| 4 |
+
|
| 5 |
+
import spaces # noqa: E402 (must precede torch)
|
| 6 |
+
import torch # noqa: E402
|
| 7 |
+
import gradio as gr # noqa: E402
|
| 8 |
+
|
| 9 |
+
import shutil
|
| 10 |
+
import subprocess
|
| 11 |
+
import sys
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def _diagnostics() -> str:
|
| 15 |
+
lines = [f"python: {sys.version}"]
|
| 16 |
+
for name in (
|
| 17 |
+
"torch",
|
| 18 |
+
"triton",
|
| 19 |
+
"diffusers",
|
| 20 |
+
"transformers",
|
| 21 |
+
"peft",
|
| 22 |
+
"accelerate",
|
| 23 |
+
"numpy",
|
| 24 |
+
"timm",
|
| 25 |
+
"kernels",
|
| 26 |
+
"imageio",
|
| 27 |
+
"huggingface_hub",
|
| 28 |
+
"gradio",
|
| 29 |
+
"spaces",
|
| 30 |
+
):
|
| 31 |
+
try:
|
| 32 |
+
mod = __import__(name)
|
| 33 |
+
lines.append(f"{name}: {getattr(mod, '__version__', '?')}")
|
| 34 |
+
except Exception as exc: # noqa: BLE001
|
| 35 |
+
lines.append(f"{name}: IMPORT FAILED {exc!r}")
|
| 36 |
+
|
| 37 |
+
lines.append("")
|
| 38 |
+
lines.append(f"cpu_count: {os.cpu_count()}")
|
| 39 |
+
lines.append(f"HF_HOME={os.environ.get('HF_HOME')}")
|
| 40 |
+
lines.append(f"HF_HUB_CACHE={os.environ.get('HF_HUB_CACHE')}")
|
| 41 |
+
lines.append(f"torch.cuda.is_available(): {torch.cuda.is_available()}")
|
| 42 |
+
|
| 43 |
+
lines.append("")
|
| 44 |
+
for path in ("/", "/tmp", "/home/user", "/data", os.getcwd()):
|
| 45 |
+
try:
|
| 46 |
+
total, used, free = shutil.disk_usage(path)
|
| 47 |
+
lines.append(
|
| 48 |
+
f"disk {path}: total={total / 2**30:.1f}G "
|
| 49 |
+
f"used={used / 2**30:.1f}G free={free / 2**30:.1f}G"
|
| 50 |
+
)
|
| 51 |
+
except Exception as exc: # noqa: BLE001
|
| 52 |
+
lines.append(f"disk {path}: {exc!r}")
|
| 53 |
+
|
| 54 |
+
for cmd in (["df", "-h"], ["free", "-g"]):
|
| 55 |
+
try:
|
| 56 |
+
out = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
|
| 57 |
+
lines.append("")
|
| 58 |
+
lines.append(f"$ {' '.join(cmd)}\n{out.stdout}{out.stderr}")
|
| 59 |
+
except Exception as exc: # noqa: BLE001
|
| 60 |
+
lines.append(f"{' '.join(cmd)}: {exc!r}")
|
| 61 |
+
|
| 62 |
+
lines.append("")
|
| 63 |
+
try:
|
| 64 |
+
with open("/sys/fs/cgroup/memory.max") as fh:
|
| 65 |
+
lines.append(f"cgroup memory.max: {fh.read().strip()}")
|
| 66 |
+
except Exception as exc: # noqa: BLE001
|
| 67 |
+
lines.append(f"cgroup memory.max: {exc!r}")
|
| 68 |
+
|
| 69 |
+
lines.append("")
|
| 70 |
+
try:
|
| 71 |
+
from worldcrafter import WorldCrafter # noqa: F401
|
| 72 |
+
|
| 73 |
+
lines.append("import worldcrafter: OK")
|
| 74 |
+
except Exception as exc: # noqa: BLE001
|
| 75 |
+
import traceback
|
| 76 |
+
|
| 77 |
+
lines.append(f"import worldcrafter: FAILED {exc!r}\n{traceback.format_exc()}")
|
| 78 |
+
|
| 79 |
+
try:
|
| 80 |
+
from worldcrafter.fast.resident import ResidentBranches # noqa: F401
|
| 81 |
+
|
| 82 |
+
lines.append("import worldcrafter.fast.resident (triton): OK")
|
| 83 |
+
except Exception as exc: # noqa: BLE001
|
| 84 |
+
lines.append(f"import worldcrafter.fast.resident: FAILED {exc!r}")
|
| 85 |
+
|
| 86 |
+
try:
|
| 87 |
+
from worldcrafter.camera import build_trajectory, parse_trajectory
|
| 88 |
+
|
| 89 |
+
events, options = parse_trajectory("forward1x2\nyaw_left30")
|
| 90 |
+
camera, records = build_trajectory(events, **options)
|
| 91 |
+
lines.append(
|
| 92 |
+
f"camera smoke: events={events} camera={camera.shape} chunks={len(records)}"
|
| 93 |
+
)
|
| 94 |
+
except Exception as exc: # noqa: BLE001
|
| 95 |
+
import traceback
|
| 96 |
+
|
| 97 |
+
lines.append(f"camera smoke: FAILED {exc!r}\n{traceback.format_exc()}")
|
| 98 |
+
|
| 99 |
+
return "\n".join(lines)
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
REPORT = _diagnostics()
|
| 103 |
+
print("==== WORLDCRAFTER SPACE DIAGNOSTICS ====", flush=True)
|
| 104 |
+
print(REPORT, flush=True)
|
| 105 |
+
print("==== END DIAGNOSTICS ====", flush=True)
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def report() -> str:
|
| 109 |
+
"""Return the environment diagnostics collected at startup."""
|
| 110 |
+
return REPORT
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
with gr.Blocks(theme=gr.themes.Citrus(), title="WorldCrafter (provisioning)") as demo:
|
| 114 |
+
gr.Markdown("# WorldCrafter — provisioning\nEnvironment diagnostics:")
|
| 115 |
+
out = gr.Textbox(value=REPORT, lines=40, label="diagnostics")
|
| 116 |
+
gr.Button("Refresh").click(fn=report, inputs=None, outputs=out)
|
| 117 |
+
|
| 118 |
+
if __name__ == "__main__":
|
| 119 |
+
demo.launch()
|
examples/I2V/00_cat_vac/actions.txt
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
@last_frame include
|
| 2 |
+
|
| 3 |
+
forward1x2
|
| 4 |
+
backward1x4
|
| 5 |
+
yaw_right45x2
|
| 6 |
+
yaw_left45x4
|
| 7 |
+
right1x2
|
| 8 |
+
yaw_right45x4
|
| 9 |
+
yaw_left45x2
|
examples/I2V/00_cat_vac/camera.npy
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:810e574e8bbbd938abcbdd4561885463ed683a1ad052f1222c5f7e22eb31e998
|
| 3 |
+
size 63488
|
examples/I2V/00_cat_vac/image.png
ADDED
|
Git LFS Details
|
examples/I2V/00_cat_vac/prompt.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
A third-person gameplay-like camera closely follows a gray robot vacuum moving through a modern interior with reflective hardwood floors and beautiful rays of light. An adult brown tabby sits upright on the circular vacuum with green eyes, striped fur, white paws, and its tail curled beside the shell. The machine has a matte gray body, raised sensor turret, rubber bumper, and a small control panel. It passes between a sofa, low wooden tables, kitchen cabinetry, rugs, potted plants, and scattered household objects. The cat shifts its paws and body to remain balanced while the vacuum turns around furniture and crosses changes in floor material.
|
examples/I2V/01_socrates/actions.txt
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
forward2
|
| 2 |
+
backward2
|
| 3 |
+
left1
|
| 4 |
+
right1
|
| 5 |
+
forward2&right2&yaw_left45
|
| 6 |
+
reverse1
|
| 7 |
+
left1.5
|
| 8 |
+
forward2x3
|
| 9 |
+
reverse4
|
| 10 |
+
up2&forward1.5&pitch_down30
|
| 11 |
+
reverse1
|
| 12 |
+
right1.5
|
| 13 |
+
forward1.5&left2&yaw_right45
|
| 14 |
+
reverse1
|
| 15 |
+
left1.5
|
examples/I2V/01_socrates/camera.npy
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:9146aad4b53b9f9c458ba21361c7f32469906d475e47c252292a39eb31ee9d8f
|
| 3 |
+
size 63488
|
examples/I2V/01_socrates/image.png
ADDED
|
Git LFS Details
|
examples/I2V/01_socrates/prompt.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
A scene of static, painted sculptures depicts a solemn stone prison chamber, with classical figures neatly arranged around a low wooden bed. An elderly philosopher sculpture sits upright in a white robe, one hand extended toward a cup and the other raised in a fixed rhetorical gesture. Companion sculptures wear red, blue, yellow, gray, and ochre garments, with sculpted expressions of grief, disbelief, and contemplation. All figures remain completely motionless, with rigid poses and fixed garment folds. Scrolls, shackles, cups, sandals, stools, and other props are neatly placed in clearly organized groups. Stone walls, orderly steps, and an arched passage frame the scene. The chamber is clean, tidy, and carefully arranged, forming a coherent historical tableau of painted sculptures.
|
examples/I2V/02_chestnut/actions.txt
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
@dtype float32
|
| 2 |
+
@last_frame include
|
| 3 |
+
|
| 4 |
+
backward1.5x4
|
| 5 |
+
yaw_left45x2
|
| 6 |
+
forward1.5x4
|
| 7 |
+
yaw_right45x2
|
| 8 |
+
forward1.5x2
|
| 9 |
+
right1.5x4
|
examples/I2V/02_chestnut/camera.npy
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:24573a503f14d7ddb593b4b1bc7902e575160b19649bdd13858727ad551f76fe
|
| 3 |
+
size 28640
|
examples/I2V/02_chestnut/image.png
ADDED
|
Git LFS Details
|
examples/I2V/02_chestnut/prompt.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
A chestnut horse stands in a rural paddock with its ears upright and its attention directed forward. The horse has a broad irregular white blaze running down its face, a dark muzzle, large alert eyes, short whiskers, and a tousled black forelock between its ears. Its reddish-brown coat continues across the neck and shoulders. A rough field, low stable buildings, fencing, distant trees, and wooded hills surround the animal, creating a simple working-farm environment. The animal stands within a complete farm landscape of worn ground, fences, low buildings, open field, mature trees, and wooded hills extending behind the paddock. The scene remains spatially coherent from nearby surfaces and vegetation to the architecture, terrain, and distant boundaries of the environment.
|
examples/I2V/06_waterfall/actions.txt
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
@dtype float32
|
| 2 |
+
|
| 3 |
+
forward1x4
|
| 4 |
+
yaw_right45x4
|
| 5 |
+
forward1x4
|
| 6 |
+
yaw_right45x4
|
examples/I2V/06_waterfall/camera.npy
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:14c7a1dfd01811dbd1625aa3c53c4d76895e4a8ba8dbd7cd732d72987bfcca82
|
| 3 |
+
size 25472
|
examples/I2V/06_waterfall/image.png
ADDED
|
Git LFS Details
|
examples/I2V/06_waterfall/prompt.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
A broad garden waterfall pours over layered dark rocks into a shallow pool surrounded by dense subtropical plants. Several parallel curtains of water descend from a ledge beneath mossy boulders, with smaller channels passing between stones and clumps of grass. Pines, broad-leaf shrubs, ferns, and long narrow leaves grow around the banks and across the rock formation. A large flat stone borders the pool on one side, while additional boulders form a natural boundary behind the falling water. The compact arrangement of water, stone, varied foliage, and concealed pond edges resembles a carefully designed botanical garden feature.
|
examples/I2V/10_case061/actions.txt
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
forward1x4
|
| 2 |
+
yaw_right45x4
|
| 3 |
+
forward1x4
|
| 4 |
+
yaw_right45x4
|
| 5 |
+
forward1.5x6
|
| 6 |
+
pitch_up30
|
| 7 |
+
forward1.5x6
|
| 8 |
+
pitch_down45
|
examples/I2V/10_case061/camera.npy
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e61560bb1fb82b50b547e46303426927efe8b5234945f3de563da478a38b2811
|
| 3 |
+
size 95168
|
examples/I2V/10_case061/image.png
ADDED
|
Git LFS Details
|
examples/I2V/10_case061/prompt.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
A third-person trailing gameplay-like view closely follows a majestic blue Amazonian parrot as it flies high through the vibrant Amazon rainforest on a beautiful clear sunny day. The parrot has layered cobalt feathers, a golden throat patch, a curved black beak, and broad articulated wings. Below, a winding river divides dense tiers of palms, ceiba trees, hanging vines, and exposed roots. An ancient stepped stone temple occupies a clearing ahead, its terraces cracked and overgrown with moss, orchids, and tangled foliage. Small birds cross between the treetops, mist gathers over distant ridges, and the riverbank contains fallen trunks, ferns, and scattered stone fragments.
|
examples/I2V/13_burrow/actions.txt
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
@dtype float32
|
| 2 |
+
@sampling smooth_turns
|
| 3 |
+
|
| 4 |
+
forward1x2
|
| 5 |
+
left1x2
|
| 6 |
+
yaw_left30x3
|
| 7 |
+
left1x3
|
| 8 |
+
yaw_right30x3
|
| 9 |
+
right1x5
|
| 10 |
+
yaw_right30x4
|
| 11 |
+
yaw_left30x3
|
| 12 |
+
reverse_frames25
|
examples/I2V/13_burrow/camera.npy
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:78a589f811cfc190ad00ee109387466c853a0c270321115fe46f18e76f59e3d3
|
| 3 |
+
size 79328
|
examples/I2V/13_burrow/image.png
ADDED
|
Git LFS Details
|
examples/I2V/13_burrow/prompt.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
A first-person view of a whimsical earthen cottage built directly into a grassy hillside. Uneven stone steps cross the foreground through thick lawn, leafy plants, and clusters of purple and pink flowers. A large round green wooden door sits beneath a broad brick arch in the middle ground, flanked by two circular divided windows and curved timber supports. Ivy and dense shrubs cover much of the plaster facade and turf roof, while mature branches spread overhead. A bright orange pumpkin rests at the left edge, and damp greenery, weathered wood, masonry, and soft daylight give the dwelling a secluded rural character.
|
examples/I2V/15_case104/actions.txt
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
forward1.5x10
|
| 2 |
+
yaw_right45x4
|
| 3 |
+
yaw_left45x4
|
| 4 |
+
forward1.5x11
|
examples/I2V/15_case104/camera.npy
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:b914b0f7552133204adf037b92db1ba99b24abd683e8c3ce0637f811ded64612
|
| 3 |
+
size 92000
|
examples/I2V/15_case104/image.png
ADDED
|
Git LFS Details
|
examples/I2V/15_case104/prompt.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
A third-person fantasy gameplay view follows a small winged fairy exploring a floating sky island. The fairy has long golden hair, a short white dress, delicate translucent wings with iridescent veins, and a light, graceful silhouette. Lush grass and colorful wildflowers cover the island's rocky surface, while waterfalls descend from sheer edges into layers of soft clouds. A branching crystal tree carries luminous jewel-like fruit, and distant floating islands create a broad aerial landscape. Glowing vines, mossy stones, and scattered blossoms add detail to the traversable ground. Vibrant anime colors and soft atmospheric light connect the fairy to the surrounding fantasy world. The view stays closely linked to the fairy while preserving nearby terrain, cliff edges, trees, waterfalls, and distant islands as one continuous explorable environment.
|
examples/README.md
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Camera and prompt guide
|
| 2 |
+
|
| 3 |
+
Each example contains `prompt.txt`, `camera.npy`, and `actions.txt`. I2V examples
|
| 4 |
+
also include `image.png`. The shared `negative_prompt.txt` is loaded by default.
|
| 5 |
+
Tokyo street includes its original `negative_prompt.txt`; select it with
|
| 6 |
+
`--negative-prompt-path test/T2V/02_tokyo_street/negative_prompt.txt`.
|
| 7 |
+
Run the commands below from the repository root.
|
| 8 |
+
|
| 9 |
+
## Choose an example
|
| 10 |
+
|
| 11 |
+
| Mode | Example | Description |
|
| 12 |
+
| --- | --- | --- |
|
| 13 |
+
| I2V | [Cat](I2V/00_cat_vac) | Default; a cat riding a moving robot vacuum |
|
| 14 |
+
| I2V | [Socrates](I2V/01_socrates) | Motionless painted sculptures in a stone chamber |
|
| 15 |
+
| T2V | [Red balloon](T2V/00_red_balloon) | Default; a balloon floating through an abandoned street |
|
| 16 |
+
| T2V | [Tokyo street](T2V/02_tokyo_street) | A woman walking through a neon-lit street |
|
| 17 |
+
|
| 18 |
+
Run the Tokyo street example with its original prompt and negative prompt:
|
| 19 |
+
|
| 20 |
+
```bash
|
| 21 |
+
python inference.py --model-type fast --mode t2v \
|
| 22 |
+
--prompt-path test/T2V/02_tokyo_street/prompt.txt \
|
| 23 |
+
--negative-prompt-path test/T2V/02_tokyo_street/negative_prompt.txt \
|
| 24 |
+
--actions-file test/T2V/02_tokyo_street/actions.txt
|
| 25 |
+
```
|
| 26 |
+
|
| 27 |
+
Additional examples:
|
| 28 |
+
|
| 29 |
+
| Mode | Cases |
|
| 30 |
+
| --- | --- |
|
| 31 |
+
| I2V | `02_chestnut`, `06_waterfall`, `10_case061`, `13_burrow`, `15_case104` |
|
| 32 |
+
| T2V | `01_t2v-mind131-00` |
|
| 33 |
+
|
| 34 |
+
## Camera inputs
|
| 35 |
+
|
| 36 |
+
Choose either the saved poses or the action description for the same example:
|
| 37 |
+
|
| 38 |
+
```bash
|
| 39 |
+
python inference.py --model-type fast \
|
| 40 |
+
--image-path test/I2V/01_socrates/image.png \
|
| 41 |
+
--prompt-path test/I2V/01_socrates/prompt.txt \
|
| 42 |
+
--camera-path test/I2V/01_socrates/camera.npy
|
| 43 |
+
```
|
| 44 |
+
|
| 45 |
+
Replace the last argument with `--actions-file test/I2V/01_socrates/actions.txt`
|
| 46 |
+
to generate the poses from actions. For T2V, use `--mode t2v`, omit `--image-path`,
|
| 47 |
+
and select a T2V example's prompt and trajectory.
|
| 48 |
+
|
| 49 |
+
### Write actions
|
| 50 |
+
|
| 51 |
+
```text
|
| 52 |
+
forward1x2
|
| 53 |
+
yaw_left30x3
|
| 54 |
+
backward1
|
| 55 |
+
```
|
| 56 |
+
|
| 57 |
+
This generates six chunks: two forward moves, three left turns, and one backward
|
| 58 |
+
move. Each chunk has 33 frames. Movement values are distances; rotation values
|
| 59 |
+
are degrees. Use `--num-chunks` to run only the beginning of a sequence.
|
| 60 |
+
|
| 61 |
+
| Movement | Actions | Short forms |
|
| 62 |
+
| --- | --- | --- |
|
| 63 |
+
| Forward / backward | `forward1`, `backward1` | `f1`, `b1` |
|
| 64 |
+
| Left / right | `left1`, `right1` | `l1`, `r1` |
|
| 65 |
+
| Up / down | `up1`, `down1` | Same |
|
| 66 |
+
| Turn left / right | `yaw_left30`, `yaw_right30` | `yl30`, `yr30` |
|
| 67 |
+
| Look up / down | `pitch_up15`, `pitch_down15` | `pu15`, `pd15` |
|
| 68 |
+
|
| 69 |
+
The camera starts at the origin, facing +Z, with +X to the right and +Y down.
|
| 70 |
+
Forward/backward and left/right follow its heading on the horizontal plane;
|
| 71 |
+
pitch does not change movement height. Up/down follows the world vertical axis.
|
| 72 |
+
Yaw turns in place. Keep the total translation distance per chunk at most 5;
|
| 73 |
+
split longer movements into repeated actions.
|
| 74 |
+
|
| 75 |
+
Use spaces, commas, or newlines between actions, and `#` for comments. `xN`
|
| 76 |
+
repeats an action. `&` combines movements and rotations in one chunk, such as
|
| 77 |
+
`forward2&right2&yaw_left45`; translation follows the heading at the chunk's
|
| 78 |
+
start. `reverseN` retraces the preceding N chunks. `reverse_framesN` replays their
|
| 79 |
+
sampled poses in reverse frame order. Each reverse command generates N chunks.
|
| 80 |
+
|
| 81 |
+
Some examples include headers to preserve their original sampling:
|
| 82 |
+
|
| 83 |
+
| Header | Meaning |
|
| 84 |
+
| --- | --- |
|
| 85 |
+
| `@dtype float32` | Store poses in float32 instead of the default float64 |
|
| 86 |
+
| `@sampling smooth_turns` | Ease motion at action changes instead of using linear sampling |
|
| 87 |
+
| `@last_frame include` | Include the final endpoint instead of excluding it |
|
| 88 |
+
|
| 89 |
+
Keep these headers when reproducing an example. To build poses separately:
|
| 90 |
+
|
| 91 |
+
```bash
|
| 92 |
+
python tools/build_trajectory.py \
|
| 93 |
+
--actions-file test/I2V/01_socrates/actions.txt \
|
| 94 |
+
--output-dir output/socrates_camera
|
| 95 |
+
```
|
| 96 |
+
|
| 97 |
+
### Supply camera poses
|
| 98 |
+
|
| 99 |
+
`camera.npy` stores global camera-to-world matrices with shape `[T, 3, 4]` or
|
| 100 |
+
`[T, 4, 4]`, using the same right/down/forward convention. Supply one pose per
|
| 101 |
+
frame and 33 frames per chunk, with translations in the model's metric scale.
|
| 102 |
+
The inference code derives the internal camera representations; do not
|
| 103 |
+
pre-normalize the file separately for UCPE or RepEncoder.
|
| 104 |
+
|
| 105 |
+
## Prompt styles
|
| 106 |
+
|
| 107 |
+
### Dynamic subjects: describe following and motion
|
| 108 |
+
|
| 109 |
+
For a moving subject that should stay in view, begin with
|
| 110 |
+
**“A third-person ... view closely follows ...”**. This encourages subject
|
| 111 |
+
following; it is a prompt cue, not a tracking constraint. Describe the subject's
|
| 112 |
+
appearance, its movement, and how it interacts with the surroundings. Keep
|
| 113 |
+
nearby obstacles and background landmarks identifiable as the subject moves.
|
| 114 |
+
|
| 115 |
+
The [Cat prompt](I2V/00_cat_vac/prompt.txt) starts:
|
| 116 |
+
|
| 117 |
+
> A third-person gameplay-like camera closely follows a gray robot vacuum moving through a modern interior with reflective hardwood floors and beautiful rays of light.
|
| 118 |
+
|
| 119 |
+
It then describes the cat, the vacuum, the furniture, and how the cat balances
|
| 120 |
+
during movement. Adapt the opening to the subject, for example
|
| 121 |
+
“A third-person trailing view closely follows a cyclist ...”.
|
| 122 |
+
For an environment with moving water or foliage but no followed subject, use
|
| 123 |
+
the scene-focused style below and describe that environmental motion directly.
|
| 124 |
+
|
| 125 |
+
### Static scenes: describe space and fixed appearance
|
| 126 |
+
|
| 127 |
+
Describe the scene as a coherent environment: its layout, foreground and
|
| 128 |
+
background, materials, lighting, and relationships between objects. Camera
|
| 129 |
+
motion comes from the trajectory. Avoid adding subject movement when the scene
|
| 130 |
+
should remain static.
|
| 131 |
+
|
| 132 |
+
The [Socrates prompt](I2V/01_socrates/prompt.txt) identifies the people as
|
| 133 |
+
**static, painted sculptures** and explicitly says that all figures remain
|
| 134 |
+
motionless, with rigid poses and fixed garment folds. This helps distinguish
|
| 135 |
+
lifelike sculptures from living people. For an ordinary room or landscape,
|
| 136 |
+
describe its actual contents rather than calling everything a sculpture.
|
| 137 |
+
|
| 138 |
+
### Length and consistency
|
| 139 |
+
|
| 140 |
+
Use one focused English paragraph. Around **80–120 words** is a useful starting
|
| 141 |
+
point; dynamic subject-following prompts often need **100–130 words** to cover
|
| 142 |
+
both motion and environment. These are writing guidelines, not input limits.
|
| 143 |
+
|
| 144 |
+
For I2V, keep the description consistent with the input image. For T2V, describe
|
| 145 |
+
the subject and setting explicitly because there is no starting image. Keep
|
| 146 |
+
appearance and lighting consistent throughout the paragraph, and avoid cuts,
|
| 147 |
+
shot changes, or camera directions that compete with the supplied trajectory.
|
| 148 |
+
The bundled prompts preserve the wording used for their original examples.
|
examples/T2V/00_red_balloon/actions.txt
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
@dtype float32
|
| 2 |
+
@sampling smooth_turns
|
| 3 |
+
|
| 4 |
+
forward1x2
|
| 5 |
+
left1x2
|
| 6 |
+
yaw_left30x3
|
| 7 |
+
left1x3
|
| 8 |
+
yaw_right30x3
|
| 9 |
+
right1x5
|
| 10 |
+
yaw_right30x4
|
| 11 |
+
yaw_left30x3
|
| 12 |
+
reverse_frames25
|
examples/T2V/00_red_balloon/camera.npy
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:78a589f811cfc190ad00ee109387466c853a0c270321115fe46f18e76f59e3d3
|
| 3 |
+
size 79328
|
examples/T2V/00_red_balloon/prompt.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
A third person view closely follows a red balloon floating above the ground in an abandoned street. The balloon drifts gracefully, its bright red color contrasting sharply against the decaying urban backdrop. The street is littered with debris and graffiti-covered walls, with broken windows and rusted cars scattered about. Shadows dance across the scene as sunlight filters through gaps in the buildings. The camera moves fluidly, capturing the balloon's gentle ascent and descent, emphasizing its playful motion. A close-up of the balloon transitions to a wider shot, showcasing the desolate environment.
|
examples/T2V/01_t2v-mind131-00/actions.txt
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
@dtype float32
|
| 2 |
+
|
| 3 |
+
left2x2
|
| 4 |
+
right2x4
|
| 5 |
+
left2x2
|
| 6 |
+
forward2x4
|
| 7 |
+
backward2x4
|
| 8 |
+
yaw_left45x8
|
examples/T2V/01_t2v-mind131-00/camera.npy
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:4519540636c34443ccc1d0a4ba60984828de07c065a608dd6b0f1ffae0a71827
|
| 3 |
+
size 38144
|
examples/T2V/01_t2v-mind131-00/prompt.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
A third person view closely follows a vibrant tropical fish swimming gracefully among colorful coral reefs in a clear, turquoise ocean. The fish has bright blue and yellow scales with a small, distinctive orange spot on its side, its fins moving fluidly. The coral reefs are alive with a variety of marine life, including small schools of colorful fish and sea turtles gliding by. The water is crystal clear, allowing for a view of the sandy ocean floor below. The reef itself is adorned with a mix of hard and soft corals in shades of red, orange, and green. The camera moves smoothly with the fish, keeping it in view as it weaves between the coral formations and explores the reef.
|
examples/T2V/02_tokyo_street/actions.txt
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
@dtype float32
|
| 2 |
+
|
| 3 |
+
forward1x4
|
| 4 |
+
yaw_right45x4
|
| 5 |
+
forward1x4
|
| 6 |
+
yaw_right45x4
|
examples/T2V/02_tokyo_street/camera.npy
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:14c7a1dfd01811dbd1625aa3c53c4d76895e4a8ba8dbd7cd732d72987bfcca82
|
| 3 |
+
size 25472
|
examples/T2V/02_tokyo_street/negative_prompt.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
overexposed, static, blurred details, subtitles, style, artwork, painting, picture, still, overall gray, worst quality, low quality, JPEG compression residue, ugly, incomplete, extra fingers, poorly drawn hands, poorly drawn faces, deformed, disfigured, malformed limbs, fused fingers, motionless picture, messy background, three legs, many people in the background, walking backwards
|
examples/T2V/02_tokyo_street/prompt.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
A stylish woman strolls down a bustling Tokyo street, the warm glow of neon lights and animated city signs casting vibrant reflections. She wears a sleek black leather jacket paired with a flowing red dress and black boots, her black purse slung over her shoulder. Sunglasses perched on her nose and a bold red lipstick add to her confident, casual demeanor. The street is damp and reflective, creating a mirror-like effect that enhances the colorful lights and shadows. Pedestrians move about, adding to the lively atmosphere. The scene is captured in a dynamic medium shot with the woman walking slightly to one side, highlighting her graceful strides.
|
examples/negative_prompt.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
Bright tones, overexposed, static, blurred details, subtitles, style, works, paintings, images, static, overall gray, worst quality, low quality, JPEG compression residue, ugly, incomplete, extra fingers, poorly drawn hands, poorly drawn faces, deformed, disfigured, misshapen limbs, fused fingers, still picture, messy background, three legs, many people in the background, walking backwards
|
requirements.txt
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
torch==2.10.0
|
| 2 |
+
torchvision==0.25.0
|
| 3 |
+
diffusers==0.37.0
|
| 4 |
+
transformers==5.3.0
|
| 5 |
+
accelerate==1.12.0
|
| 6 |
+
peft==0.18.1
|
| 7 |
+
kernels==0.13.0
|
| 8 |
+
timm==1.0.25
|
| 9 |
+
safetensors
|
| 10 |
+
numpy<2.0.0
|
| 11 |
+
Pillow
|
| 12 |
+
imageio==2.37.3
|
| 13 |
+
imageio-ffmpeg==0.6.0
|
| 14 |
+
ftfy
|
| 15 |
+
regex
|
| 16 |
+
einops
|
| 17 |
+
packaging
|
| 18 |
+
sentencepiece
|
worldcrafter/__init__.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from importlib import import_module
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
__all__ = [
|
| 5 |
+
"InferenceResult",
|
| 6 |
+
"RepEncoder",
|
| 7 |
+
"WorldCrafter",
|
| 8 |
+
"WorldCrafterPipeline",
|
| 9 |
+
"WorldCrafterScheduler",
|
| 10 |
+
"WorldCrafterTransformer3DModel",
|
| 11 |
+
]
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def __getattr__(name):
|
| 15 |
+
modules = {
|
| 16 |
+
"InferenceResult": ".inference",
|
| 17 |
+
"WorldCrafter": ".inference",
|
| 18 |
+
"RepEncoder": ".repencoder",
|
| 19 |
+
"WorldCrafterPipeline": ".diffusers",
|
| 20 |
+
"WorldCrafterScheduler": ".diffusers",
|
| 21 |
+
"WorldCrafterTransformer3DModel": ".diffusers",
|
| 22 |
+
}
|
| 23 |
+
if name not in modules:
|
| 24 |
+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
| 25 |
+
value = getattr(import_module(modules[name], __name__), name)
|
| 26 |
+
globals()[name] = value
|
| 27 |
+
return value
|
worldcrafter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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Camera actions in a right/down/forward coordinate system."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from dataclasses import asdict, dataclass
|
| 6 |
+
import hashlib
|
| 7 |
+
import json
|
| 8 |
+
import math
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
import re
|
| 11 |
+
from functools import partial
|
| 12 |
+
|
| 13 |
+
import numpy as np
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
CHUNK_FRAMES = 33
|
| 17 |
+
FPS = 16
|
| 18 |
+
MAX_TRANSLATION = 5.0
|
| 19 |
+
ACTION_FIELDS = {
|
| 20 |
+
"forward": ("forward", 1),
|
| 21 |
+
"backward": ("forward", -1),
|
| 22 |
+
"left": ("right", -1),
|
| 23 |
+
"right": ("right", 1),
|
| 24 |
+
"up": ("up", 1),
|
| 25 |
+
"down": ("up", -1),
|
| 26 |
+
"yaw_left": ("yaw", -1),
|
| 27 |
+
"yaw_right": ("yaw", 1),
|
| 28 |
+
"pitch_up": ("pitch", 1),
|
| 29 |
+
"pitch_down": ("pitch", -1),
|
| 30 |
+
}
|
| 31 |
+
ALIASES = {
|
| 32 |
+
"f": "forward", "b": "backward", "l": "left", "r": "right",
|
| 33 |
+
"yl": "yaw_left", "yr": "yaw_right", "pu": "pitch_up", "pd": "pitch_down",
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
@dataclass(frozen=True)
|
| 38 |
+
class Action:
|
| 39 |
+
forward: float = 0.0
|
| 40 |
+
right: float = 0.0
|
| 41 |
+
yaw: float = 0.0
|
| 42 |
+
pitch: float = 0.0
|
| 43 |
+
speed: float = 1.0
|
| 44 |
+
up: float = 0.0
|
| 45 |
+
|
| 46 |
+
def validate(self):
|
| 47 |
+
values = (self.forward, self.right, self.up, self.yaw, self.pitch)
|
| 48 |
+
if not all(math.isfinite(v) for v in (*values, self.speed)):
|
| 49 |
+
raise ValueError("Control values must be finite")
|
| 50 |
+
if sum(v != 0 for v in values) > 1:
|
| 51 |
+
raise ValueError("Only one movement or rotation may be active per chunk")
|
| 52 |
+
|
| 53 |
+
def normalized(self):
|
| 54 |
+
"""Apply the interactive controls' slider limits."""
|
| 55 |
+
self.validate()
|
| 56 |
+
return Action(
|
| 57 |
+
forward=max(-1.0, min(1.0, self.forward)),
|
| 58 |
+
right=max(-1.0, min(1.0, self.right)),
|
| 59 |
+
up=max(-1.0, min(1.0, self.up)),
|
| 60 |
+
yaw=max(-30.0, min(30.0, self.yaw)),
|
| 61 |
+
pitch=max(-30.0, min(30.0, self.pitch)),
|
| 62 |
+
speed=max(0.1, min(MAX_TRANSLATION, self.speed)),
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
def json(self):
|
| 66 |
+
return asdict(self)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def parse_event(event: str) -> tuple[str, float]:
|
| 70 |
+
match = re.fullmatch(r"([a-z_]+)([0-9]+(?:\.[0-9]+)?)", event.lower())
|
| 71 |
+
if match is None:
|
| 72 |
+
raise ValueError(f"Invalid action {event!r}; use e.g. forward1 or yaw_left30")
|
| 73 |
+
name, value = match.groups()
|
| 74 |
+
name = ALIASES.get(name, name)
|
| 75 |
+
if name not in ACTION_FIELDS:
|
| 76 |
+
raise ValueError(f"Unknown action {name!r}; choose from {', '.join(ACTION_FIELDS)}")
|
| 77 |
+
amount = float(value)
|
| 78 |
+
if not math.isfinite(amount):
|
| 79 |
+
raise ValueError(f"Action amount must be finite: {event}")
|
| 80 |
+
if ACTION_FIELDS[name][0] in {"forward", "right", "up"} and amount > MAX_TRANSLATION:
|
| 81 |
+
raise ValueError(f"{event}: translation must not exceed {MAX_TRANSLATION:g} per chunk")
|
| 82 |
+
return name, amount
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def parse_actions(text: str) -> list[str]:
|
| 86 |
+
"""Expand space/comma-separated actions, xN repetitions, and # comments."""
|
| 87 |
+
text = re.sub(r"#[^\n]*", "", text)
|
| 88 |
+
text = re.sub(r"\s*&\s*", "&", text)
|
| 89 |
+
events = []
|
| 90 |
+
for token in re.split(r"[\s,]+", text.strip()):
|
| 91 |
+
if not token:
|
| 92 |
+
continue
|
| 93 |
+
match = re.fullmatch(r"(.+?)(?:x([1-9][0-9]*))?", token.lower())
|
| 94 |
+
event, repeat = match.groups()
|
| 95 |
+
if re.fullmatch(r"reverse(?:_frames)?[1-9][0-9]*", event):
|
| 96 |
+
canonical = event
|
| 97 |
+
else:
|
| 98 |
+
parts = []
|
| 99 |
+
axes = set()
|
| 100 |
+
for component in event.split("&"):
|
| 101 |
+
name, _ = parse_event(component)
|
| 102 |
+
field = ACTION_FIELDS[name][0]
|
| 103 |
+
if field in axes:
|
| 104 |
+
raise ValueError(f"An action may use each axis only once: {event}")
|
| 105 |
+
axes.add(field)
|
| 106 |
+
value = re.search(r"[0-9].*", component).group()
|
| 107 |
+
parts.append(name + value)
|
| 108 |
+
canonical = "&".join(parts)
|
| 109 |
+
events.extend([canonical] * int(repeat or 1))
|
| 110 |
+
if not events:
|
| 111 |
+
raise ValueError("Provide at least one camera action")
|
| 112 |
+
return events
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def parse_trajectory(text: str) -> tuple[list[str], dict[str, str]]:
|
| 116 |
+
"""Read actions and optional @dtype, @sampling, and @last_frame headers."""
|
| 117 |
+
choices = {
|
| 118 |
+
"dtype": {"float32", "float64"},
|
| 119 |
+
"sampling": {"linear", "smooth_turns"},
|
| 120 |
+
"last_frame": {"exclude", "include"},
|
| 121 |
+
}
|
| 122 |
+
options, lines = {}, []
|
| 123 |
+
for line in text.splitlines():
|
| 124 |
+
line = line.split("#", 1)[0].strip()
|
| 125 |
+
if line.startswith("@"):
|
| 126 |
+
fields = line[1:].split()
|
| 127 |
+
if len(fields) != 2 or fields[0] not in choices or fields[1] not in choices[fields[0]]:
|
| 128 |
+
raise ValueError(f"Invalid trajectory setting: {line}")
|
| 129 |
+
if lines:
|
| 130 |
+
raise ValueError("Trajectory settings must precede the actions")
|
| 131 |
+
options[fields[0]] = fields[1]
|
| 132 |
+
elif line:
|
| 133 |
+
lines.append(line)
|
| 134 |
+
return parse_actions("\n".join(lines)), options
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def count_chunks(events: list[str]) -> int:
|
| 138 |
+
return sum(
|
| 139 |
+
int(re.search(r"[0-9]+$", event).group()) if event.startswith("reverse") else 1
|
| 140 |
+
for event in events
|
| 141 |
+
)
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def action_from_event(event: str) -> Action:
|
| 145 |
+
name, amount = parse_event(event)
|
| 146 |
+
field, sign = ACTION_FIELDS[name]
|
| 147 |
+
if field in {"yaw", "pitch"}:
|
| 148 |
+
return Action(**{field: sign * amount})
|
| 149 |
+
return Action(**{field: sign}, speed=amount)
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def rotation_y(degrees: float) -> np.ndarray:
|
| 153 |
+
angle = math.radians(degrees)
|
| 154 |
+
cosine, sine = math.cos(angle), math.sin(angle)
|
| 155 |
+
return np.asarray(
|
| 156 |
+
((cosine, 0.0, sine), (0.0, 1.0, 0.0), (-sine, 0.0, cosine)),
|
| 157 |
+
dtype=np.float64,
|
| 158 |
+
)
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def rotation_x(degrees: float) -> np.ndarray:
|
| 162 |
+
angle = math.radians(degrees)
|
| 163 |
+
cosine, sine = math.cos(angle), math.sin(angle)
|
| 164 |
+
return np.asarray(
|
| 165 |
+
((1.0, 0.0, 0.0), (0.0, cosine, -sine), (0.0, sine, cosine)),
|
| 166 |
+
dtype=np.float64,
|
| 167 |
+
)
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def horizontal_direction(rotation: np.ndarray, forward: bool) -> np.ndarray:
|
| 171 |
+
axis = rotation[:, 2 if forward else 0].copy()
|
| 172 |
+
axis[1] = 0.0
|
| 173 |
+
norm = np.linalg.norm(axis)
|
| 174 |
+
if norm < 1e-8:
|
| 175 |
+
# Keep a horizontal heading when looking straight up or down.
|
| 176 |
+
other = rotation[:, 0 if forward else 2]
|
| 177 |
+
axis = np.array([-other[2], 0.0, other[0]])
|
| 178 |
+
if not forward:
|
| 179 |
+
axis = -axis
|
| 180 |
+
norm = np.linalg.norm(axis)
|
| 181 |
+
return axis / norm
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def sample_chunk(
|
| 185 |
+
start: np.ndarray, action: Action, *, fractions: np.ndarray | None = None,
|
| 186 |
+
) -> tuple[np.ndarray, np.ndarray]:
|
| 187 |
+
"""Sample one action; the logical endpoint starts the next chunk."""
|
| 188 |
+
action.validate()
|
| 189 |
+
alpha = np.arange(CHUNK_FRAMES, dtype=np.float64) / CHUNK_FRAMES if fractions is None else fractions
|
| 190 |
+
poses = np.repeat(start[None], len(alpha), axis=0)
|
| 191 |
+
end = start.copy()
|
| 192 |
+
if action.yaw or action.pitch:
|
| 193 |
+
def rotated(fraction):
|
| 194 |
+
if action.yaw:
|
| 195 |
+
return rotation_y(action.yaw * fraction) @ start[:3, :3]
|
| 196 |
+
return start[:3, :3] @ rotation_x(action.pitch * fraction)
|
| 197 |
+
|
| 198 |
+
for index, fraction in enumerate(alpha):
|
| 199 |
+
poses[index, :3, :3] = rotated(fraction)
|
| 200 |
+
end[:3, :3] = rotated(1.0)
|
| 201 |
+
else:
|
| 202 |
+
if action.up:
|
| 203 |
+
direction = np.array([0.0, -action.up, 0.0])
|
| 204 |
+
elif action.forward:
|
| 205 |
+
direction = action.forward * horizontal_direction(start[:3, :3], True)
|
| 206 |
+
else:
|
| 207 |
+
direction = action.right * horizontal_direction(start[:3, :3], False)
|
| 208 |
+
delta = action.speed * direction
|
| 209 |
+
if np.linalg.norm(delta) > MAX_TRANSLATION + 1e-12:
|
| 210 |
+
raise ValueError(f"Translation must not exceed {MAX_TRANSLATION:g} per chunk")
|
| 211 |
+
poses[:, :3, 3] = start[:3, 3] + alpha[:, None] * delta
|
| 212 |
+
end[:3, 3] = start[:3, 3] + delta
|
| 213 |
+
return poses, end
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
def _sample_event(start: np.ndarray, event: str, fractions: np.ndarray) -> np.ndarray:
|
| 217 |
+
components = event.split("&")
|
| 218 |
+
if len(components) == 1:
|
| 219 |
+
return sample_chunk(start, action_from_event(event), fractions=fractions)[0]
|
| 220 |
+
poses = np.repeat(start[None], len(fractions), axis=0)
|
| 221 |
+
delta = np.zeros(3)
|
| 222 |
+
for component in components:
|
| 223 |
+
action = action_from_event(component)
|
| 224 |
+
if action.yaw:
|
| 225 |
+
for index, fraction in enumerate(fractions):
|
| 226 |
+
poses[index, :3, :3] = rotation_y(action.yaw * fraction) @ poses[index, :3, :3]
|
| 227 |
+
elif action.pitch:
|
| 228 |
+
for index, fraction in enumerate(fractions):
|
| 229 |
+
poses[index, :3, :3] = poses[index, :3, :3] @ rotation_x(action.pitch * fraction)
|
| 230 |
+
else:
|
| 231 |
+
_, end = sample_chunk(start, action)
|
| 232 |
+
delta += end[:3, 3] - start[:3, 3]
|
| 233 |
+
if np.linalg.norm(delta) > MAX_TRANSLATION + 1e-12:
|
| 234 |
+
raise ValueError(f"{event}: combined translation must not exceed {MAX_TRANSLATION:g} per chunk")
|
| 235 |
+
poses[:, :3, 3] = start[:3, 3] + fractions[:, None] * delta
|
| 236 |
+
return poses
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
def _sample_curve(start, event, tangent_start, tangent_end, times):
|
| 240 |
+
fractions = times
|
| 241 |
+
if tangent_start is not None:
|
| 242 |
+
fractions = (
|
| 243 |
+
-2 * times**3 + 3 * times**2
|
| 244 |
+
+ (times**3 - 2 * times**2 + times) * tangent_start
|
| 245 |
+
+ (times**3 - times**2) * tangent_end
|
| 246 |
+
)
|
| 247 |
+
return _sample_event(start, event, fractions)
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
def _reverse_curve(curve, times):
|
| 251 |
+
return curve(1.0 - times)
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
def _reverse_sampled_curve(curve, last_time, times):
|
| 255 |
+
return curve(last_time * (1.0 - times))
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
def build_trajectory(
|
| 259 |
+
events: list[str], *, dtype: str = "float64", sampling: str = "linear",
|
| 260 |
+
last_frame: str = "exclude",
|
| 261 |
+
) -> tuple[np.ndarray, list[dict[str, object]]]:
|
| 262 |
+
if not events:
|
| 263 |
+
raise ValueError("Provide at least one camera action")
|
| 264 |
+
world = np.eye(4, dtype=np.float64)
|
| 265 |
+
chunks, records, curves, sample_times = [], [], [], []
|
| 266 |
+
|
| 267 |
+
def append(event, curve, times, poses=None):
|
| 268 |
+
nonlocal world
|
| 269 |
+
start, end = curve(np.array([0.0, 1.0]))
|
| 270 |
+
chunks.append(curve(times) if poses is None else poses)
|
| 271 |
+
records.append({
|
| 272 |
+
"chunk_index": len(records), "event": event,
|
| 273 |
+
"logical_start_c2w": start.tolist(), "logical_end_c2w": end.tolist(),
|
| 274 |
+
})
|
| 275 |
+
curves.append(curve)
|
| 276 |
+
sample_times.append(times)
|
| 277 |
+
world = end
|
| 278 |
+
|
| 279 |
+
for index, event in enumerate(events):
|
| 280 |
+
if event.startswith("reverse"):
|
| 281 |
+
count = int(re.search(r"[0-9]+$", event).group())
|
| 282 |
+
if count > len(chunks):
|
| 283 |
+
raise ValueError(f"{event} needs {count} preceding chunks; only {len(chunks)} exist")
|
| 284 |
+
indices = list(range(len(chunks) - 1, len(chunks) - count - 1, -1))
|
| 285 |
+
for source in indices:
|
| 286 |
+
if event.startswith("reverse_frames"):
|
| 287 |
+
curve = partial(_reverse_sampled_curve, curves[source], sample_times[source][-1])
|
| 288 |
+
times = np.linspace(0.0, 1.0, CHUNK_FRAMES)
|
| 289 |
+
append(event, curve, times, chunks[source][::-1].copy())
|
| 290 |
+
else:
|
| 291 |
+
curve = partial(_reverse_curve, curves[source])
|
| 292 |
+
include_end = last_frame == "include" and index == len(events) - 1 and source == indices[-1]
|
| 293 |
+
times = (
|
| 294 |
+
np.linspace(0.0, 1.0, CHUNK_FRAMES) if include_end
|
| 295 |
+
else np.arange(CHUNK_FRAMES, dtype=np.float64) / CHUNK_FRAMES
|
| 296 |
+
)
|
| 297 |
+
poses = None
|
| 298 |
+
original = records[source]["event"]
|
| 299 |
+
if sampling == "linear" and "&" not in original and not original.startswith("reverse"):
|
| 300 |
+
action = action_from_event(original)
|
| 301 |
+
if not action.yaw and not action.pitch and sample_times[source][-1] < 1.0 and not include_end:
|
| 302 |
+
# Reuse linear translation samples without another interpolation roundoff.
|
| 303 |
+
endpoint = np.array(records[source]["logical_end_c2w"])
|
| 304 |
+
poses = np.concatenate([endpoint[None], chunks[source][1:][::-1]])
|
| 305 |
+
append(event, curve, times, poses)
|
| 306 |
+
continue
|
| 307 |
+
smooth = sampling == "smooth_turns"
|
| 308 |
+
entering = index > 0 and events[index - 1] == event
|
| 309 |
+
leaving = index + 1 < len(events) and events[index + 1] == event
|
| 310 |
+
include_end = (smooth and not leaving) or (last_frame == "include" and index == len(events) - 1)
|
| 311 |
+
times = (
|
| 312 |
+
np.linspace(0.0, 1.0, CHUNK_FRAMES) if include_end
|
| 313 |
+
else np.arange(CHUNK_FRAMES, dtype=np.float64) / CHUNK_FRAMES
|
| 314 |
+
)
|
| 315 |
+
curve = partial(
|
| 316 |
+
_sample_curve, world.copy(), event,
|
| 317 |
+
float(entering) if smooth else None, float(leaving),
|
| 318 |
+
)
|
| 319 |
+
append(event, curve, times)
|
| 320 |
+
return np.concatenate(chunks).astype(dtype), records
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
def save_trajectory(
|
| 324 |
+
directory: Path, camera: np.ndarray, records: list[dict[str, object]], *, fps: int = FPS,
|
| 325 |
+
events: list[str] | None = None, options: dict[str, str] | None = None,
|
| 326 |
+
) -> Path:
|
| 327 |
+
directory.mkdir(parents=True, exist_ok=True)
|
| 328 |
+
camera_path = directory / "camera.npy"
|
| 329 |
+
np.save(camera_path, camera[:, :3, :4])
|
| 330 |
+
events = events if events is not None else [record["event"] for record in records]
|
| 331 |
+
headers = [f"@{key} {value}" for key, value in (options or {}).items()]
|
| 332 |
+
(directory / "actions.txt").write_text("\n".join(headers + events) + "\n", encoding="utf-8")
|
| 333 |
+
manifest = {
|
| 334 |
+
"format": "worldcrafter_camera_trajectory_v1",
|
| 335 |
+
"fps": fps,
|
| 336 |
+
"chunk_frames": CHUNK_FRAMES,
|
| 337 |
+
"num_chunks": len(records),
|
| 338 |
+
"num_frames": len(camera),
|
| 339 |
+
"motion_sequence": events,
|
| 340 |
+
"options": options or {},
|
| 341 |
+
"camera": camera_path.name,
|
| 342 |
+
"camera_semantics": "global metric c2w; x right, y down, z forward",
|
| 343 |
+
"sha256": {"camera": hashlib.sha256(camera_path.read_bytes()).hexdigest()},
|
| 344 |
+
"chunks": records,
|
| 345 |
+
}
|
| 346 |
+
(directory / "trajectory.json").write_text(
|
| 347 |
+
json.dumps(manifest, indent=2) + "\n", encoding="utf-8",
|
| 348 |
+
)
|
| 349 |
+
return camera_path
|
worldcrafter/cli.py
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
from datetime import datetime
|
| 5 |
+
from uuid import uuid4
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
from typing import Sequence
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 11 |
+
DEFAULT_MODEL = ROOT / "weights" / "WorldCrafter-Base"
|
| 12 |
+
DEFAULT_I2V_CASE = ROOT / "test" / "I2V" / "00_cat_vac"
|
| 13 |
+
DEFAULT_T2V_CASE = ROOT / "test" / "T2V" / "00_red_balloon"
|
| 14 |
+
DEFAULT_IMAGE = DEFAULT_I2V_CASE / "image.png"
|
| 15 |
+
DEFAULT_I2V_CAMERA = DEFAULT_I2V_CASE / "camera.npy"
|
| 16 |
+
DEFAULT_T2V_CAMERA = DEFAULT_T2V_CASE / "camera.npy"
|
| 17 |
+
DEFAULT_I2V_PROMPT = DEFAULT_I2V_CASE / "prompt.txt"
|
| 18 |
+
DEFAULT_T2V_PROMPT = DEFAULT_T2V_CASE / "prompt.txt"
|
| 19 |
+
DEFAULT_NEGATIVE_PROMPT = ROOT / "test" / "negative_prompt.txt"
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def build_parser() -> argparse.ArgumentParser:
|
| 23 |
+
parser = argparse.ArgumentParser(
|
| 24 |
+
description="WorldCrafter camera-controlled image-to-video and text-to-video inference"
|
| 25 |
+
)
|
| 26 |
+
parser.add_argument("--mode", choices=("i2v", "t2v"), default="i2v")
|
| 27 |
+
parser.add_argument("--model-type", choices=("base", "fast"), default="base")
|
| 28 |
+
parser.add_argument("--model-path", type=Path)
|
| 29 |
+
parser.add_argument(
|
| 30 |
+
"--local-camera-path",
|
| 31 |
+
type=Path,
|
| 32 |
+
help="Optional precomputed chunk-local UCPE poses for fast; --camera-path always supplies global metric poses",
|
| 33 |
+
)
|
| 34 |
+
parser.add_argument("--image-path", type=Path)
|
| 35 |
+
camera = parser.add_mutually_exclusive_group()
|
| 36 |
+
camera.add_argument("--camera-path", type=Path, help="Global c2w trajectory (.npy)")
|
| 37 |
+
camera.add_argument("--actions", help='Camera actions, e.g. "forward1x2 yaw_left30x3 backward1"')
|
| 38 |
+
camera.add_argument("--actions-file", type=Path, help="TXT file of camera actions")
|
| 39 |
+
parser.add_argument("--prompt")
|
| 40 |
+
parser.add_argument("--prompt-path", type=Path)
|
| 41 |
+
parser.add_argument("--negative-prompt")
|
| 42 |
+
parser.add_argument(
|
| 43 |
+
"--negative-prompt-path", type=Path, default=DEFAULT_NEGATIVE_PROMPT
|
| 44 |
+
)
|
| 45 |
+
parser.add_argument("--output-path", type=Path)
|
| 46 |
+
parser.add_argument("--chunk-output-dir", type=Path)
|
| 47 |
+
parser.add_argument("--state-output-dir", type=Path)
|
| 48 |
+
parser.add_argument("--resume-from", type=Path)
|
| 49 |
+
parser.add_argument("--num-chunks", type=int)
|
| 50 |
+
parser.add_argument("--stop-after-chunk", type=int)
|
| 51 |
+
parser.add_argument("--device", default="cuda:0")
|
| 52 |
+
parser.add_argument("--height", type=int, default=384)
|
| 53 |
+
parser.add_argument("--width", type=int, default=640)
|
| 54 |
+
parser.add_argument("--num-inference-steps", type=int)
|
| 55 |
+
parser.add_argument("--guidance-scale", type=float)
|
| 56 |
+
parser.add_argument("--seed", type=int, default=42)
|
| 57 |
+
parser.add_argument("--fps", type=int, default=16)
|
| 58 |
+
parser.add_argument("--image-noise-sigma-min", type=float, default=0.111)
|
| 59 |
+
parser.add_argument("--image-noise-sigma-max", type=float, default=0.135)
|
| 60 |
+
parser.add_argument("--camera-x-fov", type=float, default=100.0)
|
| 61 |
+
parser.add_argument("--camera-xi", type=float, default=0.0)
|
| 62 |
+
parser.add_argument("--memory-fov-h-deg", type=float, default=100.0)
|
| 63 |
+
parser.add_argument("--memory-fov-v-deg", type=float, default=71.13349068444832)
|
| 64 |
+
parser.add_argument("--memory-fov-samples-per-axis", type=int, default=10)
|
| 65 |
+
parser.add_argument(
|
| 66 |
+
"--attention-backend",
|
| 67 |
+
choices=("native", "auto", "flash_hub", "_flash_3_hub"),
|
| 68 |
+
default="native",
|
| 69 |
+
)
|
| 70 |
+
parser.add_argument(
|
| 71 |
+
"--enable-compile",
|
| 72 |
+
action="store_true",
|
| 73 |
+
help="Enable torch.compile (off by default); Fast compiles both transformer block stacks",
|
| 74 |
+
)
|
| 75 |
+
return parser
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def _read_text(path: Path) -> str:
|
| 79 |
+
if not path.is_file():
|
| 80 |
+
raise FileNotFoundError(path)
|
| 81 |
+
value = path.read_text(encoding="utf-8").strip()
|
| 82 |
+
if not value:
|
| 83 |
+
raise ValueError(f"prompt file is empty: {path}")
|
| 84 |
+
return value
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace:
|
| 88 |
+
args = build_parser().parse_args(argv)
|
| 89 |
+
fast = args.model_type == "fast"
|
| 90 |
+
args.model_path = args.model_path or ROOT / "weights" / (
|
| 91 |
+
"WorldCrafter-Fast" if fast else "WorldCrafter-Base"
|
| 92 |
+
)
|
| 93 |
+
if args.num_inference_steps is None:
|
| 94 |
+
args.num_inference_steps = 6 if fast else 50
|
| 95 |
+
if args.guidance_scale is None:
|
| 96 |
+
args.guidance_scale = 1.0 if fast else 5.0
|
| 97 |
+
if fast and (args.num_inference_steps != 6 or args.guidance_scale != 1.0):
|
| 98 |
+
raise ValueError(
|
| 99 |
+
"Fast requires CFG=1 and six regular steps; the first T2V chunk uses twelve steps"
|
| 100 |
+
)
|
| 101 |
+
if fast and (args.resume_from or args.state_output_dir):
|
| 102 |
+
raise ValueError("Fast does not support resume/state export")
|
| 103 |
+
if args.num_chunks is not None and args.num_chunks <= 0:
|
| 104 |
+
raise ValueError("--num-chunks must be positive")
|
| 105 |
+
if args.stop_after_chunk is not None and args.stop_after_chunk < 0:
|
| 106 |
+
raise ValueError("--stop-after-chunk must be non-negative")
|
| 107 |
+
if args.resume_from is not None and args.chunk_output_dir is None:
|
| 108 |
+
raise ValueError("--resume-from requires --chunk-output-dir")
|
| 109 |
+
|
| 110 |
+
args.camera_events = None
|
| 111 |
+
args.camera_options = {}
|
| 112 |
+
if args.actions is not None or args.actions_file is not None:
|
| 113 |
+
from .camera import count_chunks, parse_trajectory
|
| 114 |
+
|
| 115 |
+
if args.local_camera_path is not None:
|
| 116 |
+
raise ValueError("--local-camera-path cannot be combined with camera actions")
|
| 117 |
+
text = args.actions if args.actions is not None else args.actions_file.read_text(encoding="utf-8-sig")
|
| 118 |
+
args.camera_events, args.camera_options = parse_trajectory(text)
|
| 119 |
+
if args.num_chunks is not None:
|
| 120 |
+
total = count_chunks(args.camera_events)
|
| 121 |
+
if args.num_chunks > total:
|
| 122 |
+
raise ValueError(f"Actions provide {total} chunks, but {args.num_chunks} were requested")
|
| 123 |
+
elif args.camera_path is None:
|
| 124 |
+
args.camera_path = (
|
| 125 |
+
DEFAULT_I2V_CAMERA if args.mode == "i2v" else DEFAULT_T2V_CAMERA
|
| 126 |
+
)
|
| 127 |
+
if args.prompt is None:
|
| 128 |
+
prompt_path = args.prompt_path
|
| 129 |
+
if prompt_path is None:
|
| 130 |
+
prompt_path = (
|
| 131 |
+
DEFAULT_I2V_PROMPT if args.mode == "i2v" else DEFAULT_T2V_PROMPT
|
| 132 |
+
)
|
| 133 |
+
args.prompt_path = prompt_path
|
| 134 |
+
args.prompt = _read_text(prompt_path)
|
| 135 |
+
elif args.prompt_path is not None:
|
| 136 |
+
raise ValueError("use either --prompt or --prompt-path, not both")
|
| 137 |
+
|
| 138 |
+
if args.negative_prompt is None:
|
| 139 |
+
args.negative_prompt = _read_text(args.negative_prompt_path)
|
| 140 |
+
if args.mode == "i2v":
|
| 141 |
+
args.image_path = args.image_path or DEFAULT_IMAGE
|
| 142 |
+
elif args.image_path is not None:
|
| 143 |
+
raise ValueError("--image-path is only valid with --mode i2v")
|
| 144 |
+
|
| 145 |
+
if args.output_path is None:
|
| 146 |
+
run_id = f"{datetime.now():%Y%m%d_%H%M%S}_{uuid4().hex[:8]}"
|
| 147 |
+
args.output_path = (
|
| 148 |
+
ROOT / "output" / args.model_type / args.mode / run_id / "video.mp4"
|
| 149 |
+
)
|
| 150 |
+
return args
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def prepare_camera(args: argparse.Namespace) -> None:
|
| 154 |
+
if args.camera_events is not None:
|
| 155 |
+
from .camera import build_trajectory, save_trajectory
|
| 156 |
+
|
| 157 |
+
camera, records = build_trajectory(args.camera_events, **args.camera_options)
|
| 158 |
+
directory = args.output_path.parent / f"{args.output_path.stem}_trajectory"
|
| 159 |
+
args.camera_path = save_trajectory(
|
| 160 |
+
directory, camera, records, fps=args.fps,
|
| 161 |
+
events=args.camera_events, options=args.camera_options,
|
| 162 |
+
)
|
| 163 |
+
print(f"[worldcrafter] saved {len(records)} camera chunks to {args.camera_path}")
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
__all__ = ["build_parser", "parse_args", "prepare_camera"]
|
worldcrafter/diffusers/__init__.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .pipeline import WorldCrafterPipeline
|
| 2 |
+
from .scheduler import WorldCrafterScheduler
|
| 3 |
+
from .transformer import WorldCrafterTransformer3DModel
|
| 4 |
+
|
| 5 |
+
__all__ = ["WorldCrafterPipeline", "WorldCrafterScheduler", "WorldCrafterTransformer3DModel"]
|
worldcrafter/diffusers/pipeline.py
ADDED
|
@@ -0,0 +1,1628 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 6 |
+
import regex as re
|
| 7 |
+
import torch
|
| 8 |
+
from transformers import AutoTokenizer, UMT5EncoderModel
|
| 9 |
+
|
| 10 |
+
from diffusers.callbacks import MultiPipelineCallbacks, PipelineCallback
|
| 11 |
+
from diffusers.image_processor import PipelineImageInput
|
| 12 |
+
from diffusers.loaders import HeliosLoraLoaderMixin as _BaseLoraLoaderMixin
|
| 13 |
+
from diffusers.models import AutoencoderKLWan
|
| 14 |
+
from diffusers.pipelines.pipeline_utils import DiffusionPipeline
|
| 15 |
+
from diffusers.utils import (
|
| 16 |
+
is_ftfy_available,
|
| 17 |
+
is_torch_xla_available,
|
| 18 |
+
logging,
|
| 19 |
+
replace_example_docstring,
|
| 20 |
+
)
|
| 21 |
+
from diffusers.utils.torch_utils import randn_tensor
|
| 22 |
+
from diffusers.video_processor import VideoProcessor
|
| 23 |
+
|
| 24 |
+
from ..ucpe.bridge import build_ucpe_attention_kwargs_for_chunk
|
| 25 |
+
from .pipeline_output import WorldCrafterPipelineOutput
|
| 26 |
+
from .scheduler import WorldCrafterScheduler
|
| 27 |
+
from .transformer import WorldCrafterTransformer3DModel
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
if is_torch_xla_available():
|
| 31 |
+
import torch_xla.core.xla_model as xm
|
| 32 |
+
|
| 33 |
+
XLA_AVAILABLE = True
|
| 34 |
+
else:
|
| 35 |
+
XLA_AVAILABLE = False
|
| 36 |
+
|
| 37 |
+
logger = logging.get_logger(__name__) # pylint: disable=invalid-name
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def _render_repencoder_memory_latents(
|
| 41 |
+
*,
|
| 42 |
+
memory_provider: Any,
|
| 43 |
+
generated_latents: torch.Tensor,
|
| 44 |
+
camera_trajectory: dict[str, Any],
|
| 45 |
+
chunk_index: int,
|
| 46 |
+
num_latent_frames_per_chunk: int,
|
| 47 |
+
vae_scale_factor_temporal: int,
|
| 48 |
+
generator: torch.Generator | list[torch.Generator] | None,
|
| 49 |
+
) -> torch.Tensor:
|
| 50 |
+
if chunk_index <= 0:
|
| 51 |
+
raise ValueError("RepEncoder rendering is only valid after chunk 0")
|
| 52 |
+
if generated_latents.ndim != 5 or generated_latents.shape[2] == 0:
|
| 53 |
+
raise RuntimeError(
|
| 54 |
+
"RepEncoder requires a non-empty [B,C,T,H,W] bank of already generated WorldCrafter latents"
|
| 55 |
+
)
|
| 56 |
+
render_memory = getattr(memory_provider, "render_memory", None)
|
| 57 |
+
if not callable(render_memory):
|
| 58 |
+
raise TypeError(
|
| 59 |
+
"memory_provider must expose a callable render_memory(...) method"
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
recent_latents = generated_latents[:, :, -1:, :, :]
|
| 63 |
+
try:
|
| 64 |
+
memory_latents = render_memory(
|
| 65 |
+
generated_latents=generated_latents,
|
| 66 |
+
recent_latents=recent_latents,
|
| 67 |
+
camera_trajectory=camera_trajectory,
|
| 68 |
+
chunk_index=chunk_index,
|
| 69 |
+
num_latent_frames_per_chunk=num_latent_frames_per_chunk,
|
| 70 |
+
vae_scale_factor_temporal=vae_scale_factor_temporal,
|
| 71 |
+
generator=generator,
|
| 72 |
+
)
|
| 73 |
+
except Exception as exc:
|
| 74 |
+
raise RuntimeError(
|
| 75 |
+
f"RepEncoder memory rendering failed for chunk_index={chunk_index}"
|
| 76 |
+
) from exc
|
| 77 |
+
|
| 78 |
+
expected_shape = (
|
| 79 |
+
generated_latents.shape[0],
|
| 80 |
+
generated_latents.shape[1],
|
| 81 |
+
4,
|
| 82 |
+
generated_latents.shape[3],
|
| 83 |
+
generated_latents.shape[4],
|
| 84 |
+
)
|
| 85 |
+
if not isinstance(memory_latents, torch.Tensor):
|
| 86 |
+
raise TypeError(
|
| 87 |
+
"memory_provider.render_memory(...) must return a torch.Tensor, "
|
| 88 |
+
f"got {type(memory_latents)!r}"
|
| 89 |
+
)
|
| 90 |
+
if tuple(memory_latents.shape) != expected_shape:
|
| 91 |
+
raise ValueError(
|
| 92 |
+
"RepEncoder memory must have shape [B,C,4,H,W]; "
|
| 93 |
+
f"expected {expected_shape}, got {tuple(memory_latents.shape)}"
|
| 94 |
+
)
|
| 95 |
+
if memory_latents.device != generated_latents.device:
|
| 96 |
+
raise ValueError(
|
| 97 |
+
"RepEncoder memory must stay on the WorldCrafter latent device; "
|
| 98 |
+
f"expected {generated_latents.device}, got {memory_latents.device}"
|
| 99 |
+
)
|
| 100 |
+
if not memory_latents.is_floating_point():
|
| 101 |
+
raise TypeError(
|
| 102 |
+
f"RepEncoder memory must be floating point, got {memory_latents.dtype}"
|
| 103 |
+
)
|
| 104 |
+
if not torch.isfinite(memory_latents).all():
|
| 105 |
+
raise FloatingPointError(
|
| 106 |
+
f"RepEncoder memory contains non-finite values at chunk_index={chunk_index}"
|
| 107 |
+
)
|
| 108 |
+
return memory_latents
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
if is_ftfy_available():
|
| 112 |
+
import ftfy
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
EXAMPLE_DOC_STRING = """
|
| 116 |
+
Examples:
|
| 117 |
+
Run camera-controlled generation through the repository entry point,
|
| 118 |
+
which loads the local weights, camera trajectory, and memory provider:
|
| 119 |
+
|
| 120 |
+
```bash
|
| 121 |
+
python inference.py --model-path weights/WorldCrafter-Base
|
| 122 |
+
python inference.py --model-type fast --model-path weights/WorldCrafter-Fast
|
| 123 |
+
```
|
| 124 |
+
"""
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def optimized_scale(positive_flat, negative_flat):
|
| 128 |
+
positive_flat = positive_flat.float()
|
| 129 |
+
negative_flat = negative_flat.float()
|
| 130 |
+
# Compute the dot product.
|
| 131 |
+
dot_product = torch.sum(positive_flat * negative_flat, dim=1, keepdim=True)
|
| 132 |
+
# Squared norm of the unconditional prediction.
|
| 133 |
+
squared_norm = torch.sum(negative_flat**2, dim=1, keepdim=True) + 1e-8
|
| 134 |
+
# st_star = v_cond^T * v_uncond / ||v_uncond||^2
|
| 135 |
+
st_star = dot_product / squared_norm
|
| 136 |
+
return st_star
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def basic_clean(text):
|
| 140 |
+
text = ftfy.fix_text(text)
|
| 141 |
+
text = html.unescape(html.unescape(text))
|
| 142 |
+
return text.strip()
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def whitespace_clean(text):
|
| 146 |
+
text = re.sub(r"\s+", " ", text)
|
| 147 |
+
text = text.strip()
|
| 148 |
+
return text
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def prompt_clean(text):
|
| 152 |
+
text = whitespace_clean(basic_clean(text))
|
| 153 |
+
return text
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
# Copied from diffusers.pipelines.flux.pipeline_flux.calculate_shift
|
| 157 |
+
def calculate_shift(
|
| 158 |
+
image_seq_len,
|
| 159 |
+
base_seq_len: int = 256,
|
| 160 |
+
max_seq_len: int = 4096,
|
| 161 |
+
base_shift: float = 0.5,
|
| 162 |
+
max_shift: float = 1.15,
|
| 163 |
+
):
|
| 164 |
+
m = (max_shift - base_shift) / (max_seq_len - base_seq_len)
|
| 165 |
+
b = base_shift - m * base_seq_len
|
| 166 |
+
mu = image_seq_len * m + b
|
| 167 |
+
return mu
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
class WorldCrafterPipeline(DiffusionPipeline, _BaseLoraLoaderMixin):
|
| 171 |
+
r"""
|
| 172 |
+
Pipeline for text-to-video / image-to-video / video-to-video generation using WorldCrafter.
|
| 173 |
+
|
| 174 |
+
This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
|
| 175 |
+
implemented for all pipelines (downloading, saving, running on a particular device, etc.).
|
| 176 |
+
|
| 177 |
+
Args:
|
| 178 |
+
tokenizer:
|
| 179 |
+
Tokenizer loaded from the local model directory with `AutoTokenizer`.
|
| 180 |
+
text_encoder ([`UMT5EncoderModel`]):
|
| 181 |
+
Text encoder loaded from the local model directory.
|
| 182 |
+
transformer ([`WorldCrafterTransformer3DModel`]):
|
| 183 |
+
Conditional Transformer to denoise the input latents.
|
| 184 |
+
scheduler ([`WorldCrafterScheduler`]):
|
| 185 |
+
A scheduler to be used in combination with `transformer` to denoise the encoded image latents.
|
| 186 |
+
vae ([`AutoencoderKLWan`]):
|
| 187 |
+
Variational Auto-Encoder (VAE) Model to encode and decode videos to and from latent representations.
|
| 188 |
+
"""
|
| 189 |
+
|
| 190 |
+
model_cpu_offload_seq = "text_encoder->transformer->vae"
|
| 191 |
+
_callback_tensor_inputs = ["latents", "prompt_embeds", "negative_prompt_embeds"]
|
| 192 |
+
_optional_components = ["transformer"]
|
| 193 |
+
|
| 194 |
+
def __init__(
|
| 195 |
+
self,
|
| 196 |
+
tokenizer: AutoTokenizer,
|
| 197 |
+
text_encoder: UMT5EncoderModel,
|
| 198 |
+
vae: AutoencoderKLWan,
|
| 199 |
+
scheduler: WorldCrafterScheduler,
|
| 200 |
+
transformer: WorldCrafterTransformer3DModel,
|
| 201 |
+
is_cfg_zero_star: bool = False,
|
| 202 |
+
is_distilled: bool = False,
|
| 203 |
+
):
|
| 204 |
+
super().__init__()
|
| 205 |
+
|
| 206 |
+
self.register_modules(
|
| 207 |
+
vae=vae,
|
| 208 |
+
text_encoder=text_encoder,
|
| 209 |
+
tokenizer=tokenizer,
|
| 210 |
+
transformer=transformer,
|
| 211 |
+
scheduler=scheduler,
|
| 212 |
+
)
|
| 213 |
+
self.register_to_config(is_cfg_zero_star=is_cfg_zero_star)
|
| 214 |
+
self.register_to_config(is_distilled=is_distilled)
|
| 215 |
+
self.vae_scale_factor_temporal = (
|
| 216 |
+
self.vae.config.scale_factor_temporal if getattr(self, "vae", None) else 4
|
| 217 |
+
)
|
| 218 |
+
self.vae_scale_factor_spatial = (
|
| 219 |
+
self.vae.config.scale_factor_spatial if getattr(self, "vae", None) else 8
|
| 220 |
+
)
|
| 221 |
+
self.video_processor = VideoProcessor(
|
| 222 |
+
vae_scale_factor=self.vae_scale_factor_spatial
|
| 223 |
+
)
|
| 224 |
+
|
| 225 |
+
def _get_t5_prompt_embeds(
|
| 226 |
+
self,
|
| 227 |
+
prompt: str | list[str] = None,
|
| 228 |
+
num_videos_per_prompt: int = 1,
|
| 229 |
+
max_sequence_length: int = 226,
|
| 230 |
+
device: torch.device | None = None,
|
| 231 |
+
dtype: torch.dtype | None = None,
|
| 232 |
+
):
|
| 233 |
+
device = device or self._execution_device
|
| 234 |
+
dtype = dtype or self.text_encoder.dtype
|
| 235 |
+
|
| 236 |
+
prompt = [prompt] if isinstance(prompt, str) else prompt
|
| 237 |
+
prompt = [prompt_clean(u) for u in prompt]
|
| 238 |
+
batch_size = len(prompt)
|
| 239 |
+
|
| 240 |
+
text_inputs = self.tokenizer(
|
| 241 |
+
prompt,
|
| 242 |
+
padding="max_length",
|
| 243 |
+
max_length=max_sequence_length,
|
| 244 |
+
truncation=True,
|
| 245 |
+
add_special_tokens=True,
|
| 246 |
+
return_attention_mask=True,
|
| 247 |
+
return_tensors="pt",
|
| 248 |
+
)
|
| 249 |
+
text_input_ids, mask = text_inputs.input_ids, text_inputs.attention_mask
|
| 250 |
+
seq_lens = mask.gt(0).sum(dim=1).long()
|
| 251 |
+
|
| 252 |
+
prompt_embeds = self.text_encoder(
|
| 253 |
+
text_input_ids.to(device), mask.to(device)
|
| 254 |
+
).last_hidden_state
|
| 255 |
+
prompt_embeds = prompt_embeds.to(dtype=dtype, device=device)
|
| 256 |
+
prompt_embeds = [u[:v] for u, v in zip(prompt_embeds, seq_lens)]
|
| 257 |
+
prompt_embeds = torch.stack(
|
| 258 |
+
[
|
| 259 |
+
torch.cat([u, u.new_zeros(max_sequence_length - u.size(0), u.size(1))])
|
| 260 |
+
for u in prompt_embeds
|
| 261 |
+
],
|
| 262 |
+
dim=0,
|
| 263 |
+
)
|
| 264 |
+
|
| 265 |
+
# duplicate text embeddings for each generation per prompt, using mps friendly method
|
| 266 |
+
_, seq_len, _ = prompt_embeds.shape
|
| 267 |
+
prompt_embeds = prompt_embeds.repeat(1, num_videos_per_prompt, 1)
|
| 268 |
+
prompt_embeds = prompt_embeds.view(
|
| 269 |
+
batch_size * num_videos_per_prompt, seq_len, -1
|
| 270 |
+
)
|
| 271 |
+
|
| 272 |
+
return prompt_embeds, text_inputs.attention_mask.bool()
|
| 273 |
+
|
| 274 |
+
def encode_prompt(
|
| 275 |
+
self,
|
| 276 |
+
prompt: str | list[str],
|
| 277 |
+
negative_prompt: str | list[str] | None = None,
|
| 278 |
+
do_classifier_free_guidance: bool = True,
|
| 279 |
+
num_videos_per_prompt: int = 1,
|
| 280 |
+
prompt_embeds: torch.Tensor | None = None,
|
| 281 |
+
negative_prompt_embeds: torch.Tensor | None = None,
|
| 282 |
+
max_sequence_length: int = 226,
|
| 283 |
+
device: torch.device | None = None,
|
| 284 |
+
dtype: torch.dtype | None = None,
|
| 285 |
+
):
|
| 286 |
+
r"""
|
| 287 |
+
Encodes the prompt into text encoder hidden states.
|
| 288 |
+
|
| 289 |
+
Args:
|
| 290 |
+
prompt (`str` or `list[str]`, *optional*):
|
| 291 |
+
prompt to be encoded
|
| 292 |
+
negative_prompt (`str` or `list[str]`, *optional*):
|
| 293 |
+
The prompt or prompts not to guide the image generation. If not defined, one has to pass
|
| 294 |
+
`negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
|
| 295 |
+
less than or equal to `1`).
|
| 296 |
+
do_classifier_free_guidance (`bool`, *optional*, defaults to `True`):
|
| 297 |
+
Whether to use classifier free guidance or not.
|
| 298 |
+
num_videos_per_prompt (`int`, *optional*, defaults to 1):
|
| 299 |
+
Number of videos to generate per prompt.
|
| 300 |
+
prompt_embeds (`torch.Tensor`, *optional*):
|
| 301 |
+
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
|
| 302 |
+
provided, text embeddings will be generated from `prompt` input argument.
|
| 303 |
+
negative_prompt_embeds (`torch.Tensor`, *optional*):
|
| 304 |
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
| 305 |
+
weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
|
| 306 |
+
argument.
|
| 307 |
+
device: (`torch.device`, *optional*):
|
| 308 |
+
torch device
|
| 309 |
+
dtype: (`torch.dtype`, *optional*):
|
| 310 |
+
torch dtype
|
| 311 |
+
"""
|
| 312 |
+
device = device or self._execution_device
|
| 313 |
+
|
| 314 |
+
prompt = [prompt] if isinstance(prompt, str) else prompt
|
| 315 |
+
if prompt is not None:
|
| 316 |
+
batch_size = len(prompt)
|
| 317 |
+
else:
|
| 318 |
+
batch_size = prompt_embeds.shape[0]
|
| 319 |
+
|
| 320 |
+
if prompt_embeds is None:
|
| 321 |
+
prompt_embeds, _ = self._get_t5_prompt_embeds(
|
| 322 |
+
prompt=prompt,
|
| 323 |
+
num_videos_per_prompt=num_videos_per_prompt,
|
| 324 |
+
max_sequence_length=max_sequence_length,
|
| 325 |
+
device=device,
|
| 326 |
+
dtype=dtype,
|
| 327 |
+
)
|
| 328 |
+
|
| 329 |
+
if do_classifier_free_guidance and negative_prompt_embeds is None:
|
| 330 |
+
negative_prompt = negative_prompt or ""
|
| 331 |
+
negative_prompt = (
|
| 332 |
+
batch_size * [negative_prompt]
|
| 333 |
+
if isinstance(negative_prompt, str)
|
| 334 |
+
else negative_prompt
|
| 335 |
+
)
|
| 336 |
+
|
| 337 |
+
if prompt is not None and type(prompt) is not type(negative_prompt):
|
| 338 |
+
raise TypeError(
|
| 339 |
+
f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
|
| 340 |
+
f" {type(prompt)}."
|
| 341 |
+
)
|
| 342 |
+
elif batch_size != len(negative_prompt):
|
| 343 |
+
raise ValueError(
|
| 344 |
+
f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
|
| 345 |
+
f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
|
| 346 |
+
" the batch size of `prompt`."
|
| 347 |
+
)
|
| 348 |
+
|
| 349 |
+
negative_prompt_embeds, _ = self._get_t5_prompt_embeds(
|
| 350 |
+
prompt=negative_prompt,
|
| 351 |
+
num_videos_per_prompt=num_videos_per_prompt,
|
| 352 |
+
max_sequence_length=max_sequence_length,
|
| 353 |
+
device=device,
|
| 354 |
+
dtype=dtype,
|
| 355 |
+
)
|
| 356 |
+
|
| 357 |
+
return prompt_embeds, negative_prompt_embeds
|
| 358 |
+
|
| 359 |
+
def check_inputs(
|
| 360 |
+
self,
|
| 361 |
+
prompt,
|
| 362 |
+
negative_prompt,
|
| 363 |
+
height,
|
| 364 |
+
width,
|
| 365 |
+
prompt_embeds=None,
|
| 366 |
+
negative_prompt_embeds=None,
|
| 367 |
+
callback_on_step_end_tensor_inputs=None,
|
| 368 |
+
image=None,
|
| 369 |
+
video=None,
|
| 370 |
+
use_interpolate_prompt=False,
|
| 371 |
+
num_videos_per_prompt=None,
|
| 372 |
+
interpolate_time_list=None,
|
| 373 |
+
interpolation_steps=None,
|
| 374 |
+
guidance_scale=None,
|
| 375 |
+
):
|
| 376 |
+
if height % 16 != 0 or width % 16 != 0:
|
| 377 |
+
raise ValueError(
|
| 378 |
+
f"`height` and `width` have to be divisible by 16 but are {height} and {width}."
|
| 379 |
+
)
|
| 380 |
+
|
| 381 |
+
if callback_on_step_end_tensor_inputs is not None and not all(
|
| 382 |
+
k in self._callback_tensor_inputs
|
| 383 |
+
for k in callback_on_step_end_tensor_inputs
|
| 384 |
+
):
|
| 385 |
+
raise ValueError(
|
| 386 |
+
f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}"
|
| 387 |
+
)
|
| 388 |
+
|
| 389 |
+
if prompt is not None and prompt_embeds is not None:
|
| 390 |
+
raise ValueError(
|
| 391 |
+
f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
|
| 392 |
+
" only forward one of the two."
|
| 393 |
+
)
|
| 394 |
+
elif negative_prompt is not None and negative_prompt_embeds is not None:
|
| 395 |
+
raise ValueError(
|
| 396 |
+
f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`: {negative_prompt_embeds}. Please make sure to"
|
| 397 |
+
" only forward one of the two."
|
| 398 |
+
)
|
| 399 |
+
elif prompt is None and prompt_embeds is None:
|
| 400 |
+
raise ValueError(
|
| 401 |
+
"Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
|
| 402 |
+
)
|
| 403 |
+
elif prompt is not None and (
|
| 404 |
+
not isinstance(prompt, str) and not isinstance(prompt, list)
|
| 405 |
+
):
|
| 406 |
+
raise ValueError(
|
| 407 |
+
f"`prompt` has to be of type `str` or `list` but is {type(prompt)}"
|
| 408 |
+
)
|
| 409 |
+
elif negative_prompt is not None and (
|
| 410 |
+
not isinstance(negative_prompt, str)
|
| 411 |
+
and not isinstance(negative_prompt, list)
|
| 412 |
+
):
|
| 413 |
+
raise ValueError(
|
| 414 |
+
f"`negative_prompt` has to be of type `str` or `list` but is {type(negative_prompt)}"
|
| 415 |
+
)
|
| 416 |
+
|
| 417 |
+
if image is not None and video is not None:
|
| 418 |
+
raise ValueError("image and video cannot be provided simultaneously")
|
| 419 |
+
|
| 420 |
+
if use_interpolate_prompt:
|
| 421 |
+
assert (
|
| 422 |
+
num_videos_per_prompt == 1
|
| 423 |
+
), f"num_videos_per_prompt must be 1, got {num_videos_per_prompt}"
|
| 424 |
+
assert isinstance(prompt, list), "prompt must be a list"
|
| 425 |
+
assert len(prompt) == len(
|
| 426 |
+
interpolate_time_list
|
| 427 |
+
), f"Length mismatch: {len(prompt)} vs {len(interpolate_time_list)}"
|
| 428 |
+
assert (
|
| 429 |
+
min(interpolate_time_list) > interpolation_steps
|
| 430 |
+
), f"Minimum value {min(interpolate_time_list)} must be greater than {interpolation_steps}"
|
| 431 |
+
|
| 432 |
+
if guidance_scale > 1.0 and self.config.is_distilled:
|
| 433 |
+
logger.warning(
|
| 434 |
+
f"Guidance scale {guidance_scale} is ignored for step-wise distilled models."
|
| 435 |
+
)
|
| 436 |
+
|
| 437 |
+
def prepare_latents(
|
| 438 |
+
self,
|
| 439 |
+
batch_size: int,
|
| 440 |
+
num_channels_latents: int = 16,
|
| 441 |
+
height: int = 384,
|
| 442 |
+
width: int = 640,
|
| 443 |
+
num_frames: int = 33,
|
| 444 |
+
dtype: torch.dtype | None = None,
|
| 445 |
+
device: torch.device | None = None,
|
| 446 |
+
generator: torch.Generator | list[torch.Generator] | None = None,
|
| 447 |
+
latents: torch.Tensor | None = None,
|
| 448 |
+
) -> torch.Tensor:
|
| 449 |
+
if latents is not None:
|
| 450 |
+
return latents.to(device=device, dtype=dtype)
|
| 451 |
+
|
| 452 |
+
num_latent_frames = (num_frames - 1) // self.vae_scale_factor_temporal + 1
|
| 453 |
+
shape = (
|
| 454 |
+
batch_size,
|
| 455 |
+
num_channels_latents,
|
| 456 |
+
num_latent_frames,
|
| 457 |
+
int(height) // self.vae_scale_factor_spatial,
|
| 458 |
+
int(width) // self.vae_scale_factor_spatial,
|
| 459 |
+
)
|
| 460 |
+
if isinstance(generator, list) and len(generator) != batch_size:
|
| 461 |
+
raise ValueError(
|
| 462 |
+
f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
|
| 463 |
+
f" size of {batch_size}. Make sure the batch size matches the length of the generators."
|
| 464 |
+
)
|
| 465 |
+
|
| 466 |
+
latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
|
| 467 |
+
return latents
|
| 468 |
+
|
| 469 |
+
def prepare_image_latents(
|
| 470 |
+
self,
|
| 471 |
+
image: torch.Tensor,
|
| 472 |
+
latents_mean: torch.Tensor,
|
| 473 |
+
latents_std: torch.Tensor,
|
| 474 |
+
num_latent_frames_per_chunk: int,
|
| 475 |
+
dtype: torch.dtype | None = None,
|
| 476 |
+
device: torch.device | None = None,
|
| 477 |
+
generator: torch.Generator | list[torch.Generator] | None = None,
|
| 478 |
+
latents: torch.Tensor | None = None,
|
| 479 |
+
fake_latents: torch.Tensor | None = None,
|
| 480 |
+
) -> torch.Tensor:
|
| 481 |
+
device = device or self._execution_device
|
| 482 |
+
if latents is None:
|
| 483 |
+
image = image.unsqueeze(2).to(device=device, dtype=self.vae.dtype)
|
| 484 |
+
latents = self.vae.encode(image).latent_dist.sample(generator=generator)
|
| 485 |
+
latents = (latents - latents_mean) * latents_std
|
| 486 |
+
if fake_latents is None:
|
| 487 |
+
min_frames = (
|
| 488 |
+
num_latent_frames_per_chunk - 1
|
| 489 |
+
) * self.vae_scale_factor_temporal + 1
|
| 490 |
+
fake_video = image.repeat(1, 1, min_frames, 1, 1).to(
|
| 491 |
+
device=device, dtype=self.vae.dtype
|
| 492 |
+
)
|
| 493 |
+
fake_latents_full = self.vae.encode(fake_video).latent_dist.sample(
|
| 494 |
+
generator=generator
|
| 495 |
+
)
|
| 496 |
+
fake_latents_full = (fake_latents_full - latents_mean) * latents_std
|
| 497 |
+
fake_latents = fake_latents_full[:, :, -1:, :, :]
|
| 498 |
+
return latents.to(device=device, dtype=dtype), fake_latents.to(
|
| 499 |
+
device=device, dtype=dtype
|
| 500 |
+
)
|
| 501 |
+
|
| 502 |
+
def prepare_video_latents(
|
| 503 |
+
self,
|
| 504 |
+
video: torch.Tensor,
|
| 505 |
+
latents_mean: torch.Tensor,
|
| 506 |
+
latents_std: torch.Tensor,
|
| 507 |
+
num_latent_frames_per_chunk: int,
|
| 508 |
+
dtype: torch.dtype | None = None,
|
| 509 |
+
device: torch.device | None = None,
|
| 510 |
+
generator: torch.Generator | list[torch.Generator] | None = None,
|
| 511 |
+
latents: torch.Tensor | None = None,
|
| 512 |
+
) -> torch.Tensor:
|
| 513 |
+
device = device or self._execution_device
|
| 514 |
+
video = video.to(device=device, dtype=self.vae.dtype)
|
| 515 |
+
if latents is None:
|
| 516 |
+
num_frames = video.shape[2]
|
| 517 |
+
min_frames = (
|
| 518 |
+
num_latent_frames_per_chunk - 1
|
| 519 |
+
) * self.vae_scale_factor_temporal + 1
|
| 520 |
+
num_chunks = num_frames // min_frames
|
| 521 |
+
if num_chunks == 0:
|
| 522 |
+
raise ValueError(
|
| 523 |
+
f"Video must have at least {min_frames} frames "
|
| 524 |
+
f"(got {num_frames} frames). "
|
| 525 |
+
f"Required: (num_latent_frames_per_chunk - 1) * {self.vae_scale_factor_temporal} + 1 = ({num_latent_frames_per_chunk} - 1) * {self.vae_scale_factor_temporal} + 1 = {min_frames}"
|
| 526 |
+
)
|
| 527 |
+
total_valid_frames = num_chunks * min_frames
|
| 528 |
+
start_frame = num_frames - total_valid_frames
|
| 529 |
+
|
| 530 |
+
first_frame = video[:, :, 0:1, :, :]
|
| 531 |
+
first_frame_latent = self.vae.encode(first_frame).latent_dist.sample(
|
| 532 |
+
generator=generator
|
| 533 |
+
)
|
| 534 |
+
first_frame_latent = (first_frame_latent - latents_mean) * latents_std
|
| 535 |
+
|
| 536 |
+
latents_chunks = []
|
| 537 |
+
for i in range(num_chunks):
|
| 538 |
+
chunk_start = start_frame + i * min_frames
|
| 539 |
+
chunk_end = chunk_start + min_frames
|
| 540 |
+
video_chunk = video[:, :, chunk_start:chunk_end, :, :]
|
| 541 |
+
chunk_latents = self.vae.encode(video_chunk).latent_dist.sample(
|
| 542 |
+
generator=generator
|
| 543 |
+
)
|
| 544 |
+
chunk_latents = (chunk_latents - latents_mean) * latents_std
|
| 545 |
+
latents_chunks.append(chunk_latents)
|
| 546 |
+
latents = torch.cat(latents_chunks, dim=2)
|
| 547 |
+
return first_frame_latent.to(device=device, dtype=dtype), latents.to(
|
| 548 |
+
device=device, dtype=dtype
|
| 549 |
+
)
|
| 550 |
+
|
| 551 |
+
def interpolate_prompt_embeds(
|
| 552 |
+
self,
|
| 553 |
+
prompt_embeds_1: torch.Tensor,
|
| 554 |
+
prompt_embeds_2: torch.Tensor,
|
| 555 |
+
interpolation_steps: int = 3,
|
| 556 |
+
):
|
| 557 |
+
x = torch.lerp(
|
| 558 |
+
prompt_embeds_1,
|
| 559 |
+
prompt_embeds_2,
|
| 560 |
+
torch.linspace(0, 1, steps=interpolation_steps)
|
| 561 |
+
.unsqueeze(1)
|
| 562 |
+
.unsqueeze(2)
|
| 563 |
+
.to(prompt_embeds_1),
|
| 564 |
+
)
|
| 565 |
+
interpolated_prompt_embeds = list(x.chunk(interpolation_steps, dim=0))
|
| 566 |
+
return interpolated_prompt_embeds
|
| 567 |
+
|
| 568 |
+
def sample_block_noise(
|
| 569 |
+
self,
|
| 570 |
+
batch_size,
|
| 571 |
+
channel,
|
| 572 |
+
num_frames,
|
| 573 |
+
height,
|
| 574 |
+
width,
|
| 575 |
+
patch_size: tuple[int, ...] = (1, 2, 2),
|
| 576 |
+
device: torch.device | None = None,
|
| 577 |
+
generator: torch.Generator | None = None,
|
| 578 |
+
):
|
| 579 |
+
# The default generator is independent of the trajectory RNG.
|
| 580 |
+
if generator is None:
|
| 581 |
+
generator = torch.Generator(device=device)
|
| 582 |
+
elif isinstance(generator, list):
|
| 583 |
+
generator = generator[0]
|
| 584 |
+
|
| 585 |
+
gamma = self.scheduler.config.gamma
|
| 586 |
+
_, ph, pw = patch_size
|
| 587 |
+
block_size = ph * pw
|
| 588 |
+
|
| 589 |
+
cov = (
|
| 590 |
+
torch.eye(block_size, device=device) * (1 + gamma)
|
| 591 |
+
- torch.ones(block_size, block_size, device=device) * gamma
|
| 592 |
+
)
|
| 593 |
+
cov += torch.eye(block_size, device=device) * 1e-8
|
| 594 |
+
cov = (
|
| 595 |
+
cov.float()
|
| 596 |
+
) # Upcast to fp32 for numerical stability — cholesky is unreliable in fp16/bf16.
|
| 597 |
+
|
| 598 |
+
L = torch.linalg.cholesky(cov)
|
| 599 |
+
block_number = (
|
| 600 |
+
batch_size * channel * num_frames * (height // ph) * (width // pw)
|
| 601 |
+
)
|
| 602 |
+
z = torch.randn(
|
| 603 |
+
block_number, block_size, generator=generator, device=generator.device
|
| 604 |
+
).to(device=device)
|
| 605 |
+
noise = z @ L.T
|
| 606 |
+
|
| 607 |
+
noise = noise.view(
|
| 608 |
+
batch_size, channel, num_frames, height // ph, width // pw, ph, pw
|
| 609 |
+
)
|
| 610 |
+
noise = noise.permute(0, 1, 2, 3, 5, 4, 6).reshape(
|
| 611 |
+
batch_size, channel, num_frames, height, width
|
| 612 |
+
)
|
| 613 |
+
|
| 614 |
+
return noise
|
| 615 |
+
|
| 616 |
+
def stage1_sample(
|
| 617 |
+
self,
|
| 618 |
+
latents: torch.Tensor = None,
|
| 619 |
+
prompt_embeds: torch.Tensor = None,
|
| 620 |
+
negative_prompt_embeds: torch.Tensor = None,
|
| 621 |
+
timesteps: torch.Tensor = None,
|
| 622 |
+
guidance_scale: float | None = 5.0,
|
| 623 |
+
indices_hidden_states: torch.Tensor = None,
|
| 624 |
+
indices_latents_history_short: torch.Tensor = None,
|
| 625 |
+
indices_latents_history_mid: torch.Tensor = None,
|
| 626 |
+
indices_latents_history_long: torch.Tensor = None,
|
| 627 |
+
latents_history_short: torch.Tensor = None,
|
| 628 |
+
latents_history_mid: torch.Tensor = None,
|
| 629 |
+
latents_history_long: torch.Tensor = None,
|
| 630 |
+
attention_kwargs: dict | None = None,
|
| 631 |
+
device: torch.device | None = None,
|
| 632 |
+
transformer_dtype: torch.dtype = None,
|
| 633 |
+
generator: torch.Generator | None = None,
|
| 634 |
+
num_warmup_steps: int | None = None,
|
| 635 |
+
# ------------ CFG Zero ------------
|
| 636 |
+
use_zero_init: bool | None = True,
|
| 637 |
+
zero_steps: int | None = 1,
|
| 638 |
+
# ------------ Callback ------------
|
| 639 |
+
callback_on_step_end: (
|
| 640 |
+
Callable[[int, int], None]
|
| 641 |
+
| PipelineCallback
|
| 642 |
+
| MultiPipelineCallbacks
|
| 643 |
+
| None
|
| 644 |
+
) = None,
|
| 645 |
+
callback_on_step_end_tensor_inputs: list[str] = ["latents"],
|
| 646 |
+
progress_bar=None,
|
| 647 |
+
):
|
| 648 |
+
batch_size = latents.shape[0]
|
| 649 |
+
|
| 650 |
+
for i, t in enumerate(timesteps):
|
| 651 |
+
if self.interrupt:
|
| 652 |
+
continue
|
| 653 |
+
|
| 654 |
+
self._current_timestep = t
|
| 655 |
+
timestep = t.expand(latents.shape[0])
|
| 656 |
+
|
| 657 |
+
latent_model_input = latents.to(transformer_dtype)
|
| 658 |
+
with self.transformer.cache_context("cond"):
|
| 659 |
+
noise_pred = self.transformer(
|
| 660 |
+
hidden_states=latent_model_input,
|
| 661 |
+
timestep=timestep,
|
| 662 |
+
encoder_hidden_states=prompt_embeds,
|
| 663 |
+
indices_hidden_states=indices_hidden_states,
|
| 664 |
+
indices_latents_history_short=indices_latents_history_short,
|
| 665 |
+
indices_latents_history_mid=indices_latents_history_mid,
|
| 666 |
+
indices_latents_history_long=indices_latents_history_long,
|
| 667 |
+
latents_history_short=latents_history_short.to(transformer_dtype),
|
| 668 |
+
latents_history_mid=latents_history_mid.to(transformer_dtype),
|
| 669 |
+
latents_history_long=latents_history_long.to(transformer_dtype),
|
| 670 |
+
attention_kwargs=attention_kwargs,
|
| 671 |
+
return_dict=False,
|
| 672 |
+
)[0]
|
| 673 |
+
|
| 674 |
+
if self.do_classifier_free_guidance:
|
| 675 |
+
with self.transformer.cache_context("uncond"):
|
| 676 |
+
noise_uncond = self.transformer(
|
| 677 |
+
hidden_states=latent_model_input,
|
| 678 |
+
timestep=timestep,
|
| 679 |
+
encoder_hidden_states=negative_prompt_embeds,
|
| 680 |
+
indices_hidden_states=indices_hidden_states,
|
| 681 |
+
indices_latents_history_short=indices_latents_history_short,
|
| 682 |
+
indices_latents_history_mid=indices_latents_history_mid,
|
| 683 |
+
indices_latents_history_long=indices_latents_history_long,
|
| 684 |
+
latents_history_short=latents_history_short.to(
|
| 685 |
+
transformer_dtype
|
| 686 |
+
),
|
| 687 |
+
latents_history_mid=latents_history_mid.to(transformer_dtype),
|
| 688 |
+
latents_history_long=latents_history_long.to(transformer_dtype),
|
| 689 |
+
attention_kwargs=attention_kwargs,
|
| 690 |
+
return_dict=False,
|
| 691 |
+
)[0]
|
| 692 |
+
|
| 693 |
+
if self.config.is_cfg_zero_star:
|
| 694 |
+
noise_pred_text = noise_pred
|
| 695 |
+
positive_flat = noise_pred_text.view(batch_size, -1)
|
| 696 |
+
negative_flat = noise_uncond.view(batch_size, -1)
|
| 697 |
+
|
| 698 |
+
alpha = optimized_scale(positive_flat, negative_flat)
|
| 699 |
+
alpha = alpha.view(
|
| 700 |
+
batch_size, *([1] * (len(noise_pred_text.shape) - 1))
|
| 701 |
+
)
|
| 702 |
+
alpha = alpha.to(noise_pred_text.dtype)
|
| 703 |
+
|
| 704 |
+
if (i <= zero_steps) and use_zero_init:
|
| 705 |
+
noise_pred = noise_pred_text * 0.0
|
| 706 |
+
else:
|
| 707 |
+
noise_pred = noise_uncond * alpha + guidance_scale * (
|
| 708 |
+
noise_pred_text - noise_uncond * alpha
|
| 709 |
+
)
|
| 710 |
+
else:
|
| 711 |
+
noise_pred = noise_uncond + guidance_scale * (
|
| 712 |
+
noise_pred - noise_uncond
|
| 713 |
+
)
|
| 714 |
+
|
| 715 |
+
latents = self.scheduler.step(
|
| 716 |
+
noise_pred,
|
| 717 |
+
t,
|
| 718 |
+
latents,
|
| 719 |
+
return_dict=False,
|
| 720 |
+
)[0]
|
| 721 |
+
|
| 722 |
+
if callback_on_step_end is not None:
|
| 723 |
+
callback_kwargs = {}
|
| 724 |
+
for k in callback_on_step_end_tensor_inputs:
|
| 725 |
+
callback_kwargs[k] = locals()[k]
|
| 726 |
+
callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
|
| 727 |
+
|
| 728 |
+
latents = callback_outputs.pop("latents", latents)
|
| 729 |
+
prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
|
| 730 |
+
negative_prompt_embeds = callback_outputs.pop(
|
| 731 |
+
"negative_prompt_embeds", negative_prompt_embeds
|
| 732 |
+
)
|
| 733 |
+
|
| 734 |
+
if i == len(timesteps) - 1 or (
|
| 735 |
+
(i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0
|
| 736 |
+
):
|
| 737 |
+
progress_bar.update()
|
| 738 |
+
|
| 739 |
+
if XLA_AVAILABLE:
|
| 740 |
+
xm.mark_step()
|
| 741 |
+
|
| 742 |
+
return latents
|
| 743 |
+
|
| 744 |
+
@property
|
| 745 |
+
def guidance_scale(self):
|
| 746 |
+
return self._guidance_scale
|
| 747 |
+
|
| 748 |
+
@property
|
| 749 |
+
def do_classifier_free_guidance(self):
|
| 750 |
+
return self._guidance_scale > 1.0
|
| 751 |
+
|
| 752 |
+
@property
|
| 753 |
+
def num_timesteps(self):
|
| 754 |
+
return self._num_timesteps
|
| 755 |
+
|
| 756 |
+
@property
|
| 757 |
+
def current_timestep(self):
|
| 758 |
+
return self._current_timestep
|
| 759 |
+
|
| 760 |
+
@property
|
| 761 |
+
def interrupt(self):
|
| 762 |
+
return self._interrupt
|
| 763 |
+
|
| 764 |
+
@property
|
| 765 |
+
def attention_kwargs(self):
|
| 766 |
+
return self._attention_kwargs
|
| 767 |
+
|
| 768 |
+
@torch.no_grad()
|
| 769 |
+
@replace_example_docstring(EXAMPLE_DOC_STRING)
|
| 770 |
+
def __call__(
|
| 771 |
+
self,
|
| 772 |
+
prompt: str | list[str] = None,
|
| 773 |
+
negative_prompt: str | list[str] = None,
|
| 774 |
+
height: int = 384,
|
| 775 |
+
width: int = 640,
|
| 776 |
+
num_frames: int = 132,
|
| 777 |
+
num_inference_steps: int = 50,
|
| 778 |
+
sigmas: list[float] = None,
|
| 779 |
+
guidance_scale: float = 5.0,
|
| 780 |
+
num_videos_per_prompt: int | None = 1,
|
| 781 |
+
generator: torch.Generator | list[torch.Generator] | None = None,
|
| 782 |
+
latents: torch.Tensor | None = None,
|
| 783 |
+
prompt_embeds: torch.Tensor | None = None,
|
| 784 |
+
negative_prompt_embeds: torch.Tensor | None = None,
|
| 785 |
+
output_type: str | None = "np",
|
| 786 |
+
return_dict: bool = True,
|
| 787 |
+
attention_kwargs: dict[str, Any] | None = None,
|
| 788 |
+
callback_on_step_end: (
|
| 789 |
+
Callable[[int, int], None]
|
| 790 |
+
| PipelineCallback
|
| 791 |
+
| MultiPipelineCallbacks
|
| 792 |
+
| None
|
| 793 |
+
) = None,
|
| 794 |
+
callback_on_step_end_tensor_inputs: list[str] = ["latents"],
|
| 795 |
+
callback_on_chunk_end: Callable[[int, torch.Tensor], None] | None = None,
|
| 796 |
+
callback_on_chunk_state: Callable[[int, dict[str, Any]], None] | None = None,
|
| 797 |
+
resume_state: dict[str, Any] | None = None,
|
| 798 |
+
stop_after_chunk: int | None = None,
|
| 799 |
+
max_sequence_length: int = 512,
|
| 800 |
+
# ------------ I2V ------------
|
| 801 |
+
image: PipelineImageInput | None = None,
|
| 802 |
+
image_latents: torch.Tensor | None = None,
|
| 803 |
+
fake_image_latents: torch.Tensor | None = None,
|
| 804 |
+
add_noise_to_image_latents: bool = True,
|
| 805 |
+
image_noise_sigma_min: float = 0.111,
|
| 806 |
+
image_noise_sigma_max: float = 0.135,
|
| 807 |
+
# ------------ V2V ------------
|
| 808 |
+
video: PipelineImageInput | None = None,
|
| 809 |
+
video_latents: torch.Tensor | None = None,
|
| 810 |
+
add_noise_to_video_latents: bool = True,
|
| 811 |
+
video_noise_sigma_min: float = 0.111,
|
| 812 |
+
video_noise_sigma_max: float = 0.135,
|
| 813 |
+
# ------------ Interactive ------------
|
| 814 |
+
use_interpolate_prompt: bool = False,
|
| 815 |
+
interpolate_time_list: list = [7, 7, 7],
|
| 816 |
+
interpolation_steps: int = 3,
|
| 817 |
+
# ------------ Stage 1 ------------
|
| 818 |
+
memory_size: int = 4,
|
| 819 |
+
history_sizes: list = [2, 1],
|
| 820 |
+
num_latent_frames_per_chunk: int = 9,
|
| 821 |
+
keep_first_frame: bool = True,
|
| 822 |
+
is_skip_first_chunk: bool = False,
|
| 823 |
+
# ------------ Camera control ------------
|
| 824 |
+
camera_trajectory: dict[str, Any] | None = None,
|
| 825 |
+
# ------------ RepEncoder 3D memory ------------
|
| 826 |
+
memory_provider: Any | None = None,
|
| 827 |
+
# ------------ Stage 2 ------------
|
| 828 |
+
is_enable_stage2: bool = False,
|
| 829 |
+
pyramid_num_stages: int = 3,
|
| 830 |
+
pyramid_num_inference_steps_list: list = [10, 10, 10],
|
| 831 |
+
# ------------ CFG Zero ------------
|
| 832 |
+
use_zero_init: bool | None = True,
|
| 833 |
+
zero_steps: int | None = 1,
|
| 834 |
+
# ------------ DMD ------------
|
| 835 |
+
is_amplify_first_chunk: bool = False,
|
| 836 |
+
):
|
| 837 |
+
r"""
|
| 838 |
+
The call function to the pipeline for generation.
|
| 839 |
+
|
| 840 |
+
Args:
|
| 841 |
+
prompt (`str` or `list[str]`, *optional*):
|
| 842 |
+
The prompt or prompts to guide the image generation. If not defined, pass `prompt_embeds` instead.
|
| 843 |
+
negative_prompt (`str` or `list[str]`, *optional*):
|
| 844 |
+
The prompt or prompts to avoid during image generation. If not defined, pass `negative_prompt_embeds`
|
| 845 |
+
instead. Ignored when not using guidance (`guidance_scale` <= `1`).
|
| 846 |
+
height (`int`, defaults to `384`):
|
| 847 |
+
The height in pixels of the generated image.
|
| 848 |
+
width (`int`, defaults to `640`):
|
| 849 |
+
The width in pixels of the generated image.
|
| 850 |
+
num_frames (`int`, defaults to `132`):
|
| 851 |
+
The number of frames in the generated video.
|
| 852 |
+
num_inference_steps (`int`, defaults to `50`):
|
| 853 |
+
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
|
| 854 |
+
expense of slower inference.
|
| 855 |
+
guidance_scale (`float`, defaults to `5.0`):
|
| 856 |
+
Guidance scale as defined in [Classifier-Free Diffusion
|
| 857 |
+
Guidance](https://huggingface.co/papers/2207.12598). `guidance_scale` is defined as `w` of equation 2.
|
| 858 |
+
of [Imagen Paper](https://huggingface.co/papers/2205.11487). Guidance scale is enabled by setting
|
| 859 |
+
`guidance_scale > 1`. Higher guidance scale encourages to generate images that are closely linked to
|
| 860 |
+
the text `prompt`, usually at the expense of lower image quality.
|
| 861 |
+
num_videos_per_prompt (`int`, *optional*, defaults to 1):
|
| 862 |
+
The number of videos to generate per prompt.
|
| 863 |
+
generator (`torch.Generator` or `list[torch.Generator]`, *optional*):
|
| 864 |
+
A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
|
| 865 |
+
generation deterministic.
|
| 866 |
+
latents (`torch.Tensor`, *optional*):
|
| 867 |
+
Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
|
| 868 |
+
generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
|
| 869 |
+
tensor is generated by sampling using the supplied random `generator`.
|
| 870 |
+
prompt_embeds (`torch.Tensor`, *optional*):
|
| 871 |
+
Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
|
| 872 |
+
provided, text embeddings are generated from the `prompt` input argument.
|
| 873 |
+
output_type (`str`, *optional*, defaults to `"np"`):
|
| 874 |
+
Video output format: `"np"`, `"pt"`, or `"pil"`; `"latent"` returns latent tensors.
|
| 875 |
+
return_dict (`bool`, *optional*, defaults to `True`):
|
| 876 |
+
Whether or not to return a [`WorldCrafterPipelineOutput`] instead of a plain tuple.
|
| 877 |
+
attention_kwargs (`dict`, *optional*):
|
| 878 |
+
A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
|
| 879 |
+
`self.processor` in
|
| 880 |
+
[diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
|
| 881 |
+
callback_on_step_end (`Callable`, `PipelineCallback`, `MultiPipelineCallbacks`, *optional*):
|
| 882 |
+
A function or a subclass of `PipelineCallback` or `MultiPipelineCallbacks` that is called at the end of
|
| 883 |
+
each denoising step during the inference. with the following arguments: `callback_on_step_end(self:
|
| 884 |
+
DiffusionPipeline, step: int, timestep: int, callback_kwargs: Dict)`. `callback_kwargs` will include a
|
| 885 |
+
list of all tensors as specified by `callback_on_step_end_tensor_inputs`.
|
| 886 |
+
callback_on_step_end_tensor_inputs (`list`, *optional*):
|
| 887 |
+
The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
|
| 888 |
+
will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
|
| 889 |
+
`._callback_tensor_inputs` attribute of your pipeline class.
|
| 890 |
+
max_sequence_length (`int`, defaults to `512`):
|
| 891 |
+
The maximum sequence length of the text encoder. If the prompt is longer than this, it will be
|
| 892 |
+
truncated. If the prompt is shorter, it will be padded to this length.
|
| 893 |
+
|
| 894 |
+
Examples:
|
| 895 |
+
|
| 896 |
+
Returns:
|
| 897 |
+
[`~WorldCrafterPipelineOutput`] or `tuple`:
|
| 898 |
+
If `return_dict` is `True`, [`WorldCrafterPipelineOutput`] is returned, otherwise a `tuple` is returned where
|
| 899 |
+
the only element contains the generated video batch. No safety-classification flags are returned.
|
| 900 |
+
"""
|
| 901 |
+
|
| 902 |
+
if image is not None and video is not None:
|
| 903 |
+
raise ValueError("image and video cannot be provided simultaneously")
|
| 904 |
+
use_fast = bool(self.config.is_distilled)
|
| 905 |
+
if use_fast:
|
| 906 |
+
if not is_enable_stage2 or guidance_scale != 1.0:
|
| 907 |
+
raise ValueError("Fast inference requires pyramid sampling and CFG=1")
|
| 908 |
+
if pyramid_num_inference_steps_list is not None:
|
| 909 |
+
raise ValueError("Fast steps are owned by the checkpoint DMD contract")
|
| 910 |
+
if resume_state is not None:
|
| 911 |
+
raise ValueError("Fast resume is not yet validated")
|
| 912 |
+
elif camera_trajectory is not None and is_enable_stage2:
|
| 913 |
+
raise ValueError("Base camera inference requires stage1 sampling")
|
| 914 |
+
if memory_size != 4:
|
| 915 |
+
raise ValueError(
|
| 916 |
+
f"RepEncoder memory contract requires memory_size=4, got {memory_size}"
|
| 917 |
+
)
|
| 918 |
+
if num_latent_frames_per_chunk != 9:
|
| 919 |
+
raise ValueError(
|
| 920 |
+
"RepEncoder target slots [2,4,6,8] require num_latent_frames_per_chunk=9, "
|
| 921 |
+
f"got {num_latent_frames_per_chunk}"
|
| 922 |
+
)
|
| 923 |
+
|
| 924 |
+
requested_window_num_frames = (
|
| 925 |
+
num_latent_frames_per_chunk - 1
|
| 926 |
+
) * self.vae_scale_factor_temporal + 1
|
| 927 |
+
requested_num_chunks = max(
|
| 928 |
+
1,
|
| 929 |
+
(max(num_frames, 1) + requested_window_num_frames - 1)
|
| 930 |
+
// requested_window_num_frames,
|
| 931 |
+
)
|
| 932 |
+
if use_interpolate_prompt:
|
| 933 |
+
requested_num_chunks = max(requested_num_chunks, sum(interpolate_time_list))
|
| 934 |
+
if requested_num_chunks > 1:
|
| 935 |
+
if camera_trajectory is None:
|
| 936 |
+
raise ValueError(
|
| 937 |
+
"Multi-chunk RepEncoder inference requires a global metric camera trajectory"
|
| 938 |
+
)
|
| 939 |
+
if memory_provider is None:
|
| 940 |
+
raise ValueError("Multi-chunk inference requires memory_provider")
|
| 941 |
+
|
| 942 |
+
history_sizes = sorted(history_sizes, reverse=True) # From big to small
|
| 943 |
+
assert (
|
| 944 |
+
memory_size <= num_latent_frames_per_chunk
|
| 945 |
+
), f"memory_size={memory_size} must be <= num_latent_frames_per_chunk={num_latent_frames_per_chunk}"
|
| 946 |
+
|
| 947 |
+
if isinstance(callback_on_step_end, (PipelineCallback, MultiPipelineCallbacks)):
|
| 948 |
+
callback_on_step_end_tensor_inputs = callback_on_step_end.tensor_inputs
|
| 949 |
+
|
| 950 |
+
# 1. Check inputs. Raise error if not correct
|
| 951 |
+
self.check_inputs(
|
| 952 |
+
prompt,
|
| 953 |
+
negative_prompt,
|
| 954 |
+
height,
|
| 955 |
+
width,
|
| 956 |
+
prompt_embeds,
|
| 957 |
+
negative_prompt_embeds,
|
| 958 |
+
callback_on_step_end_tensor_inputs,
|
| 959 |
+
image,
|
| 960 |
+
video,
|
| 961 |
+
use_interpolate_prompt,
|
| 962 |
+
num_videos_per_prompt,
|
| 963 |
+
interpolate_time_list,
|
| 964 |
+
interpolation_steps,
|
| 965 |
+
guidance_scale,
|
| 966 |
+
)
|
| 967 |
+
|
| 968 |
+
num_frames = max(num_frames, 1)
|
| 969 |
+
|
| 970 |
+
self._guidance_scale = guidance_scale
|
| 971 |
+
self._attention_kwargs = attention_kwargs
|
| 972 |
+
self._current_timestep = None
|
| 973 |
+
self._interrupt = False
|
| 974 |
+
|
| 975 |
+
device = self._execution_device
|
| 976 |
+
vae_dtype = self.vae.dtype
|
| 977 |
+
|
| 978 |
+
latents_mean = (
|
| 979 |
+
torch.tensor(self.vae.config.latents_mean)
|
| 980 |
+
.view(1, self.vae.config.z_dim, 1, 1, 1)
|
| 981 |
+
.to(device, self.vae.dtype)
|
| 982 |
+
)
|
| 983 |
+
latents_std = 1.0 / torch.tensor(self.vae.config.latents_std).view(
|
| 984 |
+
1, self.vae.config.z_dim, 1, 1, 1
|
| 985 |
+
).to(device, self.vae.dtype)
|
| 986 |
+
|
| 987 |
+
# 2. Define call parameters
|
| 988 |
+
if use_interpolate_prompt or (prompt is not None and isinstance(prompt, str)):
|
| 989 |
+
batch_size = 1
|
| 990 |
+
elif prompt is not None and isinstance(prompt, list):
|
| 991 |
+
batch_size = len(prompt)
|
| 992 |
+
else:
|
| 993 |
+
batch_size = prompt_embeds.shape[0]
|
| 994 |
+
|
| 995 |
+
# 3. Encode input prompt
|
| 996 |
+
if use_interpolate_prompt:
|
| 997 |
+
interpolate_interval_idx = None
|
| 998 |
+
interpolate_embeds = None
|
| 999 |
+
interpolate_cumulative_list = list(accumulate(interpolate_time_list))
|
| 1000 |
+
|
| 1001 |
+
all_prompt_embeds, negative_prompt_embeds = self.encode_prompt(
|
| 1002 |
+
prompt=prompt,
|
| 1003 |
+
negative_prompt=negative_prompt,
|
| 1004 |
+
do_classifier_free_guidance=self.do_classifier_free_guidance,
|
| 1005 |
+
num_videos_per_prompt=num_videos_per_prompt,
|
| 1006 |
+
prompt_embeds=prompt_embeds,
|
| 1007 |
+
negative_prompt_embeds=negative_prompt_embeds,
|
| 1008 |
+
max_sequence_length=max_sequence_length,
|
| 1009 |
+
device=device,
|
| 1010 |
+
)
|
| 1011 |
+
|
| 1012 |
+
transformer_dtype = self.transformer.dtype
|
| 1013 |
+
all_prompt_embeds = all_prompt_embeds.to(transformer_dtype)
|
| 1014 |
+
if negative_prompt_embeds is not None:
|
| 1015 |
+
if use_interpolate_prompt:
|
| 1016 |
+
negative_prompt_embeds = negative_prompt_embeds[0].unsqueeze(0)
|
| 1017 |
+
negative_prompt_embeds = negative_prompt_embeds.to(transformer_dtype)
|
| 1018 |
+
|
| 1019 |
+
# 4. Prepare image or video
|
| 1020 |
+
if image is not None:
|
| 1021 |
+
image = self.video_processor.preprocess(image, height=height, width=width)
|
| 1022 |
+
image_latents, fake_image_latents = self.prepare_image_latents(
|
| 1023 |
+
image,
|
| 1024 |
+
latents_mean=latents_mean,
|
| 1025 |
+
latents_std=latents_std,
|
| 1026 |
+
num_latent_frames_per_chunk=num_latent_frames_per_chunk,
|
| 1027 |
+
dtype=torch.float32,
|
| 1028 |
+
device=device,
|
| 1029 |
+
generator=generator,
|
| 1030 |
+
latents=image_latents,
|
| 1031 |
+
fake_latents=fake_image_latents,
|
| 1032 |
+
)
|
| 1033 |
+
|
| 1034 |
+
if image_latents is not None and add_noise_to_image_latents:
|
| 1035 |
+
image_noise_sigma = (
|
| 1036 |
+
torch.rand(1, device=device, generator=generator)
|
| 1037 |
+
* (image_noise_sigma_max - image_noise_sigma_min)
|
| 1038 |
+
+ image_noise_sigma_min
|
| 1039 |
+
)
|
| 1040 |
+
image_latents = (
|
| 1041 |
+
image_noise_sigma
|
| 1042 |
+
* randn_tensor(image_latents.shape, generator=generator, device=device)
|
| 1043 |
+
+ (1 - image_noise_sigma) * image_latents
|
| 1044 |
+
)
|
| 1045 |
+
fake_image_noise_sigma = (
|
| 1046 |
+
torch.rand(1, device=device, generator=generator)
|
| 1047 |
+
* (video_noise_sigma_max - video_noise_sigma_min)
|
| 1048 |
+
+ video_noise_sigma_min
|
| 1049 |
+
)
|
| 1050 |
+
fake_image_latents = (
|
| 1051 |
+
fake_image_noise_sigma
|
| 1052 |
+
* randn_tensor(
|
| 1053 |
+
fake_image_latents.shape, generator=generator, device=device
|
| 1054 |
+
)
|
| 1055 |
+
+ (1 - fake_image_noise_sigma) * fake_image_latents
|
| 1056 |
+
)
|
| 1057 |
+
|
| 1058 |
+
if video is not None:
|
| 1059 |
+
video = self.video_processor.preprocess_video(
|
| 1060 |
+
video, height=height, width=width
|
| 1061 |
+
)
|
| 1062 |
+
image_latents, video_latents = self.prepare_video_latents(
|
| 1063 |
+
video,
|
| 1064 |
+
latents_mean=latents_mean,
|
| 1065 |
+
latents_std=latents_std,
|
| 1066 |
+
num_latent_frames_per_chunk=num_latent_frames_per_chunk,
|
| 1067 |
+
dtype=torch.float32,
|
| 1068 |
+
device=device,
|
| 1069 |
+
generator=generator,
|
| 1070 |
+
latents=video_latents,
|
| 1071 |
+
)
|
| 1072 |
+
|
| 1073 |
+
if video_latents is not None and add_noise_to_video_latents:
|
| 1074 |
+
image_noise_sigma = (
|
| 1075 |
+
torch.rand(1, device=device, generator=generator)
|
| 1076 |
+
* (image_noise_sigma_max - image_noise_sigma_min)
|
| 1077 |
+
+ image_noise_sigma_min
|
| 1078 |
+
)
|
| 1079 |
+
image_latents = (
|
| 1080 |
+
image_noise_sigma
|
| 1081 |
+
* randn_tensor(image_latents.shape, generator=generator, device=device)
|
| 1082 |
+
+ (1 - image_noise_sigma) * image_latents
|
| 1083 |
+
)
|
| 1084 |
+
|
| 1085 |
+
noisy_latents_chunks = []
|
| 1086 |
+
num_latent_chunks = video_latents.shape[2] // num_latent_frames_per_chunk
|
| 1087 |
+
for i in range(num_latent_chunks):
|
| 1088 |
+
chunk_start = i * num_latent_frames_per_chunk
|
| 1089 |
+
chunk_end = chunk_start + num_latent_frames_per_chunk
|
| 1090 |
+
latent_chunk = video_latents[:, :, chunk_start:chunk_end, :, :]
|
| 1091 |
+
|
| 1092 |
+
chunk_frames = latent_chunk.shape[2]
|
| 1093 |
+
frame_sigmas = (
|
| 1094 |
+
torch.rand(chunk_frames, device=device, generator=generator)
|
| 1095 |
+
* (video_noise_sigma_max - video_noise_sigma_min)
|
| 1096 |
+
+ video_noise_sigma_min
|
| 1097 |
+
)
|
| 1098 |
+
frame_sigmas = frame_sigmas.view(1, 1, chunk_frames, 1, 1)
|
| 1099 |
+
|
| 1100 |
+
noisy_chunk = (
|
| 1101 |
+
frame_sigmas
|
| 1102 |
+
* randn_tensor(
|
| 1103 |
+
latent_chunk.shape, generator=generator, device=device
|
| 1104 |
+
)
|
| 1105 |
+
+ (1 - frame_sigmas) * latent_chunk
|
| 1106 |
+
)
|
| 1107 |
+
noisy_latents_chunks.append(noisy_chunk)
|
| 1108 |
+
video_latents = torch.cat(noisy_latents_chunks, dim=2)
|
| 1109 |
+
|
| 1110 |
+
# 5. Prepare latent variables
|
| 1111 |
+
num_channels_latents = self.transformer.config.in_channels
|
| 1112 |
+
window_num_frames = (
|
| 1113 |
+
num_latent_frames_per_chunk - 1
|
| 1114 |
+
) * self.vae_scale_factor_temporal + 1
|
| 1115 |
+
num_latent_chunk = max(
|
| 1116 |
+
1, (num_frames + window_num_frames - 1) // window_num_frames
|
| 1117 |
+
)
|
| 1118 |
+
history_video = None
|
| 1119 |
+
total_generated_latent_frames = 0
|
| 1120 |
+
|
| 1121 |
+
if not keep_first_frame:
|
| 1122 |
+
history_sizes[-1] = history_sizes[-1] + 1
|
| 1123 |
+
history_latents = torch.zeros(
|
| 1124 |
+
batch_size,
|
| 1125 |
+
num_channels_latents,
|
| 1126 |
+
sum(history_sizes),
|
| 1127 |
+
height // self.vae_scale_factor_spatial,
|
| 1128 |
+
width // self.vae_scale_factor_spatial,
|
| 1129 |
+
device=device,
|
| 1130 |
+
dtype=torch.float32,
|
| 1131 |
+
)
|
| 1132 |
+
if fake_image_latents is not None:
|
| 1133 |
+
history_latents = torch.cat([history_latents, fake_image_latents], dim=2)
|
| 1134 |
+
total_generated_latent_frames += 1
|
| 1135 |
+
if video_latents is not None:
|
| 1136 |
+
history_frames = history_latents.shape[2]
|
| 1137 |
+
video_frames = video_latents.shape[2]
|
| 1138 |
+
if video_frames < history_frames:
|
| 1139 |
+
keep_frames = history_frames - video_frames
|
| 1140 |
+
history_latents = torch.cat(
|
| 1141 |
+
[history_latents[:, :, :keep_frames, :, :], video_latents], dim=2
|
| 1142 |
+
)
|
| 1143 |
+
else:
|
| 1144 |
+
history_latents = video_latents
|
| 1145 |
+
total_generated_latent_frames += video_latents.shape[2]
|
| 1146 |
+
|
| 1147 |
+
generated_memory_latents = history_latents[:, :, :0, :, :]
|
| 1148 |
+
|
| 1149 |
+
start_chunk = 0
|
| 1150 |
+
if resume_state is not None:
|
| 1151 |
+
if resume_state.get("format") != "worldcrafter_chunk_state_v1":
|
| 1152 |
+
raise ValueError("unsupported WorldCrafter resume-state format")
|
| 1153 |
+
start_chunk = int(resume_state["next_chunk_index"])
|
| 1154 |
+
if start_chunk <= 0 or start_chunk >= num_latent_chunk:
|
| 1155 |
+
raise ValueError(
|
| 1156 |
+
f"resume next_chunk_index must be in [1, {num_latent_chunk - 1}], got {start_chunk}"
|
| 1157 |
+
)
|
| 1158 |
+
generated_memory_latents = resume_state["generated_memory_latents"].to(
|
| 1159 |
+
device=device, dtype=torch.float32
|
| 1160 |
+
)
|
| 1161 |
+
expected_generated = start_chunk * num_latent_frames_per_chunk
|
| 1162 |
+
if tuple(generated_memory_latents.shape) != (
|
| 1163 |
+
batch_size,
|
| 1164 |
+
num_channels_latents,
|
| 1165 |
+
expected_generated,
|
| 1166 |
+
height // self.vae_scale_factor_spatial,
|
| 1167 |
+
width // self.vae_scale_factor_spatial,
|
| 1168 |
+
):
|
| 1169 |
+
raise ValueError(
|
| 1170 |
+
"resume generated_memory_latents shape does not match next_chunk_index: "
|
| 1171 |
+
f"{tuple(generated_memory_latents.shape)}"
|
| 1172 |
+
)
|
| 1173 |
+
history_latents = resume_state["history_latents"].to(
|
| 1174 |
+
device=device, dtype=torch.float32
|
| 1175 |
+
)
|
| 1176 |
+
expected_history = (
|
| 1177 |
+
batch_size,
|
| 1178 |
+
num_channels_latents,
|
| 1179 |
+
sum(history_sizes),
|
| 1180 |
+
height // self.vae_scale_factor_spatial,
|
| 1181 |
+
width // self.vae_scale_factor_spatial,
|
| 1182 |
+
)
|
| 1183 |
+
if tuple(history_latents.shape) != expected_history:
|
| 1184 |
+
raise ValueError(
|
| 1185 |
+
f"resume history_latents must have shape {expected_history}, "
|
| 1186 |
+
f"got {tuple(history_latents.shape)}"
|
| 1187 |
+
)
|
| 1188 |
+
saved_image_latents = resume_state.get("image_latents")
|
| 1189 |
+
if saved_image_latents is None:
|
| 1190 |
+
if keep_first_frame:
|
| 1191 |
+
raise ValueError("resume state is missing fixed image_latents")
|
| 1192 |
+
image_latents = None
|
| 1193 |
+
else:
|
| 1194 |
+
image_latents = saved_image_latents.to(
|
| 1195 |
+
device=device, dtype=torch.float32
|
| 1196 |
+
)
|
| 1197 |
+
if not isinstance(generator, torch.Generator):
|
| 1198 |
+
raise TypeError(
|
| 1199 |
+
"resumable WorldCrafter inference requires one torch.Generator"
|
| 1200 |
+
)
|
| 1201 |
+
generator.set_state(resume_state["generator_state"].cpu())
|
| 1202 |
+
total_generated_latent_frames = expected_generated
|
| 1203 |
+
|
| 1204 |
+
final_chunk_index = num_latent_chunk - 1
|
| 1205 |
+
if stop_after_chunk is not None:
|
| 1206 |
+
final_chunk_index = int(stop_after_chunk)
|
| 1207 |
+
if final_chunk_index < start_chunk or final_chunk_index >= num_latent_chunk:
|
| 1208 |
+
raise ValueError("stop_after_chunk is outside this inference interval")
|
| 1209 |
+
|
| 1210 |
+
# 6. Denoising loop
|
| 1211 |
+
if use_interpolate_prompt:
|
| 1212 |
+
if num_latent_chunk < max(interpolate_cumulative_list):
|
| 1213 |
+
num_latent_chunk = sum(interpolate_cumulative_list)
|
| 1214 |
+
print(f"Update num_latent_chunk to: {num_latent_chunk}")
|
| 1215 |
+
|
| 1216 |
+
if not is_enable_stage2:
|
| 1217 |
+
patch_size = self.transformer.config.patch_size
|
| 1218 |
+
image_seq_len = (
|
| 1219 |
+
num_latent_frames_per_chunk
|
| 1220 |
+
* (height // self.vae_scale_factor_spatial)
|
| 1221 |
+
* (width // self.vae_scale_factor_spatial)
|
| 1222 |
+
// (patch_size[0] * patch_size[1] * patch_size[2])
|
| 1223 |
+
)
|
| 1224 |
+
sigmas = (
|
| 1225 |
+
np.linspace(0.999, 0.0, num_inference_steps + 1)[:-1]
|
| 1226 |
+
if sigmas is None
|
| 1227 |
+
else sigmas
|
| 1228 |
+
)
|
| 1229 |
+
mu = calculate_shift(
|
| 1230 |
+
image_seq_len,
|
| 1231 |
+
self.scheduler.config.get("base_image_seq_len", 256),
|
| 1232 |
+
self.scheduler.config.get("max_image_seq_len", 4096),
|
| 1233 |
+
self.scheduler.config.get("base_shift", 0.5),
|
| 1234 |
+
self.scheduler.config.get("max_shift", 1.15),
|
| 1235 |
+
)
|
| 1236 |
+
|
| 1237 |
+
for k in range(start_chunk, num_latent_chunk):
|
| 1238 |
+
if use_interpolate_prompt:
|
| 1239 |
+
assert num_latent_chunk >= max(interpolate_cumulative_list)
|
| 1240 |
+
|
| 1241 |
+
current_interval_idx = 0
|
| 1242 |
+
for idx, cumulative_val in enumerate(interpolate_cumulative_list):
|
| 1243 |
+
if k < cumulative_val:
|
| 1244 |
+
current_interval_idx = idx
|
| 1245 |
+
break
|
| 1246 |
+
|
| 1247 |
+
if current_interval_idx == 0:
|
| 1248 |
+
prompt_embeds = all_prompt_embeds[0].unsqueeze(0)
|
| 1249 |
+
else:
|
| 1250 |
+
interval_start = interpolate_cumulative_list[
|
| 1251 |
+
current_interval_idx - 1
|
| 1252 |
+
]
|
| 1253 |
+
position_in_interval = k - interval_start
|
| 1254 |
+
|
| 1255 |
+
if position_in_interval < interpolation_steps:
|
| 1256 |
+
if (
|
| 1257 |
+
interpolate_embeds is None
|
| 1258 |
+
or interpolate_interval_idx != current_interval_idx
|
| 1259 |
+
):
|
| 1260 |
+
interpolate_embeds = self.interpolate_prompt_embeds(
|
| 1261 |
+
prompt_embeds_1=all_prompt_embeds[
|
| 1262 |
+
current_interval_idx - 1
|
| 1263 |
+
].unsqueeze(0),
|
| 1264 |
+
prompt_embeds_2=all_prompt_embeds[
|
| 1265 |
+
current_interval_idx
|
| 1266 |
+
].unsqueeze(0),
|
| 1267 |
+
interpolation_steps=interpolation_steps,
|
| 1268 |
+
)
|
| 1269 |
+
interpolate_interval_idx = current_interval_idx
|
| 1270 |
+
|
| 1271 |
+
prompt_embeds = interpolate_embeds[position_in_interval]
|
| 1272 |
+
else:
|
| 1273 |
+
prompt_embeds = all_prompt_embeds[
|
| 1274 |
+
current_interval_idx
|
| 1275 |
+
].unsqueeze(0)
|
| 1276 |
+
else:
|
| 1277 |
+
prompt_embeds = all_prompt_embeds
|
| 1278 |
+
|
| 1279 |
+
is_first_chunk = k == 0
|
| 1280 |
+
is_second_chunk = k == 1
|
| 1281 |
+
if is_first_chunk:
|
| 1282 |
+
first_memory_latents = generated_memory_latents.new_zeros(
|
| 1283 |
+
batch_size,
|
| 1284 |
+
num_channels_latents,
|
| 1285 |
+
memory_size,
|
| 1286 |
+
height // self.vae_scale_factor_spatial,
|
| 1287 |
+
width // self.vae_scale_factor_spatial,
|
| 1288 |
+
)
|
| 1289 |
+
else:
|
| 1290 |
+
first_memory_latents = _render_repencoder_memory_latents(
|
| 1291 |
+
memory_provider=memory_provider,
|
| 1292 |
+
generated_latents=generated_memory_latents,
|
| 1293 |
+
camera_trajectory=camera_trajectory,
|
| 1294 |
+
chunk_index=k,
|
| 1295 |
+
num_latent_frames_per_chunk=num_latent_frames_per_chunk,
|
| 1296 |
+
vae_scale_factor_temporal=self.vae_scale_factor_temporal,
|
| 1297 |
+
generator=generator,
|
| 1298 |
+
)
|
| 1299 |
+
if keep_first_frame:
|
| 1300 |
+
if is_first_chunk:
|
| 1301 |
+
history_sizes_first_chunk = [1] + history_sizes.copy()
|
| 1302 |
+
history_latents_first_chunk = torch.zeros(
|
| 1303 |
+
batch_size,
|
| 1304 |
+
num_channels_latents,
|
| 1305 |
+
sum(history_sizes_first_chunk),
|
| 1306 |
+
height // self.vae_scale_factor_spatial,
|
| 1307 |
+
width // self.vae_scale_factor_spatial,
|
| 1308 |
+
device=device,
|
| 1309 |
+
dtype=torch.float32,
|
| 1310 |
+
)
|
| 1311 |
+
if fake_image_latents is not None:
|
| 1312 |
+
history_latents_first_chunk = torch.cat(
|
| 1313 |
+
[history_latents_first_chunk, fake_image_latents], dim=2
|
| 1314 |
+
)
|
| 1315 |
+
if video_latents is not None:
|
| 1316 |
+
history_frames = history_latents_first_chunk.shape[2]
|
| 1317 |
+
video_frames = video_latents.shape[2]
|
| 1318 |
+
if video_frames < history_frames:
|
| 1319 |
+
keep_frames = history_frames - video_frames
|
| 1320 |
+
history_latents_first_chunk = torch.cat(
|
| 1321 |
+
[
|
| 1322 |
+
history_latents_first_chunk[
|
| 1323 |
+
:, :, :keep_frames, :, :
|
| 1324 |
+
],
|
| 1325 |
+
video_latents,
|
| 1326 |
+
],
|
| 1327 |
+
dim=2,
|
| 1328 |
+
)
|
| 1329 |
+
else:
|
| 1330 |
+
history_latents_first_chunk = video_latents
|
| 1331 |
+
|
| 1332 |
+
indices = torch.arange(
|
| 1333 |
+
0,
|
| 1334 |
+
sum(
|
| 1335 |
+
[
|
| 1336 |
+
1,
|
| 1337 |
+
memory_size,
|
| 1338 |
+
*history_sizes,
|
| 1339 |
+
num_latent_frames_per_chunk,
|
| 1340 |
+
]
|
| 1341 |
+
),
|
| 1342 |
+
)
|
| 1343 |
+
(
|
| 1344 |
+
indices_prefix,
|
| 1345 |
+
indices_latents_memory,
|
| 1346 |
+
indices_latents_history_mid,
|
| 1347 |
+
indices_latents_history_1x,
|
| 1348 |
+
indices_hidden_states,
|
| 1349 |
+
) = indices.split(
|
| 1350 |
+
[1, memory_size, *history_sizes, num_latent_frames_per_chunk],
|
| 1351 |
+
dim=0,
|
| 1352 |
+
)
|
| 1353 |
+
indices_latents_history_short = torch.cat(
|
| 1354 |
+
[indices_prefix, indices_latents_history_1x], dim=0
|
| 1355 |
+
)
|
| 1356 |
+
|
| 1357 |
+
latents_memory = first_memory_latents
|
| 1358 |
+
latents_prefix, latents_history_mid, latents_history_1x = (
|
| 1359 |
+
history_latents_first_chunk[
|
| 1360 |
+
:, :, -sum(history_sizes_first_chunk) :
|
| 1361 |
+
].split(history_sizes_first_chunk, dim=2)
|
| 1362 |
+
)
|
| 1363 |
+
if image_latents is not None:
|
| 1364 |
+
latents_prefix = image_latents
|
| 1365 |
+
latents_history_short = torch.cat(
|
| 1366 |
+
[latents_prefix, latents_history_1x], dim=2
|
| 1367 |
+
)
|
| 1368 |
+
else:
|
| 1369 |
+
indices = torch.arange(
|
| 1370 |
+
0,
|
| 1371 |
+
sum(
|
| 1372 |
+
[
|
| 1373 |
+
1,
|
| 1374 |
+
memory_size,
|
| 1375 |
+
*history_sizes,
|
| 1376 |
+
num_latent_frames_per_chunk,
|
| 1377 |
+
]
|
| 1378 |
+
),
|
| 1379 |
+
)
|
| 1380 |
+
(
|
| 1381 |
+
indices_prefix,
|
| 1382 |
+
indices_latents_memory,
|
| 1383 |
+
indices_latents_history_mid,
|
| 1384 |
+
indices_latents_history_1x,
|
| 1385 |
+
indices_hidden_states,
|
| 1386 |
+
) = indices.split(
|
| 1387 |
+
[1, memory_size, *history_sizes, num_latent_frames_per_chunk],
|
| 1388 |
+
dim=0,
|
| 1389 |
+
)
|
| 1390 |
+
indices_latents_history_short = torch.cat(
|
| 1391 |
+
[indices_prefix, indices_latents_history_1x], dim=0
|
| 1392 |
+
)
|
| 1393 |
+
|
| 1394 |
+
latents_prefix = image_latents
|
| 1395 |
+
latents_memory = first_memory_latents
|
| 1396 |
+
latents_history_mid, latents_history_1x = history_latents[
|
| 1397 |
+
:, :, -sum(history_sizes) :
|
| 1398 |
+
].split(history_sizes, dim=2)
|
| 1399 |
+
latents_history_short = torch.cat(
|
| 1400 |
+
[latents_prefix, latents_history_1x], dim=2
|
| 1401 |
+
)
|
| 1402 |
+
else:
|
| 1403 |
+
indices = torch.arange(
|
| 1404 |
+
0, sum([memory_size, *history_sizes, num_latent_frames_per_chunk])
|
| 1405 |
+
)
|
| 1406 |
+
(
|
| 1407 |
+
indices_latents_memory,
|
| 1408 |
+
indices_latents_history_mid,
|
| 1409 |
+
indices_latents_history_short,
|
| 1410 |
+
indices_hidden_states,
|
| 1411 |
+
) = indices.split(
|
| 1412 |
+
[memory_size, *history_sizes, num_latent_frames_per_chunk], dim=0
|
| 1413 |
+
)
|
| 1414 |
+
latents_memory = first_memory_latents
|
| 1415 |
+
latents_history_mid, latents_history_short = history_latents[
|
| 1416 |
+
:, :, -sum(history_sizes) :
|
| 1417 |
+
].split(history_sizes, dim=2)
|
| 1418 |
+
|
| 1419 |
+
indices_hidden_states = indices_hidden_states.unsqueeze(0)
|
| 1420 |
+
indices_latents_history_short = indices_latents_history_short.unsqueeze(0)
|
| 1421 |
+
indices_latents_history_mid = indices_latents_history_mid.unsqueeze(0)
|
| 1422 |
+
indices_latents_memory = indices_latents_memory.unsqueeze(0)
|
| 1423 |
+
|
| 1424 |
+
latents = self.prepare_latents(
|
| 1425 |
+
batch_size,
|
| 1426 |
+
num_channels_latents,
|
| 1427 |
+
height,
|
| 1428 |
+
width,
|
| 1429 |
+
window_num_frames,
|
| 1430 |
+
dtype=torch.float32,
|
| 1431 |
+
device=device,
|
| 1432 |
+
generator=generator,
|
| 1433 |
+
latents=None,
|
| 1434 |
+
)
|
| 1435 |
+
|
| 1436 |
+
if not is_enable_stage2:
|
| 1437 |
+
self.scheduler.set_timesteps(
|
| 1438 |
+
num_inference_steps, device=device, sigmas=sigmas, mu=mu
|
| 1439 |
+
)
|
| 1440 |
+
timesteps = self.scheduler.timesteps
|
| 1441 |
+
num_warmup_steps = (
|
| 1442 |
+
len(timesteps) - num_inference_steps * self.scheduler.order
|
| 1443 |
+
)
|
| 1444 |
+
self._num_timesteps = len(timesteps)
|
| 1445 |
+
else:
|
| 1446 |
+
if use_fast:
|
| 1447 |
+
from ..fast.contract import resolve_dmd_inference_trace
|
| 1448 |
+
|
| 1449 |
+
num_inference_steps = resolve_dmd_inference_trace(
|
| 1450 |
+
self.dmd_timestep_contract,
|
| 1451 |
+
latent_shape=latents.shape[1:],
|
| 1452 |
+
history_tensors=(
|
| 1453 |
+
latents_history_short,
|
| 1454 |
+
latents_history_mid,
|
| 1455 |
+
latents_memory,
|
| 1456 |
+
),
|
| 1457 |
+
num_stages=pyramid_num_stages,
|
| 1458 |
+
).num_steps
|
| 1459 |
+
else:
|
| 1460 |
+
num_inference_steps = sum(pyramid_num_inference_steps_list)
|
| 1461 |
+
|
| 1462 |
+
with self.progress_bar(total=num_inference_steps) as progress_bar:
|
| 1463 |
+
current_attention_kwargs = attention_kwargs
|
| 1464 |
+
if camera_trajectory is not None and not use_fast:
|
| 1465 |
+
current_attention_kwargs = dict(attention_kwargs or {})
|
| 1466 |
+
ucpe_attention_kwargs = build_ucpe_attention_kwargs_for_chunk(
|
| 1467 |
+
transformer=self.transformer,
|
| 1468 |
+
camera_trajectory=camera_trajectory,
|
| 1469 |
+
height=height,
|
| 1470 |
+
width=width,
|
| 1471 |
+
num_latent_frames_per_chunk=num_latent_frames_per_chunk,
|
| 1472 |
+
chunk_index=k,
|
| 1473 |
+
vae_scale_factor_temporal=self.vae_scale_factor_temporal,
|
| 1474 |
+
)
|
| 1475 |
+
if ucpe_attention_kwargs is None:
|
| 1476 |
+
raise ValueError(
|
| 1477 |
+
f"UCPE camera control could not be built for latent chunk {k}; "
|
| 1478 |
+
"check pose length and camera adapter patching"
|
| 1479 |
+
)
|
| 1480 |
+
current_attention_kwargs.update(ucpe_attention_kwargs)
|
| 1481 |
+
if is_enable_stage2:
|
| 1482 |
+
from ..fast.sampling import sample_fast
|
| 1483 |
+
|
| 1484 |
+
# Upsample block noise uses a separate default generator.
|
| 1485 |
+
# Forwarding the trajectory generator here changes its RNG
|
| 1486 |
+
# consumption and the generated video.
|
| 1487 |
+
latents = sample_fast(
|
| 1488 |
+
self,
|
| 1489 |
+
latents=latents,
|
| 1490 |
+
pyramid_num_stages=pyramid_num_stages,
|
| 1491 |
+
pyramid_num_inference_steps_list=pyramid_num_inference_steps_list,
|
| 1492 |
+
prompt_embeds=prompt_embeds,
|
| 1493 |
+
guidance_scale=guidance_scale,
|
| 1494 |
+
indices_hidden_states=indices_hidden_states,
|
| 1495 |
+
indices_latents_history_short=indices_latents_history_short,
|
| 1496 |
+
indices_latents_history_mid=indices_latents_history_mid,
|
| 1497 |
+
indices_latents_history_long=indices_latents_memory,
|
| 1498 |
+
latents_history_short=latents_history_short,
|
| 1499 |
+
latents_history_mid=latents_history_mid,
|
| 1500 |
+
latents_history_long=latents_memory,
|
| 1501 |
+
attention_kwargs=current_attention_kwargs,
|
| 1502 |
+
device=device,
|
| 1503 |
+
transformer_dtype=transformer_dtype,
|
| 1504 |
+
camera_trajectory=camera_trajectory,
|
| 1505 |
+
num_latent_frames_per_chunk=num_latent_frames_per_chunk,
|
| 1506 |
+
chunk_index=k,
|
| 1507 |
+
camera_restart_each_chunk=False,
|
| 1508 |
+
ucpe_pixel_center=True,
|
| 1509 |
+
callback_on_step_end=callback_on_step_end,
|
| 1510 |
+
callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs,
|
| 1511 |
+
progress_bar=progress_bar,
|
| 1512 |
+
)
|
| 1513 |
+
else:
|
| 1514 |
+
latents = self.stage1_sample(
|
| 1515 |
+
latents=latents,
|
| 1516 |
+
prompt_embeds=prompt_embeds,
|
| 1517 |
+
negative_prompt_embeds=negative_prompt_embeds,
|
| 1518 |
+
timesteps=timesteps,
|
| 1519 |
+
guidance_scale=guidance_scale,
|
| 1520 |
+
indices_hidden_states=indices_hidden_states,
|
| 1521 |
+
indices_latents_history_short=indices_latents_history_short,
|
| 1522 |
+
indices_latents_history_mid=indices_latents_history_mid,
|
| 1523 |
+
indices_latents_history_long=indices_latents_memory,
|
| 1524 |
+
latents_history_short=latents_history_short,
|
| 1525 |
+
latents_history_mid=latents_history_mid,
|
| 1526 |
+
latents_history_long=latents_memory,
|
| 1527 |
+
attention_kwargs=current_attention_kwargs,
|
| 1528 |
+
device=device,
|
| 1529 |
+
transformer_dtype=transformer_dtype,
|
| 1530 |
+
generator=generator,
|
| 1531 |
+
num_warmup_steps=num_warmup_steps,
|
| 1532 |
+
# ------------ CFG Zero ------------
|
| 1533 |
+
use_zero_init=use_zero_init,
|
| 1534 |
+
zero_steps=zero_steps,
|
| 1535 |
+
# ------------ Callback ------------
|
| 1536 |
+
callback_on_step_end=callback_on_step_end,
|
| 1537 |
+
callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs,
|
| 1538 |
+
progress_bar=progress_bar,
|
| 1539 |
+
)
|
| 1540 |
+
|
| 1541 |
+
if keep_first_frame and (
|
| 1542 |
+
(is_first_chunk and image_latents is None)
|
| 1543 |
+
or (is_skip_first_chunk and is_second_chunk)
|
| 1544 |
+
):
|
| 1545 |
+
image_latents = latents[:, :, 0:1, :, :]
|
| 1546 |
+
|
| 1547 |
+
generated_memory_latents = torch.cat(
|
| 1548 |
+
[generated_memory_latents, latents], dim=2
|
| 1549 |
+
)
|
| 1550 |
+
|
| 1551 |
+
total_generated_latent_frames += latents.shape[2]
|
| 1552 |
+
history_latents = torch.cat([history_latents, latents], dim=2)
|
| 1553 |
+
real_history_latents = history_latents[
|
| 1554 |
+
:, :, -total_generated_latent_frames:
|
| 1555 |
+
]
|
| 1556 |
+
current_latents = (
|
| 1557 |
+
real_history_latents[:, :, -num_latent_frames_per_chunk:].to(
|
| 1558 |
+
vae_dtype
|
| 1559 |
+
)
|
| 1560 |
+
/ latents_std
|
| 1561 |
+
+ latents_mean
|
| 1562 |
+
)
|
| 1563 |
+
current_video = self.vae.decode(current_latents, return_dict=False)[0]
|
| 1564 |
+
|
| 1565 |
+
if callback_on_chunk_end is not None:
|
| 1566 |
+
callback_on_chunk_end(k, current_video)
|
| 1567 |
+
|
| 1568 |
+
if callback_on_chunk_state is not None:
|
| 1569 |
+
if not isinstance(generator, torch.Generator):
|
| 1570 |
+
raise TypeError(
|
| 1571 |
+
"resumable WorldCrafter inference requires one torch.Generator"
|
| 1572 |
+
)
|
| 1573 |
+
callback_on_chunk_state(
|
| 1574 |
+
k,
|
| 1575 |
+
{
|
| 1576 |
+
"format": "worldcrafter_chunk_state_v1",
|
| 1577 |
+
"completed_chunk_index": int(k),
|
| 1578 |
+
"next_chunk_index": int(k + 1),
|
| 1579 |
+
"generated_memory_latents": generated_memory_latents.detach().cpu(),
|
| 1580 |
+
"history_latents": history_latents[
|
| 1581 |
+
:, :, -sum(history_sizes) :
|
| 1582 |
+
]
|
| 1583 |
+
.detach()
|
| 1584 |
+
.cpu(),
|
| 1585 |
+
"image_latents": (
|
| 1586 |
+
image_latents.detach().cpu()
|
| 1587 |
+
if image_latents is not None
|
| 1588 |
+
else None
|
| 1589 |
+
),
|
| 1590 |
+
"generator_state": generator.get_state().cpu(),
|
| 1591 |
+
},
|
| 1592 |
+
)
|
| 1593 |
+
|
| 1594 |
+
if history_video is None:
|
| 1595 |
+
history_video = current_video
|
| 1596 |
+
else:
|
| 1597 |
+
history_video = torch.cat([history_video, current_video], dim=2)
|
| 1598 |
+
if k == final_chunk_index:
|
| 1599 |
+
break
|
| 1600 |
+
|
| 1601 |
+
self._current_timestep = None
|
| 1602 |
+
|
| 1603 |
+
if output_type != "latent":
|
| 1604 |
+
if not use_fast:
|
| 1605 |
+
# Preserve the existing base output contract. Fast decodes each
|
| 1606 |
+
# complete 33-frame chunk independently; applying the latent
|
| 1607 |
+
# length rule again would drop valid RGB frames (330 -> 329).
|
| 1608 |
+
generated_frames = history_video.size(2)
|
| 1609 |
+
generated_frames = (
|
| 1610 |
+
(generated_frames - 1)
|
| 1611 |
+
// self.vae_scale_factor_temporal
|
| 1612 |
+
* self.vae_scale_factor_temporal
|
| 1613 |
+
+ 1
|
| 1614 |
+
)
|
| 1615 |
+
history_video = history_video[:, :, :generated_frames]
|
| 1616 |
+
video = self.video_processor.postprocess_video(
|
| 1617 |
+
history_video, output_type=output_type
|
| 1618 |
+
)
|
| 1619 |
+
else:
|
| 1620 |
+
video = real_history_latents
|
| 1621 |
+
|
| 1622 |
+
# Offload all models
|
| 1623 |
+
self.maybe_free_model_hooks()
|
| 1624 |
+
|
| 1625 |
+
if not return_dict:
|
| 1626 |
+
return (video,)
|
| 1627 |
+
|
| 1628 |
+
return WorldCrafterPipelineOutput(frames=video)
|