Cccccz commited on
Commit
29b7783
·
verified ·
1 Parent(s): b910c09

Add files using upload-large-folder tool

Browse files
Files changed (50) hide show
  1. Helios/.codex +0 -0
  2. Helios/.gitignore +43 -0
  3. Helios/LICENSE.txt +201 -0
  4. Helios/README.md +594 -0
  5. Helios/_DEV/.codex +0 -0
  6. Helios/_DEV/.gitignore +43 -0
  7. Helios/_DEV/LICENSE.txt +201 -0
  8. Helios/_DEV/README.md +594 -0
  9. Helios/_DEV/app.py +322 -0
  10. Helios/_DEV/bench_infer.py +569 -0
  11. Helios/_DEV/infer_helios.py +673 -0
  12. Helios/_DEV/install.sh +10 -0
  13. Helios/_DEV/requirements.txt +35 -0
  14. Helios/_DEV/requirements_npu.txt +6 -0
  15. Helios/_DEV/run_bench.sh +275 -0
  16. Helios/_DEV/train_helios.py +0 -0
  17. Helios/_DEV2/.codex +0 -0
  18. Helios/_DEV2/.gitignore +43 -0
  19. Helios/_DEV2/LICENSE.txt +201 -0
  20. Helios/_DEV2/README.md +137 -0
  21. Helios/_DEV2/app.py +322 -0
  22. Helios/_DEV2/bench_infer.py +569 -0
  23. Helios/_DEV2/infer_helios.py +673 -0
  24. Helios/_DEV2/install.sh +10 -0
  25. Helios/_DEV2/requirements.txt +35 -0
  26. Helios/_DEV2/requirements_npu.txt +6 -0
  27. Helios/_DEV2/run_bench.sh +275 -0
  28. Helios/_DEV2/train_helios.py +0 -0
  29. Helios/_DEV3/.codex +0 -0
  30. Helios/_DEV3/.gitignore +43 -0
  31. Helios/_DEV3/LICENSE.txt +201 -0
  32. Helios/_DEV3/README.md +67 -0
  33. Helios/_DEV3/app.py +322 -0
  34. Helios/_DEV3/bench_infer.py +569 -0
  35. Helios/_DEV3/infer_helios.py +673 -0
  36. Helios/_DEV3/install.sh +10 -0
  37. Helios/_DEV3/requirements.txt +35 -0
  38. Helios/_DEV3/requirements_npu.txt +6 -0
  39. Helios/_DEV3/run_bench.sh +275 -0
  40. Helios/_DEV3/train_helios.py +0 -0
  41. Helios/__pycache__/bench_infer.cpython-312.pyc +0 -0
  42. Helios/app.py +320 -0
  43. Helios/bench_infer.py +569 -0
  44. Helios/infer_helios.py +560 -0
  45. Helios/install.sh +10 -0
  46. Helios/requirements.txt +35 -0
  47. Helios/requirements_npu.txt +6 -0
  48. Helios/run_bench.sh +275 -0
  49. Helios/temp.sh +12 -0
  50. Helios/train_helios.py +0 -0
Helios/.codex ADDED
File without changes
Helios/.gitignore ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.py[cod]
2
+ *.gif
3
+ *.bmp
4
+ *.mov
5
+ *.mkv
6
+ *.log
7
+ *.zip
8
+ *.pt
9
+ *.pth
10
+ *.ckpt
11
+ *.safetensors
12
+ *.backup
13
+ *.pt
14
+ *.pth
15
+ *.ckpt
16
+ *.pkl
17
+ *.html
18
+ *.pdf
19
+ *.whl
20
+ *.txt.gz
21
+ !.gitignore
22
+ !requirements.txt
23
+ .DS_Store
24
+ *DS_Store
25
+ poetry.lock
26
+ __pycache__/
27
+ *.cache*
28
+ *temp_path*
29
+ *_ckpt
30
+ *_results
31
+ *temp
32
+ *.pem
33
+ *profile
34
+ .gradio
35
+ ablation_*
36
+ cache
37
+ wandb
38
+ output_helios
39
+ AMT-S.yaml
40
+ bpe_simple_vocab_16e6.txt
41
+ Videoreward
42
+ 1_formal_ckpts
43
+ demo_data
Helios/LICENSE.txt ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
Helios/README.md ADDED
@@ -0,0 +1,594 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <div align=center>
2
+ <img src="https://raw.githubusercontent.com/SHYuanBest/shyuanbest_media/main/Helios/logo_white.png" width="300px">
3
+ </div>
4
+
5
+ <h1 align="center">Helios: Real Real-Time Long Video Generation Model</h1>
6
+
7
+ <h5 align="center">⭐ 14B Real-Time Long Video Generation Model can be Cheaper, Faster but Keep Stronger than 1.3B ones ⭐</h5>
8
+
9
+ <h5 align="center">
10
+
11
+ [![arXiv](https://img.shields.io/badge/arXiv-2603.04379-b31b1b.svg?logo=arxiv)](https://arxiv.org/abs/2603.04379)
12
+ [![hf_paper](https://img.shields.io/badge/🤗-Paper%20In%20HF-red.svg)](https://huggingface.co/papers/2603.04379)
13
+ [![Project Page](https://img.shields.io/badge/Project-Website-2ea44f)](https://pku-yuangroup.github.io/Helios-Page)
14
+ [![hf_space](https://img.shields.io/badge/🤗-Gradio-00b4d8.svg)](https://huggingface.co/spaces/BestWishYsh/Helios-14B-RealTime)
15
+ [![HuggingFace](https://img.shields.io/badge/🤗-HuggingFace-blue)](https://huggingface.co/collections/BestWishYsh/helios)
16
+ [![ModelScope](https://img.shields.io/badge/🤖-ModelScope-purple)](https://modelscope.cn/collections/BestWishYSH/Helios)
17
+ [![GitHub](https://img.shields.io/badge/GitHub-black?logo=github)](https://github.com/PKU-YuanGroup/Helios)
18
+ [![GitCode](https://img.shields.io/badge/GitCodes-blue?logo=gitcode)](https://gitcode.com/weixin_47617277/Helios)
19
+
20
+ [![Ascend](https://img.shields.io/badge/Inference-Ascend--NPU-red)](https://www.hiascend.com/)
21
+ [![Diffusers](https://img.shields.io/badge/Inference-Diffusers-blueviolet)](https://github.com/huggingface/diffusers/pull/13208)
22
+ [![SGLang Diffusion](https://img.shields.io/badge/Backend-SGLang--Diffusion-yellow)](https://github.com/sgl-project/sglang/pull/19782)
23
+ [![vLLM-Omni](https://img.shields.io/badge/Backend-vLLM--Omni-orange)](https://github.com/vllm-project/vllm-omni/pull/1604)
24
+
25
+
26
+
27
+ </h5>
28
+
29
+ <div align="center">
30
+ This repository is the official implementation of Helios, which is a breakthrough video generation model that achieves minute-scale, high-quality video synthesis at <strong>19.5 FPS on a single H100 GPU</strong> (about 10 FPS on a single Ascend NPU) —without relying on conventional long video anti-drifting strategies or standard video acceleration techniques.
31
+ </div>
32
+
33
+ <br>
34
+
35
+ ## ✨ Highlights
36
+
37
+
38
+ 1. **Without commonly used anti-drifting strategies** (e.g., self-forcing, error-banks, keyframe sampling, or inverted sampling), Helios generates minute-scale videos with high quality and strong coherence.
39
+
40
+ 2. **Without standard acceleration techniques** (e.g., KV-cache, causal masking, sparse/linear attention, TinyVAE, progressive noise schedules, hidden-state caching, or quantization), Helios achieves 19.5 FPS in end-to-end inference on a single H100 GPU.
41
+
42
+ 3. **We introduce optimizations that improve both training and inference throughput while reducing memory consumption,** enabling image-diffusion-scale batch sizes during training while fitting up to four 14B models within 80 GB of GPU memory.
43
+
44
+
45
+
46
+ ## 🎬 Video Demos
47
+
48
+ [![Demo Video of Helios](https://github.com/user-attachments/assets/1d10da4a-aba9-4ac1-ab02-cd0dfce8d35b)](https://www.youtube.com/watch?v=vd_AgHtOUFQ)
49
+ or you can click <a href="https://github.com/PKU-YuanGroup/Helios-Page/blob/main/videos/helios_features.mp4">here</a> to get the video. Some best prompts are [here](./example/prompt.txt).
50
+
51
+
52
+ ## 📣 Latest News!!
53
+
54
+ * `[2026.03.26]` 🔥 Add summary of FAQ, Tips, and Tutorals: https://github.com/PKU-YuanGroup/Helios/issues/47.
55
+ * `[2026.03.24]` 👋 A community-made, unofficial YouTube tutorial for Helios is available [here](https://www.youtube.com/watch?v=AvFniggt6qg). It covers installation on a **consumer-grade PC** and supports **4K video generation**.
56
+ * `[2026.03.20]` 🚀 Helios now supports [Ahead-of-Time Compilation (AOTI)](https://huggingface.co/blog/zerogpu-aoti) on Spaces, with special thanks to the HuggingFace Team! Please refer to [this Space](https://huggingface.co/spaces/BestWishYsh/Helios-14B-RealTime-AOTI) for a usage example.
57
+ * `[2026.03.20]` 🔧 Based on [issue #38](https://github.com/PKU-YuanGroup/Helios/issues/38), we've identified several ways to further improve Helios's performance, such as fixing the i2v train-inference inconsistency and fully enabling Easy Anti-Drifting. Please refer to [commits](https://github.com/PKU-YuanGroup/Helios/commits/main/) and [correct.yaml](./scripts/training/configs/correct.yaml) for details.
58
+ * `[2026.03.12]` ⚡️ Please note that real-time generation performance depends not only on the GPU, but also on the CPU, memory, CUDA driver version, etc. As [tested by a user](https://github.com/PKU-YuanGroup/Helios/issues/3#issuecomment-4034710182) on better hardware with single H100, Helios can reach up to **20.89 FPS**!
59
+ * `[2026.03.08]` 🚀 Helios now fully supports [Group Offloading](#-group-offloading-to-save-vram) and [Context Parallelism](#-context-parallelism-on-multiple-gpus)! These features significantly optimize VRAM (**only ~6GB**) usage and enable inference across multiple GPUs with *Ulysses Attention*, *Ring Attention*, *Unified Attention*, and *Ulysses Anything Attention*.
60
+ * `[2026.03.06]` 👋 [Cache-DiT](https://github.com/vipshop/cache-dit/pull/834) now supports Helios, it offers Fully Cache Acceleration and Parallelism support for Helios! Special thanks to the Cache-DiT Team for their amazing work.
61
+ * `[2026.03.06]` 🔧 We fix the Parallel Inference logits for Helios, and provide an example [here](#-context-parallelism-on-multiple-gpus).
62
+ * `[2026.03.06]` 🚀 We official release the [Gradio Demo](https://huggingface.co/spaces/BestWishYsh/Helios-14B-RealTime), welcome to try it.
63
+ * `[2026.03.05]` 🔥 We are excited to announce the release of the Helios [technical report](https://arxiv.org/abs/2603.04379) on arXiv. We welcome discussions and feedback!
64
+ * `[2026.03.04]` 👋 Day-0 support for [Ascend-NPU](https://www.hiascend.com),with sincere gratitude to the Ascend Team for their support.
65
+ * `[2026.03.04]` 👋 Day-0 support for [Diffusers](https://github.com/huggingface/diffusers/pull/13208),with special thanks to the HuggingFace Team for their support.
66
+ * `[2026.03.04]` 👋 Day-0 support for [SGLang-Diffusion](https://github.com/sgl-project/sglang/pull/19782),with huge thanks to the SGLang Team for their support.
67
+ * `[2026.03.04]` 👋 Day-0 support for [vLLM-Omni](https://github.com/vllm-project/vllm-omni/pull/1604),with heartfelt gratitude to the vLLM Team for their support.
68
+ * `[2026.03.04]` 🔥 We've released the training/inference code and weights of **Helios-Base**, **Helios-Mid** and **Helios-Distilled**.
69
+
70
+
71
+ ## 🔥 Friendly Links
72
+
73
+ If your work has improved **Helios** and you would like more people to see it, please inform us.
74
+
75
+ * [Ascend-NPU](https://www.hiascend.com/): Developed by Huawei, this hardware is designed for efficient AI model training and inference, boosting performance in tasks like computer vision, natural language processing, and autonomous driving.
76
+ * [Diffusers](https://github.com/huggingface/diffusers/pull/13208): A popular library designed for working with diffusion models and other generative models in deep learning. It supports easy integration and manipulation of a wide range of generative models.
77
+ * [SGLang-Diffusion](https://github.com/sgl-project/sglang/pull/19782): An inference framework for accelerated image and video generation using diffusion models. It provides an end-to-end unified pipeline with optimized kernels and an efficient scheduler loop.
78
+ * [vLLM-Omni](https://github.com/vllm-project/vllm-omni/pull/1604): A fully disaggregated serving system for any-to-any models. vLLM-Omni breaks complex architectures into a stage-based graph, using a decoupled backend to maximize resource efficiency and throughput.
79
+ * [Cache-DiT](https://github.com/vipshop/cache-dit/pull/834): A PyTorch-native and Flexible Inference Engine with Hybrid Cache Acceleration and Parallelism for DiTs. It built on top of the Diffusers library and now supports nearly ALL DiTs from Diffusers.
80
+
81
+ ## ⚙️ Requirements and Installation
82
+
83
+ ### Video Tutorial
84
+
85
+ If you prefer a step-by-step walkthrough, check out this **community-made** [YouTube Tutorial](https://www.youtube.com/watch?v=AvFniggt6qg). It covers local installation, 4K video generation, and how to run Helios on a **consumer-grade PC**, along with other practical usage tips.
86
+
87
+ ### Prepare Environment
88
+
89
+ ```bash
90
+ # 0. Clone the repo
91
+ git clone --depth=1 https://github.com/PKU-YuanGroup/Helios.git
92
+ cd Helios
93
+
94
+ # 1. Create conda environment
95
+ conda create -n helios python=3.11.2
96
+ conda activate helios
97
+
98
+ # 2. Install PyTorch (adjust for your CUDA version)
99
+ # CUDA 12.6
100
+ pip install torch==2.10.0 torchvision==0.25.0 torchaudio==2.10.0 --index-url https://download.pytorch.org/whl/cu126
101
+ # CUDA 12.8
102
+ pip install torch==2.10.0 torchvision==0.25.0 torchaudio==2.10.0 --index-url https://download.pytorch.org/whl/cu128
103
+ # CUDA 13.0
104
+ pip install torch==2.10.0 torchvision==0.25.0 torchaudio==2.10.0 --index-url https://download.pytorch.org/whl/cu130
105
+
106
+ # 3. Install dependencies
107
+ bash install.sh
108
+ ```
109
+
110
+ ### Model Download
111
+
112
+ | Models | Download Link | Supports | Notes |
113
+ |------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------|---------------------------------------------------------------------------------------------|
114
+ | Helios-Base | 🤗 [Huggingface](https://huggingface.co/BestWishYsh/Helios-Base) 🤖 [ModelScope](https://modelscope.cn/models/BestWishYSH/Helios-Base) | T2V ✅ I2V ✅ V2V ✅ Interactive ✅ | Best Quality, with v-prediction, standard CFG and custom HeliosScheduler. |
115
+ | Helios-Mid | 🤗 [Huggingface](https://huggingface.co/BestWishYsh/Helios-Mid) 🤖 [ModelScope](https://modelscope.cn/models/BestWishYSH/Helios-Mid) | T2V ✅ I2V ✅ V2V ✅ Interactive ✅ | Intermediate Ckpt, with v-prediction, CFG-Zero* and custom HeliosScheduler. |
116
+ | Helios-Distilled | 🤗 [Huggingface](https://huggingface.co/BestWishYsh/Helios-Distilled) 🤖 [ModelScope](https://modelscope.cn/models/BestWishYSH/Helios-Distilled) | T2V ✅ I2V ✅ V2V ✅ Interactive ✅ | Best Efficiency, with x0-prediction and custom HeliosDMDScheduler. |
117
+
118
+
119
+
120
+ > 💡Note:
121
+ > * All three models share the same architecture, but Helios-Mid and Helios-Distilled use a more aggressive multi-scale sampling pipeline to achieve better efficiency.
122
+ > * Helios-Mid is an intermediate checkpoint generated in the process of distilling Helios-Base into Helios-Distilled, and may not meet expected quality.
123
+ > * For Image-to-Video or Video-to-Video, since training is based on Text-to-Video, these two functions may be slightly inferior to Text-to-Video. You may enable `is_skip_first_chunk` if you find the first few chunks are static or imporve the value of `image_noise_sigma_min`, `image_noise_sigma_max`, `video_noise_sigma_min`, and `video_noise_sigma_max`.
124
+
125
+
126
+ Download models using huggingface-cli:
127
+ ``` sh
128
+ pip install "huggingface_hub[cli]"
129
+ huggingface-cli download BestWishYSH/Helios-Base --local-dir BestWishYSH/Helios-Base
130
+ huggingface-cli download BestWishYSH/Helios-Mid --local-dir BestWishYSH/Helios-Mid
131
+ huggingface-cli download BestWishYSH/Helios-Distilled --local-dir BestWishYSH/Helios-Distilled
132
+ ```
133
+
134
+ Download models using modelscope-cli:
135
+ ``` sh
136
+ pip install modelscope
137
+ modelscope download BestWishYSH/Helios-Base --local_dir BestWishYSH/Helios-Base
138
+ modelscope download BestWishYSH/Helios-Mid --local_dir BestWishYSH/Helios-Mid
139
+ modelscope download BestWishYSH/Helios-Distilled --local_dir BestWishYSH/Helios-Distilled
140
+ ```
141
+
142
+ ## 🚀 Inference
143
+
144
+
145
+ Helios uses an autoregressive approach that generates **33 frames per chunk**. For optimal performance, `num_frames` should be set to a multiple of `33`. If a non-multiple value is provided, it will be automatically rounded up to the nearest multiple of 33.
146
+
147
+ **Example frame counts for different video lengths:**
148
+
149
+ | num_frames | Adjusted Frames | 24 FPS | 16 FPS |
150
+ |------------|-----------------|--------|--------|
151
+ | 1449 | 1452 (33×44) | ~60s (1min) | ~90s (1min 30s) |
152
+ | 720 | 726 (33×22) | ~30s | ~45s |
153
+ | 240 | 264 (33×8) | ~11s | ~16s |
154
+ | 129 | 132 (33×4) | ~5.5s | ~8s |
155
+ | 81 | 99 (33×3) | ~4s | ~6s |
156
+
157
+ ### Run the model
158
+
159
+ We provide inference scripts for all models covering text-to-video, image-to-video, and video-to-video in this [directory](./scripts/inference).
160
+
161
+ ```bash
162
+ cd scripts/inference
163
+
164
+ # For Helios-Base
165
+ bash helios-base_t2v.sh
166
+ bash helios-base_i2v.sh
167
+ bash helios-base_v2v.sh
168
+
169
+ # For Helios-Mid
170
+ bash helios-mid_t2v.sh
171
+ bash helios-mid_i2v.sh
172
+ bash helios-mid_v2v.sh
173
+
174
+ # For Helios-Distilled
175
+ bash helios-distilled_t2v.sh
176
+ bash helios-distilled_i2v.sh
177
+ bash helios-distilled_v2v.sh
178
+
179
+ # For Interactive
180
+ # ⚠️ This feature is still under development — results may not always meet expectations
181
+ cd scripts/inference/experiment_interactive
182
+ ```
183
+
184
+ ### Sanity Check
185
+
186
+ Before trying your own inputs, we highly recommend going through the sanity check to find out if any hardware or software went wrong.
187
+
188
+ | Task | **Helios-Base** | **Helios-Mid** | **Helios-Distilled** |
189
+ | ------- | -------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- |
190
+ | **T2V** | <video src="https://github.com/user-attachments/assets/14e10753-0366-4790-ad8f-7b66d821ed11" controls width="240"></video> | <video src="https://github.com/user-attachments/assets/c1778691-a80b-428c-8094-88bb1dd1d52b" controls width="240"></video> | <video src="https://github.com/user-attachments/assets/4ca28c79-9dfa-49de-9c3a-f4c7b6c766cd" controls width="240"></video> |
191
+ | **V2V** | <video src="https://github.com/user-attachments/assets/420cb572-85c2-42d8-98d7-37b0bc24c844" controls width="240"></video> | <video src="https://github.com/user-attachments/assets/7d703fa6-dc1a-4138-a897-e58cfd9236d6" controls width="240"></video> | <video src="https://github.com/user-attachments/assets/45329c55-1a25-459c-bbf0-4e584ec5b23d" controls width="240"></video> |
192
+
193
+
194
+ ### ✨ Group Offloading to Save VRAM
195
+
196
+ Helios supports group offloading to significantly reduce VRAM consumption, allowing you to run on GPU with limited memory footprint. For more details on the underlying mechanics, please refer to the [documentation](https://huggingface.co/docs/diffusers/main/en/optimization/memory#group-offloading).
197
+
198
+ The Helios model below requires `~6GB of VRAM`.
199
+
200
+ <details>
201
+ <summary>Click to expand the code</summary>
202
+
203
+ ```bash
204
+ CUDA_VISIBLE_DEVICES=0 python infer_helios.py \
205
+ --base_model_path "BestWishYsh/Helios-Distilled" \
206
+ --transformer_path "BestWishYsh/Helios-Distilled" \
207
+ --sample_type "t2v" \
208
+ --prompt "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 photo captures the fish from a slightly elevated angle, emphasizing its lively movements and the vivid colors of its surroundings. A close-up shot with dynamic movement." \
209
+ --num_frames 240 \
210
+ --guidance_scale 1.0 \
211
+ --is_enable_stage2 \
212
+ --pyramid_num_inference_steps_list 2 2 2 \
213
+ --is_amplify_first_chunk \
214
+ --output_folder "./output_helios/helios-distilled" \
215
+ --enable_low_vram_mode \
216
+ --group_offloading_type "leaf_level"
217
+ ```
218
+
219
+ </details>
220
+
221
+ ### ✨ Context Parallelism on Multiple GPUs
222
+ Helios supports various Context Parallelism mechanisms, including `Ulysses Attention`, `Ring Attention`, `Unified Attention`, and `Ulysses Anything Attention`. For more details, please refer to the [documentation](https://huggingface.co/docs/diffusers/main/en/training/distributed_inference#context-parallelism).
223
+
224
+ For example, let's take Helios-Base with 4 GPUs.
225
+
226
+ <details>
227
+ <summary>Click to expand the code</summary>
228
+
229
+ ```bash
230
+ CUDA_VISIBLE_DEVICES=0,1,2,3 torchrun --nproc_per_node 4 infer_helios.py \
231
+ --enable_parallelism \ # remember to enable this config
232
+ --cp_backend "ulysses" \ # ["ring", "ulysses", "unified", "ulysses_anything"]
233
+ --base_model_path "BestWishYsh/Helios-Base" \
234
+ --transformer_path "BestWishYsh/Helios-Base" \
235
+ --sample_type "t2v" \
236
+ --num_frames 99 \
237
+ --fps 24 \
238
+ --prompt "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 photo captures the fish from a slightly elevated angle, emphasizing its lively movements and the vivid colors of its surroundings. A close-up shot with dynamic movement." \
239
+ --guidance_scale 5.0 \
240
+ --output_folder "./output_helios/helios-base"
241
+ ```
242
+
243
+ </details>
244
+
245
+ ### ✨ Diffusers Pipeline
246
+
247
+ Install diffusers from source:
248
+ ```bash
249
+ pip install git+https://github.com/huggingface/diffusers.git
250
+ ```
251
+
252
+ For example, let's take Helios-Distilled (**Standard Pipeline**).
253
+
254
+ <details>
255
+ <summary>Click to expand the code</summary>
256
+
257
+ ```bash
258
+ import torch
259
+ from diffusers import AutoModel, HeliosPyramidPipeline
260
+ from diffusers.utils import export_to_video, load_video, load_image
261
+
262
+ vae = AutoModel.from_pretrained("BestWishYsh/Helios-Distilled", subfolder="vae", torch_dtype=torch.float32)
263
+
264
+ pipeline = HeliosPyramidPipeline.from_pretrained(
265
+ "BestWishYsh/Helios-Distilled",
266
+ vae=vae,
267
+ torch_dtype=torch.bfloat16
268
+ )
269
+ pipeline.to("cuda")
270
+
271
+ negative_prompt = """
272
+ Bright tones, overexposed, static, blurred details, subtitles, style, works, paintings, images, static, overall gray, worst quality,
273
+ low quality, JPEG compression residue, ugly, incomplete, extra fingers, poorly drawn hands, poorly drawn faces, deformed, disfigured,
274
+ misshapen limbs, fused fingers, still picture, messy background, three legs, many people in the background, walking backwards
275
+ """
276
+
277
+ # --- T2V ---
278
+ prompt = """
279
+ A vibrant tropical fish swimming gracefully among colorful coral reefs in a clear, turquoise ocean. The fish has bright blue
280
+ and yellow scales with a small, distinctive orange spot on its side, its fins moving fluidly. The coral reefs are alive with
281
+ a variety of marine life, including small schools of colorful fish and sea turtles gliding by. The water is crystal clear,
282
+ 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
283
+ of red, orange, and green. The photo captures the fish from a slightly elevated angle, emphasizing its lively movements and
284
+ the vivid colors of its surroundings. A close-up shot with dynamic movement.
285
+ """
286
+
287
+ output = pipeline(
288
+ prompt=prompt,
289
+ negative_prompt=negative_prompt,
290
+ num_frames=240,
291
+ pyramid_num_inference_steps_list=[2, 2, 2],
292
+ guidance_scale=1.0,
293
+ is_amplify_first_chunk=True,
294
+ generator=torch.Generator("cuda").manual_seed(42),
295
+ ).frames[0]
296
+ export_to_video(output, "helios_distilled_t2v_output.mp4", fps=24)
297
+
298
+ # --- I2V ---
299
+ i2v_prompt = """
300
+ A towering emerald wave surges forward, its crest curling with raw power and energy. Sunlight glints off the translucent water,
301
+ illuminating the intricate textures and deep green hues within the wave’s body. A thick spray erupts from the breaking crest,
302
+ casting a misty veil that dances above the churning surface. As the perspective widens, the immense scale of the wave becomes
303
+ apparent, revealing the restless expanse of the ocean stretching beyond. The scene captures the ocean’s untamed beauty and
304
+ relentless force, with every droplet and ripple shimmering in the light. The dynamic motion and vivid colors evoke both awe and
305
+ respect for nature’s might.
306
+ """
307
+ image_path = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/helios/wave.jpg"
308
+
309
+ output = pipeline(
310
+ prompt=i2v_prompt,
311
+ negative_prompt=negative_prompt,
312
+ image=load_image(image_path).resize((640, 384)),
313
+ num_frames=240,
314
+ pyramid_num_inference_steps_list=[2, 2, 2],
315
+ guidance_scale=1.0,
316
+ is_amplify_first_chunk=True,
317
+ generator=torch.Generator("cuda").manual_seed(42),
318
+ ).frames[0]
319
+ export_to_video(output, "helios_distilled_i2v_output.mp4", fps=24)
320
+
321
+ # --- V2V ---
322
+ v2v_prompt = """
323
+ A bright yellow Lamborghini Huracn Tecnica speeds along a curving mountain road, surrounded by lush green trees
324
+ under a partly cloudy sky. The car's sleek design and vibrant color stand out against the natural backdrop,
325
+ emphasizing its dynamic movement. The road curves gently, with a guardrail visible on one side, adding depth to
326
+ the scene. The motion blur captures the sense of speed and energy, creating a thrilling and exhilarating atmosphere.
327
+ A front-facing shot from a slightly elevated angle, highlighting the car's aggressive stance and the surrounding greenery.
328
+ """
329
+ video_path = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/helios/car.mp4"
330
+
331
+ output = pipeline(
332
+ prompt=v2v_prompt,
333
+ negative_prompt=negative_prompt,
334
+ video=load_video(video_path),
335
+ num_frames=240,
336
+ pyramid_num_inference_steps_list=[2, 2, 2],
337
+ guidance_scale=1.0,
338
+ is_amplify_first_chunk=True,
339
+ generator=torch.Generator("cuda").manual_seed(42),
340
+ ).frames[0]
341
+ export_to_video(output, "helios_distilled_v2v_output.mp4", fps=24)
342
+ ```
343
+
344
+ </details>
345
+
346
+ For example, let's take Helios-Distilled (**Modular Pipeline**).
347
+
348
+ <details>
349
+ <summary>Click to expand the code</summary>
350
+
351
+ ```bash
352
+ import torch
353
+ from diffusers import ModularPipeline, ClassifierFreeGuidance
354
+ from diffusers.utils import export_to_video, load_image, load_video
355
+
356
+ mod_pipe = ModularPipeline.from_pretrained("BestWishYsh/Helios-Distilled")
357
+ mod_pipe.load_components(torch_dtype=torch.bfloat16)
358
+ mod_pipe.to("cuda")
359
+
360
+ # we need to upload guider to the model repo, so each checkpoint will be able to config their guidance differently
361
+ guider = ClassifierFreeGuidance(guidance_scale=1.0)
362
+ mod_pipe.update_components(guider=guider)
363
+
364
+ # --- T2V ---
365
+ print("=== T2V ===")
366
+ prompt = (
367
+ "A vibrant tropical fish swimming gracefully among colorful coral reefs in a clear, turquoise ocean. "
368
+ "The fish has bright blue and yellow scales with a small, distinctive orange spot on its side, its fins moving "
369
+ "fluidly. The coral reefs are alive with a variety of marine life, including small schools of colorful fish and "
370
+ "sea turtles gliding by. The water is crystal clear, allowing for a view of the sandy ocean floor below. The reef "
371
+ "itself is adorned with a mix of hard and soft corals in shades of red, orange, and green. The photo captures "
372
+ "the fish from a slightly elevated angle, emphasizing its lively movements and the vivid colors of its surroundings. "
373
+ "A close-up shot with dynamic movement."
374
+ )
375
+
376
+ output = mod_pipe(
377
+ prompt=prompt,
378
+ height=384,
379
+ width=640,
380
+ num_frames=240,
381
+ pyramid_num_inference_steps_list=[2, 2, 2],
382
+ is_amplify_first_chunk=True,
383
+ generator=torch.Generator("cuda").manual_seed(42),
384
+ output="videos",
385
+ )
386
+
387
+ export_to_video(output[0], "helios_distilled_modular_t2v_output.mp4", fps=24)
388
+ print(f"T2V max memory: {torch.cuda.max_memory_allocated() / 1024**3:.3f} GB")
389
+ torch.cuda.empty_cache()
390
+ torch.cuda.reset_peak_memory_stats()
391
+
392
+ # --- I2V ---
393
+ print("=== I2V ===")
394
+ image = load_image(
395
+ "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/helios/wave.jpg"
396
+ )
397
+ i2v_prompt = (
398
+ "A towering emerald wave surges forward, its crest curling with raw power and energy. "
399
+ "Sunlight glints off the translucent water, illuminating the intricate textures and deep green hues within the wave's body."
400
+ )
401
+
402
+ output = mod_pipe(
403
+ prompt=i2v_prompt,
404
+ image=image,
405
+ height=384,
406
+ width=640,
407
+ num_frames=240,
408
+ pyramid_num_inference_steps_list=[2, 2, 2],
409
+ is_amplify_first_chunk=True,
410
+ generator=torch.Generator("cuda").manual_seed(42),
411
+ output="videos",
412
+ )
413
+
414
+ export_to_video(output[0], "helios_distilled_modular_i2v_output.mp4", fps=24)
415
+ print(f"I2V max memory: {torch.cuda.max_memory_allocated() / 1024**3:.3f} GB")
416
+ torch.cuda.empty_cache()
417
+ torch.cuda.reset_peak_memory_stats()
418
+
419
+ # --- V2V ---
420
+ print("=== V2V ===")
421
+ video = load_video(
422
+ "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/helios/car.mp4"
423
+ )
424
+ v2v_prompt = (
425
+ "A dynamic time-lapse video showing the rapidly moving scenery from the window of a speeding train. "
426
+ "The camera captures various elements such as lush green fields, towering trees, quaint countryside houses, "
427
+ "and distant mountain ranges passing by quickly."
428
+ )
429
+
430
+ output = mod_pipe(
431
+ prompt=v2v_prompt,
432
+ video=video,
433
+ height=384,
434
+ width=640,
435
+ num_frames=240,
436
+ pyramid_num_inference_steps_list=[2, 2, 2],
437
+ is_amplify_first_chunk=True,
438
+ generator=torch.Generator("cuda").manual_seed(42),
439
+ output="videos",
440
+ )
441
+
442
+ export_to_video(output[0], "helios_distilled_modular_v2v_output.mp4", fps=24)
443
+ print(f"V2V max memory: {torch.cuda.max_memory_allocated() / 1024**3:.3f} GB")
444
+ ```
445
+
446
+ </details>
447
+
448
+ ### ✨ vLLM-Omni Pipeline
449
+
450
+ Install vllm-omni from source:
451
+ ```bash
452
+ pip install git+https://github.com/vllm-project/vllm-omni.git
453
+ ```
454
+
455
+ For example, let's take Text-to-Video.
456
+
457
+ <details>
458
+ <summary>Click to expand the code</summary>
459
+
460
+ ```bash
461
+ cd vllm-omni
462
+
463
+ # Helios-Base
464
+ python3 examples/offline_inference/helios/end2end.py \
465
+ --sample-type t2v \
466
+ --model ./Helios-Base \
467
+ --prompt "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 photo captures the fish from a slightly elevated angle, emphasizing its lively movements and the vivid colors of its surroundings. A close-up shot with dynamic movement." \
468
+ --num-frames 99 \
469
+ --seed 42 \
470
+ --output helios_t2v_base.mp4
471
+
472
+ # Helios-Mid
473
+ python examples/offline_inference/helios/end2end.py \
474
+ --model ./Helios-Mid --sample-type t2v \
475
+ --prompt "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 photo captures the fish from a slightly elevated angle, emphasizing its lively movements and the vivid colors of its surroundings. A close-up shot with dynamic movement." \
476
+ --guidance-scale 5.0 --is-enable-stage2 \
477
+ --pyramid-num-inference-steps-list 20 20 20 \
478
+ --num-frames 99 \
479
+ --use-cfg-zero-star --use-zero-init --zero-steps 1 \
480
+ --output helios_t2v_mid.mp4
481
+
482
+ # Helios-Distilled
483
+ python examples/offline_inference/helios/end2end.py \
484
+ --model ./Helios-Distilled --sample-type t2v \
485
+ --prompt "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 photo captures the fish from a slightly elevated angle, emphasizing its lively movements and the vivid colors of its surroundings. A close-up shot with dynamic movement." \
486
+ --num-frames 240 --guidance-scale 1.0 --is-enable-stage2 \
487
+ --pyramid-num-inference-steps-list 2 2 2 \
488
+ --is-amplify-first-chunk --output helios_t2v_distilled.mp4
489
+ ```
490
+ </details>
491
+
492
+ ### ✨ SGLang-Diffusion Pipeline
493
+
494
+ Install sglang-diffusion from source:
495
+ ```bash
496
+ pip install git+https://github.com/sgl-project/sglang.git
497
+ ```
498
+
499
+ For example, let's take Helios-Base. **(Native Support)**
500
+
501
+ <details>
502
+ <summary>Click to expand the code</summary>
503
+
504
+ ```bash
505
+ sglang generate \
506
+ --model-path BestWishYsh/Helios-Base \
507
+ --prompt "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 photo captures the fish from a slightly elevated angle, emphasizing its lively movements and the vivid colors of its surroundings. A close-up shot with dynamic movement." \
508
+ --negative-prompt "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" \
509
+ --height 384 \
510
+ --width 640 \
511
+ --num-frames 99 \
512
+ --num-inference-steps 50 \
513
+ --guidance-scale 5.0
514
+ ```
515
+ </details>
516
+
517
+ For example, let's take Helios-Base. **(Diffusers Backend)**
518
+
519
+ <details>
520
+ <summary>Click to expand the code</summary>
521
+
522
+ ```bash
523
+ sglang generate \
524
+ --model-path BestWishYsh/Helios-Base \
525
+ --prompt "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 photo captures the fish from a slightly elevated angle, emphasizing its lively movements and the vivid colors of its surroundings. A close-up shot with dynamic movement." \
526
+ --negative-prompt "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" \
527
+ --height 384 \
528
+ --width 640 \
529
+ --num-frames 99 \
530
+ --num-inference-steps 50 \
531
+ --guidance-scale 5.0 \
532
+ --backend diffusers
533
+ ```
534
+ </details>
535
+
536
+ ## 🗝️ Training
537
+
538
+ We use a three-stage progressive pipeline, all the setting can be found [here](./scripts/training/configs/). Stage-1 (Base) performs architectural adaptation: we apply Unified History Injection, Easy Anti-Drifting, and Multi-Term Memory Patchification to convert the bidirectional pretrained model into an autoregressive generator. Stage-2 (Mid) targets token compression by introducing Pyramid Unified Predictor Corrector, which aggressively reduces the number of noisy tokens and thus the overall computation. Stage-3 (Distilled) applies Adversarial Hierarchical Distillation, reducing the sampling steps from 50 to 3 and eliminating the need for classifier-free guidance (CFG). Throughout training, we apply dynamic shifting to all timestep-dependent operations to match the noise schedule to the latent size.
539
+
540
+ ### Data Preparation
541
+
542
+ Please refer to [this guide](./tools/offload_data/README.md) for how to obtain the training data required by Helios. And we prepare a toy training data [here](https://huggingface.co/BestWishYsh/HeliosBench-Weights/tree/main/demo_data).
543
+
544
+ ### Run the model
545
+
546
+ ```bash
547
+ # Use DDP
548
+ bash scripts/training/train_ddp.sh
549
+
550
+ # or
551
+
552
+ # Use DeepSpeed
553
+ bash scripts/training/train_deepspeed.sh
554
+ ```
555
+
556
+ Training configuration can be adjusted in `scripts/training/configs`. You can use `scripts/training/compare_yaml.py` to check for configuration completeness or differences between stages.
557
+
558
+ ### Model Merging
559
+
560
+ After training, you can use this [script](./tools/merge_lora_for_helios.py) to merge all the checkpoints and obtain the final safetensors file, similar to [this](https://huggingface.co/BestWishYsh/Helios-Distilled/tree/main/transformer).
561
+
562
+
563
+ ## 📊 HeliosBench
564
+
565
+ HeliosBench is a specialized benchmark for real-time long-video generation, please refer to [this guide](./eval/README.md) for how to eval your own model.
566
+
567
+
568
+ ## 👍 Acknowledgement
569
+
570
+ This project wouldn't be possible without the following open-sourced repositories: [Open-Sora Plan](https://github.com/PKU-YuanGroup/Open-Sora-Plan), [Ascend](https://www.hiascend.com), [Diffusers](https://github.com/huggingface/diffusers), [vLLM-Omni](https://github.com/vllm-project/vllm), [SGLang Diffusion](https://github.com/sgl-project/sglang), [Wan](https://github.com/Wan-Video/Wan2.1), [FramePack](https://github.com/lllyasviel/FramePack), [PyramidFlow](https://github.com/jy0205/Pyramid-Flow), [DMD](https://github.com/tianweiy/DMD2).
571
+
572
+
573
+ ## 🔒 License
574
+
575
+ This project is released under the Apache 2.0 license as found in the [LICENSE](LICENSE) file.
576
+
577
+ ## ✏️ Citation
578
+
579
+ If you find our paper and code useful in your research, please consider giving a star ⭐ and citation 📝:
580
+
581
+ ```BibTeX
582
+ @article{helios,
583
+ title={Helios: Real Real-Time Long Video Generation Model},
584
+ author={Yuan, Shenghai and Yin, Yuanyang and Li, Zongjian and Huang, Xinwei and Yang, Xiao and Yuan, Li},
585
+ journal={arXiv preprint arXiv:2603.04379},
586
+ year={2026}
587
+ }
588
+ ```
589
+
590
+ ## 🤝 Contact
591
+
592
+ For questions and feedback, please contact us at: shyuan-cs@hotmail.com
593
+
594
+
Helios/_DEV/.codex ADDED
File without changes
Helios/_DEV/.gitignore ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.py[cod]
2
+ *.gif
3
+ *.bmp
4
+ *.mov
5
+ *.mkv
6
+ *.log
7
+ *.zip
8
+ *.pt
9
+ *.pth
10
+ *.ckpt
11
+ *.safetensors
12
+ *.backup
13
+ *.pt
14
+ *.pth
15
+ *.ckpt
16
+ *.pkl
17
+ *.html
18
+ *.pdf
19
+ *.whl
20
+ *.txt.gz
21
+ !.gitignore
22
+ !requirements.txt
23
+ .DS_Store
24
+ *DS_Store
25
+ poetry.lock
26
+ __pycache__/
27
+ *.cache*
28
+ *temp_path*
29
+ *_ckpt
30
+ *_results
31
+ *temp
32
+ *.pem
33
+ *profile
34
+ .gradio
35
+ ablation_*
36
+ cache
37
+ wandb
38
+ output_helios
39
+ AMT-S.yaml
40
+ bpe_simple_vocab_16e6.txt
41
+ Videoreward
42
+ 1_formal_ckpts
43
+ demo_data
Helios/_DEV/LICENSE.txt ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
Helios/_DEV/README.md ADDED
@@ -0,0 +1,594 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <div align=center>
2
+ <img src="https://raw.githubusercontent.com/SHYuanBest/shyuanbest_media/main/Helios/logo_white.png" width="300px">
3
+ </div>
4
+
5
+ <h1 align="center">Helios: Real Real-Time Long Video Generation Model</h1>
6
+
7
+ <h5 align="center">⭐ 14B Real-Time Long Video Generation Model can be Cheaper, Faster but Keep Stronger than 1.3B ones ⭐</h5>
8
+
9
+ <h5 align="center">
10
+
11
+ [![arXiv](https://img.shields.io/badge/arXiv-2603.04379-b31b1b.svg?logo=arxiv)](https://arxiv.org/abs/2603.04379)
12
+ [![hf_paper](https://img.shields.io/badge/🤗-Paper%20In%20HF-red.svg)](https://huggingface.co/papers/2603.04379)
13
+ [![Project Page](https://img.shields.io/badge/Project-Website-2ea44f)](https://pku-yuangroup.github.io/Helios-Page)
14
+ [![hf_space](https://img.shields.io/badge/🤗-Gradio-00b4d8.svg)](https://huggingface.co/spaces/BestWishYsh/Helios-14B-RealTime)
15
+ [![HuggingFace](https://img.shields.io/badge/🤗-HuggingFace-blue)](https://huggingface.co/collections/BestWishYsh/helios)
16
+ [![ModelScope](https://img.shields.io/badge/🤖-ModelScope-purple)](https://modelscope.cn/collections/BestWishYSH/Helios)
17
+ [![GitHub](https://img.shields.io/badge/GitHub-black?logo=github)](https://github.com/PKU-YuanGroup/Helios)
18
+ [![GitCode](https://img.shields.io/badge/GitCodes-blue?logo=gitcode)](https://gitcode.com/weixin_47617277/Helios)
19
+
20
+ [![Ascend](https://img.shields.io/badge/Inference-Ascend--NPU-red)](https://www.hiascend.com/)
21
+ [![Diffusers](https://img.shields.io/badge/Inference-Diffusers-blueviolet)](https://github.com/huggingface/diffusers/pull/13208)
22
+ [![SGLang Diffusion](https://img.shields.io/badge/Backend-SGLang--Diffusion-yellow)](https://github.com/sgl-project/sglang/pull/19782)
23
+ [![vLLM-Omni](https://img.shields.io/badge/Backend-vLLM--Omni-orange)](https://github.com/vllm-project/vllm-omni/pull/1604)
24
+
25
+
26
+
27
+ </h5>
28
+
29
+ <div align="center">
30
+ This repository is the official implementation of Helios, which is a breakthrough video generation model that achieves minute-scale, high-quality video synthesis at <strong>19.5 FPS on a single H100 GPU</strong> (about 10 FPS on a single Ascend NPU) —without relying on conventional long video anti-drifting strategies or standard video acceleration techniques.
31
+ </div>
32
+
33
+ <br>
34
+
35
+ ## ✨ Highlights
36
+
37
+
38
+ 1. **Without commonly used anti-drifting strategies** (e.g., self-forcing, error-banks, keyframe sampling, or inverted sampling), Helios generates minute-scale videos with high quality and strong coherence.
39
+
40
+ 2. **Without standard acceleration techniques** (e.g., KV-cache, causal masking, sparse/linear attention, TinyVAE, progressive noise schedules, hidden-state caching, or quantization), Helios achieves 19.5 FPS in end-to-end inference on a single H100 GPU.
41
+
42
+ 3. **We introduce optimizations that improve both training and inference throughput while reducing memory consumption,** enabling image-diffusion-scale batch sizes during training while fitting up to four 14B models within 80 GB of GPU memory.
43
+
44
+
45
+
46
+ ## 🎬 Video Demos
47
+
48
+ [![Demo Video of Helios](https://github.com/user-attachments/assets/1d10da4a-aba9-4ac1-ab02-cd0dfce8d35b)](https://www.youtube.com/watch?v=vd_AgHtOUFQ)
49
+ or you can click <a href="https://github.com/PKU-YuanGroup/Helios-Page/blob/main/videos/helios_features.mp4">here</a> to get the video. Some best prompts are [here](./example/prompt.txt).
50
+
51
+
52
+ ## 📣 Latest News!!
53
+
54
+ * `[2026.03.26]` 🔥 Add summary of FAQ, Tips, and Tutorals: https://github.com/PKU-YuanGroup/Helios/issues/47.
55
+ * `[2026.03.24]` 👋 A community-made, unofficial YouTube tutorial for Helios is available [here](https://www.youtube.com/watch?v=AvFniggt6qg). It covers installation on a **consumer-grade PC** and supports **4K video generation**.
56
+ * `[2026.03.20]` 🚀 Helios now supports [Ahead-of-Time Compilation (AOTI)](https://huggingface.co/blog/zerogpu-aoti) on Spaces, with special thanks to the HuggingFace Team! Please refer to [this Space](https://huggingface.co/spaces/BestWishYsh/Helios-14B-RealTime-AOTI) for a usage example.
57
+ * `[2026.03.20]` 🔧 Based on [issue #38](https://github.com/PKU-YuanGroup/Helios/issues/38), we've identified several ways to further improve Helios's performance, such as fixing the i2v train-inference inconsistency and fully enabling Easy Anti-Drifting. Please refer to [commits](https://github.com/PKU-YuanGroup/Helios/commits/main/) and [correct.yaml](./scripts/training/configs/correct.yaml) for details.
58
+ * `[2026.03.12]` ⚡️ Please note that real-time generation performance depends not only on the GPU, but also on the CPU, memory, CUDA driver version, etc. As [tested by a user](https://github.com/PKU-YuanGroup/Helios/issues/3#issuecomment-4034710182) on better hardware with single H100, Helios can reach up to **20.89 FPS**!
59
+ * `[2026.03.08]` 🚀 Helios now fully supports [Group Offloading](#-group-offloading-to-save-vram) and [Context Parallelism](#-context-parallelism-on-multiple-gpus)! These features significantly optimize VRAM (**only ~6GB**) usage and enable inference across multiple GPUs with *Ulysses Attention*, *Ring Attention*, *Unified Attention*, and *Ulysses Anything Attention*.
60
+ * `[2026.03.06]` 👋 [Cache-DiT](https://github.com/vipshop/cache-dit/pull/834) now supports Helios, it offers Fully Cache Acceleration and Parallelism support for Helios! Special thanks to the Cache-DiT Team for their amazing work.
61
+ * `[2026.03.06]` 🔧 We fix the Parallel Inference logits for Helios, and provide an example [here](#-context-parallelism-on-multiple-gpus).
62
+ * `[2026.03.06]` 🚀 We official release the [Gradio Demo](https://huggingface.co/spaces/BestWishYsh/Helios-14B-RealTime), welcome to try it.
63
+ * `[2026.03.05]` 🔥 We are excited to announce the release of the Helios [technical report](https://arxiv.org/abs/2603.04379) on arXiv. We welcome discussions and feedback!
64
+ * `[2026.03.04]` 👋 Day-0 support for [Ascend-NPU](https://www.hiascend.com),with sincere gratitude to the Ascend Team for their support.
65
+ * `[2026.03.04]` 👋 Day-0 support for [Diffusers](https://github.com/huggingface/diffusers/pull/13208),with special thanks to the HuggingFace Team for their support.
66
+ * `[2026.03.04]` 👋 Day-0 support for [SGLang-Diffusion](https://github.com/sgl-project/sglang/pull/19782),with huge thanks to the SGLang Team for their support.
67
+ * `[2026.03.04]` 👋 Day-0 support for [vLLM-Omni](https://github.com/vllm-project/vllm-omni/pull/1604),with heartfelt gratitude to the vLLM Team for their support.
68
+ * `[2026.03.04]` 🔥 We've released the training/inference code and weights of **Helios-Base**, **Helios-Mid** and **Helios-Distilled**.
69
+
70
+
71
+ ## 🔥 Friendly Links
72
+
73
+ If your work has improved **Helios** and you would like more people to see it, please inform us.
74
+
75
+ * [Ascend-NPU](https://www.hiascend.com/): Developed by Huawei, this hardware is designed for efficient AI model training and inference, boosting performance in tasks like computer vision, natural language processing, and autonomous driving.
76
+ * [Diffusers](https://github.com/huggingface/diffusers/pull/13208): A popular library designed for working with diffusion models and other generative models in deep learning. It supports easy integration and manipulation of a wide range of generative models.
77
+ * [SGLang-Diffusion](https://github.com/sgl-project/sglang/pull/19782): An inference framework for accelerated image and video generation using diffusion models. It provides an end-to-end unified pipeline with optimized kernels and an efficient scheduler loop.
78
+ * [vLLM-Omni](https://github.com/vllm-project/vllm-omni/pull/1604): A fully disaggregated serving system for any-to-any models. vLLM-Omni breaks complex architectures into a stage-based graph, using a decoupled backend to maximize resource efficiency and throughput.
79
+ * [Cache-DiT](https://github.com/vipshop/cache-dit/pull/834): A PyTorch-native and Flexible Inference Engine with Hybrid Cache Acceleration and Parallelism for DiTs. It built on top of the Diffusers library and now supports nearly ALL DiTs from Diffusers.
80
+
81
+ ## ⚙️ Requirements and Installation
82
+
83
+ ### Video Tutorial
84
+
85
+ If you prefer a step-by-step walkthrough, check out this **community-made** [YouTube Tutorial](https://www.youtube.com/watch?v=AvFniggt6qg). It covers local installation, 4K video generation, and how to run Helios on a **consumer-grade PC**, along with other practical usage tips.
86
+
87
+ ### Prepare Environment
88
+
89
+ ```bash
90
+ # 0. Clone the repo
91
+ git clone --depth=1 https://github.com/PKU-YuanGroup/Helios.git
92
+ cd Helios
93
+
94
+ # 1. Create conda environment
95
+ conda create -n helios python=3.11.2
96
+ conda activate helios
97
+
98
+ # 2. Install PyTorch (adjust for your CUDA version)
99
+ # CUDA 12.6
100
+ pip install torch==2.10.0 torchvision==0.25.0 torchaudio==2.10.0 --index-url https://download.pytorch.org/whl/cu126
101
+ # CUDA 12.8
102
+ pip install torch==2.10.0 torchvision==0.25.0 torchaudio==2.10.0 --index-url https://download.pytorch.org/whl/cu128
103
+ # CUDA 13.0
104
+ pip install torch==2.10.0 torchvision==0.25.0 torchaudio==2.10.0 --index-url https://download.pytorch.org/whl/cu130
105
+
106
+ # 3. Install dependencies
107
+ bash install.sh
108
+ ```
109
+
110
+ ### Model Download
111
+
112
+ | Models | Download Link | Supports | Notes |
113
+ |------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------|-----------------------------------------------|---------------------------------------------------------------------------------------------|
114
+ | Helios-Base | 🤗 [Huggingface](https://huggingface.co/BestWishYsh/Helios-Base) 🤖 [ModelScope](https://modelscope.cn/models/BestWishYSH/Helios-Base) | T2V ✅ I2V ✅ V2V ✅ Interactive ✅ | Best Quality, with v-prediction, standard CFG and custom HeliosScheduler. |
115
+ | Helios-Mid | 🤗 [Huggingface](https://huggingface.co/BestWishYsh/Helios-Mid) 🤖 [ModelScope](https://modelscope.cn/models/BestWishYSH/Helios-Mid) | T2V ✅ I2V ✅ V2V ✅ Interactive ✅ | Intermediate Ckpt, with v-prediction, CFG-Zero* and custom HeliosScheduler. |
116
+ | Helios-Distilled | 🤗 [Huggingface](https://huggingface.co/BestWishYsh/Helios-Distilled) 🤖 [ModelScope](https://modelscope.cn/models/BestWishYSH/Helios-Distilled) | T2V ✅ I2V ✅ V2V ✅ Interactive ✅ | Best Efficiency, with x0-prediction and custom HeliosDMDScheduler. |
117
+
118
+
119
+
120
+ > 💡Note:
121
+ > * All three models share the same architecture, but Helios-Mid and Helios-Distilled use a more aggressive multi-scale sampling pipeline to achieve better efficiency.
122
+ > * Helios-Mid is an intermediate checkpoint generated in the process of distilling Helios-Base into Helios-Distilled, and may not meet expected quality.
123
+ > * For Image-to-Video or Video-to-Video, since training is based on Text-to-Video, these two functions may be slightly inferior to Text-to-Video. You may enable `is_skip_first_chunk` if you find the first few chunks are static or imporve the value of `image_noise_sigma_min`, `image_noise_sigma_max`, `video_noise_sigma_min`, and `video_noise_sigma_max`.
124
+
125
+
126
+ Download models using huggingface-cli:
127
+ ``` sh
128
+ pip install "huggingface_hub[cli]"
129
+ huggingface-cli download BestWishYSH/Helios-Base --local-dir BestWishYSH/Helios-Base
130
+ huggingface-cli download BestWishYSH/Helios-Mid --local-dir BestWishYSH/Helios-Mid
131
+ huggingface-cli download BestWishYSH/Helios-Distilled --local-dir BestWishYSH/Helios-Distilled
132
+ ```
133
+
134
+ Download models using modelscope-cli:
135
+ ``` sh
136
+ pip install modelscope
137
+ modelscope download BestWishYSH/Helios-Base --local_dir BestWishYSH/Helios-Base
138
+ modelscope download BestWishYSH/Helios-Mid --local_dir BestWishYSH/Helios-Mid
139
+ modelscope download BestWishYSH/Helios-Distilled --local_dir BestWishYSH/Helios-Distilled
140
+ ```
141
+
142
+ ## 🚀 Inference
143
+
144
+
145
+ Helios uses an autoregressive approach that generates **33 frames per chunk**. For optimal performance, `num_frames` should be set to a multiple of `33`. If a non-multiple value is provided, it will be automatically rounded up to the nearest multiple of 33.
146
+
147
+ **Example frame counts for different video lengths:**
148
+
149
+ | num_frames | Adjusted Frames | 24 FPS | 16 FPS |
150
+ |------------|-----------------|--------|--------|
151
+ | 1449 | 1452 (33×44) | ~60s (1min) | ~90s (1min 30s) |
152
+ | 720 | 726 (33×22) | ~30s | ~45s |
153
+ | 240 | 264 (33×8) | ~11s | ~16s |
154
+ | 129 | 132 (33×4) | ~5.5s | ~8s |
155
+ | 81 | 99 (33×3) | ~4s | ~6s |
156
+
157
+ ### Run the model
158
+
159
+ We provide inference scripts for all models covering text-to-video, image-to-video, and video-to-video in this [directory](./scripts/inference).
160
+
161
+ ```bash
162
+ cd scripts/inference
163
+
164
+ # For Helios-Base
165
+ bash helios-base_t2v.sh
166
+ bash helios-base_i2v.sh
167
+ bash helios-base_v2v.sh
168
+
169
+ # For Helios-Mid
170
+ bash helios-mid_t2v.sh
171
+ bash helios-mid_i2v.sh
172
+ bash helios-mid_v2v.sh
173
+
174
+ # For Helios-Distilled
175
+ bash helios-distilled_t2v.sh
176
+ bash helios-distilled_i2v.sh
177
+ bash helios-distilled_v2v.sh
178
+
179
+ # For Interactive
180
+ # ⚠️ This feature is still under development — results may not always meet expectations
181
+ cd scripts/inference/experiment_interactive
182
+ ```
183
+
184
+ ### Sanity Check
185
+
186
+ Before trying your own inputs, we highly recommend going through the sanity check to find out if any hardware or software went wrong.
187
+
188
+ | Task | **Helios-Base** | **Helios-Mid** | **Helios-Distilled** |
189
+ | ------- | -------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- |
190
+ | **T2V** | <video src="https://github.com/user-attachments/assets/14e10753-0366-4790-ad8f-7b66d821ed11" controls width="240"></video> | <video src="https://github.com/user-attachments/assets/c1778691-a80b-428c-8094-88bb1dd1d52b" controls width="240"></video> | <video src="https://github.com/user-attachments/assets/4ca28c79-9dfa-49de-9c3a-f4c7b6c766cd" controls width="240"></video> |
191
+ | **V2V** | <video src="https://github.com/user-attachments/assets/420cb572-85c2-42d8-98d7-37b0bc24c844" controls width="240"></video> | <video src="https://github.com/user-attachments/assets/7d703fa6-dc1a-4138-a897-e58cfd9236d6" controls width="240"></video> | <video src="https://github.com/user-attachments/assets/45329c55-1a25-459c-bbf0-4e584ec5b23d" controls width="240"></video> |
192
+
193
+
194
+ ### ✨ Group Offloading to Save VRAM
195
+
196
+ Helios supports group offloading to significantly reduce VRAM consumption, allowing you to run on GPU with limited memory footprint. For more details on the underlying mechanics, please refer to the [documentation](https://huggingface.co/docs/diffusers/main/en/optimization/memory#group-offloading).
197
+
198
+ The Helios model below requires `~6GB of VRAM`.
199
+
200
+ <details>
201
+ <summary>Click to expand the code</summary>
202
+
203
+ ```bash
204
+ CUDA_VISIBLE_DEVICES=0 python infer_helios.py \
205
+ --base_model_path "BestWishYsh/Helios-Distilled" \
206
+ --transformer_path "BestWishYsh/Helios-Distilled" \
207
+ --sample_type "t2v" \
208
+ --prompt "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 photo captures the fish from a slightly elevated angle, emphasizing its lively movements and the vivid colors of its surroundings. A close-up shot with dynamic movement." \
209
+ --num_frames 240 \
210
+ --guidance_scale 1.0 \
211
+ --is_enable_stage2 \
212
+ --pyramid_num_inference_steps_list 2 2 2 \
213
+ --is_amplify_first_chunk \
214
+ --output_folder "./output_helios/helios-distilled" \
215
+ --enable_low_vram_mode \
216
+ --group_offloading_type "leaf_level"
217
+ ```
218
+
219
+ </details>
220
+
221
+ ### ✨ Context Parallelism on Multiple GPUs
222
+ Helios supports various Context Parallelism mechanisms, including `Ulysses Attention`, `Ring Attention`, `Unified Attention`, and `Ulysses Anything Attention`. For more details, please refer to the [documentation](https://huggingface.co/docs/diffusers/main/en/training/distributed_inference#context-parallelism).
223
+
224
+ For example, let's take Helios-Base with 4 GPUs.
225
+
226
+ <details>
227
+ <summary>Click to expand the code</summary>
228
+
229
+ ```bash
230
+ CUDA_VISIBLE_DEVICES=0,1,2,3 torchrun --nproc_per_node 4 infer_helios.py \
231
+ --enable_parallelism \ # remember to enable this config
232
+ --cp_backend "ulysses" \ # ["ring", "ulysses", "unified", "ulysses_anything"]
233
+ --base_model_path "BestWishYsh/Helios-Base" \
234
+ --transformer_path "BestWishYsh/Helios-Base" \
235
+ --sample_type "t2v" \
236
+ --num_frames 99 \
237
+ --fps 24 \
238
+ --prompt "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 photo captures the fish from a slightly elevated angle, emphasizing its lively movements and the vivid colors of its surroundings. A close-up shot with dynamic movement." \
239
+ --guidance_scale 5.0 \
240
+ --output_folder "./output_helios/helios-base"
241
+ ```
242
+
243
+ </details>
244
+
245
+ ### ✨ Diffusers Pipeline
246
+
247
+ Install diffusers from source:
248
+ ```bash
249
+ pip install git+https://github.com/huggingface/diffusers.git
250
+ ```
251
+
252
+ For example, let's take Helios-Distilled (**Standard Pipeline**).
253
+
254
+ <details>
255
+ <summary>Click to expand the code</summary>
256
+
257
+ ```bash
258
+ import torch
259
+ from diffusers import AutoModel, HeliosPyramidPipeline
260
+ from diffusers.utils import export_to_video, load_video, load_image
261
+
262
+ vae = AutoModel.from_pretrained("BestWishYsh/Helios-Distilled", subfolder="vae", torch_dtype=torch.float32)
263
+
264
+ pipeline = HeliosPyramidPipeline.from_pretrained(
265
+ "BestWishYsh/Helios-Distilled",
266
+ vae=vae,
267
+ torch_dtype=torch.bfloat16
268
+ )
269
+ pipeline.to("cuda")
270
+
271
+ negative_prompt = """
272
+ Bright tones, overexposed, static, blurred details, subtitles, style, works, paintings, images, static, overall gray, worst quality,
273
+ low quality, JPEG compression residue, ugly, incomplete, extra fingers, poorly drawn hands, poorly drawn faces, deformed, disfigured,
274
+ misshapen limbs, fused fingers, still picture, messy background, three legs, many people in the background, walking backwards
275
+ """
276
+
277
+ # --- T2V ---
278
+ prompt = """
279
+ A vibrant tropical fish swimming gracefully among colorful coral reefs in a clear, turquoise ocean. The fish has bright blue
280
+ and yellow scales with a small, distinctive orange spot on its side, its fins moving fluidly. The coral reefs are alive with
281
+ a variety of marine life, including small schools of colorful fish and sea turtles gliding by. The water is crystal clear,
282
+ 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
283
+ of red, orange, and green. The photo captures the fish from a slightly elevated angle, emphasizing its lively movements and
284
+ the vivid colors of its surroundings. A close-up shot with dynamic movement.
285
+ """
286
+
287
+ output = pipeline(
288
+ prompt=prompt,
289
+ negative_prompt=negative_prompt,
290
+ num_frames=240,
291
+ pyramid_num_inference_steps_list=[2, 2, 2],
292
+ guidance_scale=1.0,
293
+ is_amplify_first_chunk=True,
294
+ generator=torch.Generator("cuda").manual_seed(42),
295
+ ).frames[0]
296
+ export_to_video(output, "helios_distilled_t2v_output.mp4", fps=24)
297
+
298
+ # --- I2V ---
299
+ i2v_prompt = """
300
+ A towering emerald wave surges forward, its crest curling with raw power and energy. Sunlight glints off the translucent water,
301
+ illuminating the intricate textures and deep green hues within the wave’s body. A thick spray erupts from the breaking crest,
302
+ casting a misty veil that dances above the churning surface. As the perspective widens, the immense scale of the wave becomes
303
+ apparent, revealing the restless expanse of the ocean stretching beyond. The scene captures the ocean’s untamed beauty and
304
+ relentless force, with every droplet and ripple shimmering in the light. The dynamic motion and vivid colors evoke both awe and
305
+ respect for nature’s might.
306
+ """
307
+ image_path = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/helios/wave.jpg"
308
+
309
+ output = pipeline(
310
+ prompt=i2v_prompt,
311
+ negative_prompt=negative_prompt,
312
+ image=load_image(image_path).resize((640, 384)),
313
+ num_frames=240,
314
+ pyramid_num_inference_steps_list=[2, 2, 2],
315
+ guidance_scale=1.0,
316
+ is_amplify_first_chunk=True,
317
+ generator=torch.Generator("cuda").manual_seed(42),
318
+ ).frames[0]
319
+ export_to_video(output, "helios_distilled_i2v_output.mp4", fps=24)
320
+
321
+ # --- V2V ---
322
+ v2v_prompt = """
323
+ A bright yellow Lamborghini Huracn Tecnica speeds along a curving mountain road, surrounded by lush green trees
324
+ under a partly cloudy sky. The car's sleek design and vibrant color stand out against the natural backdrop,
325
+ emphasizing its dynamic movement. The road curves gently, with a guardrail visible on one side, adding depth to
326
+ the scene. The motion blur captures the sense of speed and energy, creating a thrilling and exhilarating atmosphere.
327
+ A front-facing shot from a slightly elevated angle, highlighting the car's aggressive stance and the surrounding greenery.
328
+ """
329
+ video_path = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/helios/car.mp4"
330
+
331
+ output = pipeline(
332
+ prompt=v2v_prompt,
333
+ negative_prompt=negative_prompt,
334
+ video=load_video(video_path),
335
+ num_frames=240,
336
+ pyramid_num_inference_steps_list=[2, 2, 2],
337
+ guidance_scale=1.0,
338
+ is_amplify_first_chunk=True,
339
+ generator=torch.Generator("cuda").manual_seed(42),
340
+ ).frames[0]
341
+ export_to_video(output, "helios_distilled_v2v_output.mp4", fps=24)
342
+ ```
343
+
344
+ </details>
345
+
346
+ For example, let's take Helios-Distilled (**Modular Pipeline**).
347
+
348
+ <details>
349
+ <summary>Click to expand the code</summary>
350
+
351
+ ```bash
352
+ import torch
353
+ from diffusers import ModularPipeline, ClassifierFreeGuidance
354
+ from diffusers.utils import export_to_video, load_image, load_video
355
+
356
+ mod_pipe = ModularPipeline.from_pretrained("BestWishYsh/Helios-Distilled")
357
+ mod_pipe.load_components(torch_dtype=torch.bfloat16)
358
+ mod_pipe.to("cuda")
359
+
360
+ # we need to upload guider to the model repo, so each checkpoint will be able to config their guidance differently
361
+ guider = ClassifierFreeGuidance(guidance_scale=1.0)
362
+ mod_pipe.update_components(guider=guider)
363
+
364
+ # --- T2V ---
365
+ print("=== T2V ===")
366
+ prompt = (
367
+ "A vibrant tropical fish swimming gracefully among colorful coral reefs in a clear, turquoise ocean. "
368
+ "The fish has bright blue and yellow scales with a small, distinctive orange spot on its side, its fins moving "
369
+ "fluidly. The coral reefs are alive with a variety of marine life, including small schools of colorful fish and "
370
+ "sea turtles gliding by. The water is crystal clear, allowing for a view of the sandy ocean floor below. The reef "
371
+ "itself is adorned with a mix of hard and soft corals in shades of red, orange, and green. The photo captures "
372
+ "the fish from a slightly elevated angle, emphasizing its lively movements and the vivid colors of its surroundings. "
373
+ "A close-up shot with dynamic movement."
374
+ )
375
+
376
+ output = mod_pipe(
377
+ prompt=prompt,
378
+ height=384,
379
+ width=640,
380
+ num_frames=240,
381
+ pyramid_num_inference_steps_list=[2, 2, 2],
382
+ is_amplify_first_chunk=True,
383
+ generator=torch.Generator("cuda").manual_seed(42),
384
+ output="videos",
385
+ )
386
+
387
+ export_to_video(output[0], "helios_distilled_modular_t2v_output.mp4", fps=24)
388
+ print(f"T2V max memory: {torch.cuda.max_memory_allocated() / 1024**3:.3f} GB")
389
+ torch.cuda.empty_cache()
390
+ torch.cuda.reset_peak_memory_stats()
391
+
392
+ # --- I2V ---
393
+ print("=== I2V ===")
394
+ image = load_image(
395
+ "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/helios/wave.jpg"
396
+ )
397
+ i2v_prompt = (
398
+ "A towering emerald wave surges forward, its crest curling with raw power and energy. "
399
+ "Sunlight glints off the translucent water, illuminating the intricate textures and deep green hues within the wave's body."
400
+ )
401
+
402
+ output = mod_pipe(
403
+ prompt=i2v_prompt,
404
+ image=image,
405
+ height=384,
406
+ width=640,
407
+ num_frames=240,
408
+ pyramid_num_inference_steps_list=[2, 2, 2],
409
+ is_amplify_first_chunk=True,
410
+ generator=torch.Generator("cuda").manual_seed(42),
411
+ output="videos",
412
+ )
413
+
414
+ export_to_video(output[0], "helios_distilled_modular_i2v_output.mp4", fps=24)
415
+ print(f"I2V max memory: {torch.cuda.max_memory_allocated() / 1024**3:.3f} GB")
416
+ torch.cuda.empty_cache()
417
+ torch.cuda.reset_peak_memory_stats()
418
+
419
+ # --- V2V ---
420
+ print("=== V2V ===")
421
+ video = load_video(
422
+ "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/helios/car.mp4"
423
+ )
424
+ v2v_prompt = (
425
+ "A dynamic time-lapse video showing the rapidly moving scenery from the window of a speeding train. "
426
+ "The camera captures various elements such as lush green fields, towering trees, quaint countryside houses, "
427
+ "and distant mountain ranges passing by quickly."
428
+ )
429
+
430
+ output = mod_pipe(
431
+ prompt=v2v_prompt,
432
+ video=video,
433
+ height=384,
434
+ width=640,
435
+ num_frames=240,
436
+ pyramid_num_inference_steps_list=[2, 2, 2],
437
+ is_amplify_first_chunk=True,
438
+ generator=torch.Generator("cuda").manual_seed(42),
439
+ output="videos",
440
+ )
441
+
442
+ export_to_video(output[0], "helios_distilled_modular_v2v_output.mp4", fps=24)
443
+ print(f"V2V max memory: {torch.cuda.max_memory_allocated() / 1024**3:.3f} GB")
444
+ ```
445
+
446
+ </details>
447
+
448
+ ### ✨ vLLM-Omni Pipeline
449
+
450
+ Install vllm-omni from source:
451
+ ```bash
452
+ pip install git+https://github.com/vllm-project/vllm-omni.git
453
+ ```
454
+
455
+ For example, let's take Text-to-Video.
456
+
457
+ <details>
458
+ <summary>Click to expand the code</summary>
459
+
460
+ ```bash
461
+ cd vllm-omni
462
+
463
+ # Helios-Base
464
+ python3 examples/offline_inference/helios/end2end.py \
465
+ --sample-type t2v \
466
+ --model ./Helios-Base \
467
+ --prompt "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 photo captures the fish from a slightly elevated angle, emphasizing its lively movements and the vivid colors of its surroundings. A close-up shot with dynamic movement." \
468
+ --num-frames 99 \
469
+ --seed 42 \
470
+ --output helios_t2v_base.mp4
471
+
472
+ # Helios-Mid
473
+ python examples/offline_inference/helios/end2end.py \
474
+ --model ./Helios-Mid --sample-type t2v \
475
+ --prompt "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 photo captures the fish from a slightly elevated angle, emphasizing its lively movements and the vivid colors of its surroundings. A close-up shot with dynamic movement." \
476
+ --guidance-scale 5.0 --is-enable-stage2 \
477
+ --pyramid-num-inference-steps-list 20 20 20 \
478
+ --num-frames 99 \
479
+ --use-cfg-zero-star --use-zero-init --zero-steps 1 \
480
+ --output helios_t2v_mid.mp4
481
+
482
+ # Helios-Distilled
483
+ python examples/offline_inference/helios/end2end.py \
484
+ --model ./Helios-Distilled --sample-type t2v \
485
+ --prompt "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 photo captures the fish from a slightly elevated angle, emphasizing its lively movements and the vivid colors of its surroundings. A close-up shot with dynamic movement." \
486
+ --num-frames 240 --guidance-scale 1.0 --is-enable-stage2 \
487
+ --pyramid-num-inference-steps-list 2 2 2 \
488
+ --is-amplify-first-chunk --output helios_t2v_distilled.mp4
489
+ ```
490
+ </details>
491
+
492
+ ### ✨ SGLang-Diffusion Pipeline
493
+
494
+ Install sglang-diffusion from source:
495
+ ```bash
496
+ pip install git+https://github.com/sgl-project/sglang.git
497
+ ```
498
+
499
+ For example, let's take Helios-Base. **(Native Support)**
500
+
501
+ <details>
502
+ <summary>Click to expand the code</summary>
503
+
504
+ ```bash
505
+ sglang generate \
506
+ --model-path BestWishYsh/Helios-Base \
507
+ --prompt "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 photo captures the fish from a slightly elevated angle, emphasizing its lively movements and the vivid colors of its surroundings. A close-up shot with dynamic movement." \
508
+ --negative-prompt "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" \
509
+ --height 384 \
510
+ --width 640 \
511
+ --num-frames 99 \
512
+ --num-inference-steps 50 \
513
+ --guidance-scale 5.0
514
+ ```
515
+ </details>
516
+
517
+ For example, let's take Helios-Base. **(Diffusers Backend)**
518
+
519
+ <details>
520
+ <summary>Click to expand the code</summary>
521
+
522
+ ```bash
523
+ sglang generate \
524
+ --model-path BestWishYsh/Helios-Base \
525
+ --prompt "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 photo captures the fish from a slightly elevated angle, emphasizing its lively movements and the vivid colors of its surroundings. A close-up shot with dynamic movement." \
526
+ --negative-prompt "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" \
527
+ --height 384 \
528
+ --width 640 \
529
+ --num-frames 99 \
530
+ --num-inference-steps 50 \
531
+ --guidance-scale 5.0 \
532
+ --backend diffusers
533
+ ```
534
+ </details>
535
+
536
+ ## 🗝️ Training
537
+
538
+ We use a three-stage progressive pipeline, all the setting can be found [here](./scripts/training/configs/). Stage-1 (Base) performs architectural adaptation: we apply Unified History Injection, Easy Anti-Drifting, and Multi-Term Memory Patchification to convert the bidirectional pretrained model into an autoregressive generator. Stage-2 (Mid) targets token compression by introducing Pyramid Unified Predictor Corrector, which aggressively reduces the number of noisy tokens and thus the overall computation. Stage-3 (Distilled) applies Adversarial Hierarchical Distillation, reducing the sampling steps from 50 to 3 and eliminating the need for classifier-free guidance (CFG). Throughout training, we apply dynamic shifting to all timestep-dependent operations to match the noise schedule to the latent size.
539
+
540
+ ### Data Preparation
541
+
542
+ Please refer to [this guide](./tools/offload_data/README.md) for how to obtain the training data required by Helios. And we prepare a toy training data [here](https://huggingface.co/BestWishYsh/HeliosBench-Weights/tree/main/demo_data).
543
+
544
+ ### Run the model
545
+
546
+ ```bash
547
+ # Use DDP
548
+ bash scripts/training/train_ddp.sh
549
+
550
+ # or
551
+
552
+ # Use DeepSpeed
553
+ bash scripts/training/train_deepspeed.sh
554
+ ```
555
+
556
+ Training configuration can be adjusted in `scripts/training/configs`. You can use `scripts/training/compare_yaml.py` to check for configuration completeness or differences between stages.
557
+
558
+ ### Model Merging
559
+
560
+ After training, you can use this [script](./tools/merge_lora_for_helios.py) to merge all the checkpoints and obtain the final safetensors file, similar to [this](https://huggingface.co/BestWishYsh/Helios-Distilled/tree/main/transformer).
561
+
562
+
563
+ ## 📊 HeliosBench
564
+
565
+ HeliosBench is a specialized benchmark for real-time long-video generation, please refer to [this guide](./eval/README.md) for how to eval your own model.
566
+
567
+
568
+ ## 👍 Acknowledgement
569
+
570
+ This project wouldn't be possible without the following open-sourced repositories: [Open-Sora Plan](https://github.com/PKU-YuanGroup/Open-Sora-Plan), [Ascend](https://www.hiascend.com), [Diffusers](https://github.com/huggingface/diffusers), [vLLM-Omni](https://github.com/vllm-project/vllm), [SGLang Diffusion](https://github.com/sgl-project/sglang), [Wan](https://github.com/Wan-Video/Wan2.1), [FramePack](https://github.com/lllyasviel/FramePack), [PyramidFlow](https://github.com/jy0205/Pyramid-Flow), [DMD](https://github.com/tianweiy/DMD2).
571
+
572
+
573
+ ## 🔒 License
574
+
575
+ This project is released under the Apache 2.0 license as found in the [LICENSE](LICENSE) file.
576
+
577
+ ## ✏️ Citation
578
+
579
+ If you find our paper and code useful in your research, please consider giving a star ⭐ and citation 📝:
580
+
581
+ ```BibTeX
582
+ @article{helios,
583
+ title={Helios: Real Real-Time Long Video Generation Model},
584
+ author={Yuan, Shenghai and Yin, Yuanyang and Li, Zongjian and Huang, Xinwei and Yang, Xiao and Yuan, Li},
585
+ journal={arXiv preprint arXiv:2603.04379},
586
+ year={2026}
587
+ }
588
+ ```
589
+
590
+ ## 🤝 Contact
591
+
592
+ For questions and feedback, please contact us at: shyuan-cs@hotmail.com
593
+
594
+
Helios/_DEV/app.py ADDED
@@ -0,0 +1,322 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import tempfile
2
+ import time
3
+ from pathlib import Path
4
+
5
+ import gradio as gr
6
+ import spaces
7
+ import torch
8
+
9
+ from torch.utils._pytree import tree_map
10
+ from diffusers import AutoencoderKLWan, HeliosDMDScheduler, HeliosPyramidPipeline
11
+ from diffusers.utils import export_to_video, load_image, load_video
12
+
13
+
14
+ # ---------------------------------------------------------------------------
15
+ # Pre-load model
16
+ # ---------------------------------------------------------------------------
17
+ PROJECT_ROOT = Path(__file__).resolve().parent
18
+ MODEL_ID = str(PROJECT_ROOT / "checkpoints" / "Helios-Distilled")
19
+
20
+ vae = AutoencoderKLWan.from_pretrained(MODEL_ID, subfolder="vae", torch_dtype=torch.float32)
21
+ scheduler = HeliosDMDScheduler.from_pretrained(MODEL_ID, subfolder="scheduler")
22
+ pipe = HeliosPyramidPipeline.from_pretrained(
23
+ MODEL_ID, vae=vae, scheduler=scheduler, torch_dtype=torch.bfloat16, is_distilled=True
24
+ )
25
+ pipe.to("cuda")
26
+
27
+ cuda_major = torch.cuda.get_device_capability()[0]
28
+ if cuda_major >= 9:
29
+ # H100/H800 (SM90+) with FA3
30
+ try:
31
+ pipe.transformer.set_attention_backend("_flash_3_hub")
32
+ except Exception:
33
+ pipe.transformer.set_attention_backend("flash_hub")
34
+ else:
35
+ # 4090/A100 etc (SM89+) with FA2
36
+ pipe.transformer.set_attention_backend("flash_hub")
37
+
38
+ # ---------------------------------------------------------------------------
39
+ # AoTI
40
+ # ---------------------------------------------------------------------------
41
+
42
+ # Dynamic shapes: within a generation, only hidden_states H/W change across
43
+ # pyramid stages (history latents stay at full resolution). text_seq_length
44
+ # varies between different prompts.
45
+ _AUTO = torch.export.Dim.AUTO
46
+
47
+ TRANSFORMER_DYNAMIC_SHAPES = {
48
+ "hidden_states": {
49
+ 3: _AUTO, # H — doubles each pyramid stage
50
+ 4: _AUTO, # W — doubles each pyramid stage
51
+ },
52
+ "encoder_hidden_states": {
53
+ 1: _AUTO, # text_seq_length — varies with prompt
54
+ },
55
+ }
56
+
57
+ INDUCTOR_CONFIGS = {
58
+ "conv_1x1_as_mm": True,
59
+ "epilogue_fusion": False,
60
+ "coordinate_descent_tuning": True,
61
+ "coordinate_descent_check_all_directions": True,
62
+ # "max_autotune": True,
63
+ "triton.cudagraphs": True,
64
+ }
65
+
66
+ @spaces.GPU(duration=1500) # maximum duration allowed during startup
67
+ def compile_transformer():
68
+ with spaces.aoti_capture(pipe.transformer) as call:
69
+ pipe(
70
+ "arbitrary example prompt",
71
+ height=384,
72
+ width=640,
73
+ num_frames=33,
74
+ guidance_scale=1.0,
75
+ generator=torch.Generator(device="cuda").manual_seed(42),
76
+ pyramid_num_inference_steps_list=[2, 2, 2],
77
+ is_amplify_first_chunk=True,
78
+ )
79
+
80
+ dynamic_shapes = tree_map(lambda t: None, call.kwargs)
81
+ dynamic_shapes |= TRANSFORMER_DYNAMIC_SHAPES
82
+
83
+ with torch.no_grad():
84
+ exported = torch.export.export(
85
+ pipe.transformer,
86
+ args=call.args,
87
+ kwargs=call.kwargs,
88
+ dynamic_shapes=dynamic_shapes,
89
+ )
90
+
91
+ return spaces.aoti_compile(exported, INDUCTOR_CONFIGS)
92
+
93
+ compiled_transformer = compile_transformer()
94
+ spaces.aoti_apply(compiled_transformer, pipe.transformer)
95
+
96
+
97
+ # ---------------------------------------------------------------------------
98
+ # Generation
99
+ # ---------------------------------------------------------------------------
100
+ @spaces.GPU(duration=60)
101
+ def generate_video(
102
+ mode: str,
103
+ prompt: str,
104
+ image_input,
105
+ video_input,
106
+ height: int,
107
+ width: int,
108
+ num_frames: int,
109
+ num_inference_steps: int,
110
+ seed: int,
111
+ is_amplify_first_chunk: bool,
112
+ progress=gr.Progress(track_tqdm=True),
113
+ ):
114
+ if not prompt:
115
+ raise gr.Error("Please provide a prompt.")
116
+
117
+ generator = torch.Generator(device="cuda").manual_seed(int(seed))
118
+
119
+ kwargs = {
120
+ "prompt": prompt,
121
+ "height": int(height),
122
+ "width": int(width),
123
+ "num_frames": int(num_frames),
124
+ "guidance_scale": 1.0,
125
+ "generator": generator,
126
+ "output_type": "np",
127
+ "pyramid_num_inference_steps_list": [
128
+ int(num_inference_steps),
129
+ int(num_inference_steps),
130
+ int(num_inference_steps),
131
+ ],
132
+ "is_amplify_first_chunk": is_amplify_first_chunk,
133
+ }
134
+
135
+ if mode == "Image-to-Video" and image_input is not None:
136
+ img = load_image(image_input).resize((int(width), int(height)))
137
+ kwargs["image"] = img
138
+ elif mode == "Video-to-Video" and video_input is not None:
139
+ kwargs["video"] = load_video(video_input)
140
+
141
+ t0 = time.time()
142
+ output = pipe(**kwargs).frames[0]
143
+ elapsed = time.time() - t0
144
+
145
+ tmp = tempfile.NamedTemporaryFile(suffix=".mp4", delete=False)
146
+ export_to_video(output, tmp.name, fps=24)
147
+ info = f"Generated in {elapsed:.1f}s · {num_frames} frames · {height}×{width}"
148
+ return tmp.name, info
149
+
150
+
151
+ # ---------------------------------------------------------------------------
152
+ # UI Setup
153
+ # ---------------------------------------------------------------------------
154
+ def update_conditional_visibility(mode):
155
+ if mode == "Image-to-Video":
156
+ return gr.update(visible=True), gr.update(visible=False)
157
+ elif mode == "Video-to-Video":
158
+ return gr.update(visible=False), gr.update(visible=True)
159
+ else:
160
+ return gr.update(visible=False), gr.update(visible=False)
161
+
162
+
163
+ CSS = """
164
+ #header { text-align: center; margin-bottom: 1.5em; }
165
+ #header h1 { font-size: 2.2em; margin-bottom: 0.2em; }
166
+ .logo { max-height: 100px; margin: 0 auto 10px auto; display: block; }
167
+ .link-buttons { display: flex; justify-content: center; gap: 15px; margin-top: 10px; }
168
+ .link-buttons a {
169
+ background-color: #2b3137;
170
+ color: #ffffff !important;
171
+ padding: 8px 20px;
172
+ border-radius: 6px;
173
+ text-decoration: none;
174
+ font-weight: 600;
175
+ font-size: 1em;
176
+ transition: all 0.2s ease-in-out;
177
+ box-shadow: 0 2px 4px rgba(0,0,0,0.1);
178
+ }
179
+ .link-buttons a:hover { background-color: #4a535c; transform: translateY(-1px); }
180
+ .contain { max-width: 1350px; margin: 0 auto !important; }
181
+ """
182
+
183
+ with gr.Blocks(title="Helios Video Generation") as demo:
184
+ gr.HTML(
185
+ """
186
+ <div style='display: flex; align-items: center; justify-content: center; width: 100%;'>
187
+ <img src="https://raw.githubusercontent.com/SHYuanBest/shyuanbest_media/main/Helios/logo_white.png" style='width: 400px; height: auto;' />
188
+ </div>
189
+ <div id="header">
190
+ <h1>🎬 Helios 14B Distilled: Real Real-Time Long Video Generation Model</h1>
191
+ <p style="font-size: 1.1em; color: #666; margin-top: 0.5em; margin-bottom: 1em;">
192
+ If you like our project, please give us a star ⭐ on GitHub for the latest update.
193
+ </p>
194
+ <div class="link-buttons">
195
+ <a href="https://github.com/PKU-YuanGroup/Helios" target="_blank">💻 Code</a>
196
+ <a href="https://pku-yuangroup.github.io/Helios-Page" target="_blank">📄 Page</a>
197
+ <a href="https://www.youtube.com/watch?v=vd_AgHtOUFQ" target="_blank">🎥 Main Feature</a>
198
+ <a href="https://www.youtube.com/watch?v=1GeIU2Dn7UY" target="_blank">⚡ Inference Speed</a>
199
+ </div>
200
+ </div>
201
+ """
202
+ )
203
+
204
+ with gr.Row():
205
+ with gr.Column(scale=1):
206
+ mode = gr.Radio(
207
+ choices=["Text-to-Video", "Image-to-Video", "Video-to-Video"],
208
+ value="Text-to-Video",
209
+ label="Generation Mode",
210
+ )
211
+ image_input = gr.Image(label="Image (for I2V)", type="filepath", visible=False)
212
+ video_input = gr.Video(label="Video (for V2V)", visible=False)
213
+ prompt = gr.Textbox(
214
+ label="Prompt",
215
+ lines=4,
216
+ value=(
217
+ "A vibrant tropical fish swimming gracefully among colorful coral reefs in "
218
+ "a clear, turquoise ocean. The fish has bright blue and yellow scales with a "
219
+ "small, distinctive orange spot on its side, its fins moving fluidly. The coral "
220
+ "reefs are alive with a variety of marine life, including small schools of "
221
+ "colorful fish and sea turtles gliding by. The water is crystal clear, allowing "
222
+ "for a view of the sandy ocean floor below. The reef itself is adorned with a mix "
223
+ "of hard and soft corals in shades of red, orange, and green. The photo captures "
224
+ "the fish from a slightly elevated angle, emphasizing its lively movements and the "
225
+ "vivid colors of its surroundings. A close-up shot with dynamic movement."
226
+ ),
227
+ )
228
+ with gr.Accordion("Advanced Settings", open=False):
229
+ with gr.Row():
230
+ height = gr.Number(value=384, label="Height", precision=0, interactive=False)
231
+ width = gr.Number(value=640, label="Width", precision=0, interactive=False)
232
+ with gr.Row():
233
+ num_frames = gr.Slider(33, 231, value=231, step=33, label="Num Frames")
234
+ num_inference_steps = gr.Slider(1, 10, value=2, step=1, label="Steps per stage")
235
+ with gr.Row():
236
+ seed = gr.Number(value=42, label="Seed", precision=0)
237
+ is_amplify_first_chunk = gr.Checkbox(label="Amplify First Chunk", value=True)
238
+
239
+ generate_btn = gr.Button("🚀 Generate Video", variant="primary", size="lg")
240
+
241
+ with gr.Column(scale=1):
242
+ video_output = gr.Video(label="Generated Video", autoplay=True)
243
+ info_output = gr.Textbox(label="Info", interactive=False)
244
+
245
+ mode.change(fn=update_conditional_visibility, inputs=[mode], outputs=[image_input, video_input])
246
+ generate_btn.click(
247
+ fn=generate_video,
248
+ inputs=[
249
+ mode,
250
+ prompt,
251
+ image_input,
252
+ video_input,
253
+ height,
254
+ width,
255
+ num_frames,
256
+ num_inference_steps,
257
+ seed,
258
+ is_amplify_first_chunk,
259
+ ],
260
+ outputs=[video_output, info_output],
261
+ )
262
+
263
+ gr.Examples(
264
+ examples=[
265
+ [
266
+ "Text-to-Video",
267
+ "A vibrant tropical fish swimming gracefully among colorful coral reefs in "
268
+ "a clear, turquoise ocean. The fish has bright blue and yellow scales with a "
269
+ "small, distinctive orange spot on its side, its fins moving fluidly. The coral "
270
+ "reefs are alive with a variety of marine life, including small schools of "
271
+ "colorful fish and sea turtles gliding by. The water is crystal clear, allowing "
272
+ "for a view of the sandy ocean floor below. The reef itself is adorned with a mix "
273
+ "of hard and soft corals in shades of red, orange, and green. The photo captures "
274
+ "the fish from a slightly elevated angle, emphasizing its lively movements and the "
275
+ "vivid colors of its surroundings. A close-up shot with dynamic movement.",
276
+ None,
277
+ None,
278
+ ],
279
+ [
280
+ "Text-to-Video",
281
+ "An extreme close-up of an gray-haired man with a beard in his 60s, he is deep in "
282
+ "thought pondering the history of the universe as he sits at a cafe in Paris, his eyes "
283
+ "focus on people offscreen as they walk as he sits mostly motionless, he is dressed in "
284
+ "a wool coat suit coat with a button-down shirt , he wears a brown beret and glasses "
285
+ "and has a very professorial appearance, and the end he offers a subtle closed-mouth "
286
+ "smile as if he found the answer to the mystery of life, the lighting is very cinematic "
287
+ "with the golden light and the Parisian streets and city in the background, depth of "
288
+ "field, cinematic 35mm film.",
289
+ None,
290
+ None,
291
+ ],
292
+ [
293
+ "Text-to-Video",
294
+ "A drone camera circles around a beautiful historic church built on a rocky outcropping "
295
+ "along the Amalfi Coast, the view showcases historic and magnificent architectural "
296
+ "details and tiered pathways and patios, waves are seen crashing against the rocks "
297
+ "below as the view overlooks the horizon of the coastal waters and hilly landscapes "
298
+ "of the Amalfi Coast Italy, several distant people are seen walking and enjoying vistas "
299
+ "on patios of the dramatic ocean views, the warm glow of the afternoon sun creates a "
300
+ "magical and romantic feeling to the scene, the view is stunning captured with beautiful photography.",
301
+ None,
302
+ None,
303
+ ],
304
+ [
305
+ "Image-to-Video",
306
+ "A towering emerald wave surges forward, its crest curling with raw power and energy. Sunlight glints off the translucent water, illuminating the intricate textures and deep green hues within the wave’s body. A thick spray erupts from the breaking crest, casting a misty veil that dances above the churning surface. As the perspective widens, the immense scale of the wave becomes apparent, revealing the restless expanse of the ocean stretching beyond. The scene captures the ocean’s untamed beauty and relentless force, with every droplet and ripple shimmering in the light. The dynamic motion and vivid colors evoke both awe and respect for nature’s might.",
307
+ "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/helios/wave.jpg",
308
+ None,
309
+ ],
310
+ [
311
+ "Video-to-Video",
312
+ "A bright yellow Lamborghini Huracn Tecnica speeds along a curving mountain road, surrounded by lush green trees under a partly cloudy sky. The car's sleek design and vibrant color stand out against the natural backdrop, emphasizing its dynamic movement. The road curves gently, with a guardrail visible on one side, adding depth to the scene. The motion blur captures the sense of speed and energy, creating a thrilling and exhilarating atmosphere. A front-facing shot from a slightly elevated angle, highlighting the car's aggressive stance and the surrounding greenery.",
313
+ None,
314
+ "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/helios/car.mp4",
315
+ ],
316
+ ],
317
+ inputs=[mode, prompt, image_input, video_input],
318
+ label="Example Prompts",
319
+ )
320
+
321
+ if __name__ == "__main__":
322
+ demo.launch(share=True, css=CSS, theme=gr.themes.Soft())
Helios/_DEV/bench_infer.py ADDED
@@ -0,0 +1,569 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Helios Benchmark Inference Script
3
+ - Runs T2V inference for a single model version on a single GPU
4
+ - Uses the first N prompts from a txt file
5
+ - Saves videos in two layouts: by_prompt/<slug>/<version>.mp4
6
+ by_version/<version>/<slug>.mp4
7
+ - Records per-video timing to timing_<version>.txt and computes summary stats
8
+ """
9
+
10
+ import importlib
11
+ import os
12
+ import re
13
+ import shutil
14
+ import sys
15
+ import time
16
+
17
+ os.environ["HF_ENABLE_PARALLEL_LOADING"] = "yes"
18
+ os.environ["HF_PARALLEL_LOADING_WORKERS"] = "8"
19
+
20
+ import argparse
21
+ import subprocess
22
+ from pathlib import Path
23
+
24
+
25
+ SCRIPT_DIR = Path(__file__).resolve().parent
26
+ DEFAULT_PROMPT_FILE = SCRIPT_DIR / "demo_data" / "MovieGenVideoBench_extended.txt"
27
+ DEFAULT_MODEL_ROOT = SCRIPT_DIR / "checkpoints"
28
+ DEFAULT_OUTPUT_ROOT = SCRIPT_DIR / "output_helios" / "bench"
29
+
30
+
31
+ def pick_gpu_by_free_vram(min_free_mib=20000):
32
+ """Pick physical GPU index with the most free memory (via nvidia-smi). No torch import."""
33
+ try:
34
+ out = subprocess.check_output(
35
+ [
36
+ "nvidia-smi",
37
+ "--query-gpu=index,memory.free",
38
+ "--format=csv,noheader,nounits",
39
+ ],
40
+ text=True,
41
+ stderr=subprocess.DEVNULL,
42
+ )
43
+ except (subprocess.CalledProcessError, FileNotFoundError) as e:
44
+ raise RuntimeError("nvidia-smi failed; specify --gpu explicitly") from e
45
+
46
+ best_idx, best_free = None, -1
47
+ for line in out.strip().splitlines():
48
+ parts = [p.strip() for p in line.split(",")]
49
+ if len(parts) < 2:
50
+ continue
51
+ idx, free = int(parts[0]), int(parts[1])
52
+ if free > best_free:
53
+ best_free, best_idx = free, idx
54
+ if best_idx is None:
55
+ raise RuntimeError("Could not parse nvidia-smi GPU list")
56
+ if best_free < min_free_mib:
57
+ print(
58
+ f"[warn] Best GPU {best_idx} has only {best_free} MiB free "
59
+ f"(<{min_free_mib} MiB); OOM risk — consider --enable_low_vram_mode",
60
+ file=sys.stderr,
61
+ )
62
+ return best_idx, best_free
63
+
64
+
65
+ def _apply_cuda_visible_devices_before_torch():
66
+ """CUDA_VISIBLE_DEVICES must be set before `import torch` (first CUDA init)."""
67
+ pre = argparse.ArgumentParser(add_help=False)
68
+ pre.add_argument("--gpu", type=str, default="auto")
69
+ known, _ = pre.parse_known_args()
70
+ g = known.gpu.strip().lower()
71
+ if g == "auto":
72
+ idx, free = pick_gpu_by_free_vram()
73
+ os.environ["CUDA_VISIBLE_DEVICES"] = str(idx)
74
+ os.environ["_BENCH_PHYSICAL_GPU"] = f"{idx} ({free} MiB free)"
75
+ else:
76
+ os.environ["CUDA_VISIBLE_DEVICES"] = known.gpu.strip()
77
+ os.environ["_BENCH_PHYSICAL_GPU"] = known.gpu.strip()
78
+ os.environ["_BENCH_GPU_ARG"] = known.gpu.strip()
79
+
80
+
81
+ _apply_cuda_visible_devices_before_torch()
82
+
83
+ import torch
84
+ from tqdm import tqdm
85
+
86
+ if importlib.util.find_spec("torch_npu") is not None:
87
+ import torch_npu # noqa: F401
88
+
89
+ from helios.diffusers_version.pipeline_helios_diffusers import HeliosPipeline
90
+ from helios.diffusers_version.scheduling_helios_diffusers import HeliosScheduler
91
+ from helios.diffusers_version.transformer_helios_diffusers import HeliosTransformer3DModel
92
+ from helios.modules.helios_kernels import (
93
+ replace_all_norms_with_flash_norms,
94
+ replace_rmsnorm_with_fp32,
95
+ replace_rope_with_flash_rope,
96
+ )
97
+ from diffusers.models import AutoencoderKLWan
98
+ from diffusers.utils import export_to_video
99
+
100
+ # ── per-version inference presets (matching official scripts) ─────────────────
101
+
102
+ MODEL_PRESETS = {
103
+ "base": dict(
104
+ model_dir="Helios-Base",
105
+ num_frames=99,
106
+ num_inference_steps=50,
107
+ guidance_scale=5.0,
108
+ is_enable_stage2=False,
109
+ pyramid_num_inference_steps_list=[20, 20, 20],
110
+ is_amplify_first_chunk=False,
111
+ use_zero_init=False,
112
+ zero_steps=1,
113
+ ),
114
+ "mid": dict(
115
+ model_dir="Helios-Mid",
116
+ num_frames=99,
117
+ num_inference_steps=50,
118
+ guidance_scale=5.0,
119
+ is_enable_stage2=True,
120
+ pyramid_num_inference_steps_list=[20, 20, 20],
121
+ is_amplify_first_chunk=False,
122
+ use_zero_init=True,
123
+ zero_steps=1,
124
+ ),
125
+ "distilled": dict(
126
+ model_dir="Helios-Distilled",
127
+ num_frames=240,
128
+ num_inference_steps=50,
129
+ guidance_scale=1.0,
130
+ is_enable_stage2=True,
131
+ pyramid_num_inference_steps_list=[2, 2, 2],
132
+ is_amplify_first_chunk=True,
133
+ use_zero_init=False,
134
+ zero_steps=1,
135
+ ),
136
+ }
137
+
138
+ NEGATIVE_PROMPT = (
139
+ "Bright tones, overexposed, static, blurred details, subtitles, style, "
140
+ "works, paintings, images, static, overall gray, worst quality, low quality, "
141
+ "JPEG compression residue, ugly, incomplete, extra fingers, poorly drawn hands, "
142
+ "poorly drawn faces, deformed, disfigured, misshapen limbs, fused fingers, "
143
+ "still picture, messy background, three legs, many people in the background, "
144
+ "walking backwards"
145
+ )
146
+
147
+
148
+ def sanitize_filename(text, max_len=80):
149
+ """Turn a prompt into a filesystem-safe slug."""
150
+ text = text.strip().lower()
151
+ text = re.sub(r"[^a-z0-9]+", "_", text)
152
+ text = text.strip("_")
153
+ return text[:max_len]
154
+
155
+
156
+ def load_prompt_indices(path):
157
+ indices = []
158
+ with open(path, "r", encoding="utf-8") as f:
159
+ for line_no, raw_line in enumerate(f, start=1):
160
+ line = raw_line.strip()
161
+ if not line or line.startswith("#"):
162
+ continue
163
+ try:
164
+ idx = int(line)
165
+ except ValueError as exc:
166
+ raise ValueError(
167
+ f"Invalid prompt index at {path}:{line_no}: {line!r}"
168
+ ) from exc
169
+ if idx < 0:
170
+ raise ValueError(f"Prompt index must be >= 0 at {path}:{line_no}")
171
+ indices.append(idx)
172
+ return indices
173
+
174
+
175
+ def load_prompts(path, prompt_start=0, prompt_end=None, prompt_indices=None):
176
+ with open(path, "r", encoding="utf-8") as f:
177
+ lines = [line.strip() for line in f if line.strip()]
178
+ if prompt_indices is not None:
179
+ selected = []
180
+ total = len(lines)
181
+ for idx in prompt_indices:
182
+ if idx >= total:
183
+ raise ValueError(
184
+ f"Prompt index {idx} is out of range; prompt file has {total} prompts"
185
+ )
186
+ selected.append((idx, lines[idx]))
187
+ return selected
188
+
189
+ if prompt_start < 0:
190
+ raise ValueError("prompt_start must be >= 0")
191
+ if prompt_end is not None and prompt_end < prompt_start:
192
+ raise ValueError("prompt_end must be >= prompt_start")
193
+
194
+ selected = lines[prompt_start:prompt_end]
195
+ return [(prompt_start + offset, prompt) for offset, prompt in enumerate(selected)]
196
+
197
+
198
+ def build_expected_outputs(prompts, version, by_version_dir):
199
+ version_dir = os.path.join(by_version_dir, version)
200
+ expected = []
201
+ for idx, prompt in prompts:
202
+ slug = sanitize_filename(prompt)
203
+ vid_name = f"{idx:04d}_{slug}"
204
+ expected.append((idx, slug, os.path.join(version_dir, f"{vid_name}.mp4")))
205
+ return version_dir, expected
206
+
207
+
208
+ def output_exists(path):
209
+ return os.path.isfile(path) and os.path.getsize(path) > 0
210
+
211
+
212
+ def find_missing_outputs(expected_outputs):
213
+ return [item for item in expected_outputs if not output_exists(item[2])]
214
+
215
+
216
+ def make_timing_line(version, idx, elapsed, slug):
217
+ return (
218
+ f" {version:10s} #{idx:04d} {elapsed:8.2f}s "
219
+ f"({elapsed / 60:5.2f}min) {slug[:50]}"
220
+ )
221
+
222
+
223
+ def load_existing_timing_records(timing_file, version):
224
+ if not os.path.exists(timing_file):
225
+ return {}
226
+
227
+ pattern = re.compile(
228
+ rf"^\s*{re.escape(version)}\s+#(\d+)\s+([0-9.]+)s\s+\([^)]+\)\s+(.*)$"
229
+ )
230
+ records = {}
231
+ with open(timing_file, "r", encoding="utf-8") as f:
232
+ for raw_line in f:
233
+ line = raw_line.rstrip("\n")
234
+ match = pattern.match(line)
235
+ if not match:
236
+ continue
237
+ idx = int(match.group(1))
238
+ elapsed = float(match.group(2))
239
+ slug = match.group(3)
240
+ records[idx] = (elapsed, slug)
241
+ return records
242
+
243
+
244
+ def build_pipeline(
245
+ model_path,
246
+ device,
247
+ weight_dtype,
248
+ enable_low_vram=False,
249
+ group_offloading_type="leaf_level",
250
+ num_blocks_per_group=4,
251
+ ):
252
+ transformer = HeliosTransformer3DModel.from_pretrained(
253
+ model_path, subfolder="transformer", torch_dtype=weight_dtype,
254
+ )
255
+ transformer = replace_rmsnorm_with_fp32(transformer)
256
+ transformer = replace_all_norms_with_flash_norms(transformer)
257
+ replace_rope_with_flash_rope()
258
+
259
+ cuda_major = torch.cuda.get_device_capability()[0]
260
+ if cuda_major >= 9:
261
+ try:
262
+ transformer.set_attention_backend("_flash_3_hub")
263
+ except Exception:
264
+ transformer.set_attention_backend("flash_hub")
265
+ else:
266
+ transformer.set_attention_backend("flash_hub")
267
+
268
+ vae = AutoencoderKLWan.from_pretrained(
269
+ model_path, subfolder="vae", torch_dtype=torch.float32,
270
+ )
271
+ scheduler = HeliosScheduler.from_pretrained(model_path, subfolder="scheduler")
272
+
273
+ pipe = HeliosPipeline.from_pretrained(
274
+ model_path,
275
+ transformer=transformer,
276
+ vae=vae,
277
+ scheduler=scheduler,
278
+ torch_dtype=weight_dtype,
279
+ )
280
+ if enable_low_vram:
281
+ nbg = int(num_blocks_per_group) if group_offloading_type == "block_level" else None
282
+ pipe.enable_group_offload(
283
+ onload_device=torch.device("cuda"),
284
+ offload_device=torch.device("cpu"),
285
+ offload_type=group_offloading_type,
286
+ num_blocks_per_group=nbg,
287
+ use_stream=True,
288
+ record_stream=True,
289
+ )
290
+ else:
291
+ pipe = pipe.to(device)
292
+ return pipe
293
+
294
+
295
+ def run_single(pipe, prompt, preset, height, width, seed):
296
+ gen = torch.Generator(device="cuda").manual_seed(seed)
297
+
298
+ t0 = time.time()
299
+ with torch.no_grad():
300
+ output = pipe(
301
+ prompt=prompt,
302
+ negative_prompt=NEGATIVE_PROMPT,
303
+ height=height,
304
+ width=width,
305
+ num_frames=preset["num_frames"],
306
+ num_inference_steps=preset["num_inference_steps"],
307
+ guidance_scale=preset["guidance_scale"],
308
+ generator=gen,
309
+ history_sizes=[16, 2, 1],
310
+ num_latent_frames_per_chunk=9,
311
+ keep_first_frame=True,
312
+ is_enable_stage2=preset["is_enable_stage2"],
313
+ pyramid_num_inference_steps_list=preset["pyramid_num_inference_steps_list"],
314
+ is_skip_first_chunk=False,
315
+ is_amplify_first_chunk=preset["is_amplify_first_chunk"],
316
+ use_zero_init=preset["use_zero_init"],
317
+ zero_steps=preset["zero_steps"],
318
+ ).frames[0]
319
+ elapsed = time.time() - t0
320
+ return output, elapsed
321
+
322
+
323
+ def _parse_gpu(s):
324
+ if isinstance(s, str) and s.lower() == "auto":
325
+ return "auto"
326
+ return int(s)
327
+
328
+
329
+ def parse_args():
330
+ p = argparse.ArgumentParser(description="Helios benchmark inference for one model version")
331
+ p.add_argument("--prompt_file", type=str,
332
+ default=str(DEFAULT_PROMPT_FILE))
333
+ p.add_argument("--prompt_start", type=int, default=0)
334
+ p.add_argument("--prompt_end", type=int, default=100,
335
+ help="Exclusive end index for prompts, e.g. 50 means up to #49")
336
+ p.add_argument("--prompt_indices_file", type=str, default=None,
337
+ help="Optional file containing exact prompt indices to run, one per line")
338
+ p.add_argument("--model_root", type=str, default=str(DEFAULT_MODEL_ROOT),
339
+ help="Parent dir containing Helios-Base / Helios-Mid / Helios-Distilled")
340
+ p.add_argument("--output_root", type=str, default=str(DEFAULT_OUTPUT_ROOT))
341
+ p.add_argument("--version", type=str, choices=sorted(MODEL_PRESETS.keys()), required=True,
342
+ help="Which model version to run")
343
+ p.add_argument("--timing_file", type=str, default=None,
344
+ help="Optional override for timing report path")
345
+ p.add_argument("--height", type=int, default=384)
346
+ p.add_argument("--width", type=int, default=640)
347
+ p.add_argument("--num_frames", type=int, default=None,
348
+ help="Override preset frame count for all selected versions")
349
+ p.add_argument("--seed", type=int, default=42)
350
+ p.add_argument(
351
+ "--gpu",
352
+ type=_parse_gpu,
353
+ default="auto",
354
+ help='Physical GPU id or "auto" (pick most free VRAM via nvidia-smi)',
355
+ )
356
+ p.add_argument(
357
+ "--enable_low_vram_mode",
358
+ action="store_true",
359
+ help="CPU group-offload (slower, less VRAM); use if GPU is shared or OOM",
360
+ )
361
+ p.add_argument(
362
+ "--group_offloading_type",
363
+ type=str,
364
+ choices=["leaf_level", "block_level"],
365
+ default="leaf_level",
366
+ )
367
+ p.add_argument("--num_blocks_per_group", type=int, default=4)
368
+ return p.parse_args()
369
+
370
+
371
+ def main():
372
+ args = parse_args()
373
+
374
+ if not os.path.isfile(args.prompt_file):
375
+ raise FileNotFoundError(f"Prompt file not found: {args.prompt_file}")
376
+ if not os.path.isdir(args.model_root):
377
+ raise FileNotFoundError(f"Model root not found: {args.model_root}")
378
+
379
+ os.environ["CUDA_VISIBLE_DEVICES"] = str(args.gpu)
380
+ device = torch.device("cuda")
381
+ weight_dtype = torch.bfloat16
382
+
383
+ prompt_indices = None
384
+ if args.prompt_indices_file:
385
+ if not os.path.isfile(args.prompt_indices_file):
386
+ raise FileNotFoundError(f"Prompt indices file not found: {args.prompt_indices_file}")
387
+ prompt_indices = load_prompt_indices(args.prompt_indices_file)
388
+
389
+ prompts = load_prompts(
390
+ args.prompt_file,
391
+ args.prompt_start,
392
+ args.prompt_end,
393
+ prompt_indices=prompt_indices,
394
+ )
395
+ prompt_map = dict(prompts)
396
+ if args.prompt_indices_file:
397
+ print(
398
+ f"Loaded {len(prompts)} prompts from {args.prompt_file} "
399
+ f"(indices: {args.prompt_indices_file})"
400
+ )
401
+ else:
402
+ print(
403
+ f"Loaded {len(prompts)} prompts from {args.prompt_file} "
404
+ f"(range: {args.prompt_start}:{args.prompt_end})"
405
+ )
406
+
407
+ if args.num_frames is not None:
408
+ MODEL_PRESETS[args.version]["num_frames"] = args.num_frames
409
+
410
+ by_prompt_dir = os.path.join(args.output_root, "by_prompt")
411
+ by_version_dir = os.path.join(args.output_root, "by_version")
412
+ timing_file = args.timing_file or os.path.join(args.output_root, f"timing_{args.version}.txt")
413
+ os.makedirs(args.output_root, exist_ok=True)
414
+
415
+ preset = MODEL_PRESETS[args.version]
416
+ model_path = os.path.join(args.model_root, preset["model_dir"])
417
+ timing_records = load_existing_timing_records(timing_file, args.version)
418
+ selected_indices = set(prompt_map)
419
+ timing_records = {
420
+ idx: record for idx, record in timing_records.items() if idx in selected_indices
421
+ }
422
+ ver_dir, expected_outputs = build_expected_outputs(prompts, args.version, by_version_dir)
423
+ missing_outputs = find_missing_outputs(expected_outputs)
424
+ if not os.path.isdir(model_path):
425
+ raise FileNotFoundError(f"Model not found: {model_path}")
426
+
427
+ peak_mem = None
428
+ if not missing_outputs:
429
+ print(
430
+ f"[SKIP] All outputs already exist for version={args.version} under {ver_dir}"
431
+ )
432
+ else:
433
+ header = (
434
+ f"\n{'=' * 60}\n"
435
+ f" Version: {args.version} | Model: {preset['model_dir']}\n"
436
+ f" Frames: {preset['num_frames']} | guidance_scale: {preset['guidance_scale']}\n"
437
+ f" stage2: {preset['is_enable_stage2']} | pyramid_steps: {preset['pyramid_num_inference_steps_list']}\n"
438
+ f"{'=' * 60}\n"
439
+ )
440
+ print(header)
441
+
442
+ pipe = build_pipeline(
443
+ model_path,
444
+ device,
445
+ weight_dtype,
446
+ enable_low_vram=args.enable_low_vram_mode,
447
+ group_offloading_type=args.group_offloading_type,
448
+ num_blocks_per_group=args.num_blocks_per_group,
449
+ )
450
+
451
+ os.makedirs(ver_dir, exist_ok=True)
452
+
453
+ print(
454
+ f"[resume] version={args.version} existing={len(expected_outputs) - len(missing_outputs)} "
455
+ f"missing={len(missing_outputs)} timed={len(timing_records)}"
456
+ )
457
+ for idx, slug, ver_out in tqdm(missing_outputs, desc=f"[{args.version}]"):
458
+ if os.path.exists(ver_out):
459
+ print(f" [skip] {ver_out}")
460
+ continue
461
+
462
+ try:
463
+ frames, elapsed = run_single(
464
+ pipe, prompt_map[idx], preset, args.height, args.width, args.seed,
465
+ )
466
+ except Exception as e:
467
+ msg = f" [FAIL] {args.version} #{idx:04d}: {e}"
468
+ print(msg)
469
+ continue
470
+
471
+ export_to_video(frames, ver_out, fps=24)
472
+
473
+ vid_name = os.path.splitext(os.path.basename(ver_out))[0]
474
+ prompt_dir = os.path.join(by_prompt_dir, vid_name)
475
+ os.makedirs(prompt_dir, exist_ok=True)
476
+ shutil.copy2(ver_out, os.path.join(prompt_dir, f"{args.version}.mp4"))
477
+
478
+ timing_records[idx] = (elapsed, slug)
479
+ print(make_timing_line(args.version, idx, elapsed, slug))
480
+
481
+ peak_mem = torch.cuda.max_memory_allocated() / 1024 ** 3
482
+ print(f" >> [{args.version}] peak GPU memory: {peak_mem:.2f} GB")
483
+
484
+ del pipe
485
+ torch.cuda.empty_cache()
486
+ torch.cuda.reset_peak_memory_stats()
487
+
488
+ sorted_records = [timing_records[idx] for idx in sorted(timing_records)]
489
+ all_timings = [elapsed for elapsed, _ in sorted_records]
490
+
491
+ with open(timing_file, "w", encoding="utf-8") as tf:
492
+ tf.write(f"{'=' * 80}\n")
493
+ tf.write(f" Helios Benchmark Inference Timing Report\n")
494
+ tf.write(f" {time.strftime('%Y-%m-%d %H:%M:%S')}\n")
495
+ tf.write(
496
+ f" Prompts: {len(prompts)} | Range: {args.prompt_start}:{args.prompt_end} "
497
+ f"| Version: {args.version}\n"
498
+ )
499
+ if args.prompt_indices_file:
500
+ tf.write(f" Prompt indices file: {args.prompt_indices_file}\n")
501
+ tf.write(
502
+ f" Resolution: {args.width}x{args.height} | Seed: {args.seed} | "
503
+ f"GPU: {args.gpu} | low_vram: {args.enable_low_vram_mode}\n"
504
+ )
505
+ tf.write(f"{'=' * 80}\n\n")
506
+
507
+ tf.write(
508
+ f"\n{'=' * 60}\n"
509
+ f" Version: {args.version} | Model: {preset['model_dir']}\n"
510
+ f" Frames: {preset['num_frames']} | guidance_scale: {preset['guidance_scale']}\n"
511
+ f" stage2: {preset['is_enable_stage2']} | pyramid_steps: {preset['pyramid_num_inference_steps_list']}\n"
512
+ f"{'=' * 60}\n"
513
+ )
514
+ tf.write(
515
+ f" Existing timing records: {len(timing_records)} / expected outputs: {len(expected_outputs)}\n"
516
+ )
517
+
518
+ for idx in sorted(timing_records):
519
+ elapsed, slug = timing_records[idx]
520
+ tf.write(make_timing_line(args.version, idx, elapsed, slug) + "\n")
521
+
522
+ if all_timings:
523
+ avg_t = sum(all_timings) / len(all_timings)
524
+ total_t = sum(all_timings)
525
+ summary = (
526
+ f"\n >> [{args.version}] completed {len(all_timings)} videos | "
527
+ f"avg: {avg_t:.2f}s ({avg_t / 60:.2f}min) | "
528
+ f"total: {total_t:.1f}s ({total_t / 60:.1f}min)\n"
529
+ )
530
+ else:
531
+ summary = f"\n >> [{args.version}] no timing records available\n"
532
+ print(summary)
533
+ tf.write(summary)
534
+
535
+ if peak_mem is not None:
536
+ mem_line = f" >> [{args.version}] peak GPU memory: {peak_mem:.2f} GB\n"
537
+ tf.write(mem_line)
538
+
539
+ sep = f"\n{'=' * 80}\n"
540
+ tf.write(sep)
541
+ tf.write(" FINAL SUMMARY\n")
542
+ tf.write(f"{'=' * 80}\n")
543
+ print(sep)
544
+ print(" FINAL SUMMARY")
545
+ print(f"{'=' * 80}")
546
+
547
+ fmt = " {ver:12s} | videos: {n:3d} | avg: {avg:8.2f}s ({avgm:5.2f}min) | min: {mn:8.2f}s | max: {mx:8.2f}s | total: {tot:8.1f}s ({totm:5.1f}min)"
548
+ if all_timings:
549
+ line = fmt.format(
550
+ ver=args.version, n=len(all_timings),
551
+ avg=sum(all_timings) / len(all_timings), avgm=sum(all_timings) / len(all_timings) / 60,
552
+ mn=min(all_timings), mx=max(all_timings),
553
+ tot=sum(all_timings), totm=sum(all_timings) / 60,
554
+ )
555
+ else:
556
+ line = f" {args.version:12s} | N/A (no timing records)"
557
+ print(line)
558
+ tf.write(line + "\n")
559
+
560
+ tf.write(f"{'=' * 80}\n")
561
+
562
+ print(f"{'=' * 80}")
563
+ print(f"\nTiming report: {timing_file}")
564
+ print(f"Videos: {by_prompt_dir}")
565
+ print(f" {by_version_dir}")
566
+
567
+
568
+ if __name__ == "__main__":
569
+ main()
Helios/_DEV/infer_helios.py ADDED
@@ -0,0 +1,673 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import importlib
2
+ import os
3
+
4
+
5
+ os.environ["HF_ENABLE_PARALLEL_LOADING"] = "yes"
6
+ os.environ["HF_PARALLEL_LOADING_WORKERS"] = "8"
7
+
8
+ import argparse
9
+ import time
10
+ from pathlib import Path
11
+
12
+ import pandas as pd
13
+ import torch
14
+ import torch.distributed as dist
15
+ from tqdm import tqdm
16
+
17
+
18
+ if importlib.util.find_spec("torch_npu") is not None:
19
+ import torch_npu
20
+ else:
21
+ torch_npu = None
22
+
23
+ from helios.diffusers_version.pipeline_helios_diffusers import HeliosPipeline
24
+ from helios.diffusers_version.scheduling_helios_diffusers import HeliosScheduler
25
+ from helios.diffusers_version.transformer_helios_diffusers import HeliosTransformer3DModel
26
+ from helios.modules.helios_kernels import (
27
+ replace_all_norms_with_flash_norms,
28
+ replace_rmsnorm_with_fp32,
29
+ replace_rope_with_flash_rope,
30
+ )
31
+ from helios.utils.utils_base import load_extra_components
32
+
33
+ from diffusers import ContextParallelConfig
34
+ from diffusers.models import AutoencoderKLWan
35
+ from diffusers.utils import export_to_video, load_image, load_video
36
+
37
+ PROJECT_ROOT = Path(__file__).resolve().parent
38
+ DEFAULT_BASE_MODEL_PATH = str(PROJECT_ROOT / "checkpoints" / "Helios-Base")
39
+
40
+
41
+ def parse_args():
42
+ parser = argparse.ArgumentParser(description="Generate video with model")
43
+
44
+ # === Model paths ===
45
+ parser.add_argument("--base_model_path", type=str, default=DEFAULT_BASE_MODEL_PATH)
46
+ parser.add_argument(
47
+ "--transformer_path",
48
+ type=str,
49
+ default=DEFAULT_BASE_MODEL_PATH,
50
+ )
51
+ parser.add_argument(
52
+ "--lora_path",
53
+ type=str,
54
+ default=None,
55
+ )
56
+ parser.add_argument(
57
+ "--partial_path",
58
+ type=str,
59
+ default=None,
60
+ )
61
+ parser.add_argument("--output_folder", type=str, default="./output_helios")
62
+ parser.add_argument("--enable_compile", action="store_true")
63
+
64
+ # === Generation parameters ===
65
+ # environment
66
+ parser.add_argument(
67
+ "--sample_type",
68
+ type=str,
69
+ default="t2v",
70
+ choices=["t2v", "i2v", "v2v"],
71
+ )
72
+ parser.add_argument(
73
+ "--weight_dtype",
74
+ type=str,
75
+ default="bf16",
76
+ choices=["bf16", "fp16", "fp32"],
77
+ help="Data type for model weights.",
78
+ )
79
+ parser.add_argument("--seed", type=int, default=42, help="Seed for random number generator.")
80
+ # base
81
+ parser.add_argument("--height", type=int, default=384)
82
+ parser.add_argument("--width", type=int, default=640)
83
+ parser.add_argument("--num_frames", type=int, default=99)
84
+ parser.add_argument("--fps", type=int, default=24)
85
+ parser.add_argument("--num_inference_steps", type=int, default=50)
86
+ parser.add_argument("--guidance_scale", type=float, default=5.0)
87
+ # cfg zero
88
+ parser.add_argument("--use_zero_init", action="store_true")
89
+ parser.add_argument("--zero_steps", type=int, default=1)
90
+ # stage 1
91
+ parser.add_argument("--num_latent_frames_per_chunk", type=int, default=9)
92
+ # stage 2
93
+ parser.add_argument("--is_enable_stage2", action="store_true")
94
+ parser.add_argument("--pyramid_num_inference_steps_list", type=int, nargs="+", default=[20, 20, 20])
95
+ # stage 3
96
+ parser.add_argument("--is_skip_first_chunk", action="store_true")
97
+ parser.add_argument("--is_amplify_first_chunk", action="store_true")
98
+ parser.add_argument(
99
+ "--visualize_relative_l1",
100
+ action="store_true",
101
+ help="Save per-chunk denoising relative L1 records and a timestep plot.",
102
+ )
103
+ parser.add_argument(
104
+ "--relative_l1_output_folder",
105
+ type=str,
106
+ default=None,
107
+ help="Deprecated. Relative L1 files are saved next to the mp4 in each prompt timestamp folder.",
108
+ )
109
+
110
+ # === Prompts ===
111
+ parser.add_argument("--use_interpolate_prompt", action="store_true")
112
+ parser.add_argument("--interpolation_steps", type=int, default=3)
113
+ parser.add_argument("--interpolate_time", type=int, default=7)
114
+ parser.add_argument(
115
+ "--image_path",
116
+ type=str,
117
+ default=None,
118
+ )
119
+ parser.add_argument(
120
+ "--image_noise_sigma_min", type=float, default=0.111, help="Balance motion amplitude and visual consistency"
121
+ )
122
+ parser.add_argument(
123
+ "--image_noise_sigma_max", type=float, default=0.135, help="Balance motion amplitude and visual consistency"
124
+ )
125
+ parser.add_argument(
126
+ "--video_path",
127
+ type=str,
128
+ default=None,
129
+ )
130
+ parser.add_argument(
131
+ "--video_noise_sigma_min", type=float, default=0.111, help="Balance motion amplitude and visual consistency"
132
+ )
133
+ parser.add_argument(
134
+ "--video_noise_sigma_max", type=float, default=0.135, help="Balance motion amplitude and visual consistency"
135
+ )
136
+ parser.add_argument(
137
+ "--prompt",
138
+ type=str,
139
+ default="A dynamic time-lapse video showing the rapidly moving scenery from the window of a speeding train. The camera captures various elements such as lush green fields, towering trees, quaint countryside houses, and distant mountain ranges passing by quickly. The train window frames the view, adding a sense of speed and motion as the landscape rushes past. The camera remains static but emphasizes the fast-paced movement outside. The overall atmosphere is serene yet exhilarating, capturing the essence of travel and exploration. Medium shot focusing on the train window and the rushing scenery beyond.",
140
+ )
141
+ parser.add_argument(
142
+ "--negative_prompt",
143
+ type=str,
144
+ default="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",
145
+ )
146
+ parser.add_argument(
147
+ "--prompt_txt_path",
148
+ type=str,
149
+ default=None,
150
+ )
151
+ parser.add_argument(
152
+ "--base_image_prompt_path",
153
+ type=str,
154
+ default=None,
155
+ )
156
+ parser.add_argument(
157
+ "--image_prompt_csv_path",
158
+ type=str,
159
+ default=None,
160
+ )
161
+ parser.add_argument(
162
+ "--interactive_prompt_csv_path",
163
+ type=str,
164
+ default=None,
165
+ )
166
+
167
+ # === Context parallelism ===
168
+ # Please refer to https://huggingface.co/docs/diffusers/main/en/training/distributed_inference#context-parallelism
169
+ parser.add_argument("--enable_parallelism", action="store_true")
170
+ parser.add_argument(
171
+ "--cp_backend",
172
+ type=str,
173
+ choices=["ring", "ulysses", "unified", "ulysses_anything"],
174
+ default="ulysses",
175
+ help="Context parallel backend to use.",
176
+ )
177
+
178
+ # === Group-Offloading ===
179
+ # Please refer to https://huggingface.co/docs/diffusers/main/en/optimization/memory#group-offloading
180
+ parser.add_argument("--enable_low_vram_mode", action="store_true")
181
+ parser.add_argument(
182
+ "--group_offloading_type",
183
+ type=str,
184
+ choices=["leaf_level", "block_level"],
185
+ default="leaf_level",
186
+ help="Specifies the granularity for group CPU offloading. Choose between 'leaf_level' (individual modules) or 'block_level' (entire blocks).",
187
+ )
188
+ parser.add_argument(
189
+ "--num_blocks_per_group",
190
+ type=str,
191
+ default="4",
192
+ help="The number of blocks to bundle together in each offloading group. Only relevant when using block-level offloading.",
193
+ )
194
+
195
+ return parser.parse_args()
196
+
197
+
198
+ def build_sample_output_dir(output_folder, prompt_or_prompts):
199
+ if isinstance(prompt_or_prompts, list):
200
+ prompt_text = prompt_or_prompts[0] if prompt_or_prompts else "prompt"
201
+ else:
202
+ prompt_text = prompt_or_prompts or "prompt"
203
+
204
+ prompt_text = str(prompt_text).strip()
205
+ safe_chars = []
206
+ previous_was_sep = False
207
+ for char in prompt_text:
208
+ if char.isalnum():
209
+ safe_chars.append(char)
210
+ previous_was_sep = False
211
+ elif not previous_was_sep:
212
+ safe_chars.append("_")
213
+ previous_was_sep = True
214
+
215
+ prompt_stem = "".join(safe_chars).strip("_")[:80] or "prompt"
216
+ sample_dir = Path(output_folder) / f"{prompt_stem}_{int(time.time())}"
217
+
218
+ suffix = 1
219
+ base_sample_dir = sample_dir
220
+ while sample_dir.exists():
221
+ sample_dir = Path(f"{base_sample_dir}_{suffix}")
222
+ suffix += 1
223
+
224
+ sample_dir.mkdir(parents=True, exist_ok=False)
225
+ return sample_dir
226
+
227
+
228
+ def save_relative_l1_outputs(records, output_folder):
229
+ if not records:
230
+ print(f"No relative L1 records for {output_folder}.")
231
+ return
232
+
233
+ metrics_dir = Path(output_folder)
234
+ metrics_dir.mkdir(parents=True, exist_ok=True)
235
+ df = pd.DataFrame(records).sort_values(["chunk_index", "step_index", "stage_index"])
236
+
237
+ csv_path = metrics_dir / "relative_l1.csv"
238
+ df.to_csv(csv_path, index=False)
239
+
240
+ try:
241
+ import matplotlib
242
+
243
+ matplotlib.use("Agg")
244
+ import matplotlib.pyplot as plt
245
+
246
+ def save_metric_plot(metric_name, ylabel, title, plot_name):
247
+ fig, ax = plt.subplots(figsize=(9, 5))
248
+ for chunk_index, chunk_df in df.groupby("chunk_index"):
249
+ chunk_df = chunk_df.sort_values(["step_index", "stage_index"])
250
+ ax.plot(
251
+ chunk_df["timestep"],
252
+ chunk_df[metric_name],
253
+ marker="o",
254
+ linewidth=1.5,
255
+ markersize=3,
256
+ label=f"chunk {chunk_index}",
257
+ )
258
+
259
+ ax.set_xlabel("timestep")
260
+ ax.set_ylabel(ylabel)
261
+ ax.set_title(title)
262
+ ax.grid(True, alpha=0.3)
263
+ ax.invert_xaxis()
264
+ ax.legend()
265
+ fig.tight_layout()
266
+
267
+ plot_path = metrics_dir / plot_name
268
+ fig.savefig(plot_path, dpi=200)
269
+ plt.close(fig)
270
+ return plot_path
271
+
272
+ plot_path = save_metric_plot(
273
+ "relative_l1",
274
+ "mean relative L1",
275
+ "Denoising relative L1 per chunk",
276
+ "relative_l1.png",
277
+ )
278
+ ratio_plot_path = None
279
+ if "relative_l1_ratio" in df.columns:
280
+ ratio_plot_path = save_metric_plot(
281
+ "relative_l1_ratio",
282
+ "mean(delta L1) / mean(latent L1)",
283
+ "Denoising relative L1 ratio per chunk",
284
+ "relative_l1_ratio.png",
285
+ )
286
+
287
+ if ratio_plot_path is None:
288
+ print(f"Saved relative L1 CSV to {csv_path} and plot to {plot_path}")
289
+ else:
290
+ print(f"Saved relative L1 CSV to {csv_path} and plots to {plot_path}, {ratio_plot_path}")
291
+ except Exception as exc:
292
+ print(f"Saved relative L1 CSV to {csv_path}, but failed to save plot: {exc}")
293
+
294
+
295
+ def main():
296
+ args = parse_args()
297
+
298
+ assert not (args.enable_low_vram_mode and args.enable_compile), (
299
+ "enable_low_vram_mode and enable_compile cannot be used together."
300
+ )
301
+
302
+ if args.weight_dtype == "fp32":
303
+ args.weight_dtype = torch.float32
304
+ elif args.weight_dtype == "fp16":
305
+ args.weight_dtype = torch.float16
306
+ else:
307
+ args.weight_dtype = torch.bfloat16
308
+
309
+ os.makedirs(args.output_folder, exist_ok=True)
310
+
311
+ if dist.is_available() and "RANK" in os.environ:
312
+ if args.cp_backend == "ulysses_anything":
313
+ dist.init_process_group(backend="cpu:gloo,cuda:nccl")
314
+ else:
315
+ dist.init_process_group(backend="nccl")
316
+ rank = dist.get_rank()
317
+ device = torch.device("cuda", rank % torch.cuda.device_count())
318
+ world_size = dist.get_world_size()
319
+ torch.cuda.set_device(device)
320
+ assert world_size == 1 or not args.enable_low_vram_mode, "enable_low_vram_mode is only for single GPU."
321
+ else:
322
+ rank = 0
323
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
324
+ world_size = 1
325
+
326
+ prompt = None
327
+ image_path = None
328
+ video_path = None
329
+ interpolate_time_list = None
330
+ if args.sample_type == "t2v" and args.prompt is None:
331
+ prompt = "An extreme close-up of an gray-haired man with a beard in his 60s, he is deep in thought pondering the history of the universe as he sits at a cafe in Paris, his eyes focus on people offscreen as they walk as he sits mostly motionless, he is dressed in a wool coat suit coat with a button-down shirt , he wears a brown beret and glasses and has a very professorial appearance, and the end he offers a subtle closed-mouth smile as if he found the answer to the mystery of life, the lighting is very cinematic with the golden light and the Parisian streets and city in the background, depth of field, cinematic 35mm film."
332
+ elif args.sample_type == "i2v" and (args.image_path is None and args.prompt is None):
333
+ image_path = (
334
+ "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/astronaut.jpg"
335
+ )
336
+ prompt = "An astronaut hatching from an egg, on the surface of the moon, the darkness and depth of space realised in the background. High quality, ultrarealistic detail and breath-taking movie-like camera shot."
337
+ elif args.sample_type == "v2v" and (args.video_path is None and args.prompt is None):
338
+ video_path = (
339
+ "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/hiker.mp4"
340
+ )
341
+ prompt = "A robot standing on a mountain top. The sun is setting in the background."
342
+ else:
343
+ image_path = args.image_path
344
+ video_path = args.video_path
345
+ prompt = args.prompt
346
+
347
+ transformer = HeliosTransformer3DModel.from_pretrained(
348
+ args.transformer_path,
349
+ subfolder="transformer",
350
+ torch_dtype=args.weight_dtype,
351
+ )
352
+ if not args.enable_compile:
353
+ transformer = replace_rmsnorm_with_fp32(transformer)
354
+ transformer = replace_all_norms_with_flash_norms(transformer)
355
+ replace_rope_with_flash_rope()
356
+ cuda_major = torch.cuda.get_device_capability()[0]
357
+ if cuda_major >= 9:
358
+ # H100/H800 (SM90+) with FA3
359
+ try:
360
+ transformer.set_attention_backend("_flash_3_hub")
361
+ except Exception:
362
+ transformer.set_attention_backend("flash_hub")
363
+ else:
364
+ # 4090/A100 etc (SM89+) with FA2
365
+ transformer.set_attention_backend("flash_hub")
366
+
367
+ vae = AutoencoderKLWan.from_pretrained(
368
+ args.base_model_path,
369
+ subfolder="vae",
370
+ torch_dtype=torch.float32,
371
+ )
372
+ scheduler = HeliosScheduler.from_pretrained(
373
+ args.base_model_path,
374
+ subfolder="scheduler",
375
+ )
376
+ pipe = HeliosPipeline.from_pretrained(
377
+ args.base_model_path,
378
+ transformer=transformer,
379
+ vae=vae,
380
+ scheduler=scheduler,
381
+ torch_dtype=args.weight_dtype,
382
+ )
383
+
384
+ if args.lora_path is not None:
385
+ pipe.load_lora_weights(args.lora_path, adapter_name="default")
386
+ pipe.set_adapters(["default"], adapter_weights=[1.0])
387
+
388
+ if args.partial_path is not None:
389
+ if not hasattr(args, "training_config"):
390
+ from argparse import Namespace
391
+
392
+ args.training_config = Namespace()
393
+ args.training_config.is_enable_stage1 = True
394
+ args.training_config.restrict_self_attn = True
395
+ args.training_config.is_amplify_history = True
396
+ args.training_config.is_use_gan = True
397
+ load_extra_components(args, transformer, args.partial_path)
398
+
399
+ if args.enable_compile:
400
+ torch.backends.cudnn.benchmark = True
401
+ pipe.text_encoder.compile(mode="max-autotune-no-cudagraphs", dynamic=False)
402
+ pipe.vae.compile(mode="max-autotune-no-cudagraphs", dynamic=False)
403
+ pipe.transformer.compile(mode="max-autotune-no-cudagraphs", dynamic=False)
404
+
405
+ if args.enable_low_vram_mode:
406
+ pipe.enable_group_offload(
407
+ onload_device=torch.device("cuda"),
408
+ offload_device=torch.device("cpu"),
409
+ offload_type=args.group_offloading_type,
410
+ num_blocks_per_group=args.num_blocks_per_group if args.group_offloading_type == "block_level" else None,
411
+ use_stream=True,
412
+ record_stream=True,
413
+ )
414
+ else:
415
+ pipe = pipe.to(device)
416
+
417
+ if world_size > 1 and args.enable_parallelism:
418
+ if args.cp_backend == "ring":
419
+ cp_config = ContextParallelConfig(ring_degree=world_size)
420
+ elif args.cp_backend == "unified":
421
+ cp_config = ContextParallelConfig(ring_degree=world_size // 2, ulysses_degree=world_size // 2)
422
+ elif args.cp_backend == "ulysses":
423
+ cp_config = ContextParallelConfig(ulysses_degree=world_size)
424
+ elif args.cp_backend == "ulysses_anything":
425
+ cp_config = ContextParallelConfig(ulysses_degree=world_size, ulysses_anything=True)
426
+ else:
427
+ raise ValueError(f"Unsupported cp_backend: {args.cp_backend}")
428
+
429
+ pipe.transformer.enable_parallelism(config=cp_config)
430
+
431
+ if args.prompt_txt_path is not None:
432
+ with open(args.prompt_txt_path, "r") as f:
433
+ prompt_list = [line.strip() for line in f.readlines() if line.strip()]
434
+ if not args.enable_parallelism:
435
+ prompt_list_with_idx = [(i, prompt) for i, prompt in enumerate(prompt_list)]
436
+ prompt_list_with_idx = prompt_list_with_idx[rank::world_size]
437
+ else:
438
+ prompt_list_with_idx = [(i, prompt) for i, prompt in enumerate(prompt_list)]
439
+
440
+ for idx, prompt in tqdm(prompt_list_with_idx, desc="Processing prompts"):
441
+ with torch.no_grad():
442
+ try:
443
+ pipe_output = pipe(
444
+ prompt=prompt,
445
+ negative_prompt=args.negative_prompt,
446
+ height=args.height,
447
+ width=args.width,
448
+ num_frames=args.num_frames,
449
+ num_inference_steps=args.num_inference_steps,
450
+ guidance_scale=args.guidance_scale,
451
+ generator=torch.Generator(device="cuda").manual_seed(args.seed),
452
+ # stage 1
453
+ history_sizes=[16, 2, 1],
454
+ num_latent_frames_per_chunk=args.num_latent_frames_per_chunk,
455
+ keep_first_frame=True,
456
+ # stage 2
457
+ is_enable_stage2=args.is_enable_stage2,
458
+ pyramid_num_inference_steps_list=args.pyramid_num_inference_steps_list,
459
+ # stage 3
460
+ is_skip_first_chunk=args.is_skip_first_chunk,
461
+ is_amplify_first_chunk=args.is_amplify_first_chunk,
462
+ # cfg zero
463
+ use_zero_init=args.use_zero_init,
464
+ zero_steps=args.zero_steps,
465
+ # i2v
466
+ image=load_image(image_path).resize((args.width, args.height))
467
+ if image_path is not None
468
+ else None,
469
+ image_noise_sigma_min=args.image_noise_sigma_min,
470
+ image_noise_sigma_max=args.image_noise_sigma_max,
471
+ # v2v
472
+ video=load_video(video_path) if video_path is not None else None,
473
+ video_noise_sigma_min=args.video_noise_sigma_min,
474
+ video_noise_sigma_max=args.video_noise_sigma_max,
475
+ # interpolate_prompt
476
+ use_interpolate_prompt=args.use_interpolate_prompt,
477
+ interpolation_steps=args.interpolation_steps,
478
+ interpolate_time_list=interpolate_time_list,
479
+ output_relative_l1=args.visualize_relative_l1,
480
+ )
481
+ output = pipe_output.frames[0]
482
+ except Exception:
483
+ continue
484
+ if not args.enable_parallelism or rank == 0:
485
+ sample_dir = build_sample_output_dir(args.output_folder, prompt)
486
+ output_path = sample_dir / "video.mp4"
487
+ export_to_video(output, str(output_path), fps=24)
488
+ if args.visualize_relative_l1:
489
+ save_relative_l1_outputs(pipe_output.relative_l1, sample_dir)
490
+ elif args.image_prompt_csv_path is not None:
491
+ df = pd.read_csv(args.image_prompt_csv_path)
492
+ if not args.enable_parallelism:
493
+ df = df.iloc[rank::world_size]
494
+
495
+ for idx, row in tqdm(df.iterrows(), total=len(df), desc="Processing prompts"):
496
+ prompt = row.get("refined_prompt") or row["prompt"]
497
+ image_path = os.path.join(args.base_image_prompt_path, row["image_name"])
498
+
499
+ with torch.no_grad():
500
+ try:
501
+ pipe_output = pipe(
502
+ prompt=prompt,
503
+ negative_prompt=args.negative_prompt,
504
+ height=args.height,
505
+ width=args.width,
506
+ num_frames=args.num_frames,
507
+ num_inference_steps=args.num_inference_steps,
508
+ guidance_scale=args.guidance_scale,
509
+ generator=torch.Generator(device="cuda").manual_seed(args.seed),
510
+ # stage 1
511
+ history_sizes=[16, 2, 1],
512
+ num_latent_frames_per_chunk=args.num_latent_frames_per_chunk,
513
+ keep_first_frame=True,
514
+ # stage 2
515
+ is_enable_stage2=args.is_enable_stage2,
516
+ pyramid_num_inference_steps_list=args.pyramid_num_inference_steps_list,
517
+ # stage 3
518
+ is_skip_first_chunk=args.is_skip_first_chunk,
519
+ is_amplify_first_chunk=args.is_amplify_first_chunk,
520
+ # cfg zero
521
+ use_zero_init=args.use_zero_init,
522
+ zero_steps=args.zero_steps,
523
+ # i2v
524
+ image=load_image(image_path).resize((args.width, args.height))
525
+ if image_path is not None
526
+ else None,
527
+ image_noise_sigma_min=args.image_noise_sigma_min,
528
+ image_noise_sigma_max=args.image_noise_sigma_max,
529
+ # v2v
530
+ video=load_video(video_path) if video_path is not None else None,
531
+ video_noise_sigma_min=args.video_noise_sigma_min,
532
+ video_noise_sigma_max=args.video_noise_sigma_max,
533
+ # interpolate_prompt
534
+ use_interpolate_prompt=args.use_interpolate_prompt,
535
+ interpolation_steps=args.interpolation_steps,
536
+ interpolate_time_list=interpolate_time_list,
537
+ output_relative_l1=args.visualize_relative_l1,
538
+ )
539
+ output = pipe_output.frames[0]
540
+ except Exception:
541
+ continue
542
+ if not args.enable_parallelism or rank == 0:
543
+ sample_dir = build_sample_output_dir(args.output_folder, prompt)
544
+ output_path = sample_dir / "video.mp4"
545
+ export_to_video(output, str(output_path), fps=24)
546
+ if args.visualize_relative_l1:
547
+ save_relative_l1_outputs(pipe_output.relative_l1, sample_dir)
548
+ elif args.interactive_prompt_csv_path is not None:
549
+ df = pd.read_csv(args.interactive_prompt_csv_path)
550
+
551
+ df = df.sort_values(by=["id", "prompt_index"])
552
+ all_video_ids = df["id"].unique()
553
+
554
+ if not args.enable_parallelism:
555
+ my_video_ids = all_video_ids[rank::world_size]
556
+ else:
557
+ my_video_ids = all_video_ids
558
+
559
+ for video_id in tqdm(my_video_ids, desc="Processing prompts"):
560
+ group_df = df[df["id"] == video_id]
561
+
562
+ if "refined_prompt" in df.columns:
563
+ prompt_list = group_df["refined_prompt"].fillna(group_df["prompt"]).tolist()
564
+ else:
565
+ prompt_list = group_df["prompt"].tolist()
566
+ interpolate_time_list = [args.interpolate_time] * len(prompt_list)
567
+
568
+ with torch.no_grad():
569
+ try:
570
+ pipe_output = pipe(
571
+ prompt=prompt_list,
572
+ negative_prompt=args.negative_prompt,
573
+ height=args.height,
574
+ width=args.width,
575
+ num_frames=args.num_frames,
576
+ num_inference_steps=args.num_inference_steps,
577
+ guidance_scale=args.guidance_scale,
578
+ generator=torch.Generator(device="cuda").manual_seed(args.seed),
579
+ # stage 1
580
+ history_sizes=[16, 2, 1],
581
+ num_latent_frames_per_chunk=args.num_latent_frames_per_chunk,
582
+ keep_first_frame=True,
583
+ # stage 2
584
+ is_enable_stage2=args.is_enable_stage2,
585
+ pyramid_num_inference_steps_list=args.pyramid_num_inference_steps_list,
586
+ # stage 3
587
+ is_skip_first_chunk=args.is_skip_first_chunk,
588
+ is_amplify_first_chunk=args.is_amplify_first_chunk,
589
+ # cfg zero
590
+ use_zero_init=args.use_zero_init,
591
+ zero_steps=args.zero_steps,
592
+ # i2v
593
+ image=load_image(image_path).resize((args.width, args.height))
594
+ if image_path is not None
595
+ else None,
596
+ image_noise_sigma_min=args.image_noise_sigma_min,
597
+ image_noise_sigma_max=args.image_noise_sigma_max,
598
+ # v2v
599
+ video=load_video(video_path) if video_path is not None else None,
600
+ video_noise_sigma_min=args.video_noise_sigma_min,
601
+ video_noise_sigma_max=args.video_noise_sigma_max,
602
+ # interpolate_prompt
603
+ use_interpolate_prompt=args.use_interpolate_prompt,
604
+ interpolation_steps=args.interpolation_steps,
605
+ interpolate_time_list=interpolate_time_list,
606
+ output_relative_l1=args.visualize_relative_l1,
607
+ )
608
+ output = pipe_output.frames[0]
609
+ except Exception:
610
+ continue
611
+ if not args.enable_parallelism or rank == 0:
612
+ sample_dir = build_sample_output_dir(args.output_folder, prompt_list)
613
+ output_path = sample_dir / "video.mp4"
614
+ export_to_video(output, str(output_path), fps=24)
615
+ if args.visualize_relative_l1:
616
+ save_relative_l1_outputs(pipe_output.relative_l1, sample_dir)
617
+ else:
618
+ with torch.no_grad():
619
+ # import time
620
+ # for _ in range(20):
621
+ # start_time = time.time()
622
+ pipe_output = pipe(
623
+ prompt=prompt,
624
+ negative_prompt=args.negative_prompt,
625
+ height=args.height,
626
+ width=args.width,
627
+ num_frames=args.num_frames,
628
+ num_inference_steps=args.num_inference_steps,
629
+ guidance_scale=args.guidance_scale,
630
+ generator=torch.Generator(device="cuda").manual_seed(args.seed),
631
+ # stage 1
632
+ history_sizes=[16, 2, 1],
633
+ num_latent_frames_per_chunk=args.num_latent_frames_per_chunk,
634
+ keep_first_frame=True,
635
+ # stage 2
636
+ is_enable_stage2=args.is_enable_stage2,
637
+ pyramid_num_inference_steps_list=args.pyramid_num_inference_steps_list,
638
+ # stage 3
639
+ is_skip_first_chunk=args.is_skip_first_chunk,
640
+ is_amplify_first_chunk=args.is_amplify_first_chunk,
641
+ # cfg zero
642
+ use_zero_init=args.use_zero_init,
643
+ zero_steps=args.zero_steps,
644
+ # i2v
645
+ image=load_image(image_path).resize((args.width, args.height)) if image_path is not None else None,
646
+ image_noise_sigma_min=args.image_noise_sigma_min,
647
+ image_noise_sigma_max=args.image_noise_sigma_max,
648
+ # v2v
649
+ video=load_video(video_path) if video_path is not None else None,
650
+ video_noise_sigma_min=args.video_noise_sigma_min,
651
+ video_noise_sigma_max=args.video_noise_sigma_max,
652
+ # interpolate_prompt
653
+ use_interpolate_prompt=args.use_interpolate_prompt,
654
+ interpolation_steps=args.interpolation_steps,
655
+ interpolate_time_list=interpolate_time_list,
656
+ output_relative_l1=args.visualize_relative_l1,
657
+ )
658
+ output = pipe_output.frames[0]
659
+ # elapsed_time = time.time() - start_time
660
+ # print(f"Inference time: {elapsed_time:.2f} seconds ({elapsed_time/60:.2f} minutes)")
661
+
662
+ if not args.enable_parallelism or rank == 0:
663
+ sample_dir = build_sample_output_dir(args.output_folder, prompt)
664
+ output_path = sample_dir / "video.mp4"
665
+ export_to_video(output, str(output_path), fps=24)
666
+ if args.visualize_relative_l1:
667
+ save_relative_l1_outputs(pipe_output.relative_l1, sample_dir)
668
+
669
+ print(f"Max memory: {torch.cuda.max_memory_allocated() / 1024**3:.3f} GB")
670
+
671
+
672
+ if __name__ == "__main__":
673
+ main()
Helios/_DEV/install.sh ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ pip install -r requirements.txt
2
+
3
+ rm -rf ~/.triton/cache/
4
+ rm -rf /tmp/torchinductor_*
5
+
6
+ pip uninstall triton torchao xformers wandb tensorflow tensorflow-cpu -y
7
+ pip install wandb==0.23.0 triton==3.6.0
8
+
9
+ rm -rf ~/.triton/cache/
10
+ rm -rf /tmp/torchinductor_*
Helios/_DEV/requirements.txt ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ torch==2.10.0
2
+ torchvision==0.25.0
3
+ torchaudio==2.10.0
4
+ triton==3.6.0
5
+ kernels==0.13.0
6
+ # diffusers==0.36.0
7
+ # transformers==4.57.6
8
+ git+https://github.com/huggingface/diffusers.git
9
+ transformers==5.3.0
10
+ sentence-transformers==5.2.3
11
+ accelerate==1.12.0
12
+ deepspeed==0.18.4
13
+ peft==0.18.1
14
+ huggingface-hub==1.4.1
15
+ zstandard==0.25.0
16
+ wandb==0.23.0
17
+ video-reader-rs==0.4.1
18
+ numpy<2.0.0
19
+ opencv-python
20
+ gradio
21
+ spaces
22
+ moviepy
23
+ imageio-ffmpeg
24
+ ftfy
25
+ Jinja2
26
+ einops
27
+ nvitop
28
+ packaging
29
+ ninja
30
+ omegaconf
31
+ mpi4py
32
+ hf-doc-builder
33
+ torchdata
34
+ loguru
35
+ tf_keras
Helios/_DEV/requirements_npu.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ # Please refer to here for installation the latest version: https://github.com/Ascend/pytorch?tab=readme-ov-file#ascend-auxiliary-software
2
+ torch==2.9.0
3
+ torchvision==0.24.0
4
+ torchaudio==2.9.0
5
+ torch_npu==2.9.0
6
+ triton==3.5.1
Helios/_DEV/run_bench.sh ADDED
@@ -0,0 +1,275 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # =============================================================================
3
+ # Helios Benchmark Inference Runner
4
+ # 用法: bash run_bench.sh [--gpus 5 6 7] [--prompt_range 0-50] [--num_frames 240]
5
+ # [--version base] [--version mid distilled]
6
+ # 默认使用所有可见 GPU;默认跑全部版本(base/mid/distilled),也可手动指定版本
7
+ # 同一时刻只跑一个版本;若有多张卡,会先扫描输出目录,只把缺失 case 均分到多张卡并行
8
+ # 低显存: LOW_VRAM=1 bash run_bench.sh
9
+ # =============================================================================
10
+ set -euo pipefail
11
+
12
+ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
13
+ if [[ -n "${PYTHON:-}" ]]; then
14
+ PYTHON_BIN="${PYTHON}"
15
+ elif command -v python3 >/dev/null 2>&1; then
16
+ PYTHON_BIN="$(command -v python3)"
17
+ elif command -v python >/dev/null 2>&1; then
18
+ PYTHON_BIN="$(command -v python)"
19
+ else
20
+ echo "Python interpreter not found. Set PYTHON=/path/to/python." >&2
21
+ exit 1
22
+ fi
23
+
24
+ GPUS=()
25
+ PROMPT_START="${PROMPT_START:-0}"
26
+ PROMPT_END="${PROMPT_END:-100}"
27
+ NUM_FRAMES="${NUM_FRAMES:-}"
28
+ VERSIONS=(base mid distilled)
29
+ OUTPUT_ROOT="${OUTPUT_ROOT:-}"
30
+ PROMPT_FILE="${PROMPT_FILE:-${SCRIPT_DIR}/demo_data/MovieGenVideoBench_extended.txt}"
31
+ LOW_VRAM="${LOW_VRAM:-0}"
32
+
33
+ discover_gpus() {
34
+ if ! command -v nvidia-smi >/dev/null 2>&1; then
35
+ echo "nvidia-smi not found; use --gpus to specify GPU ids explicitly." >&2
36
+ exit 1
37
+ fi
38
+
39
+ mapfile -t GPUS < <(nvidia-smi --query-gpu=index --format=csv,noheader,nounits)
40
+ if [[ ${#GPUS[@]} -eq 0 ]]; then
41
+ echo "No GPUs found." >&2
42
+ exit 1
43
+ fi
44
+ }
45
+
46
+ while [[ $# -gt 0 ]]; do
47
+ case "$1" in
48
+ --gpus) shift; GPUS=(); while [[ $# -gt 0 && ! "$1" =~ ^-- ]]; do GPUS+=("$1"); shift; done ;;
49
+ --prompt_range)
50
+ if [[ ! "$2" =~ ^([0-9]+)-([0-9]+)$ ]]; then
51
+ echo "Invalid --prompt_range: $2 (expected START-END, e.g. 0-50)" >&2
52
+ exit 1
53
+ fi
54
+ PROMPT_START="${BASH_REMATCH[1]}"
55
+ PROMPT_END="${BASH_REMATCH[2]}"
56
+ shift 2
57
+ ;;
58
+ --prompt_start) PROMPT_START="$2"; shift 2 ;;
59
+ --prompt_end) PROMPT_END="$2"; shift 2 ;;
60
+ --num_frames) NUM_FRAMES="$2"; shift 2 ;;
61
+ --version) shift; VERSIONS=(); while [[ $# -gt 0 && ! "$1" =~ ^-- ]]; do VERSIONS+=("$1"); shift; done ;;
62
+ --output_root) OUTPUT_ROOT="$2"; shift 2 ;;
63
+ --prompt_file) PROMPT_FILE="$2"; shift 2 ;;
64
+ *) echo "Unknown option: $1"; exit 1 ;;
65
+ esac
66
+ done
67
+
68
+ if [[ ${#GPUS[@]} -eq 0 ]]; then
69
+ discover_gpus
70
+ fi
71
+
72
+ if [[ ${#VERSIONS[@]} -eq 0 ]]; then
73
+ echo "No versions specified. Use --version base [mid distilled]." >&2
74
+ exit 1
75
+ fi
76
+
77
+ if [[ ! "${PROMPT_START}" =~ ^[0-9]+$ ]] || [[ ! "${PROMPT_END}" =~ ^[0-9]+$ ]]; then
78
+ echo "prompt_start and prompt_end must be non-negative integers." >&2
79
+ exit 1
80
+ fi
81
+
82
+ if (( PROMPT_END <= PROMPT_START )); then
83
+ echo "prompt_end must be greater than prompt_start." >&2
84
+ exit 1
85
+ fi
86
+
87
+ if [[ -z "${OUTPUT_ROOT}" ]]; then
88
+ if [[ -n "${NUM_FRAMES}" ]]; then
89
+ OUTPUT_ROOT="${SCRIPT_DIR}/outputs/num_frames_${NUM_FRAMES}"
90
+ else
91
+ OUTPUT_ROOT="${SCRIPT_DIR}/outputs/num_frames_default"
92
+ fi
93
+ fi
94
+
95
+ echo "============================================================"
96
+ echo " Helios Benchmark Inference"
97
+ echo " $(date '+%Y-%m-%d %H:%M:%S')"
98
+ echo " Python: ${PYTHON_BIN}"
99
+ echo " GPUs: ${GPUS[*]} | Prompt range: ${PROMPT_START}-${PROMPT_END} | Versions: ${VERSIONS[*]}"
100
+ [[ -n "${NUM_FRAMES}" ]] && echo " Frames: ${NUM_FRAMES}"
101
+ echo " Prompt file: ${PROMPT_FILE}"
102
+ echo " Output: ${OUTPUT_ROOT}"
103
+ echo "============================================================"
104
+
105
+ mkdir -p "${OUTPUT_ROOT}"
106
+
107
+ if [[ ! -f "${PROMPT_FILE}" ]]; then
108
+ echo "Prompt file not found: ${PROMPT_FILE}" >&2
109
+ exit 1
110
+ fi
111
+
112
+ TOTAL_PROMPTS=$(awk 'NF {count++} END {print count + 0}' "${PROMPT_FILE}")
113
+ if (( PROMPT_START >= TOTAL_PROMPTS )); then
114
+ echo "prompt_start (${PROMPT_START}) is out of range; prompt file has ${TOTAL_PROMPTS} non-empty prompts." >&2
115
+ exit 1
116
+ fi
117
+
118
+ if (( PROMPT_END > TOTAL_PROMPTS )); then
119
+ echo "prompt_end (${PROMPT_END}) exceeds total prompts (${TOTAL_PROMPTS}); clamping to ${TOTAL_PROMPTS}."
120
+ PROMPT_END="${TOTAL_PROMPTS}"
121
+ fi
122
+
123
+ EXTRA=()
124
+ if [[ "${LOW_VRAM}" == "1" ]]; then
125
+ EXTRA+=(--enable_low_vram_mode)
126
+ fi
127
+ if [[ -n "${NUM_FRAMES}" ]]; then
128
+ EXTRA+=(--num_frames "${NUM_FRAMES}")
129
+ fi
130
+
131
+ EXIT_CODE=0
132
+ WORKER_PIDS=()
133
+ WORKER_GPUS=()
134
+ WORKER_SHARDS=()
135
+
136
+ prepare_missing_shards() {
137
+ local version="$1"
138
+ local shard_dir="${OUTPUT_ROOT}/shards/${version}_${PROMPT_START}_${PROMPT_END}_$$"
139
+ mkdir -p "${shard_dir}"
140
+
141
+ "${PYTHON_BIN}" - \
142
+ "${PROMPT_FILE}" \
143
+ "${OUTPUT_ROOT}" \
144
+ "${version}" \
145
+ "${PROMPT_START}" \
146
+ "${PROMPT_END}" \
147
+ "${#GPUS[@]}" \
148
+ "${shard_dir}" <<'PY'
149
+ import os
150
+ import re
151
+ import sys
152
+ from pathlib import Path
153
+
154
+ prompt_file = Path(sys.argv[1])
155
+ output_root = Path(sys.argv[2])
156
+ version = sys.argv[3]
157
+ prompt_start = int(sys.argv[4])
158
+ prompt_end = int(sys.argv[5])
159
+ gpu_count = int(sys.argv[6])
160
+ shard_dir = Path(sys.argv[7])
161
+
162
+ with prompt_file.open("r", encoding="utf-8") as f:
163
+ prompts = [line.strip() for line in f if line.strip()]
164
+
165
+ def sanitize_filename(text, max_len=80):
166
+ text = text.strip().lower()
167
+ text = re.sub(r"[^a-z0-9]+", "_", text)
168
+ text = text.strip("_")
169
+ return text[:max_len]
170
+
171
+ missing = []
172
+ existing = 0
173
+ version_dir = output_root / "by_version" / version
174
+ for idx in range(prompt_start, prompt_end):
175
+ slug = sanitize_filename(prompts[idx])
176
+ video_path = version_dir / f"{idx:04d}_{slug}.mp4"
177
+ if video_path.is_file() and video_path.stat().st_size > 0:
178
+ existing += 1
179
+ else:
180
+ missing.append(idx)
181
+
182
+ print(
183
+ f"[scan] version={version} range={prompt_start}-{prompt_end} "
184
+ f"existing={existing} missing={len(missing)} output={version_dir}",
185
+ file=sys.stderr,
186
+ )
187
+
188
+ if not missing:
189
+ sys.exit(0)
190
+
191
+ active_workers = min(gpu_count, len(missing))
192
+ base_chunk = len(missing) // active_workers
193
+ remainder = len(missing) % active_workers
194
+ offset = 0
195
+
196
+ for shard_idx in range(active_workers):
197
+ shard_size = base_chunk + (1 if shard_idx < remainder else 0)
198
+ shard_indices = missing[offset:offset + shard_size]
199
+ offset += shard_size
200
+ shard_path = shard_dir / f"shard_{shard_idx:02d}.txt"
201
+ shard_path.write_text(
202
+ "".join(f"{idx}\n" for idx in shard_indices),
203
+ encoding="utf-8",
204
+ )
205
+ print(shard_path)
206
+ print(
207
+ f"[shard] version={version} shard={shard_idx} count={len(shard_indices)} "
208
+ f"indices={shard_indices[0]}-{shard_indices[-1]} file={shard_path}",
209
+ file=sys.stderr,
210
+ )
211
+ PY
212
+ }
213
+
214
+ launch_job() {
215
+ local version="$1"
216
+ local gpu="$2"
217
+ local shard_file="$3"
218
+ local shard_id
219
+ shard_id="$(basename "${shard_file}" .txt)"
220
+ local timing_file="${OUTPUT_ROOT}/timing_${version}_${shard_id}.txt"
221
+
222
+ echo "[launch] version=${version} gpu=${gpu} shard=${shard_id} indices=${shard_file} output=${OUTPUT_ROOT}"
223
+ "${PYTHON_BIN}" "${SCRIPT_DIR}/bench_infer.py" \
224
+ --prompt_file "${PROMPT_FILE}" \
225
+ --prompt_start "${PROMPT_START}" \
226
+ --prompt_end "${PROMPT_END}" \
227
+ --prompt_indices_file "${shard_file}" \
228
+ --output_root "${OUTPUT_ROOT}" \
229
+ --timing_file "${timing_file}" \
230
+ --version "${version}" \
231
+ --gpu "${gpu}" \
232
+ "${EXTRA[@]}" &
233
+
234
+ WORKER_PIDS+=("$!")
235
+ WORKER_GPUS+=("${gpu}")
236
+ WORKER_SHARDS+=("${shard_id}")
237
+ }
238
+
239
+ wait_for_current_version() {
240
+ local version="$1"
241
+ for idx in "${!WORKER_PIDS[@]}"; do
242
+ local pid="${WORKER_PIDS[$idx]}"
243
+ local gpu="${WORKER_GPUS[$idx]}"
244
+ local shard_id="${WORKER_SHARDS[$idx]}"
245
+ if wait "${pid}"; then
246
+ echo "[done] ${version} finished on gpu=${gpu} shard=${shard_id}"
247
+ else
248
+ echo "[fail] ${version} failed on gpu=${gpu} shard=${shard_id}"
249
+ EXIT_CODE=1
250
+ fi
251
+ done
252
+ WORKER_PIDS=()
253
+ WORKER_GPUS=()
254
+ WORKER_SHARDS=()
255
+ }
256
+
257
+ for version in "${VERSIONS[@]}"; do
258
+ echo ""
259
+ echo "-------------------- version=${version} --------------------"
260
+ mapfile -t SHARD_FILES < <(prepare_missing_shards "${version}")
261
+ if (( ${#SHARD_FILES[@]} == 0 )); then
262
+ echo "[skip] version=${version} has no missing cases in ${PROMPT_START}-${PROMPT_END}"
263
+ continue
264
+ fi
265
+
266
+ for worker_idx in "${!SHARD_FILES[@]}"; do
267
+ launch_job "${version}" "${GPUS[$worker_idx]}" "${SHARD_FILES[$worker_idx]}"
268
+ done
269
+ wait_for_current_version "${version}"
270
+ done
271
+
272
+ echo ""
273
+ echo "Done. Per-shard timing reports are under ${OUTPUT_ROOT}/timing_<version>_shard_<id>.txt"
274
+
275
+ exit ${EXIT_CODE:-0}
Helios/_DEV/train_helios.py ADDED
The diff for this file is too large to render. See raw diff
 
Helios/_DEV2/.codex ADDED
File without changes
Helios/_DEV2/.gitignore ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.py[cod]
2
+ *.gif
3
+ *.bmp
4
+ *.mov
5
+ *.mkv
6
+ *.log
7
+ *.zip
8
+ *.pt
9
+ *.pth
10
+ *.ckpt
11
+ *.safetensors
12
+ *.backup
13
+ *.pt
14
+ *.pth
15
+ *.ckpt
16
+ *.pkl
17
+ *.html
18
+ *.pdf
19
+ *.whl
20
+ *.txt.gz
21
+ !.gitignore
22
+ !requirements.txt
23
+ .DS_Store
24
+ *DS_Store
25
+ poetry.lock
26
+ __pycache__/
27
+ *.cache*
28
+ *temp_path*
29
+ *_ckpt
30
+ *_results
31
+ *temp
32
+ *.pem
33
+ *profile
34
+ .gradio
35
+ ablation_*
36
+ cache
37
+ wandb
38
+ output_helios
39
+ AMT-S.yaml
40
+ bpe_simple_vocab_16e6.txt
41
+ Videoreward
42
+ 1_formal_ckpts
43
+ demo_data
Helios/_DEV2/LICENSE.txt ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
Helios/_DEV2/README.md ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Short History Attention Debug
2
+
3
+ 本次修改实现了一个默认关闭的 debug hook,用来分析 current token 到 short history 上一帧 token 的对应关系。
4
+
5
+ ## 背景结论
6
+
7
+ 默认设置下:
8
+
9
+ - current chunk 是 33 个视频帧,对应 9 个 latent frames。
10
+ - 默认视频分辨率是 384x640。
11
+ - VAE latent 分辨率是 48x80。
12
+ - transformer patch 是 `(1, 2, 2)`,所以 current token grid 是 `9 x 24 x 40`。
13
+ - short history 经过 `patch_short` 后是 `2 x 24 x 40`。
14
+ - 本次只在 short history 的上一帧里找对应 token,也就是每个 current latent frame 的 `24 x 40` tokens 对应 previous short frame 的 `24 x 40` tokens。
15
+
16
+ ## 已实现内容
17
+
18
+ 新增 `short_attn_debug` pipeline 参数。开启后,attention hook 会在指定 block、chunk、denoise step、current frame 上导出 current token 到 previous short token 的 top-k 匹配。
19
+
20
+ 实现位置:
21
+
22
+ - `helios/diffusers_version/transformer_helios_diffusers.py`
23
+ - `helios/diffusers_version/pipeline_helios_diffusers.py`
24
+ - `helios/modules/transformer_helios.py`
25
+ - `helios/pipelines/pipeline_helios.py`
26
+ - `tools/visualize_short_attention_matches.py`
27
+
28
+ 导出的 artifact 默认包含:
29
+
30
+ - `match_yx`: 每个 current token 匹配到的 previous short token 坐标
31
+ - `query_yx`: current token 自身坐标
32
+ - `displacement_yx`: token 位移
33
+ - `topk_indices`: top-k 匹配 index
34
+ - `topk_scores`: top-k raw attention scores
35
+ - `top1_score`
36
+ - `top2_score`
37
+ - `margin`: `top1_score - top2_score`
38
+
39
+ 不会保存完整 `960 x 960` attention matrix,避免显存和磁盘开销过大。
40
+
41
+ ## 使用示例
42
+
43
+ 在 pipeline 调用里加:
44
+
45
+ ```python
46
+ output = pipe(
47
+ prompt=prompt,
48
+ negative_prompt=negative_prompt,
49
+ height=384,
50
+ width=640,
51
+ num_frames=99,
52
+ short_attn_debug={
53
+ "output_dir": "short_attn_debug",
54
+ "blocks": [30],
55
+ "steps": ["last"],
56
+ "chunks": [0],
57
+ "current_frame": -1,
58
+ "prev_short_frame": 1,
59
+ "pass_names": ["cond"],
60
+ "topk": 2,
61
+ "query_chunk_size": 128,
62
+ },
63
+ ).frames[0]
64
+ ```
65
+
66
+ 默认推荐先看:
67
+
68
+ - block `30`
69
+ - denoise last step
70
+ - chunk `0`
71
+ - current latent frame `-1`
72
+ - previous short frame `1`
73
+ - cond pass
74
+
75
+ ## 可视化
76
+
77
+ 生成图:
78
+
79
+ ```bash
80
+ python tools/visualize_short_attention_matches.py \
81
+ short_attn_debug/short_attn_chunk0_step49_block30_frame8_cond.pt \
82
+ --output-dir short_attn_debug \
83
+ --stride 4
84
+ ```
85
+
86
+ 输出:
87
+
88
+ - `*_flow_quiver.png`: 稀疏 token flow 箭头图
89
+ - `*_displacement_heatmap.png`: 位移大小热图
90
+ - `*_confidence_heatmap.png`: `top1 - top2` margin 热图
91
+ - `*_top1_score_heatmap.png`: top1 raw score 热图
92
+
93
+ ## 当前实现细节
94
+
95
+ 匹配计算使用 attn1 里已经 projection、norm、rotary 后的 Q/K:
96
+
97
+ ```text
98
+ score = Q_current_frame @ K_previous_short_frame.T / sqrt(head_dim)
99
+ ```
100
+
101
+ 然后对 heads 做平均,再取 top-k。
102
+
103
+ 为了控制开销,计算按 query chunk 分块进行。默认每次处理 128 个 query tokens。
104
+
105
+ ## 未做但可继续扩展的方案
106
+
107
+ 1. full softmax attention heatmap
108
+
109
+ 当前保存的是 top-k raw scores,不保存完整 softmax 分布。后续如果要做单点 token viewer,可以只对用户点击的 token 计算完整 `24 x 40` softmax heatmap。
110
+
111
+ 2. click-to-inspect viewer
112
+
113
+ 可以做一个交互式界面:左边点 current token,右边显示它对 previous short frame 的 `24 x 40` score/attention heatmap,并框出 top-k。
114
+
115
+ 3. 多层对比
116
+
117
+ 当前支持配置多个 blocks,例如 `[10, 20, 30, 39]`。后续可以把这些层的 flow 和 confidence 并排画出来,观察 correspondence 在不同深度的变化。
118
+
119
+ 4. 多 denoise step 对比
120
+
121
+ 当前支持 `steps=["first", "last"]` 或具体 step index。后续可以把 first/mid/last step 的图并排,观察匹配是否从噪声期到收敛期变稳定。
122
+
123
+ 5. 多 current latent frame 可视化
124
+
125
+ 当前推荐只看一个 current frame,例如 `-1`。后续可以对 `0..8` 全部导出,生成 grid 或小视频。
126
+
127
+ 6. warped previous frame
128
+
129
+ 可以用 token correspondence 把 previous short frame 的 patch/grid warp 到 current frame,再与 current frame 做差分。这比 flow 图更接近视觉验证,但实现成本更高。
130
+
131
+ 7. mutual nearest neighbor 过滤
132
+
133
+ 当前是 current -> previous short 的单向 top-k。后续可加 previous short -> current,再保留互为 top-1 的 matches,用来过滤不稳定对应。
134
+
135
+ 8. one-to-one matching
136
+
137
+ 如果需要严格的一对一 token matching,可以在 score matrix 上做 Hungarian 或 optimal transport。但 `960 x 960` 会比当前 top-k 更重,而且未必符合 attention 本身的多对一行为。
Helios/_DEV2/app.py ADDED
@@ -0,0 +1,322 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import tempfile
2
+ import time
3
+ from pathlib import Path
4
+
5
+ import gradio as gr
6
+ import spaces
7
+ import torch
8
+
9
+ from torch.utils._pytree import tree_map
10
+ from diffusers import AutoencoderKLWan, HeliosDMDScheduler, HeliosPyramidPipeline
11
+ from diffusers.utils import export_to_video, load_image, load_video
12
+
13
+
14
+ # ---------------------------------------------------------------------------
15
+ # Pre-load model
16
+ # ---------------------------------------------------------------------------
17
+ PROJECT_ROOT = Path(__file__).resolve().parent
18
+ MODEL_ID = str(PROJECT_ROOT / "checkpoints" / "Helios-Distilled")
19
+
20
+ vae = AutoencoderKLWan.from_pretrained(MODEL_ID, subfolder="vae", torch_dtype=torch.float32)
21
+ scheduler = HeliosDMDScheduler.from_pretrained(MODEL_ID, subfolder="scheduler")
22
+ pipe = HeliosPyramidPipeline.from_pretrained(
23
+ MODEL_ID, vae=vae, scheduler=scheduler, torch_dtype=torch.bfloat16, is_distilled=True
24
+ )
25
+ pipe.to("cuda")
26
+
27
+ cuda_major = torch.cuda.get_device_capability()[0]
28
+ if cuda_major >= 9:
29
+ # H100/H800 (SM90+) with FA3
30
+ try:
31
+ pipe.transformer.set_attention_backend("_flash_3_hub")
32
+ except Exception:
33
+ pipe.transformer.set_attention_backend("flash_hub")
34
+ else:
35
+ # 4090/A100 etc (SM89+) with FA2
36
+ pipe.transformer.set_attention_backend("flash_hub")
37
+
38
+ # ---------------------------------------------------------------------------
39
+ # AoTI
40
+ # ---------------------------------------------------------------------------
41
+
42
+ # Dynamic shapes: within a generation, only hidden_states H/W change across
43
+ # pyramid stages (history latents stay at full resolution). text_seq_length
44
+ # varies between different prompts.
45
+ _AUTO = torch.export.Dim.AUTO
46
+
47
+ TRANSFORMER_DYNAMIC_SHAPES = {
48
+ "hidden_states": {
49
+ 3: _AUTO, # H — doubles each pyramid stage
50
+ 4: _AUTO, # W — doubles each pyramid stage
51
+ },
52
+ "encoder_hidden_states": {
53
+ 1: _AUTO, # text_seq_length — varies with prompt
54
+ },
55
+ }
56
+
57
+ INDUCTOR_CONFIGS = {
58
+ "conv_1x1_as_mm": True,
59
+ "epilogue_fusion": False,
60
+ "coordinate_descent_tuning": True,
61
+ "coordinate_descent_check_all_directions": True,
62
+ # "max_autotune": True,
63
+ "triton.cudagraphs": True,
64
+ }
65
+
66
+ @spaces.GPU(duration=1500) # maximum duration allowed during startup
67
+ def compile_transformer():
68
+ with spaces.aoti_capture(pipe.transformer) as call:
69
+ pipe(
70
+ "arbitrary example prompt",
71
+ height=384,
72
+ width=640,
73
+ num_frames=33,
74
+ guidance_scale=1.0,
75
+ generator=torch.Generator(device="cuda").manual_seed(42),
76
+ pyramid_num_inference_steps_list=[2, 2, 2],
77
+ is_amplify_first_chunk=True,
78
+ )
79
+
80
+ dynamic_shapes = tree_map(lambda t: None, call.kwargs)
81
+ dynamic_shapes |= TRANSFORMER_DYNAMIC_SHAPES
82
+
83
+ with torch.no_grad():
84
+ exported = torch.export.export(
85
+ pipe.transformer,
86
+ args=call.args,
87
+ kwargs=call.kwargs,
88
+ dynamic_shapes=dynamic_shapes,
89
+ )
90
+
91
+ return spaces.aoti_compile(exported, INDUCTOR_CONFIGS)
92
+
93
+ compiled_transformer = compile_transformer()
94
+ spaces.aoti_apply(compiled_transformer, pipe.transformer)
95
+
96
+
97
+ # ---------------------------------------------------------------------------
98
+ # Generation
99
+ # ---------------------------------------------------------------------------
100
+ @spaces.GPU(duration=60)
101
+ def generate_video(
102
+ mode: str,
103
+ prompt: str,
104
+ image_input,
105
+ video_input,
106
+ height: int,
107
+ width: int,
108
+ num_frames: int,
109
+ num_inference_steps: int,
110
+ seed: int,
111
+ is_amplify_first_chunk: bool,
112
+ progress=gr.Progress(track_tqdm=True),
113
+ ):
114
+ if not prompt:
115
+ raise gr.Error("Please provide a prompt.")
116
+
117
+ generator = torch.Generator(device="cuda").manual_seed(int(seed))
118
+
119
+ kwargs = {
120
+ "prompt": prompt,
121
+ "height": int(height),
122
+ "width": int(width),
123
+ "num_frames": int(num_frames),
124
+ "guidance_scale": 1.0,
125
+ "generator": generator,
126
+ "output_type": "np",
127
+ "pyramid_num_inference_steps_list": [
128
+ int(num_inference_steps),
129
+ int(num_inference_steps),
130
+ int(num_inference_steps),
131
+ ],
132
+ "is_amplify_first_chunk": is_amplify_first_chunk,
133
+ }
134
+
135
+ if mode == "Image-to-Video" and image_input is not None:
136
+ img = load_image(image_input).resize((int(width), int(height)))
137
+ kwargs["image"] = img
138
+ elif mode == "Video-to-Video" and video_input is not None:
139
+ kwargs["video"] = load_video(video_input)
140
+
141
+ t0 = time.time()
142
+ output = pipe(**kwargs).frames[0]
143
+ elapsed = time.time() - t0
144
+
145
+ tmp = tempfile.NamedTemporaryFile(suffix=".mp4", delete=False)
146
+ export_to_video(output, tmp.name, fps=24)
147
+ info = f"Generated in {elapsed:.1f}s · {num_frames} frames · {height}×{width}"
148
+ return tmp.name, info
149
+
150
+
151
+ # ---------------------------------------------------------------------------
152
+ # UI Setup
153
+ # ---------------------------------------------------------------------------
154
+ def update_conditional_visibility(mode):
155
+ if mode == "Image-to-Video":
156
+ return gr.update(visible=True), gr.update(visible=False)
157
+ elif mode == "Video-to-Video":
158
+ return gr.update(visible=False), gr.update(visible=True)
159
+ else:
160
+ return gr.update(visible=False), gr.update(visible=False)
161
+
162
+
163
+ CSS = """
164
+ #header { text-align: center; margin-bottom: 1.5em; }
165
+ #header h1 { font-size: 2.2em; margin-bottom: 0.2em; }
166
+ .logo { max-height: 100px; margin: 0 auto 10px auto; display: block; }
167
+ .link-buttons { display: flex; justify-content: center; gap: 15px; margin-top: 10px; }
168
+ .link-buttons a {
169
+ background-color: #2b3137;
170
+ color: #ffffff !important;
171
+ padding: 8px 20px;
172
+ border-radius: 6px;
173
+ text-decoration: none;
174
+ font-weight: 600;
175
+ font-size: 1em;
176
+ transition: all 0.2s ease-in-out;
177
+ box-shadow: 0 2px 4px rgba(0,0,0,0.1);
178
+ }
179
+ .link-buttons a:hover { background-color: #4a535c; transform: translateY(-1px); }
180
+ .contain { max-width: 1350px; margin: 0 auto !important; }
181
+ """
182
+
183
+ with gr.Blocks(title="Helios Video Generation") as demo:
184
+ gr.HTML(
185
+ """
186
+ <div style='display: flex; align-items: center; justify-content: center; width: 100%;'>
187
+ <img src="https://raw.githubusercontent.com/SHYuanBest/shyuanbest_media/main/Helios/logo_white.png" style='width: 400px; height: auto;' />
188
+ </div>
189
+ <div id="header">
190
+ <h1>🎬 Helios 14B Distilled: Real Real-Time Long Video Generation Model</h1>
191
+ <p style="font-size: 1.1em; color: #666; margin-top: 0.5em; margin-bottom: 1em;">
192
+ If you like our project, please give us a star ⭐ on GitHub for the latest update.
193
+ </p>
194
+ <div class="link-buttons">
195
+ <a href="https://github.com/PKU-YuanGroup/Helios" target="_blank">💻 Code</a>
196
+ <a href="https://pku-yuangroup.github.io/Helios-Page" target="_blank">📄 Page</a>
197
+ <a href="https://www.youtube.com/watch?v=vd_AgHtOUFQ" target="_blank">🎥 Main Feature</a>
198
+ <a href="https://www.youtube.com/watch?v=1GeIU2Dn7UY" target="_blank">⚡ Inference Speed</a>
199
+ </div>
200
+ </div>
201
+ """
202
+ )
203
+
204
+ with gr.Row():
205
+ with gr.Column(scale=1):
206
+ mode = gr.Radio(
207
+ choices=["Text-to-Video", "Image-to-Video", "Video-to-Video"],
208
+ value="Text-to-Video",
209
+ label="Generation Mode",
210
+ )
211
+ image_input = gr.Image(label="Image (for I2V)", type="filepath", visible=False)
212
+ video_input = gr.Video(label="Video (for V2V)", visible=False)
213
+ prompt = gr.Textbox(
214
+ label="Prompt",
215
+ lines=4,
216
+ value=(
217
+ "A vibrant tropical fish swimming gracefully among colorful coral reefs in "
218
+ "a clear, turquoise ocean. The fish has bright blue and yellow scales with a "
219
+ "small, distinctive orange spot on its side, its fins moving fluidly. The coral "
220
+ "reefs are alive with a variety of marine life, including small schools of "
221
+ "colorful fish and sea turtles gliding by. The water is crystal clear, allowing "
222
+ "for a view of the sandy ocean floor below. The reef itself is adorned with a mix "
223
+ "of hard and soft corals in shades of red, orange, and green. The photo captures "
224
+ "the fish from a slightly elevated angle, emphasizing its lively movements and the "
225
+ "vivid colors of its surroundings. A close-up shot with dynamic movement."
226
+ ),
227
+ )
228
+ with gr.Accordion("Advanced Settings", open=False):
229
+ with gr.Row():
230
+ height = gr.Number(value=384, label="Height", precision=0, interactive=False)
231
+ width = gr.Number(value=640, label="Width", precision=0, interactive=False)
232
+ with gr.Row():
233
+ num_frames = gr.Slider(33, 231, value=231, step=33, label="Num Frames")
234
+ num_inference_steps = gr.Slider(1, 10, value=2, step=1, label="Steps per stage")
235
+ with gr.Row():
236
+ seed = gr.Number(value=42, label="Seed", precision=0)
237
+ is_amplify_first_chunk = gr.Checkbox(label="Amplify First Chunk", value=True)
238
+
239
+ generate_btn = gr.Button("🚀 Generate Video", variant="primary", size="lg")
240
+
241
+ with gr.Column(scale=1):
242
+ video_output = gr.Video(label="Generated Video", autoplay=True)
243
+ info_output = gr.Textbox(label="Info", interactive=False)
244
+
245
+ mode.change(fn=update_conditional_visibility, inputs=[mode], outputs=[image_input, video_input])
246
+ generate_btn.click(
247
+ fn=generate_video,
248
+ inputs=[
249
+ mode,
250
+ prompt,
251
+ image_input,
252
+ video_input,
253
+ height,
254
+ width,
255
+ num_frames,
256
+ num_inference_steps,
257
+ seed,
258
+ is_amplify_first_chunk,
259
+ ],
260
+ outputs=[video_output, info_output],
261
+ )
262
+
263
+ gr.Examples(
264
+ examples=[
265
+ [
266
+ "Text-to-Video",
267
+ "A vibrant tropical fish swimming gracefully among colorful coral reefs in "
268
+ "a clear, turquoise ocean. The fish has bright blue and yellow scales with a "
269
+ "small, distinctive orange spot on its side, its fins moving fluidly. The coral "
270
+ "reefs are alive with a variety of marine life, including small schools of "
271
+ "colorful fish and sea turtles gliding by. The water is crystal clear, allowing "
272
+ "for a view of the sandy ocean floor below. The reef itself is adorned with a mix "
273
+ "of hard and soft corals in shades of red, orange, and green. The photo captures "
274
+ "the fish from a slightly elevated angle, emphasizing its lively movements and the "
275
+ "vivid colors of its surroundings. A close-up shot with dynamic movement.",
276
+ None,
277
+ None,
278
+ ],
279
+ [
280
+ "Text-to-Video",
281
+ "An extreme close-up of an gray-haired man with a beard in his 60s, he is deep in "
282
+ "thought pondering the history of the universe as he sits at a cafe in Paris, his eyes "
283
+ "focus on people offscreen as they walk as he sits mostly motionless, he is dressed in "
284
+ "a wool coat suit coat with a button-down shirt , he wears a brown beret and glasses "
285
+ "and has a very professorial appearance, and the end he offers a subtle closed-mouth "
286
+ "smile as if he found the answer to the mystery of life, the lighting is very cinematic "
287
+ "with the golden light and the Parisian streets and city in the background, depth of "
288
+ "field, cinematic 35mm film.",
289
+ None,
290
+ None,
291
+ ],
292
+ [
293
+ "Text-to-Video",
294
+ "A drone camera circles around a beautiful historic church built on a rocky outcropping "
295
+ "along the Amalfi Coast, the view showcases historic and magnificent architectural "
296
+ "details and tiered pathways and patios, waves are seen crashing against the rocks "
297
+ "below as the view overlooks the horizon of the coastal waters and hilly landscapes "
298
+ "of the Amalfi Coast Italy, several distant people are seen walking and enjoying vistas "
299
+ "on patios of the dramatic ocean views, the warm glow of the afternoon sun creates a "
300
+ "magical and romantic feeling to the scene, the view is stunning captured with beautiful photography.",
301
+ None,
302
+ None,
303
+ ],
304
+ [
305
+ "Image-to-Video",
306
+ "A towering emerald wave surges forward, its crest curling with raw power and energy. Sunlight glints off the translucent water, illuminating the intricate textures and deep green hues within the wave’s body. A thick spray erupts from the breaking crest, casting a misty veil that dances above the churning surface. As the perspective widens, the immense scale of the wave becomes apparent, revealing the restless expanse of the ocean stretching beyond. The scene captures the ocean’s untamed beauty and relentless force, with every droplet and ripple shimmering in the light. The dynamic motion and vivid colors evoke both awe and respect for nature’s might.",
307
+ "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/helios/wave.jpg",
308
+ None,
309
+ ],
310
+ [
311
+ "Video-to-Video",
312
+ "A bright yellow Lamborghini Huracn Tecnica speeds along a curving mountain road, surrounded by lush green trees under a partly cloudy sky. The car's sleek design and vibrant color stand out against the natural backdrop, emphasizing its dynamic movement. The road curves gently, with a guardrail visible on one side, adding depth to the scene. The motion blur captures the sense of speed and energy, creating a thrilling and exhilarating atmosphere. A front-facing shot from a slightly elevated angle, highlighting the car's aggressive stance and the surrounding greenery.",
313
+ None,
314
+ "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/helios/car.mp4",
315
+ ],
316
+ ],
317
+ inputs=[mode, prompt, image_input, video_input],
318
+ label="Example Prompts",
319
+ )
320
+
321
+ if __name__ == "__main__":
322
+ demo.launch(share=True, css=CSS, theme=gr.themes.Soft())
Helios/_DEV2/bench_infer.py ADDED
@@ -0,0 +1,569 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Helios Benchmark Inference Script
3
+ - Runs T2V inference for a single model version on a single GPU
4
+ - Uses the first N prompts from a txt file
5
+ - Saves videos in two layouts: by_prompt/<slug>/<version>.mp4
6
+ by_version/<version>/<slug>.mp4
7
+ - Records per-video timing to timing_<version>.txt and computes summary stats
8
+ """
9
+
10
+ import importlib
11
+ import os
12
+ import re
13
+ import shutil
14
+ import sys
15
+ import time
16
+
17
+ os.environ["HF_ENABLE_PARALLEL_LOADING"] = "yes"
18
+ os.environ["HF_PARALLEL_LOADING_WORKERS"] = "8"
19
+
20
+ import argparse
21
+ import subprocess
22
+ from pathlib import Path
23
+
24
+
25
+ SCRIPT_DIR = Path(__file__).resolve().parent
26
+ DEFAULT_PROMPT_FILE = SCRIPT_DIR / "demo_data" / "MovieGenVideoBench_extended.txt"
27
+ DEFAULT_MODEL_ROOT = SCRIPT_DIR / "checkpoints"
28
+ DEFAULT_OUTPUT_ROOT = SCRIPT_DIR / "output_helios" / "bench"
29
+
30
+
31
+ def pick_gpu_by_free_vram(min_free_mib=20000):
32
+ """Pick physical GPU index with the most free memory (via nvidia-smi). No torch import."""
33
+ try:
34
+ out = subprocess.check_output(
35
+ [
36
+ "nvidia-smi",
37
+ "--query-gpu=index,memory.free",
38
+ "--format=csv,noheader,nounits",
39
+ ],
40
+ text=True,
41
+ stderr=subprocess.DEVNULL,
42
+ )
43
+ except (subprocess.CalledProcessError, FileNotFoundError) as e:
44
+ raise RuntimeError("nvidia-smi failed; specify --gpu explicitly") from e
45
+
46
+ best_idx, best_free = None, -1
47
+ for line in out.strip().splitlines():
48
+ parts = [p.strip() for p in line.split(",")]
49
+ if len(parts) < 2:
50
+ continue
51
+ idx, free = int(parts[0]), int(parts[1])
52
+ if free > best_free:
53
+ best_free, best_idx = free, idx
54
+ if best_idx is None:
55
+ raise RuntimeError("Could not parse nvidia-smi GPU list")
56
+ if best_free < min_free_mib:
57
+ print(
58
+ f"[warn] Best GPU {best_idx} has only {best_free} MiB free "
59
+ f"(<{min_free_mib} MiB); OOM risk — consider --enable_low_vram_mode",
60
+ file=sys.stderr,
61
+ )
62
+ return best_idx, best_free
63
+
64
+
65
+ def _apply_cuda_visible_devices_before_torch():
66
+ """CUDA_VISIBLE_DEVICES must be set before `import torch` (first CUDA init)."""
67
+ pre = argparse.ArgumentParser(add_help=False)
68
+ pre.add_argument("--gpu", type=str, default="auto")
69
+ known, _ = pre.parse_known_args()
70
+ g = known.gpu.strip().lower()
71
+ if g == "auto":
72
+ idx, free = pick_gpu_by_free_vram()
73
+ os.environ["CUDA_VISIBLE_DEVICES"] = str(idx)
74
+ os.environ["_BENCH_PHYSICAL_GPU"] = f"{idx} ({free} MiB free)"
75
+ else:
76
+ os.environ["CUDA_VISIBLE_DEVICES"] = known.gpu.strip()
77
+ os.environ["_BENCH_PHYSICAL_GPU"] = known.gpu.strip()
78
+ os.environ["_BENCH_GPU_ARG"] = known.gpu.strip()
79
+
80
+
81
+ _apply_cuda_visible_devices_before_torch()
82
+
83
+ import torch
84
+ from tqdm import tqdm
85
+
86
+ if importlib.util.find_spec("torch_npu") is not None:
87
+ import torch_npu # noqa: F401
88
+
89
+ from helios.diffusers_version.pipeline_helios_diffusers import HeliosPipeline
90
+ from helios.diffusers_version.scheduling_helios_diffusers import HeliosScheduler
91
+ from helios.diffusers_version.transformer_helios_diffusers import HeliosTransformer3DModel
92
+ from helios.modules.helios_kernels import (
93
+ replace_all_norms_with_flash_norms,
94
+ replace_rmsnorm_with_fp32,
95
+ replace_rope_with_flash_rope,
96
+ )
97
+ from diffusers.models import AutoencoderKLWan
98
+ from diffusers.utils import export_to_video
99
+
100
+ # ── per-version inference presets (matching official scripts) ─────────────────
101
+
102
+ MODEL_PRESETS = {
103
+ "base": dict(
104
+ model_dir="Helios-Base",
105
+ num_frames=99,
106
+ num_inference_steps=50,
107
+ guidance_scale=5.0,
108
+ is_enable_stage2=False,
109
+ pyramid_num_inference_steps_list=[20, 20, 20],
110
+ is_amplify_first_chunk=False,
111
+ use_zero_init=False,
112
+ zero_steps=1,
113
+ ),
114
+ "mid": dict(
115
+ model_dir="Helios-Mid",
116
+ num_frames=99,
117
+ num_inference_steps=50,
118
+ guidance_scale=5.0,
119
+ is_enable_stage2=True,
120
+ pyramid_num_inference_steps_list=[20, 20, 20],
121
+ is_amplify_first_chunk=False,
122
+ use_zero_init=True,
123
+ zero_steps=1,
124
+ ),
125
+ "distilled": dict(
126
+ model_dir="Helios-Distilled",
127
+ num_frames=240,
128
+ num_inference_steps=50,
129
+ guidance_scale=1.0,
130
+ is_enable_stage2=True,
131
+ pyramid_num_inference_steps_list=[2, 2, 2],
132
+ is_amplify_first_chunk=True,
133
+ use_zero_init=False,
134
+ zero_steps=1,
135
+ ),
136
+ }
137
+
138
+ NEGATIVE_PROMPT = (
139
+ "Bright tones, overexposed, static, blurred details, subtitles, style, "
140
+ "works, paintings, images, static, overall gray, worst quality, low quality, "
141
+ "JPEG compression residue, ugly, incomplete, extra fingers, poorly drawn hands, "
142
+ "poorly drawn faces, deformed, disfigured, misshapen limbs, fused fingers, "
143
+ "still picture, messy background, three legs, many people in the background, "
144
+ "walking backwards"
145
+ )
146
+
147
+
148
+ def sanitize_filename(text, max_len=80):
149
+ """Turn a prompt into a filesystem-safe slug."""
150
+ text = text.strip().lower()
151
+ text = re.sub(r"[^a-z0-9]+", "_", text)
152
+ text = text.strip("_")
153
+ return text[:max_len]
154
+
155
+
156
+ def load_prompt_indices(path):
157
+ indices = []
158
+ with open(path, "r", encoding="utf-8") as f:
159
+ for line_no, raw_line in enumerate(f, start=1):
160
+ line = raw_line.strip()
161
+ if not line or line.startswith("#"):
162
+ continue
163
+ try:
164
+ idx = int(line)
165
+ except ValueError as exc:
166
+ raise ValueError(
167
+ f"Invalid prompt index at {path}:{line_no}: {line!r}"
168
+ ) from exc
169
+ if idx < 0:
170
+ raise ValueError(f"Prompt index must be >= 0 at {path}:{line_no}")
171
+ indices.append(idx)
172
+ return indices
173
+
174
+
175
+ def load_prompts(path, prompt_start=0, prompt_end=None, prompt_indices=None):
176
+ with open(path, "r", encoding="utf-8") as f:
177
+ lines = [line.strip() for line in f if line.strip()]
178
+ if prompt_indices is not None:
179
+ selected = []
180
+ total = len(lines)
181
+ for idx in prompt_indices:
182
+ if idx >= total:
183
+ raise ValueError(
184
+ f"Prompt index {idx} is out of range; prompt file has {total} prompts"
185
+ )
186
+ selected.append((idx, lines[idx]))
187
+ return selected
188
+
189
+ if prompt_start < 0:
190
+ raise ValueError("prompt_start must be >= 0")
191
+ if prompt_end is not None and prompt_end < prompt_start:
192
+ raise ValueError("prompt_end must be >= prompt_start")
193
+
194
+ selected = lines[prompt_start:prompt_end]
195
+ return [(prompt_start + offset, prompt) for offset, prompt in enumerate(selected)]
196
+
197
+
198
+ def build_expected_outputs(prompts, version, by_version_dir):
199
+ version_dir = os.path.join(by_version_dir, version)
200
+ expected = []
201
+ for idx, prompt in prompts:
202
+ slug = sanitize_filename(prompt)
203
+ vid_name = f"{idx:04d}_{slug}"
204
+ expected.append((idx, slug, os.path.join(version_dir, f"{vid_name}.mp4")))
205
+ return version_dir, expected
206
+
207
+
208
+ def output_exists(path):
209
+ return os.path.isfile(path) and os.path.getsize(path) > 0
210
+
211
+
212
+ def find_missing_outputs(expected_outputs):
213
+ return [item for item in expected_outputs if not output_exists(item[2])]
214
+
215
+
216
+ def make_timing_line(version, idx, elapsed, slug):
217
+ return (
218
+ f" {version:10s} #{idx:04d} {elapsed:8.2f}s "
219
+ f"({elapsed / 60:5.2f}min) {slug[:50]}"
220
+ )
221
+
222
+
223
+ def load_existing_timing_records(timing_file, version):
224
+ if not os.path.exists(timing_file):
225
+ return {}
226
+
227
+ pattern = re.compile(
228
+ rf"^\s*{re.escape(version)}\s+#(\d+)\s+([0-9.]+)s\s+\([^)]+\)\s+(.*)$"
229
+ )
230
+ records = {}
231
+ with open(timing_file, "r", encoding="utf-8") as f:
232
+ for raw_line in f:
233
+ line = raw_line.rstrip("\n")
234
+ match = pattern.match(line)
235
+ if not match:
236
+ continue
237
+ idx = int(match.group(1))
238
+ elapsed = float(match.group(2))
239
+ slug = match.group(3)
240
+ records[idx] = (elapsed, slug)
241
+ return records
242
+
243
+
244
+ def build_pipeline(
245
+ model_path,
246
+ device,
247
+ weight_dtype,
248
+ enable_low_vram=False,
249
+ group_offloading_type="leaf_level",
250
+ num_blocks_per_group=4,
251
+ ):
252
+ transformer = HeliosTransformer3DModel.from_pretrained(
253
+ model_path, subfolder="transformer", torch_dtype=weight_dtype,
254
+ )
255
+ transformer = replace_rmsnorm_with_fp32(transformer)
256
+ transformer = replace_all_norms_with_flash_norms(transformer)
257
+ replace_rope_with_flash_rope()
258
+
259
+ cuda_major = torch.cuda.get_device_capability()[0]
260
+ if cuda_major >= 9:
261
+ try:
262
+ transformer.set_attention_backend("_flash_3_hub")
263
+ except Exception:
264
+ transformer.set_attention_backend("flash_hub")
265
+ else:
266
+ transformer.set_attention_backend("flash_hub")
267
+
268
+ vae = AutoencoderKLWan.from_pretrained(
269
+ model_path, subfolder="vae", torch_dtype=torch.float32,
270
+ )
271
+ scheduler = HeliosScheduler.from_pretrained(model_path, subfolder="scheduler")
272
+
273
+ pipe = HeliosPipeline.from_pretrained(
274
+ model_path,
275
+ transformer=transformer,
276
+ vae=vae,
277
+ scheduler=scheduler,
278
+ torch_dtype=weight_dtype,
279
+ )
280
+ if enable_low_vram:
281
+ nbg = int(num_blocks_per_group) if group_offloading_type == "block_level" else None
282
+ pipe.enable_group_offload(
283
+ onload_device=torch.device("cuda"),
284
+ offload_device=torch.device("cpu"),
285
+ offload_type=group_offloading_type,
286
+ num_blocks_per_group=nbg,
287
+ use_stream=True,
288
+ record_stream=True,
289
+ )
290
+ else:
291
+ pipe = pipe.to(device)
292
+ return pipe
293
+
294
+
295
+ def run_single(pipe, prompt, preset, height, width, seed):
296
+ gen = torch.Generator(device="cuda").manual_seed(seed)
297
+
298
+ t0 = time.time()
299
+ with torch.no_grad():
300
+ output = pipe(
301
+ prompt=prompt,
302
+ negative_prompt=NEGATIVE_PROMPT,
303
+ height=height,
304
+ width=width,
305
+ num_frames=preset["num_frames"],
306
+ num_inference_steps=preset["num_inference_steps"],
307
+ guidance_scale=preset["guidance_scale"],
308
+ generator=gen,
309
+ history_sizes=[16, 2, 1],
310
+ num_latent_frames_per_chunk=9,
311
+ keep_first_frame=True,
312
+ is_enable_stage2=preset["is_enable_stage2"],
313
+ pyramid_num_inference_steps_list=preset["pyramid_num_inference_steps_list"],
314
+ is_skip_first_chunk=False,
315
+ is_amplify_first_chunk=preset["is_amplify_first_chunk"],
316
+ use_zero_init=preset["use_zero_init"],
317
+ zero_steps=preset["zero_steps"],
318
+ ).frames[0]
319
+ elapsed = time.time() - t0
320
+ return output, elapsed
321
+
322
+
323
+ def _parse_gpu(s):
324
+ if isinstance(s, str) and s.lower() == "auto":
325
+ return "auto"
326
+ return int(s)
327
+
328
+
329
+ def parse_args():
330
+ p = argparse.ArgumentParser(description="Helios benchmark inference for one model version")
331
+ p.add_argument("--prompt_file", type=str,
332
+ default=str(DEFAULT_PROMPT_FILE))
333
+ p.add_argument("--prompt_start", type=int, default=0)
334
+ p.add_argument("--prompt_end", type=int, default=100,
335
+ help="Exclusive end index for prompts, e.g. 50 means up to #49")
336
+ p.add_argument("--prompt_indices_file", type=str, default=None,
337
+ help="Optional file containing exact prompt indices to run, one per line")
338
+ p.add_argument("--model_root", type=str, default=str(DEFAULT_MODEL_ROOT),
339
+ help="Parent dir containing Helios-Base / Helios-Mid / Helios-Distilled")
340
+ p.add_argument("--output_root", type=str, default=str(DEFAULT_OUTPUT_ROOT))
341
+ p.add_argument("--version", type=str, choices=sorted(MODEL_PRESETS.keys()), required=True,
342
+ help="Which model version to run")
343
+ p.add_argument("--timing_file", type=str, default=None,
344
+ help="Optional override for timing report path")
345
+ p.add_argument("--height", type=int, default=384)
346
+ p.add_argument("--width", type=int, default=640)
347
+ p.add_argument("--num_frames", type=int, default=None,
348
+ help="Override preset frame count for all selected versions")
349
+ p.add_argument("--seed", type=int, default=42)
350
+ p.add_argument(
351
+ "--gpu",
352
+ type=_parse_gpu,
353
+ default="auto",
354
+ help='Physical GPU id or "auto" (pick most free VRAM via nvidia-smi)',
355
+ )
356
+ p.add_argument(
357
+ "--enable_low_vram_mode",
358
+ action="store_true",
359
+ help="CPU group-offload (slower, less VRAM); use if GPU is shared or OOM",
360
+ )
361
+ p.add_argument(
362
+ "--group_offloading_type",
363
+ type=str,
364
+ choices=["leaf_level", "block_level"],
365
+ default="leaf_level",
366
+ )
367
+ p.add_argument("--num_blocks_per_group", type=int, default=4)
368
+ return p.parse_args()
369
+
370
+
371
+ def main():
372
+ args = parse_args()
373
+
374
+ if not os.path.isfile(args.prompt_file):
375
+ raise FileNotFoundError(f"Prompt file not found: {args.prompt_file}")
376
+ if not os.path.isdir(args.model_root):
377
+ raise FileNotFoundError(f"Model root not found: {args.model_root}")
378
+
379
+ os.environ["CUDA_VISIBLE_DEVICES"] = str(args.gpu)
380
+ device = torch.device("cuda")
381
+ weight_dtype = torch.bfloat16
382
+
383
+ prompt_indices = None
384
+ if args.prompt_indices_file:
385
+ if not os.path.isfile(args.prompt_indices_file):
386
+ raise FileNotFoundError(f"Prompt indices file not found: {args.prompt_indices_file}")
387
+ prompt_indices = load_prompt_indices(args.prompt_indices_file)
388
+
389
+ prompts = load_prompts(
390
+ args.prompt_file,
391
+ args.prompt_start,
392
+ args.prompt_end,
393
+ prompt_indices=prompt_indices,
394
+ )
395
+ prompt_map = dict(prompts)
396
+ if args.prompt_indices_file:
397
+ print(
398
+ f"Loaded {len(prompts)} prompts from {args.prompt_file} "
399
+ f"(indices: {args.prompt_indices_file})"
400
+ )
401
+ else:
402
+ print(
403
+ f"Loaded {len(prompts)} prompts from {args.prompt_file} "
404
+ f"(range: {args.prompt_start}:{args.prompt_end})"
405
+ )
406
+
407
+ if args.num_frames is not None:
408
+ MODEL_PRESETS[args.version]["num_frames"] = args.num_frames
409
+
410
+ by_prompt_dir = os.path.join(args.output_root, "by_prompt")
411
+ by_version_dir = os.path.join(args.output_root, "by_version")
412
+ timing_file = args.timing_file or os.path.join(args.output_root, f"timing_{args.version}.txt")
413
+ os.makedirs(args.output_root, exist_ok=True)
414
+
415
+ preset = MODEL_PRESETS[args.version]
416
+ model_path = os.path.join(args.model_root, preset["model_dir"])
417
+ timing_records = load_existing_timing_records(timing_file, args.version)
418
+ selected_indices = set(prompt_map)
419
+ timing_records = {
420
+ idx: record for idx, record in timing_records.items() if idx in selected_indices
421
+ }
422
+ ver_dir, expected_outputs = build_expected_outputs(prompts, args.version, by_version_dir)
423
+ missing_outputs = find_missing_outputs(expected_outputs)
424
+ if not os.path.isdir(model_path):
425
+ raise FileNotFoundError(f"Model not found: {model_path}")
426
+
427
+ peak_mem = None
428
+ if not missing_outputs:
429
+ print(
430
+ f"[SKIP] All outputs already exist for version={args.version} under {ver_dir}"
431
+ )
432
+ else:
433
+ header = (
434
+ f"\n{'=' * 60}\n"
435
+ f" Version: {args.version} | Model: {preset['model_dir']}\n"
436
+ f" Frames: {preset['num_frames']} | guidance_scale: {preset['guidance_scale']}\n"
437
+ f" stage2: {preset['is_enable_stage2']} | pyramid_steps: {preset['pyramid_num_inference_steps_list']}\n"
438
+ f"{'=' * 60}\n"
439
+ )
440
+ print(header)
441
+
442
+ pipe = build_pipeline(
443
+ model_path,
444
+ device,
445
+ weight_dtype,
446
+ enable_low_vram=args.enable_low_vram_mode,
447
+ group_offloading_type=args.group_offloading_type,
448
+ num_blocks_per_group=args.num_blocks_per_group,
449
+ )
450
+
451
+ os.makedirs(ver_dir, exist_ok=True)
452
+
453
+ print(
454
+ f"[resume] version={args.version} existing={len(expected_outputs) - len(missing_outputs)} "
455
+ f"missing={len(missing_outputs)} timed={len(timing_records)}"
456
+ )
457
+ for idx, slug, ver_out in tqdm(missing_outputs, desc=f"[{args.version}]"):
458
+ if os.path.exists(ver_out):
459
+ print(f" [skip] {ver_out}")
460
+ continue
461
+
462
+ try:
463
+ frames, elapsed = run_single(
464
+ pipe, prompt_map[idx], preset, args.height, args.width, args.seed,
465
+ )
466
+ except Exception as e:
467
+ msg = f" [FAIL] {args.version} #{idx:04d}: {e}"
468
+ print(msg)
469
+ continue
470
+
471
+ export_to_video(frames, ver_out, fps=24)
472
+
473
+ vid_name = os.path.splitext(os.path.basename(ver_out))[0]
474
+ prompt_dir = os.path.join(by_prompt_dir, vid_name)
475
+ os.makedirs(prompt_dir, exist_ok=True)
476
+ shutil.copy2(ver_out, os.path.join(prompt_dir, f"{args.version}.mp4"))
477
+
478
+ timing_records[idx] = (elapsed, slug)
479
+ print(make_timing_line(args.version, idx, elapsed, slug))
480
+
481
+ peak_mem = torch.cuda.max_memory_allocated() / 1024 ** 3
482
+ print(f" >> [{args.version}] peak GPU memory: {peak_mem:.2f} GB")
483
+
484
+ del pipe
485
+ torch.cuda.empty_cache()
486
+ torch.cuda.reset_peak_memory_stats()
487
+
488
+ sorted_records = [timing_records[idx] for idx in sorted(timing_records)]
489
+ all_timings = [elapsed for elapsed, _ in sorted_records]
490
+
491
+ with open(timing_file, "w", encoding="utf-8") as tf:
492
+ tf.write(f"{'=' * 80}\n")
493
+ tf.write(f" Helios Benchmark Inference Timing Report\n")
494
+ tf.write(f" {time.strftime('%Y-%m-%d %H:%M:%S')}\n")
495
+ tf.write(
496
+ f" Prompts: {len(prompts)} | Range: {args.prompt_start}:{args.prompt_end} "
497
+ f"| Version: {args.version}\n"
498
+ )
499
+ if args.prompt_indices_file:
500
+ tf.write(f" Prompt indices file: {args.prompt_indices_file}\n")
501
+ tf.write(
502
+ f" Resolution: {args.width}x{args.height} | Seed: {args.seed} | "
503
+ f"GPU: {args.gpu} | low_vram: {args.enable_low_vram_mode}\n"
504
+ )
505
+ tf.write(f"{'=' * 80}\n\n")
506
+
507
+ tf.write(
508
+ f"\n{'=' * 60}\n"
509
+ f" Version: {args.version} | Model: {preset['model_dir']}\n"
510
+ f" Frames: {preset['num_frames']} | guidance_scale: {preset['guidance_scale']}\n"
511
+ f" stage2: {preset['is_enable_stage2']} | pyramid_steps: {preset['pyramid_num_inference_steps_list']}\n"
512
+ f"{'=' * 60}\n"
513
+ )
514
+ tf.write(
515
+ f" Existing timing records: {len(timing_records)} / expected outputs: {len(expected_outputs)}\n"
516
+ )
517
+
518
+ for idx in sorted(timing_records):
519
+ elapsed, slug = timing_records[idx]
520
+ tf.write(make_timing_line(args.version, idx, elapsed, slug) + "\n")
521
+
522
+ if all_timings:
523
+ avg_t = sum(all_timings) / len(all_timings)
524
+ total_t = sum(all_timings)
525
+ summary = (
526
+ f"\n >> [{args.version}] completed {len(all_timings)} videos | "
527
+ f"avg: {avg_t:.2f}s ({avg_t / 60:.2f}min) | "
528
+ f"total: {total_t:.1f}s ({total_t / 60:.1f}min)\n"
529
+ )
530
+ else:
531
+ summary = f"\n >> [{args.version}] no timing records available\n"
532
+ print(summary)
533
+ tf.write(summary)
534
+
535
+ if peak_mem is not None:
536
+ mem_line = f" >> [{args.version}] peak GPU memory: {peak_mem:.2f} GB\n"
537
+ tf.write(mem_line)
538
+
539
+ sep = f"\n{'=' * 80}\n"
540
+ tf.write(sep)
541
+ tf.write(" FINAL SUMMARY\n")
542
+ tf.write(f"{'=' * 80}\n")
543
+ print(sep)
544
+ print(" FINAL SUMMARY")
545
+ print(f"{'=' * 80}")
546
+
547
+ fmt = " {ver:12s} | videos: {n:3d} | avg: {avg:8.2f}s ({avgm:5.2f}min) | min: {mn:8.2f}s | max: {mx:8.2f}s | total: {tot:8.1f}s ({totm:5.1f}min)"
548
+ if all_timings:
549
+ line = fmt.format(
550
+ ver=args.version, n=len(all_timings),
551
+ avg=sum(all_timings) / len(all_timings), avgm=sum(all_timings) / len(all_timings) / 60,
552
+ mn=min(all_timings), mx=max(all_timings),
553
+ tot=sum(all_timings), totm=sum(all_timings) / 60,
554
+ )
555
+ else:
556
+ line = f" {args.version:12s} | N/A (no timing records)"
557
+ print(line)
558
+ tf.write(line + "\n")
559
+
560
+ tf.write(f"{'=' * 80}\n")
561
+
562
+ print(f"{'=' * 80}")
563
+ print(f"\nTiming report: {timing_file}")
564
+ print(f"Videos: {by_prompt_dir}")
565
+ print(f" {by_version_dir}")
566
+
567
+
568
+ if __name__ == "__main__":
569
+ main()
Helios/_DEV2/infer_helios.py ADDED
@@ -0,0 +1,673 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import importlib
2
+ import os
3
+
4
+
5
+ os.environ["HF_ENABLE_PARALLEL_LOADING"] = "yes"
6
+ os.environ["HF_PARALLEL_LOADING_WORKERS"] = "8"
7
+
8
+ import argparse
9
+ import time
10
+ from pathlib import Path
11
+
12
+ import pandas as pd
13
+ import torch
14
+ import torch.distributed as dist
15
+ from tqdm import tqdm
16
+
17
+
18
+ if importlib.util.find_spec("torch_npu") is not None:
19
+ import torch_npu
20
+ else:
21
+ torch_npu = None
22
+
23
+ from helios.diffusers_version.pipeline_helios_diffusers import HeliosPipeline
24
+ from helios.diffusers_version.scheduling_helios_diffusers import HeliosScheduler
25
+ from helios.diffusers_version.transformer_helios_diffusers import HeliosTransformer3DModel
26
+ from helios.modules.helios_kernels import (
27
+ replace_all_norms_with_flash_norms,
28
+ replace_rmsnorm_with_fp32,
29
+ replace_rope_with_flash_rope,
30
+ )
31
+ from helios.utils.utils_base import load_extra_components
32
+
33
+ from diffusers import ContextParallelConfig
34
+ from diffusers.models import AutoencoderKLWan
35
+ from diffusers.utils import export_to_video, load_image, load_video
36
+
37
+ PROJECT_ROOT = Path(__file__).resolve().parent
38
+ DEFAULT_BASE_MODEL_PATH = str(PROJECT_ROOT / "checkpoints" / "Helios-Base")
39
+
40
+
41
+ def parse_args():
42
+ parser = argparse.ArgumentParser(description="Generate video with model")
43
+
44
+ # === Model paths ===
45
+ parser.add_argument("--base_model_path", type=str, default=DEFAULT_BASE_MODEL_PATH)
46
+ parser.add_argument(
47
+ "--transformer_path",
48
+ type=str,
49
+ default=DEFAULT_BASE_MODEL_PATH,
50
+ )
51
+ parser.add_argument(
52
+ "--lora_path",
53
+ type=str,
54
+ default=None,
55
+ )
56
+ parser.add_argument(
57
+ "--partial_path",
58
+ type=str,
59
+ default=None,
60
+ )
61
+ parser.add_argument("--output_folder", type=str, default="./output_helios")
62
+ parser.add_argument("--enable_compile", action="store_true")
63
+
64
+ # === Generation parameters ===
65
+ # environment
66
+ parser.add_argument(
67
+ "--sample_type",
68
+ type=str,
69
+ default="t2v",
70
+ choices=["t2v", "i2v", "v2v"],
71
+ )
72
+ parser.add_argument(
73
+ "--weight_dtype",
74
+ type=str,
75
+ default="bf16",
76
+ choices=["bf16", "fp16", "fp32"],
77
+ help="Data type for model weights.",
78
+ )
79
+ parser.add_argument("--seed", type=int, default=42, help="Seed for random number generator.")
80
+ # base
81
+ parser.add_argument("--height", type=int, default=384)
82
+ parser.add_argument("--width", type=int, default=640)
83
+ parser.add_argument("--num_frames", type=int, default=99)
84
+ parser.add_argument("--fps", type=int, default=24)
85
+ parser.add_argument("--num_inference_steps", type=int, default=50)
86
+ parser.add_argument("--guidance_scale", type=float, default=5.0)
87
+ # cfg zero
88
+ parser.add_argument("--use_zero_init", action="store_true")
89
+ parser.add_argument("--zero_steps", type=int, default=1)
90
+ # stage 1
91
+ parser.add_argument("--num_latent_frames_per_chunk", type=int, default=9)
92
+ # stage 2
93
+ parser.add_argument("--is_enable_stage2", action="store_true")
94
+ parser.add_argument("--pyramid_num_inference_steps_list", type=int, nargs="+", default=[20, 20, 20])
95
+ # stage 3
96
+ parser.add_argument("--is_skip_first_chunk", action="store_true")
97
+ parser.add_argument("--is_amplify_first_chunk", action="store_true")
98
+ parser.add_argument(
99
+ "--visualize_relative_l1",
100
+ action="store_true",
101
+ help="Save per-chunk denoising relative L1 records and a timestep plot.",
102
+ )
103
+ parser.add_argument(
104
+ "--relative_l1_output_folder",
105
+ type=str,
106
+ default=None,
107
+ help="Deprecated. Relative L1 files are saved next to the mp4 in each prompt timestamp folder.",
108
+ )
109
+
110
+ # === Prompts ===
111
+ parser.add_argument("--use_interpolate_prompt", action="store_true")
112
+ parser.add_argument("--interpolation_steps", type=int, default=3)
113
+ parser.add_argument("--interpolate_time", type=int, default=7)
114
+ parser.add_argument(
115
+ "--image_path",
116
+ type=str,
117
+ default=None,
118
+ )
119
+ parser.add_argument(
120
+ "--image_noise_sigma_min", type=float, default=0.111, help="Balance motion amplitude and visual consistency"
121
+ )
122
+ parser.add_argument(
123
+ "--image_noise_sigma_max", type=float, default=0.135, help="Balance motion amplitude and visual consistency"
124
+ )
125
+ parser.add_argument(
126
+ "--video_path",
127
+ type=str,
128
+ default=None,
129
+ )
130
+ parser.add_argument(
131
+ "--video_noise_sigma_min", type=float, default=0.111, help="Balance motion amplitude and visual consistency"
132
+ )
133
+ parser.add_argument(
134
+ "--video_noise_sigma_max", type=float, default=0.135, help="Balance motion amplitude and visual consistency"
135
+ )
136
+ parser.add_argument(
137
+ "--prompt",
138
+ type=str,
139
+ default="A dynamic time-lapse video showing the rapidly moving scenery from the window of a speeding train. The camera captures various elements such as lush green fields, towering trees, quaint countryside houses, and distant mountain ranges passing by quickly. The train window frames the view, adding a sense of speed and motion as the landscape rushes past. The camera remains static but emphasizes the fast-paced movement outside. The overall atmosphere is serene yet exhilarating, capturing the essence of travel and exploration. Medium shot focusing on the train window and the rushing scenery beyond.",
140
+ )
141
+ parser.add_argument(
142
+ "--negative_prompt",
143
+ type=str,
144
+ default="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",
145
+ )
146
+ parser.add_argument(
147
+ "--prompt_txt_path",
148
+ type=str,
149
+ default=None,
150
+ )
151
+ parser.add_argument(
152
+ "--base_image_prompt_path",
153
+ type=str,
154
+ default=None,
155
+ )
156
+ parser.add_argument(
157
+ "--image_prompt_csv_path",
158
+ type=str,
159
+ default=None,
160
+ )
161
+ parser.add_argument(
162
+ "--interactive_prompt_csv_path",
163
+ type=str,
164
+ default=None,
165
+ )
166
+
167
+ # === Context parallelism ===
168
+ # Please refer to https://huggingface.co/docs/diffusers/main/en/training/distributed_inference#context-parallelism
169
+ parser.add_argument("--enable_parallelism", action="store_true")
170
+ parser.add_argument(
171
+ "--cp_backend",
172
+ type=str,
173
+ choices=["ring", "ulysses", "unified", "ulysses_anything"],
174
+ default="ulysses",
175
+ help="Context parallel backend to use.",
176
+ )
177
+
178
+ # === Group-Offloading ===
179
+ # Please refer to https://huggingface.co/docs/diffusers/main/en/optimization/memory#group-offloading
180
+ parser.add_argument("--enable_low_vram_mode", action="store_true")
181
+ parser.add_argument(
182
+ "--group_offloading_type",
183
+ type=str,
184
+ choices=["leaf_level", "block_level"],
185
+ default="leaf_level",
186
+ help="Specifies the granularity for group CPU offloading. Choose between 'leaf_level' (individual modules) or 'block_level' (entire blocks).",
187
+ )
188
+ parser.add_argument(
189
+ "--num_blocks_per_group",
190
+ type=str,
191
+ default="4",
192
+ help="The number of blocks to bundle together in each offloading group. Only relevant when using block-level offloading.",
193
+ )
194
+
195
+ return parser.parse_args()
196
+
197
+
198
+ def build_sample_output_dir(output_folder, prompt_or_prompts):
199
+ if isinstance(prompt_or_prompts, list):
200
+ prompt_text = prompt_or_prompts[0] if prompt_or_prompts else "prompt"
201
+ else:
202
+ prompt_text = prompt_or_prompts or "prompt"
203
+
204
+ prompt_text = str(prompt_text).strip()
205
+ safe_chars = []
206
+ previous_was_sep = False
207
+ for char in prompt_text:
208
+ if char.isalnum():
209
+ safe_chars.append(char)
210
+ previous_was_sep = False
211
+ elif not previous_was_sep:
212
+ safe_chars.append("_")
213
+ previous_was_sep = True
214
+
215
+ prompt_stem = "".join(safe_chars).strip("_")[:80] or "prompt"
216
+ sample_dir = Path(output_folder) / f"{prompt_stem}_{int(time.time())}"
217
+
218
+ suffix = 1
219
+ base_sample_dir = sample_dir
220
+ while sample_dir.exists():
221
+ sample_dir = Path(f"{base_sample_dir}_{suffix}")
222
+ suffix += 1
223
+
224
+ sample_dir.mkdir(parents=True, exist_ok=False)
225
+ return sample_dir
226
+
227
+
228
+ def save_relative_l1_outputs(records, output_folder):
229
+ if not records:
230
+ print(f"No relative L1 records for {output_folder}.")
231
+ return
232
+
233
+ metrics_dir = Path(output_folder)
234
+ metrics_dir.mkdir(parents=True, exist_ok=True)
235
+ df = pd.DataFrame(records).sort_values(["chunk_index", "step_index", "stage_index"])
236
+
237
+ csv_path = metrics_dir / "relative_l1.csv"
238
+ df.to_csv(csv_path, index=False)
239
+
240
+ try:
241
+ import matplotlib
242
+
243
+ matplotlib.use("Agg")
244
+ import matplotlib.pyplot as plt
245
+
246
+ def save_metric_plot(metric_name, ylabel, title, plot_name):
247
+ fig, ax = plt.subplots(figsize=(9, 5))
248
+ for chunk_index, chunk_df in df.groupby("chunk_index"):
249
+ chunk_df = chunk_df.sort_values(["step_index", "stage_index"])
250
+ ax.plot(
251
+ chunk_df["timestep"],
252
+ chunk_df[metric_name],
253
+ marker="o",
254
+ linewidth=1.5,
255
+ markersize=3,
256
+ label=f"chunk {chunk_index}",
257
+ )
258
+
259
+ ax.set_xlabel("timestep")
260
+ ax.set_ylabel(ylabel)
261
+ ax.set_title(title)
262
+ ax.grid(True, alpha=0.3)
263
+ ax.invert_xaxis()
264
+ ax.legend()
265
+ fig.tight_layout()
266
+
267
+ plot_path = metrics_dir / plot_name
268
+ fig.savefig(plot_path, dpi=200)
269
+ plt.close(fig)
270
+ return plot_path
271
+
272
+ plot_path = save_metric_plot(
273
+ "relative_l1",
274
+ "mean relative L1",
275
+ "Denoising relative L1 per chunk",
276
+ "relative_l1.png",
277
+ )
278
+ ratio_plot_path = None
279
+ if "relative_l1_ratio" in df.columns:
280
+ ratio_plot_path = save_metric_plot(
281
+ "relative_l1_ratio",
282
+ "mean(delta L1) / mean(latent L1)",
283
+ "Denoising relative L1 ratio per chunk",
284
+ "relative_l1_ratio.png",
285
+ )
286
+
287
+ if ratio_plot_path is None:
288
+ print(f"Saved relative L1 CSV to {csv_path} and plot to {plot_path}")
289
+ else:
290
+ print(f"Saved relative L1 CSV to {csv_path} and plots to {plot_path}, {ratio_plot_path}")
291
+ except Exception as exc:
292
+ print(f"Saved relative L1 CSV to {csv_path}, but failed to save plot: {exc}")
293
+
294
+
295
+ def main():
296
+ args = parse_args()
297
+
298
+ assert not (args.enable_low_vram_mode and args.enable_compile), (
299
+ "enable_low_vram_mode and enable_compile cannot be used together."
300
+ )
301
+
302
+ if args.weight_dtype == "fp32":
303
+ args.weight_dtype = torch.float32
304
+ elif args.weight_dtype == "fp16":
305
+ args.weight_dtype = torch.float16
306
+ else:
307
+ args.weight_dtype = torch.bfloat16
308
+
309
+ os.makedirs(args.output_folder, exist_ok=True)
310
+
311
+ if dist.is_available() and "RANK" in os.environ:
312
+ if args.cp_backend == "ulysses_anything":
313
+ dist.init_process_group(backend="cpu:gloo,cuda:nccl")
314
+ else:
315
+ dist.init_process_group(backend="nccl")
316
+ rank = dist.get_rank()
317
+ device = torch.device("cuda", rank % torch.cuda.device_count())
318
+ world_size = dist.get_world_size()
319
+ torch.cuda.set_device(device)
320
+ assert world_size == 1 or not args.enable_low_vram_mode, "enable_low_vram_mode is only for single GPU."
321
+ else:
322
+ rank = 0
323
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
324
+ world_size = 1
325
+
326
+ prompt = None
327
+ image_path = None
328
+ video_path = None
329
+ interpolate_time_list = None
330
+ if args.sample_type == "t2v" and args.prompt is None:
331
+ prompt = "An extreme close-up of an gray-haired man with a beard in his 60s, he is deep in thought pondering the history of the universe as he sits at a cafe in Paris, his eyes focus on people offscreen as they walk as he sits mostly motionless, he is dressed in a wool coat suit coat with a button-down shirt , he wears a brown beret and glasses and has a very professorial appearance, and the end he offers a subtle closed-mouth smile as if he found the answer to the mystery of life, the lighting is very cinematic with the golden light and the Parisian streets and city in the background, depth of field, cinematic 35mm film."
332
+ elif args.sample_type == "i2v" and (args.image_path is None and args.prompt is None):
333
+ image_path = (
334
+ "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/astronaut.jpg"
335
+ )
336
+ prompt = "An astronaut hatching from an egg, on the surface of the moon, the darkness and depth of space realised in the background. High quality, ultrarealistic detail and breath-taking movie-like camera shot."
337
+ elif args.sample_type == "v2v" and (args.video_path is None and args.prompt is None):
338
+ video_path = (
339
+ "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/hiker.mp4"
340
+ )
341
+ prompt = "A robot standing on a mountain top. The sun is setting in the background."
342
+ else:
343
+ image_path = args.image_path
344
+ video_path = args.video_path
345
+ prompt = args.prompt
346
+
347
+ transformer = HeliosTransformer3DModel.from_pretrained(
348
+ args.transformer_path,
349
+ subfolder="transformer",
350
+ torch_dtype=args.weight_dtype,
351
+ )
352
+ if not args.enable_compile:
353
+ transformer = replace_rmsnorm_with_fp32(transformer)
354
+ transformer = replace_all_norms_with_flash_norms(transformer)
355
+ replace_rope_with_flash_rope()
356
+ cuda_major = torch.cuda.get_device_capability()[0]
357
+ if cuda_major >= 9:
358
+ # H100/H800 (SM90+) with FA3
359
+ try:
360
+ transformer.set_attention_backend("_flash_3_hub")
361
+ except Exception:
362
+ transformer.set_attention_backend("flash_hub")
363
+ else:
364
+ # 4090/A100 etc (SM89+) with FA2
365
+ transformer.set_attention_backend("flash_hub")
366
+
367
+ vae = AutoencoderKLWan.from_pretrained(
368
+ args.base_model_path,
369
+ subfolder="vae",
370
+ torch_dtype=torch.float32,
371
+ )
372
+ scheduler = HeliosScheduler.from_pretrained(
373
+ args.base_model_path,
374
+ subfolder="scheduler",
375
+ )
376
+ pipe = HeliosPipeline.from_pretrained(
377
+ args.base_model_path,
378
+ transformer=transformer,
379
+ vae=vae,
380
+ scheduler=scheduler,
381
+ torch_dtype=args.weight_dtype,
382
+ )
383
+
384
+ if args.lora_path is not None:
385
+ pipe.load_lora_weights(args.lora_path, adapter_name="default")
386
+ pipe.set_adapters(["default"], adapter_weights=[1.0])
387
+
388
+ if args.partial_path is not None:
389
+ if not hasattr(args, "training_config"):
390
+ from argparse import Namespace
391
+
392
+ args.training_config = Namespace()
393
+ args.training_config.is_enable_stage1 = True
394
+ args.training_config.restrict_self_attn = True
395
+ args.training_config.is_amplify_history = True
396
+ args.training_config.is_use_gan = True
397
+ load_extra_components(args, transformer, args.partial_path)
398
+
399
+ if args.enable_compile:
400
+ torch.backends.cudnn.benchmark = True
401
+ pipe.text_encoder.compile(mode="max-autotune-no-cudagraphs", dynamic=False)
402
+ pipe.vae.compile(mode="max-autotune-no-cudagraphs", dynamic=False)
403
+ pipe.transformer.compile(mode="max-autotune-no-cudagraphs", dynamic=False)
404
+
405
+ if args.enable_low_vram_mode:
406
+ pipe.enable_group_offload(
407
+ onload_device=torch.device("cuda"),
408
+ offload_device=torch.device("cpu"),
409
+ offload_type=args.group_offloading_type,
410
+ num_blocks_per_group=args.num_blocks_per_group if args.group_offloading_type == "block_level" else None,
411
+ use_stream=True,
412
+ record_stream=True,
413
+ )
414
+ else:
415
+ pipe = pipe.to(device)
416
+
417
+ if world_size > 1 and args.enable_parallelism:
418
+ if args.cp_backend == "ring":
419
+ cp_config = ContextParallelConfig(ring_degree=world_size)
420
+ elif args.cp_backend == "unified":
421
+ cp_config = ContextParallelConfig(ring_degree=world_size // 2, ulysses_degree=world_size // 2)
422
+ elif args.cp_backend == "ulysses":
423
+ cp_config = ContextParallelConfig(ulysses_degree=world_size)
424
+ elif args.cp_backend == "ulysses_anything":
425
+ cp_config = ContextParallelConfig(ulysses_degree=world_size, ulysses_anything=True)
426
+ else:
427
+ raise ValueError(f"Unsupported cp_backend: {args.cp_backend}")
428
+
429
+ pipe.transformer.enable_parallelism(config=cp_config)
430
+
431
+ if args.prompt_txt_path is not None:
432
+ with open(args.prompt_txt_path, "r") as f:
433
+ prompt_list = [line.strip() for line in f.readlines() if line.strip()]
434
+ if not args.enable_parallelism:
435
+ prompt_list_with_idx = [(i, prompt) for i, prompt in enumerate(prompt_list)]
436
+ prompt_list_with_idx = prompt_list_with_idx[rank::world_size]
437
+ else:
438
+ prompt_list_with_idx = [(i, prompt) for i, prompt in enumerate(prompt_list)]
439
+
440
+ for idx, prompt in tqdm(prompt_list_with_idx, desc="Processing prompts"):
441
+ with torch.no_grad():
442
+ try:
443
+ pipe_output = pipe(
444
+ prompt=prompt,
445
+ negative_prompt=args.negative_prompt,
446
+ height=args.height,
447
+ width=args.width,
448
+ num_frames=args.num_frames,
449
+ num_inference_steps=args.num_inference_steps,
450
+ guidance_scale=args.guidance_scale,
451
+ generator=torch.Generator(device="cuda").manual_seed(args.seed),
452
+ # stage 1
453
+ history_sizes=[16, 2, 1],
454
+ num_latent_frames_per_chunk=args.num_latent_frames_per_chunk,
455
+ keep_first_frame=True,
456
+ # stage 2
457
+ is_enable_stage2=args.is_enable_stage2,
458
+ pyramid_num_inference_steps_list=args.pyramid_num_inference_steps_list,
459
+ # stage 3
460
+ is_skip_first_chunk=args.is_skip_first_chunk,
461
+ is_amplify_first_chunk=args.is_amplify_first_chunk,
462
+ # cfg zero
463
+ use_zero_init=args.use_zero_init,
464
+ zero_steps=args.zero_steps,
465
+ # i2v
466
+ image=load_image(image_path).resize((args.width, args.height))
467
+ if image_path is not None
468
+ else None,
469
+ image_noise_sigma_min=args.image_noise_sigma_min,
470
+ image_noise_sigma_max=args.image_noise_sigma_max,
471
+ # v2v
472
+ video=load_video(video_path) if video_path is not None else None,
473
+ video_noise_sigma_min=args.video_noise_sigma_min,
474
+ video_noise_sigma_max=args.video_noise_sigma_max,
475
+ # interpolate_prompt
476
+ use_interpolate_prompt=args.use_interpolate_prompt,
477
+ interpolation_steps=args.interpolation_steps,
478
+ interpolate_time_list=interpolate_time_list,
479
+ output_relative_l1=args.visualize_relative_l1,
480
+ )
481
+ output = pipe_output.frames[0]
482
+ except Exception:
483
+ continue
484
+ if not args.enable_parallelism or rank == 0:
485
+ sample_dir = build_sample_output_dir(args.output_folder, prompt)
486
+ output_path = sample_dir / "video.mp4"
487
+ export_to_video(output, str(output_path), fps=24)
488
+ if args.visualize_relative_l1:
489
+ save_relative_l1_outputs(pipe_output.relative_l1, sample_dir)
490
+ elif args.image_prompt_csv_path is not None:
491
+ df = pd.read_csv(args.image_prompt_csv_path)
492
+ if not args.enable_parallelism:
493
+ df = df.iloc[rank::world_size]
494
+
495
+ for idx, row in tqdm(df.iterrows(), total=len(df), desc="Processing prompts"):
496
+ prompt = row.get("refined_prompt") or row["prompt"]
497
+ image_path = os.path.join(args.base_image_prompt_path, row["image_name"])
498
+
499
+ with torch.no_grad():
500
+ try:
501
+ pipe_output = pipe(
502
+ prompt=prompt,
503
+ negative_prompt=args.negative_prompt,
504
+ height=args.height,
505
+ width=args.width,
506
+ num_frames=args.num_frames,
507
+ num_inference_steps=args.num_inference_steps,
508
+ guidance_scale=args.guidance_scale,
509
+ generator=torch.Generator(device="cuda").manual_seed(args.seed),
510
+ # stage 1
511
+ history_sizes=[16, 2, 1],
512
+ num_latent_frames_per_chunk=args.num_latent_frames_per_chunk,
513
+ keep_first_frame=True,
514
+ # stage 2
515
+ is_enable_stage2=args.is_enable_stage2,
516
+ pyramid_num_inference_steps_list=args.pyramid_num_inference_steps_list,
517
+ # stage 3
518
+ is_skip_first_chunk=args.is_skip_first_chunk,
519
+ is_amplify_first_chunk=args.is_amplify_first_chunk,
520
+ # cfg zero
521
+ use_zero_init=args.use_zero_init,
522
+ zero_steps=args.zero_steps,
523
+ # i2v
524
+ image=load_image(image_path).resize((args.width, args.height))
525
+ if image_path is not None
526
+ else None,
527
+ image_noise_sigma_min=args.image_noise_sigma_min,
528
+ image_noise_sigma_max=args.image_noise_sigma_max,
529
+ # v2v
530
+ video=load_video(video_path) if video_path is not None else None,
531
+ video_noise_sigma_min=args.video_noise_sigma_min,
532
+ video_noise_sigma_max=args.video_noise_sigma_max,
533
+ # interpolate_prompt
534
+ use_interpolate_prompt=args.use_interpolate_prompt,
535
+ interpolation_steps=args.interpolation_steps,
536
+ interpolate_time_list=interpolate_time_list,
537
+ output_relative_l1=args.visualize_relative_l1,
538
+ )
539
+ output = pipe_output.frames[0]
540
+ except Exception:
541
+ continue
542
+ if not args.enable_parallelism or rank == 0:
543
+ sample_dir = build_sample_output_dir(args.output_folder, prompt)
544
+ output_path = sample_dir / "video.mp4"
545
+ export_to_video(output, str(output_path), fps=24)
546
+ if args.visualize_relative_l1:
547
+ save_relative_l1_outputs(pipe_output.relative_l1, sample_dir)
548
+ elif args.interactive_prompt_csv_path is not None:
549
+ df = pd.read_csv(args.interactive_prompt_csv_path)
550
+
551
+ df = df.sort_values(by=["id", "prompt_index"])
552
+ all_video_ids = df["id"].unique()
553
+
554
+ if not args.enable_parallelism:
555
+ my_video_ids = all_video_ids[rank::world_size]
556
+ else:
557
+ my_video_ids = all_video_ids
558
+
559
+ for video_id in tqdm(my_video_ids, desc="Processing prompts"):
560
+ group_df = df[df["id"] == video_id]
561
+
562
+ if "refined_prompt" in df.columns:
563
+ prompt_list = group_df["refined_prompt"].fillna(group_df["prompt"]).tolist()
564
+ else:
565
+ prompt_list = group_df["prompt"].tolist()
566
+ interpolate_time_list = [args.interpolate_time] * len(prompt_list)
567
+
568
+ with torch.no_grad():
569
+ try:
570
+ pipe_output = pipe(
571
+ prompt=prompt_list,
572
+ negative_prompt=args.negative_prompt,
573
+ height=args.height,
574
+ width=args.width,
575
+ num_frames=args.num_frames,
576
+ num_inference_steps=args.num_inference_steps,
577
+ guidance_scale=args.guidance_scale,
578
+ generator=torch.Generator(device="cuda").manual_seed(args.seed),
579
+ # stage 1
580
+ history_sizes=[16, 2, 1],
581
+ num_latent_frames_per_chunk=args.num_latent_frames_per_chunk,
582
+ keep_first_frame=True,
583
+ # stage 2
584
+ is_enable_stage2=args.is_enable_stage2,
585
+ pyramid_num_inference_steps_list=args.pyramid_num_inference_steps_list,
586
+ # stage 3
587
+ is_skip_first_chunk=args.is_skip_first_chunk,
588
+ is_amplify_first_chunk=args.is_amplify_first_chunk,
589
+ # cfg zero
590
+ use_zero_init=args.use_zero_init,
591
+ zero_steps=args.zero_steps,
592
+ # i2v
593
+ image=load_image(image_path).resize((args.width, args.height))
594
+ if image_path is not None
595
+ else None,
596
+ image_noise_sigma_min=args.image_noise_sigma_min,
597
+ image_noise_sigma_max=args.image_noise_sigma_max,
598
+ # v2v
599
+ video=load_video(video_path) if video_path is not None else None,
600
+ video_noise_sigma_min=args.video_noise_sigma_min,
601
+ video_noise_sigma_max=args.video_noise_sigma_max,
602
+ # interpolate_prompt
603
+ use_interpolate_prompt=args.use_interpolate_prompt,
604
+ interpolation_steps=args.interpolation_steps,
605
+ interpolate_time_list=interpolate_time_list,
606
+ output_relative_l1=args.visualize_relative_l1,
607
+ )
608
+ output = pipe_output.frames[0]
609
+ except Exception:
610
+ continue
611
+ if not args.enable_parallelism or rank == 0:
612
+ sample_dir = build_sample_output_dir(args.output_folder, prompt_list)
613
+ output_path = sample_dir / "video.mp4"
614
+ export_to_video(output, str(output_path), fps=24)
615
+ if args.visualize_relative_l1:
616
+ save_relative_l1_outputs(pipe_output.relative_l1, sample_dir)
617
+ else:
618
+ with torch.no_grad():
619
+ # import time
620
+ # for _ in range(20):
621
+ # start_time = time.time()
622
+ pipe_output = pipe(
623
+ prompt=prompt,
624
+ negative_prompt=args.negative_prompt,
625
+ height=args.height,
626
+ width=args.width,
627
+ num_frames=args.num_frames,
628
+ num_inference_steps=args.num_inference_steps,
629
+ guidance_scale=args.guidance_scale,
630
+ generator=torch.Generator(device="cuda").manual_seed(args.seed),
631
+ # stage 1
632
+ history_sizes=[16, 2, 1],
633
+ num_latent_frames_per_chunk=args.num_latent_frames_per_chunk,
634
+ keep_first_frame=True,
635
+ # stage 2
636
+ is_enable_stage2=args.is_enable_stage2,
637
+ pyramid_num_inference_steps_list=args.pyramid_num_inference_steps_list,
638
+ # stage 3
639
+ is_skip_first_chunk=args.is_skip_first_chunk,
640
+ is_amplify_first_chunk=args.is_amplify_first_chunk,
641
+ # cfg zero
642
+ use_zero_init=args.use_zero_init,
643
+ zero_steps=args.zero_steps,
644
+ # i2v
645
+ image=load_image(image_path).resize((args.width, args.height)) if image_path is not None else None,
646
+ image_noise_sigma_min=args.image_noise_sigma_min,
647
+ image_noise_sigma_max=args.image_noise_sigma_max,
648
+ # v2v
649
+ video=load_video(video_path) if video_path is not None else None,
650
+ video_noise_sigma_min=args.video_noise_sigma_min,
651
+ video_noise_sigma_max=args.video_noise_sigma_max,
652
+ # interpolate_prompt
653
+ use_interpolate_prompt=args.use_interpolate_prompt,
654
+ interpolation_steps=args.interpolation_steps,
655
+ interpolate_time_list=interpolate_time_list,
656
+ output_relative_l1=args.visualize_relative_l1,
657
+ )
658
+ output = pipe_output.frames[0]
659
+ # elapsed_time = time.time() - start_time
660
+ # print(f"Inference time: {elapsed_time:.2f} seconds ({elapsed_time/60:.2f} minutes)")
661
+
662
+ if not args.enable_parallelism or rank == 0:
663
+ sample_dir = build_sample_output_dir(args.output_folder, prompt)
664
+ output_path = sample_dir / "video.mp4"
665
+ export_to_video(output, str(output_path), fps=24)
666
+ if args.visualize_relative_l1:
667
+ save_relative_l1_outputs(pipe_output.relative_l1, sample_dir)
668
+
669
+ print(f"Max memory: {torch.cuda.max_memory_allocated() / 1024**3:.3f} GB")
670
+
671
+
672
+ if __name__ == "__main__":
673
+ main()
Helios/_DEV2/install.sh ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ pip install -r requirements.txt
2
+
3
+ rm -rf ~/.triton/cache/
4
+ rm -rf /tmp/torchinductor_*
5
+
6
+ pip uninstall triton torchao xformers wandb tensorflow tensorflow-cpu -y
7
+ pip install wandb==0.23.0 triton==3.6.0
8
+
9
+ rm -rf ~/.triton/cache/
10
+ rm -rf /tmp/torchinductor_*
Helios/_DEV2/requirements.txt ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ torch==2.10.0
2
+ torchvision==0.25.0
3
+ torchaudio==2.10.0
4
+ triton==3.6.0
5
+ kernels==0.13.0
6
+ # diffusers==0.36.0
7
+ # transformers==4.57.6
8
+ git+https://github.com/huggingface/diffusers.git
9
+ transformers==5.3.0
10
+ sentence-transformers==5.2.3
11
+ accelerate==1.12.0
12
+ deepspeed==0.18.4
13
+ peft==0.18.1
14
+ huggingface-hub==1.4.1
15
+ zstandard==0.25.0
16
+ wandb==0.23.0
17
+ video-reader-rs==0.4.1
18
+ numpy<2.0.0
19
+ opencv-python
20
+ gradio
21
+ spaces
22
+ moviepy
23
+ imageio-ffmpeg
24
+ ftfy
25
+ Jinja2
26
+ einops
27
+ nvitop
28
+ packaging
29
+ ninja
30
+ omegaconf
31
+ mpi4py
32
+ hf-doc-builder
33
+ torchdata
34
+ loguru
35
+ tf_keras
Helios/_DEV2/requirements_npu.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ # Please refer to here for installation the latest version: https://github.com/Ascend/pytorch?tab=readme-ov-file#ascend-auxiliary-software
2
+ torch==2.9.0
3
+ torchvision==0.24.0
4
+ torchaudio==2.9.0
5
+ torch_npu==2.9.0
6
+ triton==3.5.1
Helios/_DEV2/run_bench.sh ADDED
@@ -0,0 +1,275 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # =============================================================================
3
+ # Helios Benchmark Inference Runner
4
+ # 用法: bash run_bench.sh [--gpus 5 6 7] [--prompt_range 0-50] [--num_frames 240]
5
+ # [--version base] [--version mid distilled]
6
+ # 默认使用所有可见 GPU;默认跑全部版本(base/mid/distilled),也可手动指定版本
7
+ # 同一时刻只跑一个版本;若有多张卡,会先扫描输出目录,只把缺失 case 均分到多张卡并行
8
+ # 低显存: LOW_VRAM=1 bash run_bench.sh
9
+ # =============================================================================
10
+ set -euo pipefail
11
+
12
+ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
13
+ if [[ -n "${PYTHON:-}" ]]; then
14
+ PYTHON_BIN="${PYTHON}"
15
+ elif command -v python3 >/dev/null 2>&1; then
16
+ PYTHON_BIN="$(command -v python3)"
17
+ elif command -v python >/dev/null 2>&1; then
18
+ PYTHON_BIN="$(command -v python)"
19
+ else
20
+ echo "Python interpreter not found. Set PYTHON=/path/to/python." >&2
21
+ exit 1
22
+ fi
23
+
24
+ GPUS=()
25
+ PROMPT_START="${PROMPT_START:-0}"
26
+ PROMPT_END="${PROMPT_END:-100}"
27
+ NUM_FRAMES="${NUM_FRAMES:-}"
28
+ VERSIONS=(base mid distilled)
29
+ OUTPUT_ROOT="${OUTPUT_ROOT:-}"
30
+ PROMPT_FILE="${PROMPT_FILE:-${SCRIPT_DIR}/demo_data/MovieGenVideoBench_extended.txt}"
31
+ LOW_VRAM="${LOW_VRAM:-0}"
32
+
33
+ discover_gpus() {
34
+ if ! command -v nvidia-smi >/dev/null 2>&1; then
35
+ echo "nvidia-smi not found; use --gpus to specify GPU ids explicitly." >&2
36
+ exit 1
37
+ fi
38
+
39
+ mapfile -t GPUS < <(nvidia-smi --query-gpu=index --format=csv,noheader,nounits)
40
+ if [[ ${#GPUS[@]} -eq 0 ]]; then
41
+ echo "No GPUs found." >&2
42
+ exit 1
43
+ fi
44
+ }
45
+
46
+ while [[ $# -gt 0 ]]; do
47
+ case "$1" in
48
+ --gpus) shift; GPUS=(); while [[ $# -gt 0 && ! "$1" =~ ^-- ]]; do GPUS+=("$1"); shift; done ;;
49
+ --prompt_range)
50
+ if [[ ! "$2" =~ ^([0-9]+)-([0-9]+)$ ]]; then
51
+ echo "Invalid --prompt_range: $2 (expected START-END, e.g. 0-50)" >&2
52
+ exit 1
53
+ fi
54
+ PROMPT_START="${BASH_REMATCH[1]}"
55
+ PROMPT_END="${BASH_REMATCH[2]}"
56
+ shift 2
57
+ ;;
58
+ --prompt_start) PROMPT_START="$2"; shift 2 ;;
59
+ --prompt_end) PROMPT_END="$2"; shift 2 ;;
60
+ --num_frames) NUM_FRAMES="$2"; shift 2 ;;
61
+ --version) shift; VERSIONS=(); while [[ $# -gt 0 && ! "$1" =~ ^-- ]]; do VERSIONS+=("$1"); shift; done ;;
62
+ --output_root) OUTPUT_ROOT="$2"; shift 2 ;;
63
+ --prompt_file) PROMPT_FILE="$2"; shift 2 ;;
64
+ *) echo "Unknown option: $1"; exit 1 ;;
65
+ esac
66
+ done
67
+
68
+ if [[ ${#GPUS[@]} -eq 0 ]]; then
69
+ discover_gpus
70
+ fi
71
+
72
+ if [[ ${#VERSIONS[@]} -eq 0 ]]; then
73
+ echo "No versions specified. Use --version base [mid distilled]." >&2
74
+ exit 1
75
+ fi
76
+
77
+ if [[ ! "${PROMPT_START}" =~ ^[0-9]+$ ]] || [[ ! "${PROMPT_END}" =~ ^[0-9]+$ ]]; then
78
+ echo "prompt_start and prompt_end must be non-negative integers." >&2
79
+ exit 1
80
+ fi
81
+
82
+ if (( PROMPT_END <= PROMPT_START )); then
83
+ echo "prompt_end must be greater than prompt_start." >&2
84
+ exit 1
85
+ fi
86
+
87
+ if [[ -z "${OUTPUT_ROOT}" ]]; then
88
+ if [[ -n "${NUM_FRAMES}" ]]; then
89
+ OUTPUT_ROOT="${SCRIPT_DIR}/outputs/num_frames_${NUM_FRAMES}"
90
+ else
91
+ OUTPUT_ROOT="${SCRIPT_DIR}/outputs/num_frames_default"
92
+ fi
93
+ fi
94
+
95
+ echo "============================================================"
96
+ echo " Helios Benchmark Inference"
97
+ echo " $(date '+%Y-%m-%d %H:%M:%S')"
98
+ echo " Python: ${PYTHON_BIN}"
99
+ echo " GPUs: ${GPUS[*]} | Prompt range: ${PROMPT_START}-${PROMPT_END} | Versions: ${VERSIONS[*]}"
100
+ [[ -n "${NUM_FRAMES}" ]] && echo " Frames: ${NUM_FRAMES}"
101
+ echo " Prompt file: ${PROMPT_FILE}"
102
+ echo " Output: ${OUTPUT_ROOT}"
103
+ echo "============================================================"
104
+
105
+ mkdir -p "${OUTPUT_ROOT}"
106
+
107
+ if [[ ! -f "${PROMPT_FILE}" ]]; then
108
+ echo "Prompt file not found: ${PROMPT_FILE}" >&2
109
+ exit 1
110
+ fi
111
+
112
+ TOTAL_PROMPTS=$(awk 'NF {count++} END {print count + 0}' "${PROMPT_FILE}")
113
+ if (( PROMPT_START >= TOTAL_PROMPTS )); then
114
+ echo "prompt_start (${PROMPT_START}) is out of range; prompt file has ${TOTAL_PROMPTS} non-empty prompts." >&2
115
+ exit 1
116
+ fi
117
+
118
+ if (( PROMPT_END > TOTAL_PROMPTS )); then
119
+ echo "prompt_end (${PROMPT_END}) exceeds total prompts (${TOTAL_PROMPTS}); clamping to ${TOTAL_PROMPTS}."
120
+ PROMPT_END="${TOTAL_PROMPTS}"
121
+ fi
122
+
123
+ EXTRA=()
124
+ if [[ "${LOW_VRAM}" == "1" ]]; then
125
+ EXTRA+=(--enable_low_vram_mode)
126
+ fi
127
+ if [[ -n "${NUM_FRAMES}" ]]; then
128
+ EXTRA+=(--num_frames "${NUM_FRAMES}")
129
+ fi
130
+
131
+ EXIT_CODE=0
132
+ WORKER_PIDS=()
133
+ WORKER_GPUS=()
134
+ WORKER_SHARDS=()
135
+
136
+ prepare_missing_shards() {
137
+ local version="$1"
138
+ local shard_dir="${OUTPUT_ROOT}/shards/${version}_${PROMPT_START}_${PROMPT_END}_$$"
139
+ mkdir -p "${shard_dir}"
140
+
141
+ "${PYTHON_BIN}" - \
142
+ "${PROMPT_FILE}" \
143
+ "${OUTPUT_ROOT}" \
144
+ "${version}" \
145
+ "${PROMPT_START}" \
146
+ "${PROMPT_END}" \
147
+ "${#GPUS[@]}" \
148
+ "${shard_dir}" <<'PY'
149
+ import os
150
+ import re
151
+ import sys
152
+ from pathlib import Path
153
+
154
+ prompt_file = Path(sys.argv[1])
155
+ output_root = Path(sys.argv[2])
156
+ version = sys.argv[3]
157
+ prompt_start = int(sys.argv[4])
158
+ prompt_end = int(sys.argv[5])
159
+ gpu_count = int(sys.argv[6])
160
+ shard_dir = Path(sys.argv[7])
161
+
162
+ with prompt_file.open("r", encoding="utf-8") as f:
163
+ prompts = [line.strip() for line in f if line.strip()]
164
+
165
+ def sanitize_filename(text, max_len=80):
166
+ text = text.strip().lower()
167
+ text = re.sub(r"[^a-z0-9]+", "_", text)
168
+ text = text.strip("_")
169
+ return text[:max_len]
170
+
171
+ missing = []
172
+ existing = 0
173
+ version_dir = output_root / "by_version" / version
174
+ for idx in range(prompt_start, prompt_end):
175
+ slug = sanitize_filename(prompts[idx])
176
+ video_path = version_dir / f"{idx:04d}_{slug}.mp4"
177
+ if video_path.is_file() and video_path.stat().st_size > 0:
178
+ existing += 1
179
+ else:
180
+ missing.append(idx)
181
+
182
+ print(
183
+ f"[scan] version={version} range={prompt_start}-{prompt_end} "
184
+ f"existing={existing} missing={len(missing)} output={version_dir}",
185
+ file=sys.stderr,
186
+ )
187
+
188
+ if not missing:
189
+ sys.exit(0)
190
+
191
+ active_workers = min(gpu_count, len(missing))
192
+ base_chunk = len(missing) // active_workers
193
+ remainder = len(missing) % active_workers
194
+ offset = 0
195
+
196
+ for shard_idx in range(active_workers):
197
+ shard_size = base_chunk + (1 if shard_idx < remainder else 0)
198
+ shard_indices = missing[offset:offset + shard_size]
199
+ offset += shard_size
200
+ shard_path = shard_dir / f"shard_{shard_idx:02d}.txt"
201
+ shard_path.write_text(
202
+ "".join(f"{idx}\n" for idx in shard_indices),
203
+ encoding="utf-8",
204
+ )
205
+ print(shard_path)
206
+ print(
207
+ f"[shard] version={version} shard={shard_idx} count={len(shard_indices)} "
208
+ f"indices={shard_indices[0]}-{shard_indices[-1]} file={shard_path}",
209
+ file=sys.stderr,
210
+ )
211
+ PY
212
+ }
213
+
214
+ launch_job() {
215
+ local version="$1"
216
+ local gpu="$2"
217
+ local shard_file="$3"
218
+ local shard_id
219
+ shard_id="$(basename "${shard_file}" .txt)"
220
+ local timing_file="${OUTPUT_ROOT}/timing_${version}_${shard_id}.txt"
221
+
222
+ echo "[launch] version=${version} gpu=${gpu} shard=${shard_id} indices=${shard_file} output=${OUTPUT_ROOT}"
223
+ "${PYTHON_BIN}" "${SCRIPT_DIR}/bench_infer.py" \
224
+ --prompt_file "${PROMPT_FILE}" \
225
+ --prompt_start "${PROMPT_START}" \
226
+ --prompt_end "${PROMPT_END}" \
227
+ --prompt_indices_file "${shard_file}" \
228
+ --output_root "${OUTPUT_ROOT}" \
229
+ --timing_file "${timing_file}" \
230
+ --version "${version}" \
231
+ --gpu "${gpu}" \
232
+ "${EXTRA[@]}" &
233
+
234
+ WORKER_PIDS+=("$!")
235
+ WORKER_GPUS+=("${gpu}")
236
+ WORKER_SHARDS+=("${shard_id}")
237
+ }
238
+
239
+ wait_for_current_version() {
240
+ local version="$1"
241
+ for idx in "${!WORKER_PIDS[@]}"; do
242
+ local pid="${WORKER_PIDS[$idx]}"
243
+ local gpu="${WORKER_GPUS[$idx]}"
244
+ local shard_id="${WORKER_SHARDS[$idx]}"
245
+ if wait "${pid}"; then
246
+ echo "[done] ${version} finished on gpu=${gpu} shard=${shard_id}"
247
+ else
248
+ echo "[fail] ${version} failed on gpu=${gpu} shard=${shard_id}"
249
+ EXIT_CODE=1
250
+ fi
251
+ done
252
+ WORKER_PIDS=()
253
+ WORKER_GPUS=()
254
+ WORKER_SHARDS=()
255
+ }
256
+
257
+ for version in "${VERSIONS[@]}"; do
258
+ echo ""
259
+ echo "-------------------- version=${version} --------------------"
260
+ mapfile -t SHARD_FILES < <(prepare_missing_shards "${version}")
261
+ if (( ${#SHARD_FILES[@]} == 0 )); then
262
+ echo "[skip] version=${version} has no missing cases in ${PROMPT_START}-${PROMPT_END}"
263
+ continue
264
+ fi
265
+
266
+ for worker_idx in "${!SHARD_FILES[@]}"; do
267
+ launch_job "${version}" "${GPUS[$worker_idx]}" "${SHARD_FILES[$worker_idx]}"
268
+ done
269
+ wait_for_current_version "${version}"
270
+ done
271
+
272
+ echo ""
273
+ echo "Done. Per-shard timing reports are under ${OUTPUT_ROOT}/timing_<version>_shard_<id>.txt"
274
+
275
+ exit ${EXIT_CODE:-0}
Helios/_DEV2/train_helios.py ADDED
The diff for this file is too large to render. See raw diff
 
Helios/_DEV3/.codex ADDED
File without changes
Helios/_DEV3/.gitignore ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.py[cod]
2
+ *.gif
3
+ *.bmp
4
+ *.mov
5
+ *.mkv
6
+ *.log
7
+ *.zip
8
+ *.pt
9
+ *.pth
10
+ *.ckpt
11
+ *.safetensors
12
+ *.backup
13
+ *.pt
14
+ *.pth
15
+ *.ckpt
16
+ *.pkl
17
+ *.html
18
+ *.pdf
19
+ *.whl
20
+ *.txt.gz
21
+ !.gitignore
22
+ !requirements.txt
23
+ .DS_Store
24
+ *DS_Store
25
+ poetry.lock
26
+ __pycache__/
27
+ *.cache*
28
+ *temp_path*
29
+ *_ckpt
30
+ *_results
31
+ *temp
32
+ *.pem
33
+ *profile
34
+ .gradio
35
+ ablation_*
36
+ cache
37
+ wandb
38
+ output_helios
39
+ AMT-S.yaml
40
+ bpe_simple_vocab_16e6.txt
41
+ Videoreward
42
+ 1_formal_ckpts
43
+ demo_data
Helios/_DEV3/LICENSE.txt ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
Helios/_DEV3/README.md ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # _DEV3 Token Dynamics Debug
2
+
3
+ 分析 **short history 最近一帧** 与 **current chunk 第一帧(noise frame)** 之间 token 的匹配关系,以及去噪过程中 token 变化率的对比。
4
+
5
+ ## 实现逻辑
6
+
7
+ 1. **最后一步开始时匹配**(基于 patch 后的 latent token)
8
+ 在 denoise 最后一步的 forward 开始时,取:
9
+ - short history 最近一帧(默认 `history_frame=-1` → 第 2 帧)
10
+ - current chunk 第一帧(默认 `noise_frame=0`)
11
+ 对 noise 帧每个 token,在历史帧中找 **cos 相似度最高** 的 token 作为匹配。
12
+
13
+ 2. **去噪过程变化率**(基于 patch 后 latent token)
14
+ 只记录调试需要的两帧(默认 `CHUNKS=1`:`history_frame=-1` + `noise_frame=0`):
15
+ - chunk 0 **最后一帧**(将作为 history)
16
+ - chunk 1 **第 0 帧**(将作为 noise)
17
+ 各自去噪时逐步记录:
18
+ ```text
19
+ change_rate(token) = (||token_t|| - ||token_{t-1}||) / ||token_t||
20
+ ```
21
+ 在 chunk 1 最后一步做 cos 匹配后,按匹配 token 对比两条曲线。
22
+
23
+ 3. **可视化**
24
+ - 变化率曲线:每一对匹配 token 一张图,两根曲线(history / noise 逐步变化率)
25
+ - 匹配帧空间图:chunk 去噪**完成后**,用 fully-denoised latent 经 VAE decode,左 history、右 noise,框出 cos 匹配 token 对
26
+
27
+ ## 运行
28
+
29
+ ```bash
30
+ cd _DEV3
31
+ CUDA_VISIBLE_DEVICES=0 bash scripts/inference/run_token_dynamics_debug.sh
32
+ ```
33
+
34
+ 常用环境变量:
35
+
36
+ | 变量 | 默认 | 说明 |
37
+ |------|------|------|
38
+ | `CHUNKS` | `1` | 分析哪个 chunk(需 `NUM_FRAMES>=66` 才有 chunk 1) |
39
+ | `HISTORY_FRAME` | `-1` | short history 帧索引(-1=最后一帧) |
40
+ | `NOISE_FRAME` | `0` | current chunk 帧索引(0=第一帧) |
41
+ | `VIS_STRIDE` | `16` | 每 N 个 token 画一对图 |
42
+ | `VIS_MAX_PAIRS` | `32` | 最多画多少对 |
43
+
44
+ ## 输出
45
+
46
+ - `output_helios/token_dynamics_debug/token_dynamics_debug_video.mp4`
47
+ - `output_helios/token_dynamics_debug/artifacts/token_dynamics_chunk*.pt`
48
+ - `output_helios/token_dynamics_debug/artifacts/*_pair_*.png` — 每对 token 双曲线图
49
+ - `output_helios/token_dynamics_debug/artifacts/*_mean_summary.png` — 全体均值对比
50
+ - `output_helios/token_dynamics_debug/artifacts/*_match_frames/noise*.png` — 每个 noise token 一张图:左 history 前一帧,右 noise0,分别框出匹配 token
51
+
52
+ 单独跑匹配帧可视化(默认保存全部 960 个 noise token):
53
+
54
+ ```bash
55
+ python tools/visualize_token_match_frames.py \
56
+ output_helios/token_dynamics_debug/artifacts/token_dynamics_chunk1_hist-1_noise0_cond.pt \
57
+ --model-path ./checkpoints/Helios-Base \
58
+ --tokens "4:0,10:16" # 可选:只画指定 token
59
+ ```
60
+
61
+ ## 代码位置
62
+
63
+ - `helios/utils/token_dynamics_debug.py` — 匹配与变化率核心逻辑
64
+ - `helios/diffusers_version/transformer_helios_diffusers.py` — forward hook
65
+ - `helios/diffusers_version/pipeline_helios_diffusers.py` — pipeline 参数 `token_dynamics_debug`
66
+ - `tools/visualize_token_dynamics.py` — 变化率曲线可视化
67
+ - `tools/visualize_token_match_frames.py` — 匹配帧空间可视化(VAE decode + 框选 token)
Helios/_DEV3/app.py ADDED
@@ -0,0 +1,322 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import tempfile
2
+ import time
3
+ from pathlib import Path
4
+
5
+ import gradio as gr
6
+ import spaces
7
+ import torch
8
+
9
+ from torch.utils._pytree import tree_map
10
+ from diffusers import AutoencoderKLWan, HeliosDMDScheduler, HeliosPyramidPipeline
11
+ from diffusers.utils import export_to_video, load_image, load_video
12
+
13
+
14
+ # ---------------------------------------------------------------------------
15
+ # Pre-load model
16
+ # ---------------------------------------------------------------------------
17
+ PROJECT_ROOT = Path(__file__).resolve().parent
18
+ MODEL_ID = str(PROJECT_ROOT / "checkpoints" / "Helios-Distilled")
19
+
20
+ vae = AutoencoderKLWan.from_pretrained(MODEL_ID, subfolder="vae", torch_dtype=torch.float32)
21
+ scheduler = HeliosDMDScheduler.from_pretrained(MODEL_ID, subfolder="scheduler")
22
+ pipe = HeliosPyramidPipeline.from_pretrained(
23
+ MODEL_ID, vae=vae, scheduler=scheduler, torch_dtype=torch.bfloat16, is_distilled=True
24
+ )
25
+ pipe.to("cuda")
26
+
27
+ cuda_major = torch.cuda.get_device_capability()[0]
28
+ if cuda_major >= 9:
29
+ # H100/H800 (SM90+) with FA3
30
+ try:
31
+ pipe.transformer.set_attention_backend("_flash_3_hub")
32
+ except Exception:
33
+ pipe.transformer.set_attention_backend("flash_hub")
34
+ else:
35
+ # 4090/A100 etc (SM89+) with FA2
36
+ pipe.transformer.set_attention_backend("flash_hub")
37
+
38
+ # ---------------------------------------------------------------------------
39
+ # AoTI
40
+ # ---------------------------------------------------------------------------
41
+
42
+ # Dynamic shapes: within a generation, only hidden_states H/W change across
43
+ # pyramid stages (history latents stay at full resolution). text_seq_length
44
+ # varies between different prompts.
45
+ _AUTO = torch.export.Dim.AUTO
46
+
47
+ TRANSFORMER_DYNAMIC_SHAPES = {
48
+ "hidden_states": {
49
+ 3: _AUTO, # H — doubles each pyramid stage
50
+ 4: _AUTO, # W — doubles each pyramid stage
51
+ },
52
+ "encoder_hidden_states": {
53
+ 1: _AUTO, # text_seq_length — varies with prompt
54
+ },
55
+ }
56
+
57
+ INDUCTOR_CONFIGS = {
58
+ "conv_1x1_as_mm": True,
59
+ "epilogue_fusion": False,
60
+ "coordinate_descent_tuning": True,
61
+ "coordinate_descent_check_all_directions": True,
62
+ # "max_autotune": True,
63
+ "triton.cudagraphs": True,
64
+ }
65
+
66
+ @spaces.GPU(duration=1500) # maximum duration allowed during startup
67
+ def compile_transformer():
68
+ with spaces.aoti_capture(pipe.transformer) as call:
69
+ pipe(
70
+ "arbitrary example prompt",
71
+ height=384,
72
+ width=640,
73
+ num_frames=33,
74
+ guidance_scale=1.0,
75
+ generator=torch.Generator(device="cuda").manual_seed(42),
76
+ pyramid_num_inference_steps_list=[2, 2, 2],
77
+ is_amplify_first_chunk=True,
78
+ )
79
+
80
+ dynamic_shapes = tree_map(lambda t: None, call.kwargs)
81
+ dynamic_shapes |= TRANSFORMER_DYNAMIC_SHAPES
82
+
83
+ with torch.no_grad():
84
+ exported = torch.export.export(
85
+ pipe.transformer,
86
+ args=call.args,
87
+ kwargs=call.kwargs,
88
+ dynamic_shapes=dynamic_shapes,
89
+ )
90
+
91
+ return spaces.aoti_compile(exported, INDUCTOR_CONFIGS)
92
+
93
+ compiled_transformer = compile_transformer()
94
+ spaces.aoti_apply(compiled_transformer, pipe.transformer)
95
+
96
+
97
+ # ---------------------------------------------------------------------------
98
+ # Generation
99
+ # ---------------------------------------------------------------------------
100
+ @spaces.GPU(duration=60)
101
+ def generate_video(
102
+ mode: str,
103
+ prompt: str,
104
+ image_input,
105
+ video_input,
106
+ height: int,
107
+ width: int,
108
+ num_frames: int,
109
+ num_inference_steps: int,
110
+ seed: int,
111
+ is_amplify_first_chunk: bool,
112
+ progress=gr.Progress(track_tqdm=True),
113
+ ):
114
+ if not prompt:
115
+ raise gr.Error("Please provide a prompt.")
116
+
117
+ generator = torch.Generator(device="cuda").manual_seed(int(seed))
118
+
119
+ kwargs = {
120
+ "prompt": prompt,
121
+ "height": int(height),
122
+ "width": int(width),
123
+ "num_frames": int(num_frames),
124
+ "guidance_scale": 1.0,
125
+ "generator": generator,
126
+ "output_type": "np",
127
+ "pyramid_num_inference_steps_list": [
128
+ int(num_inference_steps),
129
+ int(num_inference_steps),
130
+ int(num_inference_steps),
131
+ ],
132
+ "is_amplify_first_chunk": is_amplify_first_chunk,
133
+ }
134
+
135
+ if mode == "Image-to-Video" and image_input is not None:
136
+ img = load_image(image_input).resize((int(width), int(height)))
137
+ kwargs["image"] = img
138
+ elif mode == "Video-to-Video" and video_input is not None:
139
+ kwargs["video"] = load_video(video_input)
140
+
141
+ t0 = time.time()
142
+ output = pipe(**kwargs).frames[0]
143
+ elapsed = time.time() - t0
144
+
145
+ tmp = tempfile.NamedTemporaryFile(suffix=".mp4", delete=False)
146
+ export_to_video(output, tmp.name, fps=24)
147
+ info = f"Generated in {elapsed:.1f}s · {num_frames} frames · {height}×{width}"
148
+ return tmp.name, info
149
+
150
+
151
+ # ---------------------------------------------------------------------------
152
+ # UI Setup
153
+ # ---------------------------------------------------------------------------
154
+ def update_conditional_visibility(mode):
155
+ if mode == "Image-to-Video":
156
+ return gr.update(visible=True), gr.update(visible=False)
157
+ elif mode == "Video-to-Video":
158
+ return gr.update(visible=False), gr.update(visible=True)
159
+ else:
160
+ return gr.update(visible=False), gr.update(visible=False)
161
+
162
+
163
+ CSS = """
164
+ #header { text-align: center; margin-bottom: 1.5em; }
165
+ #header h1 { font-size: 2.2em; margin-bottom: 0.2em; }
166
+ .logo { max-height: 100px; margin: 0 auto 10px auto; display: block; }
167
+ .link-buttons { display: flex; justify-content: center; gap: 15px; margin-top: 10px; }
168
+ .link-buttons a {
169
+ background-color: #2b3137;
170
+ color: #ffffff !important;
171
+ padding: 8px 20px;
172
+ border-radius: 6px;
173
+ text-decoration: none;
174
+ font-weight: 600;
175
+ font-size: 1em;
176
+ transition: all 0.2s ease-in-out;
177
+ box-shadow: 0 2px 4px rgba(0,0,0,0.1);
178
+ }
179
+ .link-buttons a:hover { background-color: #4a535c; transform: translateY(-1px); }
180
+ .contain { max-width: 1350px; margin: 0 auto !important; }
181
+ """
182
+
183
+ with gr.Blocks(title="Helios Video Generation") as demo:
184
+ gr.HTML(
185
+ """
186
+ <div style='display: flex; align-items: center; justify-content: center; width: 100%;'>
187
+ <img src="https://raw.githubusercontent.com/SHYuanBest/shyuanbest_media/main/Helios/logo_white.png" style='width: 400px; height: auto;' />
188
+ </div>
189
+ <div id="header">
190
+ <h1>🎬 Helios 14B Distilled: Real Real-Time Long Video Generation Model</h1>
191
+ <p style="font-size: 1.1em; color: #666; margin-top: 0.5em; margin-bottom: 1em;">
192
+ If you like our project, please give us a star ⭐ on GitHub for the latest update.
193
+ </p>
194
+ <div class="link-buttons">
195
+ <a href="https://github.com/PKU-YuanGroup/Helios" target="_blank">💻 Code</a>
196
+ <a href="https://pku-yuangroup.github.io/Helios-Page" target="_blank">📄 Page</a>
197
+ <a href="https://www.youtube.com/watch?v=vd_AgHtOUFQ" target="_blank">🎥 Main Feature</a>
198
+ <a href="https://www.youtube.com/watch?v=1GeIU2Dn7UY" target="_blank">⚡ Inference Speed</a>
199
+ </div>
200
+ </div>
201
+ """
202
+ )
203
+
204
+ with gr.Row():
205
+ with gr.Column(scale=1):
206
+ mode = gr.Radio(
207
+ choices=["Text-to-Video", "Image-to-Video", "Video-to-Video"],
208
+ value="Text-to-Video",
209
+ label="Generation Mode",
210
+ )
211
+ image_input = gr.Image(label="Image (for I2V)", type="filepath", visible=False)
212
+ video_input = gr.Video(label="Video (for V2V)", visible=False)
213
+ prompt = gr.Textbox(
214
+ label="Prompt",
215
+ lines=4,
216
+ value=(
217
+ "A vibrant tropical fish swimming gracefully among colorful coral reefs in "
218
+ "a clear, turquoise ocean. The fish has bright blue and yellow scales with a "
219
+ "small, distinctive orange spot on its side, its fins moving fluidly. The coral "
220
+ "reefs are alive with a variety of marine life, including small schools of "
221
+ "colorful fish and sea turtles gliding by. The water is crystal clear, allowing "
222
+ "for a view of the sandy ocean floor below. The reef itself is adorned with a mix "
223
+ "of hard and soft corals in shades of red, orange, and green. The photo captures "
224
+ "the fish from a slightly elevated angle, emphasizing its lively movements and the "
225
+ "vivid colors of its surroundings. A close-up shot with dynamic movement."
226
+ ),
227
+ )
228
+ with gr.Accordion("Advanced Settings", open=False):
229
+ with gr.Row():
230
+ height = gr.Number(value=384, label="Height", precision=0, interactive=False)
231
+ width = gr.Number(value=640, label="Width", precision=0, interactive=False)
232
+ with gr.Row():
233
+ num_frames = gr.Slider(33, 231, value=231, step=33, label="Num Frames")
234
+ num_inference_steps = gr.Slider(1, 10, value=2, step=1, label="Steps per stage")
235
+ with gr.Row():
236
+ seed = gr.Number(value=42, label="Seed", precision=0)
237
+ is_amplify_first_chunk = gr.Checkbox(label="Amplify First Chunk", value=True)
238
+
239
+ generate_btn = gr.Button("🚀 Generate Video", variant="primary", size="lg")
240
+
241
+ with gr.Column(scale=1):
242
+ video_output = gr.Video(label="Generated Video", autoplay=True)
243
+ info_output = gr.Textbox(label="Info", interactive=False)
244
+
245
+ mode.change(fn=update_conditional_visibility, inputs=[mode], outputs=[image_input, video_input])
246
+ generate_btn.click(
247
+ fn=generate_video,
248
+ inputs=[
249
+ mode,
250
+ prompt,
251
+ image_input,
252
+ video_input,
253
+ height,
254
+ width,
255
+ num_frames,
256
+ num_inference_steps,
257
+ seed,
258
+ is_amplify_first_chunk,
259
+ ],
260
+ outputs=[video_output, info_output],
261
+ )
262
+
263
+ gr.Examples(
264
+ examples=[
265
+ [
266
+ "Text-to-Video",
267
+ "A vibrant tropical fish swimming gracefully among colorful coral reefs in "
268
+ "a clear, turquoise ocean. The fish has bright blue and yellow scales with a "
269
+ "small, distinctive orange spot on its side, its fins moving fluidly. The coral "
270
+ "reefs are alive with a variety of marine life, including small schools of "
271
+ "colorful fish and sea turtles gliding by. The water is crystal clear, allowing "
272
+ "for a view of the sandy ocean floor below. The reef itself is adorned with a mix "
273
+ "of hard and soft corals in shades of red, orange, and green. The photo captures "
274
+ "the fish from a slightly elevated angle, emphasizing its lively movements and the "
275
+ "vivid colors of its surroundings. A close-up shot with dynamic movement.",
276
+ None,
277
+ None,
278
+ ],
279
+ [
280
+ "Text-to-Video",
281
+ "An extreme close-up of an gray-haired man with a beard in his 60s, he is deep in "
282
+ "thought pondering the history of the universe as he sits at a cafe in Paris, his eyes "
283
+ "focus on people offscreen as they walk as he sits mostly motionless, he is dressed in "
284
+ "a wool coat suit coat with a button-down shirt , he wears a brown beret and glasses "
285
+ "and has a very professorial appearance, and the end he offers a subtle closed-mouth "
286
+ "smile as if he found the answer to the mystery of life, the lighting is very cinematic "
287
+ "with the golden light and the Parisian streets and city in the background, depth of "
288
+ "field, cinematic 35mm film.",
289
+ None,
290
+ None,
291
+ ],
292
+ [
293
+ "Text-to-Video",
294
+ "A drone camera circles around a beautiful historic church built on a rocky outcropping "
295
+ "along the Amalfi Coast, the view showcases historic and magnificent architectural "
296
+ "details and tiered pathways and patios, waves are seen crashing against the rocks "
297
+ "below as the view overlooks the horizon of the coastal waters and hilly landscapes "
298
+ "of the Amalfi Coast Italy, several distant people are seen walking and enjoying vistas "
299
+ "on patios of the dramatic ocean views, the warm glow of the afternoon sun creates a "
300
+ "magical and romantic feeling to the scene, the view is stunning captured with beautiful photography.",
301
+ None,
302
+ None,
303
+ ],
304
+ [
305
+ "Image-to-Video",
306
+ "A towering emerald wave surges forward, its crest curling with raw power and energy. Sunlight glints off the translucent water, illuminating the intricate textures and deep green hues within the wave’s body. A thick spray erupts from the breaking crest, casting a misty veil that dances above the churning surface. As the perspective widens, the immense scale of the wave becomes apparent, revealing the restless expanse of the ocean stretching beyond. The scene captures the ocean’s untamed beauty and relentless force, with every droplet and ripple shimmering in the light. The dynamic motion and vivid colors evoke both awe and respect for nature’s might.",
307
+ "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/helios/wave.jpg",
308
+ None,
309
+ ],
310
+ [
311
+ "Video-to-Video",
312
+ "A bright yellow Lamborghini Huracn Tecnica speeds along a curving mountain road, surrounded by lush green trees under a partly cloudy sky. The car's sleek design and vibrant color stand out against the natural backdrop, emphasizing its dynamic movement. The road curves gently, with a guardrail visible on one side, adding depth to the scene. The motion blur captures the sense of speed and energy, creating a thrilling and exhilarating atmosphere. A front-facing shot from a slightly elevated angle, highlighting the car's aggressive stance and the surrounding greenery.",
313
+ None,
314
+ "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/helios/car.mp4",
315
+ ],
316
+ ],
317
+ inputs=[mode, prompt, image_input, video_input],
318
+ label="Example Prompts",
319
+ )
320
+
321
+ if __name__ == "__main__":
322
+ demo.launch(share=True, css=CSS, theme=gr.themes.Soft())
Helios/_DEV3/bench_infer.py ADDED
@@ -0,0 +1,569 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Helios Benchmark Inference Script
3
+ - Runs T2V inference for a single model version on a single GPU
4
+ - Uses the first N prompts from a txt file
5
+ - Saves videos in two layouts: by_prompt/<slug>/<version>.mp4
6
+ by_version/<version>/<slug>.mp4
7
+ - Records per-video timing to timing_<version>.txt and computes summary stats
8
+ """
9
+
10
+ import importlib
11
+ import os
12
+ import re
13
+ import shutil
14
+ import sys
15
+ import time
16
+
17
+ os.environ["HF_ENABLE_PARALLEL_LOADING"] = "yes"
18
+ os.environ["HF_PARALLEL_LOADING_WORKERS"] = "8"
19
+
20
+ import argparse
21
+ import subprocess
22
+ from pathlib import Path
23
+
24
+
25
+ SCRIPT_DIR = Path(__file__).resolve().parent
26
+ DEFAULT_PROMPT_FILE = SCRIPT_DIR / "demo_data" / "MovieGenVideoBench_extended.txt"
27
+ DEFAULT_MODEL_ROOT = SCRIPT_DIR / "checkpoints"
28
+ DEFAULT_OUTPUT_ROOT = SCRIPT_DIR / "output_helios" / "bench"
29
+
30
+
31
+ def pick_gpu_by_free_vram(min_free_mib=20000):
32
+ """Pick physical GPU index with the most free memory (via nvidia-smi). No torch import."""
33
+ try:
34
+ out = subprocess.check_output(
35
+ [
36
+ "nvidia-smi",
37
+ "--query-gpu=index,memory.free",
38
+ "--format=csv,noheader,nounits",
39
+ ],
40
+ text=True,
41
+ stderr=subprocess.DEVNULL,
42
+ )
43
+ except (subprocess.CalledProcessError, FileNotFoundError) as e:
44
+ raise RuntimeError("nvidia-smi failed; specify --gpu explicitly") from e
45
+
46
+ best_idx, best_free = None, -1
47
+ for line in out.strip().splitlines():
48
+ parts = [p.strip() for p in line.split(",")]
49
+ if len(parts) < 2:
50
+ continue
51
+ idx, free = int(parts[0]), int(parts[1])
52
+ if free > best_free:
53
+ best_free, best_idx = free, idx
54
+ if best_idx is None:
55
+ raise RuntimeError("Could not parse nvidia-smi GPU list")
56
+ if best_free < min_free_mib:
57
+ print(
58
+ f"[warn] Best GPU {best_idx} has only {best_free} MiB free "
59
+ f"(<{min_free_mib} MiB); OOM risk — consider --enable_low_vram_mode",
60
+ file=sys.stderr,
61
+ )
62
+ return best_idx, best_free
63
+
64
+
65
+ def _apply_cuda_visible_devices_before_torch():
66
+ """CUDA_VISIBLE_DEVICES must be set before `import torch` (first CUDA init)."""
67
+ pre = argparse.ArgumentParser(add_help=False)
68
+ pre.add_argument("--gpu", type=str, default="auto")
69
+ known, _ = pre.parse_known_args()
70
+ g = known.gpu.strip().lower()
71
+ if g == "auto":
72
+ idx, free = pick_gpu_by_free_vram()
73
+ os.environ["CUDA_VISIBLE_DEVICES"] = str(idx)
74
+ os.environ["_BENCH_PHYSICAL_GPU"] = f"{idx} ({free} MiB free)"
75
+ else:
76
+ os.environ["CUDA_VISIBLE_DEVICES"] = known.gpu.strip()
77
+ os.environ["_BENCH_PHYSICAL_GPU"] = known.gpu.strip()
78
+ os.environ["_BENCH_GPU_ARG"] = known.gpu.strip()
79
+
80
+
81
+ _apply_cuda_visible_devices_before_torch()
82
+
83
+ import torch
84
+ from tqdm import tqdm
85
+
86
+ if importlib.util.find_spec("torch_npu") is not None:
87
+ import torch_npu # noqa: F401
88
+
89
+ from helios.diffusers_version.pipeline_helios_diffusers import HeliosPipeline
90
+ from helios.diffusers_version.scheduling_helios_diffusers import HeliosScheduler
91
+ from helios.diffusers_version.transformer_helios_diffusers import HeliosTransformer3DModel
92
+ from helios.modules.helios_kernels import (
93
+ replace_all_norms_with_flash_norms,
94
+ replace_rmsnorm_with_fp32,
95
+ replace_rope_with_flash_rope,
96
+ )
97
+ from diffusers.models import AutoencoderKLWan
98
+ from diffusers.utils import export_to_video
99
+
100
+ # ── per-version inference presets (matching official scripts) ─────────────────
101
+
102
+ MODEL_PRESETS = {
103
+ "base": dict(
104
+ model_dir="Helios-Base",
105
+ num_frames=99,
106
+ num_inference_steps=50,
107
+ guidance_scale=5.0,
108
+ is_enable_stage2=False,
109
+ pyramid_num_inference_steps_list=[20, 20, 20],
110
+ is_amplify_first_chunk=False,
111
+ use_zero_init=False,
112
+ zero_steps=1,
113
+ ),
114
+ "mid": dict(
115
+ model_dir="Helios-Mid",
116
+ num_frames=99,
117
+ num_inference_steps=50,
118
+ guidance_scale=5.0,
119
+ is_enable_stage2=True,
120
+ pyramid_num_inference_steps_list=[20, 20, 20],
121
+ is_amplify_first_chunk=False,
122
+ use_zero_init=True,
123
+ zero_steps=1,
124
+ ),
125
+ "distilled": dict(
126
+ model_dir="Helios-Distilled",
127
+ num_frames=240,
128
+ num_inference_steps=50,
129
+ guidance_scale=1.0,
130
+ is_enable_stage2=True,
131
+ pyramid_num_inference_steps_list=[2, 2, 2],
132
+ is_amplify_first_chunk=True,
133
+ use_zero_init=False,
134
+ zero_steps=1,
135
+ ),
136
+ }
137
+
138
+ NEGATIVE_PROMPT = (
139
+ "Bright tones, overexposed, static, blurred details, subtitles, style, "
140
+ "works, paintings, images, static, overall gray, worst quality, low quality, "
141
+ "JPEG compression residue, ugly, incomplete, extra fingers, poorly drawn hands, "
142
+ "poorly drawn faces, deformed, disfigured, misshapen limbs, fused fingers, "
143
+ "still picture, messy background, three legs, many people in the background, "
144
+ "walking backwards"
145
+ )
146
+
147
+
148
+ def sanitize_filename(text, max_len=80):
149
+ """Turn a prompt into a filesystem-safe slug."""
150
+ text = text.strip().lower()
151
+ text = re.sub(r"[^a-z0-9]+", "_", text)
152
+ text = text.strip("_")
153
+ return text[:max_len]
154
+
155
+
156
+ def load_prompt_indices(path):
157
+ indices = []
158
+ with open(path, "r", encoding="utf-8") as f:
159
+ for line_no, raw_line in enumerate(f, start=1):
160
+ line = raw_line.strip()
161
+ if not line or line.startswith("#"):
162
+ continue
163
+ try:
164
+ idx = int(line)
165
+ except ValueError as exc:
166
+ raise ValueError(
167
+ f"Invalid prompt index at {path}:{line_no}: {line!r}"
168
+ ) from exc
169
+ if idx < 0:
170
+ raise ValueError(f"Prompt index must be >= 0 at {path}:{line_no}")
171
+ indices.append(idx)
172
+ return indices
173
+
174
+
175
+ def load_prompts(path, prompt_start=0, prompt_end=None, prompt_indices=None):
176
+ with open(path, "r", encoding="utf-8") as f:
177
+ lines = [line.strip() for line in f if line.strip()]
178
+ if prompt_indices is not None:
179
+ selected = []
180
+ total = len(lines)
181
+ for idx in prompt_indices:
182
+ if idx >= total:
183
+ raise ValueError(
184
+ f"Prompt index {idx} is out of range; prompt file has {total} prompts"
185
+ )
186
+ selected.append((idx, lines[idx]))
187
+ return selected
188
+
189
+ if prompt_start < 0:
190
+ raise ValueError("prompt_start must be >= 0")
191
+ if prompt_end is not None and prompt_end < prompt_start:
192
+ raise ValueError("prompt_end must be >= prompt_start")
193
+
194
+ selected = lines[prompt_start:prompt_end]
195
+ return [(prompt_start + offset, prompt) for offset, prompt in enumerate(selected)]
196
+
197
+
198
+ def build_expected_outputs(prompts, version, by_version_dir):
199
+ version_dir = os.path.join(by_version_dir, version)
200
+ expected = []
201
+ for idx, prompt in prompts:
202
+ slug = sanitize_filename(prompt)
203
+ vid_name = f"{idx:04d}_{slug}"
204
+ expected.append((idx, slug, os.path.join(version_dir, f"{vid_name}.mp4")))
205
+ return version_dir, expected
206
+
207
+
208
+ def output_exists(path):
209
+ return os.path.isfile(path) and os.path.getsize(path) > 0
210
+
211
+
212
+ def find_missing_outputs(expected_outputs):
213
+ return [item for item in expected_outputs if not output_exists(item[2])]
214
+
215
+
216
+ def make_timing_line(version, idx, elapsed, slug):
217
+ return (
218
+ f" {version:10s} #{idx:04d} {elapsed:8.2f}s "
219
+ f"({elapsed / 60:5.2f}min) {slug[:50]}"
220
+ )
221
+
222
+
223
+ def load_existing_timing_records(timing_file, version):
224
+ if not os.path.exists(timing_file):
225
+ return {}
226
+
227
+ pattern = re.compile(
228
+ rf"^\s*{re.escape(version)}\s+#(\d+)\s+([0-9.]+)s\s+\([^)]+\)\s+(.*)$"
229
+ )
230
+ records = {}
231
+ with open(timing_file, "r", encoding="utf-8") as f:
232
+ for raw_line in f:
233
+ line = raw_line.rstrip("\n")
234
+ match = pattern.match(line)
235
+ if not match:
236
+ continue
237
+ idx = int(match.group(1))
238
+ elapsed = float(match.group(2))
239
+ slug = match.group(3)
240
+ records[idx] = (elapsed, slug)
241
+ return records
242
+
243
+
244
+ def build_pipeline(
245
+ model_path,
246
+ device,
247
+ weight_dtype,
248
+ enable_low_vram=False,
249
+ group_offloading_type="leaf_level",
250
+ num_blocks_per_group=4,
251
+ ):
252
+ transformer = HeliosTransformer3DModel.from_pretrained(
253
+ model_path, subfolder="transformer", torch_dtype=weight_dtype,
254
+ )
255
+ transformer = replace_rmsnorm_with_fp32(transformer)
256
+ transformer = replace_all_norms_with_flash_norms(transformer)
257
+ replace_rope_with_flash_rope()
258
+
259
+ cuda_major = torch.cuda.get_device_capability()[0]
260
+ if cuda_major >= 9:
261
+ try:
262
+ transformer.set_attention_backend("_flash_3_hub")
263
+ except Exception:
264
+ transformer.set_attention_backend("flash_hub")
265
+ else:
266
+ transformer.set_attention_backend("flash_hub")
267
+
268
+ vae = AutoencoderKLWan.from_pretrained(
269
+ model_path, subfolder="vae", torch_dtype=torch.float32,
270
+ )
271
+ scheduler = HeliosScheduler.from_pretrained(model_path, subfolder="scheduler")
272
+
273
+ pipe = HeliosPipeline.from_pretrained(
274
+ model_path,
275
+ transformer=transformer,
276
+ vae=vae,
277
+ scheduler=scheduler,
278
+ torch_dtype=weight_dtype,
279
+ )
280
+ if enable_low_vram:
281
+ nbg = int(num_blocks_per_group) if group_offloading_type == "block_level" else None
282
+ pipe.enable_group_offload(
283
+ onload_device=torch.device("cuda"),
284
+ offload_device=torch.device("cpu"),
285
+ offload_type=group_offloading_type,
286
+ num_blocks_per_group=nbg,
287
+ use_stream=True,
288
+ record_stream=True,
289
+ )
290
+ else:
291
+ pipe = pipe.to(device)
292
+ return pipe
293
+
294
+
295
+ def run_single(pipe, prompt, preset, height, width, seed):
296
+ gen = torch.Generator(device="cuda").manual_seed(seed)
297
+
298
+ t0 = time.time()
299
+ with torch.no_grad():
300
+ output = pipe(
301
+ prompt=prompt,
302
+ negative_prompt=NEGATIVE_PROMPT,
303
+ height=height,
304
+ width=width,
305
+ num_frames=preset["num_frames"],
306
+ num_inference_steps=preset["num_inference_steps"],
307
+ guidance_scale=preset["guidance_scale"],
308
+ generator=gen,
309
+ history_sizes=[16, 2, 1],
310
+ num_latent_frames_per_chunk=9,
311
+ keep_first_frame=True,
312
+ is_enable_stage2=preset["is_enable_stage2"],
313
+ pyramid_num_inference_steps_list=preset["pyramid_num_inference_steps_list"],
314
+ is_skip_first_chunk=False,
315
+ is_amplify_first_chunk=preset["is_amplify_first_chunk"],
316
+ use_zero_init=preset["use_zero_init"],
317
+ zero_steps=preset["zero_steps"],
318
+ ).frames[0]
319
+ elapsed = time.time() - t0
320
+ return output, elapsed
321
+
322
+
323
+ def _parse_gpu(s):
324
+ if isinstance(s, str) and s.lower() == "auto":
325
+ return "auto"
326
+ return int(s)
327
+
328
+
329
+ def parse_args():
330
+ p = argparse.ArgumentParser(description="Helios benchmark inference for one model version")
331
+ p.add_argument("--prompt_file", type=str,
332
+ default=str(DEFAULT_PROMPT_FILE))
333
+ p.add_argument("--prompt_start", type=int, default=0)
334
+ p.add_argument("--prompt_end", type=int, default=100,
335
+ help="Exclusive end index for prompts, e.g. 50 means up to #49")
336
+ p.add_argument("--prompt_indices_file", type=str, default=None,
337
+ help="Optional file containing exact prompt indices to run, one per line")
338
+ p.add_argument("--model_root", type=str, default=str(DEFAULT_MODEL_ROOT),
339
+ help="Parent dir containing Helios-Base / Helios-Mid / Helios-Distilled")
340
+ p.add_argument("--output_root", type=str, default=str(DEFAULT_OUTPUT_ROOT))
341
+ p.add_argument("--version", type=str, choices=sorted(MODEL_PRESETS.keys()), required=True,
342
+ help="Which model version to run")
343
+ p.add_argument("--timing_file", type=str, default=None,
344
+ help="Optional override for timing report path")
345
+ p.add_argument("--height", type=int, default=384)
346
+ p.add_argument("--width", type=int, default=640)
347
+ p.add_argument("--num_frames", type=int, default=None,
348
+ help="Override preset frame count for all selected versions")
349
+ p.add_argument("--seed", type=int, default=42)
350
+ p.add_argument(
351
+ "--gpu",
352
+ type=_parse_gpu,
353
+ default="auto",
354
+ help='Physical GPU id or "auto" (pick most free VRAM via nvidia-smi)',
355
+ )
356
+ p.add_argument(
357
+ "--enable_low_vram_mode",
358
+ action="store_true",
359
+ help="CPU group-offload (slower, less VRAM); use if GPU is shared or OOM",
360
+ )
361
+ p.add_argument(
362
+ "--group_offloading_type",
363
+ type=str,
364
+ choices=["leaf_level", "block_level"],
365
+ default="leaf_level",
366
+ )
367
+ p.add_argument("--num_blocks_per_group", type=int, default=4)
368
+ return p.parse_args()
369
+
370
+
371
+ def main():
372
+ args = parse_args()
373
+
374
+ if not os.path.isfile(args.prompt_file):
375
+ raise FileNotFoundError(f"Prompt file not found: {args.prompt_file}")
376
+ if not os.path.isdir(args.model_root):
377
+ raise FileNotFoundError(f"Model root not found: {args.model_root}")
378
+
379
+ os.environ["CUDA_VISIBLE_DEVICES"] = str(args.gpu)
380
+ device = torch.device("cuda")
381
+ weight_dtype = torch.bfloat16
382
+
383
+ prompt_indices = None
384
+ if args.prompt_indices_file:
385
+ if not os.path.isfile(args.prompt_indices_file):
386
+ raise FileNotFoundError(f"Prompt indices file not found: {args.prompt_indices_file}")
387
+ prompt_indices = load_prompt_indices(args.prompt_indices_file)
388
+
389
+ prompts = load_prompts(
390
+ args.prompt_file,
391
+ args.prompt_start,
392
+ args.prompt_end,
393
+ prompt_indices=prompt_indices,
394
+ )
395
+ prompt_map = dict(prompts)
396
+ if args.prompt_indices_file:
397
+ print(
398
+ f"Loaded {len(prompts)} prompts from {args.prompt_file} "
399
+ f"(indices: {args.prompt_indices_file})"
400
+ )
401
+ else:
402
+ print(
403
+ f"Loaded {len(prompts)} prompts from {args.prompt_file} "
404
+ f"(range: {args.prompt_start}:{args.prompt_end})"
405
+ )
406
+
407
+ if args.num_frames is not None:
408
+ MODEL_PRESETS[args.version]["num_frames"] = args.num_frames
409
+
410
+ by_prompt_dir = os.path.join(args.output_root, "by_prompt")
411
+ by_version_dir = os.path.join(args.output_root, "by_version")
412
+ timing_file = args.timing_file or os.path.join(args.output_root, f"timing_{args.version}.txt")
413
+ os.makedirs(args.output_root, exist_ok=True)
414
+
415
+ preset = MODEL_PRESETS[args.version]
416
+ model_path = os.path.join(args.model_root, preset["model_dir"])
417
+ timing_records = load_existing_timing_records(timing_file, args.version)
418
+ selected_indices = set(prompt_map)
419
+ timing_records = {
420
+ idx: record for idx, record in timing_records.items() if idx in selected_indices
421
+ }
422
+ ver_dir, expected_outputs = build_expected_outputs(prompts, args.version, by_version_dir)
423
+ missing_outputs = find_missing_outputs(expected_outputs)
424
+ if not os.path.isdir(model_path):
425
+ raise FileNotFoundError(f"Model not found: {model_path}")
426
+
427
+ peak_mem = None
428
+ if not missing_outputs:
429
+ print(
430
+ f"[SKIP] All outputs already exist for version={args.version} under {ver_dir}"
431
+ )
432
+ else:
433
+ header = (
434
+ f"\n{'=' * 60}\n"
435
+ f" Version: {args.version} | Model: {preset['model_dir']}\n"
436
+ f" Frames: {preset['num_frames']} | guidance_scale: {preset['guidance_scale']}\n"
437
+ f" stage2: {preset['is_enable_stage2']} | pyramid_steps: {preset['pyramid_num_inference_steps_list']}\n"
438
+ f"{'=' * 60}\n"
439
+ )
440
+ print(header)
441
+
442
+ pipe = build_pipeline(
443
+ model_path,
444
+ device,
445
+ weight_dtype,
446
+ enable_low_vram=args.enable_low_vram_mode,
447
+ group_offloading_type=args.group_offloading_type,
448
+ num_blocks_per_group=args.num_blocks_per_group,
449
+ )
450
+
451
+ os.makedirs(ver_dir, exist_ok=True)
452
+
453
+ print(
454
+ f"[resume] version={args.version} existing={len(expected_outputs) - len(missing_outputs)} "
455
+ f"missing={len(missing_outputs)} timed={len(timing_records)}"
456
+ )
457
+ for idx, slug, ver_out in tqdm(missing_outputs, desc=f"[{args.version}]"):
458
+ if os.path.exists(ver_out):
459
+ print(f" [skip] {ver_out}")
460
+ continue
461
+
462
+ try:
463
+ frames, elapsed = run_single(
464
+ pipe, prompt_map[idx], preset, args.height, args.width, args.seed,
465
+ )
466
+ except Exception as e:
467
+ msg = f" [FAIL] {args.version} #{idx:04d}: {e}"
468
+ print(msg)
469
+ continue
470
+
471
+ export_to_video(frames, ver_out, fps=24)
472
+
473
+ vid_name = os.path.splitext(os.path.basename(ver_out))[0]
474
+ prompt_dir = os.path.join(by_prompt_dir, vid_name)
475
+ os.makedirs(prompt_dir, exist_ok=True)
476
+ shutil.copy2(ver_out, os.path.join(prompt_dir, f"{args.version}.mp4"))
477
+
478
+ timing_records[idx] = (elapsed, slug)
479
+ print(make_timing_line(args.version, idx, elapsed, slug))
480
+
481
+ peak_mem = torch.cuda.max_memory_allocated() / 1024 ** 3
482
+ print(f" >> [{args.version}] peak GPU memory: {peak_mem:.2f} GB")
483
+
484
+ del pipe
485
+ torch.cuda.empty_cache()
486
+ torch.cuda.reset_peak_memory_stats()
487
+
488
+ sorted_records = [timing_records[idx] for idx in sorted(timing_records)]
489
+ all_timings = [elapsed for elapsed, _ in sorted_records]
490
+
491
+ with open(timing_file, "w", encoding="utf-8") as tf:
492
+ tf.write(f"{'=' * 80}\n")
493
+ tf.write(f" Helios Benchmark Inference Timing Report\n")
494
+ tf.write(f" {time.strftime('%Y-%m-%d %H:%M:%S')}\n")
495
+ tf.write(
496
+ f" Prompts: {len(prompts)} | Range: {args.prompt_start}:{args.prompt_end} "
497
+ f"| Version: {args.version}\n"
498
+ )
499
+ if args.prompt_indices_file:
500
+ tf.write(f" Prompt indices file: {args.prompt_indices_file}\n")
501
+ tf.write(
502
+ f" Resolution: {args.width}x{args.height} | Seed: {args.seed} | "
503
+ f"GPU: {args.gpu} | low_vram: {args.enable_low_vram_mode}\n"
504
+ )
505
+ tf.write(f"{'=' * 80}\n\n")
506
+
507
+ tf.write(
508
+ f"\n{'=' * 60}\n"
509
+ f" Version: {args.version} | Model: {preset['model_dir']}\n"
510
+ f" Frames: {preset['num_frames']} | guidance_scale: {preset['guidance_scale']}\n"
511
+ f" stage2: {preset['is_enable_stage2']} | pyramid_steps: {preset['pyramid_num_inference_steps_list']}\n"
512
+ f"{'=' * 60}\n"
513
+ )
514
+ tf.write(
515
+ f" Existing timing records: {len(timing_records)} / expected outputs: {len(expected_outputs)}\n"
516
+ )
517
+
518
+ for idx in sorted(timing_records):
519
+ elapsed, slug = timing_records[idx]
520
+ tf.write(make_timing_line(args.version, idx, elapsed, slug) + "\n")
521
+
522
+ if all_timings:
523
+ avg_t = sum(all_timings) / len(all_timings)
524
+ total_t = sum(all_timings)
525
+ summary = (
526
+ f"\n >> [{args.version}] completed {len(all_timings)} videos | "
527
+ f"avg: {avg_t:.2f}s ({avg_t / 60:.2f}min) | "
528
+ f"total: {total_t:.1f}s ({total_t / 60:.1f}min)\n"
529
+ )
530
+ else:
531
+ summary = f"\n >> [{args.version}] no timing records available\n"
532
+ print(summary)
533
+ tf.write(summary)
534
+
535
+ if peak_mem is not None:
536
+ mem_line = f" >> [{args.version}] peak GPU memory: {peak_mem:.2f} GB\n"
537
+ tf.write(mem_line)
538
+
539
+ sep = f"\n{'=' * 80}\n"
540
+ tf.write(sep)
541
+ tf.write(" FINAL SUMMARY\n")
542
+ tf.write(f"{'=' * 80}\n")
543
+ print(sep)
544
+ print(" FINAL SUMMARY")
545
+ print(f"{'=' * 80}")
546
+
547
+ fmt = " {ver:12s} | videos: {n:3d} | avg: {avg:8.2f}s ({avgm:5.2f}min) | min: {mn:8.2f}s | max: {mx:8.2f}s | total: {tot:8.1f}s ({totm:5.1f}min)"
548
+ if all_timings:
549
+ line = fmt.format(
550
+ ver=args.version, n=len(all_timings),
551
+ avg=sum(all_timings) / len(all_timings), avgm=sum(all_timings) / len(all_timings) / 60,
552
+ mn=min(all_timings), mx=max(all_timings),
553
+ tot=sum(all_timings), totm=sum(all_timings) / 60,
554
+ )
555
+ else:
556
+ line = f" {args.version:12s} | N/A (no timing records)"
557
+ print(line)
558
+ tf.write(line + "\n")
559
+
560
+ tf.write(f"{'=' * 80}\n")
561
+
562
+ print(f"{'=' * 80}")
563
+ print(f"\nTiming report: {timing_file}")
564
+ print(f"Videos: {by_prompt_dir}")
565
+ print(f" {by_version_dir}")
566
+
567
+
568
+ if __name__ == "__main__":
569
+ main()
Helios/_DEV3/infer_helios.py ADDED
@@ -0,0 +1,673 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import importlib
2
+ import os
3
+
4
+
5
+ os.environ["HF_ENABLE_PARALLEL_LOADING"] = "yes"
6
+ os.environ["HF_PARALLEL_LOADING_WORKERS"] = "8"
7
+
8
+ import argparse
9
+ import time
10
+ from pathlib import Path
11
+
12
+ import pandas as pd
13
+ import torch
14
+ import torch.distributed as dist
15
+ from tqdm import tqdm
16
+
17
+
18
+ if importlib.util.find_spec("torch_npu") is not None:
19
+ import torch_npu
20
+ else:
21
+ torch_npu = None
22
+
23
+ from helios.diffusers_version.pipeline_helios_diffusers import HeliosPipeline
24
+ from helios.diffusers_version.scheduling_helios_diffusers import HeliosScheduler
25
+ from helios.diffusers_version.transformer_helios_diffusers import HeliosTransformer3DModel
26
+ from helios.modules.helios_kernels import (
27
+ replace_all_norms_with_flash_norms,
28
+ replace_rmsnorm_with_fp32,
29
+ replace_rope_with_flash_rope,
30
+ )
31
+ from helios.utils.utils_base import load_extra_components
32
+
33
+ from diffusers import ContextParallelConfig
34
+ from diffusers.models import AutoencoderKLWan
35
+ from diffusers.utils import export_to_video, load_image, load_video
36
+
37
+ PROJECT_ROOT = Path(__file__).resolve().parent
38
+ DEFAULT_BASE_MODEL_PATH = str(PROJECT_ROOT / "checkpoints" / "Helios-Base")
39
+
40
+
41
+ def parse_args():
42
+ parser = argparse.ArgumentParser(description="Generate video with model")
43
+
44
+ # === Model paths ===
45
+ parser.add_argument("--base_model_path", type=str, default=DEFAULT_BASE_MODEL_PATH)
46
+ parser.add_argument(
47
+ "--transformer_path",
48
+ type=str,
49
+ default=DEFAULT_BASE_MODEL_PATH,
50
+ )
51
+ parser.add_argument(
52
+ "--lora_path",
53
+ type=str,
54
+ default=None,
55
+ )
56
+ parser.add_argument(
57
+ "--partial_path",
58
+ type=str,
59
+ default=None,
60
+ )
61
+ parser.add_argument("--output_folder", type=str, default="./output_helios")
62
+ parser.add_argument("--enable_compile", action="store_true")
63
+
64
+ # === Generation parameters ===
65
+ # environment
66
+ parser.add_argument(
67
+ "--sample_type",
68
+ type=str,
69
+ default="t2v",
70
+ choices=["t2v", "i2v", "v2v"],
71
+ )
72
+ parser.add_argument(
73
+ "--weight_dtype",
74
+ type=str,
75
+ default="bf16",
76
+ choices=["bf16", "fp16", "fp32"],
77
+ help="Data type for model weights.",
78
+ )
79
+ parser.add_argument("--seed", type=int, default=42, help="Seed for random number generator.")
80
+ # base
81
+ parser.add_argument("--height", type=int, default=384)
82
+ parser.add_argument("--width", type=int, default=640)
83
+ parser.add_argument("--num_frames", type=int, default=99)
84
+ parser.add_argument("--fps", type=int, default=24)
85
+ parser.add_argument("--num_inference_steps", type=int, default=50)
86
+ parser.add_argument("--guidance_scale", type=float, default=5.0)
87
+ # cfg zero
88
+ parser.add_argument("--use_zero_init", action="store_true")
89
+ parser.add_argument("--zero_steps", type=int, default=1)
90
+ # stage 1
91
+ parser.add_argument("--num_latent_frames_per_chunk", type=int, default=9)
92
+ # stage 2
93
+ parser.add_argument("--is_enable_stage2", action="store_true")
94
+ parser.add_argument("--pyramid_num_inference_steps_list", type=int, nargs="+", default=[20, 20, 20])
95
+ # stage 3
96
+ parser.add_argument("--is_skip_first_chunk", action="store_true")
97
+ parser.add_argument("--is_amplify_first_chunk", action="store_true")
98
+ parser.add_argument(
99
+ "--visualize_relative_l1",
100
+ action="store_true",
101
+ help="Save per-chunk denoising relative L1 records and a timestep plot.",
102
+ )
103
+ parser.add_argument(
104
+ "--relative_l1_output_folder",
105
+ type=str,
106
+ default=None,
107
+ help="Deprecated. Relative L1 files are saved next to the mp4 in each prompt timestamp folder.",
108
+ )
109
+
110
+ # === Prompts ===
111
+ parser.add_argument("--use_interpolate_prompt", action="store_true")
112
+ parser.add_argument("--interpolation_steps", type=int, default=3)
113
+ parser.add_argument("--interpolate_time", type=int, default=7)
114
+ parser.add_argument(
115
+ "--image_path",
116
+ type=str,
117
+ default=None,
118
+ )
119
+ parser.add_argument(
120
+ "--image_noise_sigma_min", type=float, default=0.111, help="Balance motion amplitude and visual consistency"
121
+ )
122
+ parser.add_argument(
123
+ "--image_noise_sigma_max", type=float, default=0.135, help="Balance motion amplitude and visual consistency"
124
+ )
125
+ parser.add_argument(
126
+ "--video_path",
127
+ type=str,
128
+ default=None,
129
+ )
130
+ parser.add_argument(
131
+ "--video_noise_sigma_min", type=float, default=0.111, help="Balance motion amplitude and visual consistency"
132
+ )
133
+ parser.add_argument(
134
+ "--video_noise_sigma_max", type=float, default=0.135, help="Balance motion amplitude and visual consistency"
135
+ )
136
+ parser.add_argument(
137
+ "--prompt",
138
+ type=str,
139
+ default="A dynamic time-lapse video showing the rapidly moving scenery from the window of a speeding train. The camera captures various elements such as lush green fields, towering trees, quaint countryside houses, and distant mountain ranges passing by quickly. The train window frames the view, adding a sense of speed and motion as the landscape rushes past. The camera remains static but emphasizes the fast-paced movement outside. The overall atmosphere is serene yet exhilarating, capturing the essence of travel and exploration. Medium shot focusing on the train window and the rushing scenery beyond.",
140
+ )
141
+ parser.add_argument(
142
+ "--negative_prompt",
143
+ type=str,
144
+ default="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",
145
+ )
146
+ parser.add_argument(
147
+ "--prompt_txt_path",
148
+ type=str,
149
+ default=None,
150
+ )
151
+ parser.add_argument(
152
+ "--base_image_prompt_path",
153
+ type=str,
154
+ default=None,
155
+ )
156
+ parser.add_argument(
157
+ "--image_prompt_csv_path",
158
+ type=str,
159
+ default=None,
160
+ )
161
+ parser.add_argument(
162
+ "--interactive_prompt_csv_path",
163
+ type=str,
164
+ default=None,
165
+ )
166
+
167
+ # === Context parallelism ===
168
+ # Please refer to https://huggingface.co/docs/diffusers/main/en/training/distributed_inference#context-parallelism
169
+ parser.add_argument("--enable_parallelism", action="store_true")
170
+ parser.add_argument(
171
+ "--cp_backend",
172
+ type=str,
173
+ choices=["ring", "ulysses", "unified", "ulysses_anything"],
174
+ default="ulysses",
175
+ help="Context parallel backend to use.",
176
+ )
177
+
178
+ # === Group-Offloading ===
179
+ # Please refer to https://huggingface.co/docs/diffusers/main/en/optimization/memory#group-offloading
180
+ parser.add_argument("--enable_low_vram_mode", action="store_true")
181
+ parser.add_argument(
182
+ "--group_offloading_type",
183
+ type=str,
184
+ choices=["leaf_level", "block_level"],
185
+ default="leaf_level",
186
+ help="Specifies the granularity for group CPU offloading. Choose between 'leaf_level' (individual modules) or 'block_level' (entire blocks).",
187
+ )
188
+ parser.add_argument(
189
+ "--num_blocks_per_group",
190
+ type=str,
191
+ default="4",
192
+ help="The number of blocks to bundle together in each offloading group. Only relevant when using block-level offloading.",
193
+ )
194
+
195
+ return parser.parse_args()
196
+
197
+
198
+ def build_sample_output_dir(output_folder, prompt_or_prompts):
199
+ if isinstance(prompt_or_prompts, list):
200
+ prompt_text = prompt_or_prompts[0] if prompt_or_prompts else "prompt"
201
+ else:
202
+ prompt_text = prompt_or_prompts or "prompt"
203
+
204
+ prompt_text = str(prompt_text).strip()
205
+ safe_chars = []
206
+ previous_was_sep = False
207
+ for char in prompt_text:
208
+ if char.isalnum():
209
+ safe_chars.append(char)
210
+ previous_was_sep = False
211
+ elif not previous_was_sep:
212
+ safe_chars.append("_")
213
+ previous_was_sep = True
214
+
215
+ prompt_stem = "".join(safe_chars).strip("_")[:80] or "prompt"
216
+ sample_dir = Path(output_folder) / f"{prompt_stem}_{int(time.time())}"
217
+
218
+ suffix = 1
219
+ base_sample_dir = sample_dir
220
+ while sample_dir.exists():
221
+ sample_dir = Path(f"{base_sample_dir}_{suffix}")
222
+ suffix += 1
223
+
224
+ sample_dir.mkdir(parents=True, exist_ok=False)
225
+ return sample_dir
226
+
227
+
228
+ def save_relative_l1_outputs(records, output_folder):
229
+ if not records:
230
+ print(f"No relative L1 records for {output_folder}.")
231
+ return
232
+
233
+ metrics_dir = Path(output_folder)
234
+ metrics_dir.mkdir(parents=True, exist_ok=True)
235
+ df = pd.DataFrame(records).sort_values(["chunk_index", "step_index", "stage_index"])
236
+
237
+ csv_path = metrics_dir / "relative_l1.csv"
238
+ df.to_csv(csv_path, index=False)
239
+
240
+ try:
241
+ import matplotlib
242
+
243
+ matplotlib.use("Agg")
244
+ import matplotlib.pyplot as plt
245
+
246
+ def save_metric_plot(metric_name, ylabel, title, plot_name):
247
+ fig, ax = plt.subplots(figsize=(9, 5))
248
+ for chunk_index, chunk_df in df.groupby("chunk_index"):
249
+ chunk_df = chunk_df.sort_values(["step_index", "stage_index"])
250
+ ax.plot(
251
+ chunk_df["timestep"],
252
+ chunk_df[metric_name],
253
+ marker="o",
254
+ linewidth=1.5,
255
+ markersize=3,
256
+ label=f"chunk {chunk_index}",
257
+ )
258
+
259
+ ax.set_xlabel("timestep")
260
+ ax.set_ylabel(ylabel)
261
+ ax.set_title(title)
262
+ ax.grid(True, alpha=0.3)
263
+ ax.invert_xaxis()
264
+ ax.legend()
265
+ fig.tight_layout()
266
+
267
+ plot_path = metrics_dir / plot_name
268
+ fig.savefig(plot_path, dpi=200)
269
+ plt.close(fig)
270
+ return plot_path
271
+
272
+ plot_path = save_metric_plot(
273
+ "relative_l1",
274
+ "mean relative L1",
275
+ "Denoising relative L1 per chunk",
276
+ "relative_l1.png",
277
+ )
278
+ ratio_plot_path = None
279
+ if "relative_l1_ratio" in df.columns:
280
+ ratio_plot_path = save_metric_plot(
281
+ "relative_l1_ratio",
282
+ "mean(delta L1) / mean(latent L1)",
283
+ "Denoising relative L1 ratio per chunk",
284
+ "relative_l1_ratio.png",
285
+ )
286
+
287
+ if ratio_plot_path is None:
288
+ print(f"Saved relative L1 CSV to {csv_path} and plot to {plot_path}")
289
+ else:
290
+ print(f"Saved relative L1 CSV to {csv_path} and plots to {plot_path}, {ratio_plot_path}")
291
+ except Exception as exc:
292
+ print(f"Saved relative L1 CSV to {csv_path}, but failed to save plot: {exc}")
293
+
294
+
295
+ def main():
296
+ args = parse_args()
297
+
298
+ assert not (args.enable_low_vram_mode and args.enable_compile), (
299
+ "enable_low_vram_mode and enable_compile cannot be used together."
300
+ )
301
+
302
+ if args.weight_dtype == "fp32":
303
+ args.weight_dtype = torch.float32
304
+ elif args.weight_dtype == "fp16":
305
+ args.weight_dtype = torch.float16
306
+ else:
307
+ args.weight_dtype = torch.bfloat16
308
+
309
+ os.makedirs(args.output_folder, exist_ok=True)
310
+
311
+ if dist.is_available() and "RANK" in os.environ:
312
+ if args.cp_backend == "ulysses_anything":
313
+ dist.init_process_group(backend="cpu:gloo,cuda:nccl")
314
+ else:
315
+ dist.init_process_group(backend="nccl")
316
+ rank = dist.get_rank()
317
+ device = torch.device("cuda", rank % torch.cuda.device_count())
318
+ world_size = dist.get_world_size()
319
+ torch.cuda.set_device(device)
320
+ assert world_size == 1 or not args.enable_low_vram_mode, "enable_low_vram_mode is only for single GPU."
321
+ else:
322
+ rank = 0
323
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
324
+ world_size = 1
325
+
326
+ prompt = None
327
+ image_path = None
328
+ video_path = None
329
+ interpolate_time_list = None
330
+ if args.sample_type == "t2v" and args.prompt is None:
331
+ prompt = "An extreme close-up of an gray-haired man with a beard in his 60s, he is deep in thought pondering the history of the universe as he sits at a cafe in Paris, his eyes focus on people offscreen as they walk as he sits mostly motionless, he is dressed in a wool coat suit coat with a button-down shirt , he wears a brown beret and glasses and has a very professorial appearance, and the end he offers a subtle closed-mouth smile as if he found the answer to the mystery of life, the lighting is very cinematic with the golden light and the Parisian streets and city in the background, depth of field, cinematic 35mm film."
332
+ elif args.sample_type == "i2v" and (args.image_path is None and args.prompt is None):
333
+ image_path = (
334
+ "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/astronaut.jpg"
335
+ )
336
+ prompt = "An astronaut hatching from an egg, on the surface of the moon, the darkness and depth of space realised in the background. High quality, ultrarealistic detail and breath-taking movie-like camera shot."
337
+ elif args.sample_type == "v2v" and (args.video_path is None and args.prompt is None):
338
+ video_path = (
339
+ "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/hiker.mp4"
340
+ )
341
+ prompt = "A robot standing on a mountain top. The sun is setting in the background."
342
+ else:
343
+ image_path = args.image_path
344
+ video_path = args.video_path
345
+ prompt = args.prompt
346
+
347
+ transformer = HeliosTransformer3DModel.from_pretrained(
348
+ args.transformer_path,
349
+ subfolder="transformer",
350
+ torch_dtype=args.weight_dtype,
351
+ )
352
+ if not args.enable_compile:
353
+ transformer = replace_rmsnorm_with_fp32(transformer)
354
+ transformer = replace_all_norms_with_flash_norms(transformer)
355
+ replace_rope_with_flash_rope()
356
+ cuda_major = torch.cuda.get_device_capability()[0]
357
+ if cuda_major >= 9:
358
+ # H100/H800 (SM90+) with FA3
359
+ try:
360
+ transformer.set_attention_backend("_flash_3_hub")
361
+ except Exception:
362
+ transformer.set_attention_backend("flash_hub")
363
+ else:
364
+ # 4090/A100 etc (SM89+) with FA2
365
+ transformer.set_attention_backend("flash_hub")
366
+
367
+ vae = AutoencoderKLWan.from_pretrained(
368
+ args.base_model_path,
369
+ subfolder="vae",
370
+ torch_dtype=torch.float32,
371
+ )
372
+ scheduler = HeliosScheduler.from_pretrained(
373
+ args.base_model_path,
374
+ subfolder="scheduler",
375
+ )
376
+ pipe = HeliosPipeline.from_pretrained(
377
+ args.base_model_path,
378
+ transformer=transformer,
379
+ vae=vae,
380
+ scheduler=scheduler,
381
+ torch_dtype=args.weight_dtype,
382
+ )
383
+
384
+ if args.lora_path is not None:
385
+ pipe.load_lora_weights(args.lora_path, adapter_name="default")
386
+ pipe.set_adapters(["default"], adapter_weights=[1.0])
387
+
388
+ if args.partial_path is not None:
389
+ if not hasattr(args, "training_config"):
390
+ from argparse import Namespace
391
+
392
+ args.training_config = Namespace()
393
+ args.training_config.is_enable_stage1 = True
394
+ args.training_config.restrict_self_attn = True
395
+ args.training_config.is_amplify_history = True
396
+ args.training_config.is_use_gan = True
397
+ load_extra_components(args, transformer, args.partial_path)
398
+
399
+ if args.enable_compile:
400
+ torch.backends.cudnn.benchmark = True
401
+ pipe.text_encoder.compile(mode="max-autotune-no-cudagraphs", dynamic=False)
402
+ pipe.vae.compile(mode="max-autotune-no-cudagraphs", dynamic=False)
403
+ pipe.transformer.compile(mode="max-autotune-no-cudagraphs", dynamic=False)
404
+
405
+ if args.enable_low_vram_mode:
406
+ pipe.enable_group_offload(
407
+ onload_device=torch.device("cuda"),
408
+ offload_device=torch.device("cpu"),
409
+ offload_type=args.group_offloading_type,
410
+ num_blocks_per_group=args.num_blocks_per_group if args.group_offloading_type == "block_level" else None,
411
+ use_stream=True,
412
+ record_stream=True,
413
+ )
414
+ else:
415
+ pipe = pipe.to(device)
416
+
417
+ if world_size > 1 and args.enable_parallelism:
418
+ if args.cp_backend == "ring":
419
+ cp_config = ContextParallelConfig(ring_degree=world_size)
420
+ elif args.cp_backend == "unified":
421
+ cp_config = ContextParallelConfig(ring_degree=world_size // 2, ulysses_degree=world_size // 2)
422
+ elif args.cp_backend == "ulysses":
423
+ cp_config = ContextParallelConfig(ulysses_degree=world_size)
424
+ elif args.cp_backend == "ulysses_anything":
425
+ cp_config = ContextParallelConfig(ulysses_degree=world_size, ulysses_anything=True)
426
+ else:
427
+ raise ValueError(f"Unsupported cp_backend: {args.cp_backend}")
428
+
429
+ pipe.transformer.enable_parallelism(config=cp_config)
430
+
431
+ if args.prompt_txt_path is not None:
432
+ with open(args.prompt_txt_path, "r") as f:
433
+ prompt_list = [line.strip() for line in f.readlines() if line.strip()]
434
+ if not args.enable_parallelism:
435
+ prompt_list_with_idx = [(i, prompt) for i, prompt in enumerate(prompt_list)]
436
+ prompt_list_with_idx = prompt_list_with_idx[rank::world_size]
437
+ else:
438
+ prompt_list_with_idx = [(i, prompt) for i, prompt in enumerate(prompt_list)]
439
+
440
+ for idx, prompt in tqdm(prompt_list_with_idx, desc="Processing prompts"):
441
+ with torch.no_grad():
442
+ try:
443
+ pipe_output = pipe(
444
+ prompt=prompt,
445
+ negative_prompt=args.negative_prompt,
446
+ height=args.height,
447
+ width=args.width,
448
+ num_frames=args.num_frames,
449
+ num_inference_steps=args.num_inference_steps,
450
+ guidance_scale=args.guidance_scale,
451
+ generator=torch.Generator(device="cuda").manual_seed(args.seed),
452
+ # stage 1
453
+ history_sizes=[16, 2, 1],
454
+ num_latent_frames_per_chunk=args.num_latent_frames_per_chunk,
455
+ keep_first_frame=True,
456
+ # stage 2
457
+ is_enable_stage2=args.is_enable_stage2,
458
+ pyramid_num_inference_steps_list=args.pyramid_num_inference_steps_list,
459
+ # stage 3
460
+ is_skip_first_chunk=args.is_skip_first_chunk,
461
+ is_amplify_first_chunk=args.is_amplify_first_chunk,
462
+ # cfg zero
463
+ use_zero_init=args.use_zero_init,
464
+ zero_steps=args.zero_steps,
465
+ # i2v
466
+ image=load_image(image_path).resize((args.width, args.height))
467
+ if image_path is not None
468
+ else None,
469
+ image_noise_sigma_min=args.image_noise_sigma_min,
470
+ image_noise_sigma_max=args.image_noise_sigma_max,
471
+ # v2v
472
+ video=load_video(video_path) if video_path is not None else None,
473
+ video_noise_sigma_min=args.video_noise_sigma_min,
474
+ video_noise_sigma_max=args.video_noise_sigma_max,
475
+ # interpolate_prompt
476
+ use_interpolate_prompt=args.use_interpolate_prompt,
477
+ interpolation_steps=args.interpolation_steps,
478
+ interpolate_time_list=interpolate_time_list,
479
+ output_relative_l1=args.visualize_relative_l1,
480
+ )
481
+ output = pipe_output.frames[0]
482
+ except Exception:
483
+ continue
484
+ if not args.enable_parallelism or rank == 0:
485
+ sample_dir = build_sample_output_dir(args.output_folder, prompt)
486
+ output_path = sample_dir / "video.mp4"
487
+ export_to_video(output, str(output_path), fps=24)
488
+ if args.visualize_relative_l1:
489
+ save_relative_l1_outputs(pipe_output.relative_l1, sample_dir)
490
+ elif args.image_prompt_csv_path is not None:
491
+ df = pd.read_csv(args.image_prompt_csv_path)
492
+ if not args.enable_parallelism:
493
+ df = df.iloc[rank::world_size]
494
+
495
+ for idx, row in tqdm(df.iterrows(), total=len(df), desc="Processing prompts"):
496
+ prompt = row.get("refined_prompt") or row["prompt"]
497
+ image_path = os.path.join(args.base_image_prompt_path, row["image_name"])
498
+
499
+ with torch.no_grad():
500
+ try:
501
+ pipe_output = pipe(
502
+ prompt=prompt,
503
+ negative_prompt=args.negative_prompt,
504
+ height=args.height,
505
+ width=args.width,
506
+ num_frames=args.num_frames,
507
+ num_inference_steps=args.num_inference_steps,
508
+ guidance_scale=args.guidance_scale,
509
+ generator=torch.Generator(device="cuda").manual_seed(args.seed),
510
+ # stage 1
511
+ history_sizes=[16, 2, 1],
512
+ num_latent_frames_per_chunk=args.num_latent_frames_per_chunk,
513
+ keep_first_frame=True,
514
+ # stage 2
515
+ is_enable_stage2=args.is_enable_stage2,
516
+ pyramid_num_inference_steps_list=args.pyramid_num_inference_steps_list,
517
+ # stage 3
518
+ is_skip_first_chunk=args.is_skip_first_chunk,
519
+ is_amplify_first_chunk=args.is_amplify_first_chunk,
520
+ # cfg zero
521
+ use_zero_init=args.use_zero_init,
522
+ zero_steps=args.zero_steps,
523
+ # i2v
524
+ image=load_image(image_path).resize((args.width, args.height))
525
+ if image_path is not None
526
+ else None,
527
+ image_noise_sigma_min=args.image_noise_sigma_min,
528
+ image_noise_sigma_max=args.image_noise_sigma_max,
529
+ # v2v
530
+ video=load_video(video_path) if video_path is not None else None,
531
+ video_noise_sigma_min=args.video_noise_sigma_min,
532
+ video_noise_sigma_max=args.video_noise_sigma_max,
533
+ # interpolate_prompt
534
+ use_interpolate_prompt=args.use_interpolate_prompt,
535
+ interpolation_steps=args.interpolation_steps,
536
+ interpolate_time_list=interpolate_time_list,
537
+ output_relative_l1=args.visualize_relative_l1,
538
+ )
539
+ output = pipe_output.frames[0]
540
+ except Exception:
541
+ continue
542
+ if not args.enable_parallelism or rank == 0:
543
+ sample_dir = build_sample_output_dir(args.output_folder, prompt)
544
+ output_path = sample_dir / "video.mp4"
545
+ export_to_video(output, str(output_path), fps=24)
546
+ if args.visualize_relative_l1:
547
+ save_relative_l1_outputs(pipe_output.relative_l1, sample_dir)
548
+ elif args.interactive_prompt_csv_path is not None:
549
+ df = pd.read_csv(args.interactive_prompt_csv_path)
550
+
551
+ df = df.sort_values(by=["id", "prompt_index"])
552
+ all_video_ids = df["id"].unique()
553
+
554
+ if not args.enable_parallelism:
555
+ my_video_ids = all_video_ids[rank::world_size]
556
+ else:
557
+ my_video_ids = all_video_ids
558
+
559
+ for video_id in tqdm(my_video_ids, desc="Processing prompts"):
560
+ group_df = df[df["id"] == video_id]
561
+
562
+ if "refined_prompt" in df.columns:
563
+ prompt_list = group_df["refined_prompt"].fillna(group_df["prompt"]).tolist()
564
+ else:
565
+ prompt_list = group_df["prompt"].tolist()
566
+ interpolate_time_list = [args.interpolate_time] * len(prompt_list)
567
+
568
+ with torch.no_grad():
569
+ try:
570
+ pipe_output = pipe(
571
+ prompt=prompt_list,
572
+ negative_prompt=args.negative_prompt,
573
+ height=args.height,
574
+ width=args.width,
575
+ num_frames=args.num_frames,
576
+ num_inference_steps=args.num_inference_steps,
577
+ guidance_scale=args.guidance_scale,
578
+ generator=torch.Generator(device="cuda").manual_seed(args.seed),
579
+ # stage 1
580
+ history_sizes=[16, 2, 1],
581
+ num_latent_frames_per_chunk=args.num_latent_frames_per_chunk,
582
+ keep_first_frame=True,
583
+ # stage 2
584
+ is_enable_stage2=args.is_enable_stage2,
585
+ pyramid_num_inference_steps_list=args.pyramid_num_inference_steps_list,
586
+ # stage 3
587
+ is_skip_first_chunk=args.is_skip_first_chunk,
588
+ is_amplify_first_chunk=args.is_amplify_first_chunk,
589
+ # cfg zero
590
+ use_zero_init=args.use_zero_init,
591
+ zero_steps=args.zero_steps,
592
+ # i2v
593
+ image=load_image(image_path).resize((args.width, args.height))
594
+ if image_path is not None
595
+ else None,
596
+ image_noise_sigma_min=args.image_noise_sigma_min,
597
+ image_noise_sigma_max=args.image_noise_sigma_max,
598
+ # v2v
599
+ video=load_video(video_path) if video_path is not None else None,
600
+ video_noise_sigma_min=args.video_noise_sigma_min,
601
+ video_noise_sigma_max=args.video_noise_sigma_max,
602
+ # interpolate_prompt
603
+ use_interpolate_prompt=args.use_interpolate_prompt,
604
+ interpolation_steps=args.interpolation_steps,
605
+ interpolate_time_list=interpolate_time_list,
606
+ output_relative_l1=args.visualize_relative_l1,
607
+ )
608
+ output = pipe_output.frames[0]
609
+ except Exception:
610
+ continue
611
+ if not args.enable_parallelism or rank == 0:
612
+ sample_dir = build_sample_output_dir(args.output_folder, prompt_list)
613
+ output_path = sample_dir / "video.mp4"
614
+ export_to_video(output, str(output_path), fps=24)
615
+ if args.visualize_relative_l1:
616
+ save_relative_l1_outputs(pipe_output.relative_l1, sample_dir)
617
+ else:
618
+ with torch.no_grad():
619
+ # import time
620
+ # for _ in range(20):
621
+ # start_time = time.time()
622
+ pipe_output = pipe(
623
+ prompt=prompt,
624
+ negative_prompt=args.negative_prompt,
625
+ height=args.height,
626
+ width=args.width,
627
+ num_frames=args.num_frames,
628
+ num_inference_steps=args.num_inference_steps,
629
+ guidance_scale=args.guidance_scale,
630
+ generator=torch.Generator(device="cuda").manual_seed(args.seed),
631
+ # stage 1
632
+ history_sizes=[16, 2, 1],
633
+ num_latent_frames_per_chunk=args.num_latent_frames_per_chunk,
634
+ keep_first_frame=True,
635
+ # stage 2
636
+ is_enable_stage2=args.is_enable_stage2,
637
+ pyramid_num_inference_steps_list=args.pyramid_num_inference_steps_list,
638
+ # stage 3
639
+ is_skip_first_chunk=args.is_skip_first_chunk,
640
+ is_amplify_first_chunk=args.is_amplify_first_chunk,
641
+ # cfg zero
642
+ use_zero_init=args.use_zero_init,
643
+ zero_steps=args.zero_steps,
644
+ # i2v
645
+ image=load_image(image_path).resize((args.width, args.height)) if image_path is not None else None,
646
+ image_noise_sigma_min=args.image_noise_sigma_min,
647
+ image_noise_sigma_max=args.image_noise_sigma_max,
648
+ # v2v
649
+ video=load_video(video_path) if video_path is not None else None,
650
+ video_noise_sigma_min=args.video_noise_sigma_min,
651
+ video_noise_sigma_max=args.video_noise_sigma_max,
652
+ # interpolate_prompt
653
+ use_interpolate_prompt=args.use_interpolate_prompt,
654
+ interpolation_steps=args.interpolation_steps,
655
+ interpolate_time_list=interpolate_time_list,
656
+ output_relative_l1=args.visualize_relative_l1,
657
+ )
658
+ output = pipe_output.frames[0]
659
+ # elapsed_time = time.time() - start_time
660
+ # print(f"Inference time: {elapsed_time:.2f} seconds ({elapsed_time/60:.2f} minutes)")
661
+
662
+ if not args.enable_parallelism or rank == 0:
663
+ sample_dir = build_sample_output_dir(args.output_folder, prompt)
664
+ output_path = sample_dir / "video.mp4"
665
+ export_to_video(output, str(output_path), fps=24)
666
+ if args.visualize_relative_l1:
667
+ save_relative_l1_outputs(pipe_output.relative_l1, sample_dir)
668
+
669
+ print(f"Max memory: {torch.cuda.max_memory_allocated() / 1024**3:.3f} GB")
670
+
671
+
672
+ if __name__ == "__main__":
673
+ main()
Helios/_DEV3/install.sh ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ pip install -r requirements.txt
2
+
3
+ rm -rf ~/.triton/cache/
4
+ rm -rf /tmp/torchinductor_*
5
+
6
+ pip uninstall triton torchao xformers wandb tensorflow tensorflow-cpu -y
7
+ pip install wandb==0.23.0 triton==3.6.0
8
+
9
+ rm -rf ~/.triton/cache/
10
+ rm -rf /tmp/torchinductor_*
Helios/_DEV3/requirements.txt ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ torch==2.10.0
2
+ torchvision==0.25.0
3
+ torchaudio==2.10.0
4
+ triton==3.6.0
5
+ kernels==0.13.0
6
+ # diffusers==0.36.0
7
+ # transformers==4.57.6
8
+ git+https://github.com/huggingface/diffusers.git
9
+ transformers==5.3.0
10
+ sentence-transformers==5.2.3
11
+ accelerate==1.12.0
12
+ deepspeed==0.18.4
13
+ peft==0.18.1
14
+ huggingface-hub==1.4.1
15
+ zstandard==0.25.0
16
+ wandb==0.23.0
17
+ video-reader-rs==0.4.1
18
+ numpy<2.0.0
19
+ opencv-python
20
+ gradio
21
+ spaces
22
+ moviepy
23
+ imageio-ffmpeg
24
+ ftfy
25
+ Jinja2
26
+ einops
27
+ nvitop
28
+ packaging
29
+ ninja
30
+ omegaconf
31
+ mpi4py
32
+ hf-doc-builder
33
+ torchdata
34
+ loguru
35
+ tf_keras
Helios/_DEV3/requirements_npu.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ # Please refer to here for installation the latest version: https://github.com/Ascend/pytorch?tab=readme-ov-file#ascend-auxiliary-software
2
+ torch==2.9.0
3
+ torchvision==0.24.0
4
+ torchaudio==2.9.0
5
+ torch_npu==2.9.0
6
+ triton==3.5.1
Helios/_DEV3/run_bench.sh ADDED
@@ -0,0 +1,275 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # =============================================================================
3
+ # Helios Benchmark Inference Runner
4
+ # 用法: bash run_bench.sh [--gpus 5 6 7] [--prompt_range 0-50] [--num_frames 240]
5
+ # [--version base] [--version mid distilled]
6
+ # 默认使用所有可见 GPU;默认跑全部版本(base/mid/distilled),也可手动指定版本
7
+ # 同一时刻只跑一个版本;若有多张卡,会先扫描输出目录,只把缺失 case 均分到多张卡并行
8
+ # 低显存: LOW_VRAM=1 bash run_bench.sh
9
+ # =============================================================================
10
+ set -euo pipefail
11
+
12
+ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
13
+ if [[ -n "${PYTHON:-}" ]]; then
14
+ PYTHON_BIN="${PYTHON}"
15
+ elif command -v python3 >/dev/null 2>&1; then
16
+ PYTHON_BIN="$(command -v python3)"
17
+ elif command -v python >/dev/null 2>&1; then
18
+ PYTHON_BIN="$(command -v python)"
19
+ else
20
+ echo "Python interpreter not found. Set PYTHON=/path/to/python." >&2
21
+ exit 1
22
+ fi
23
+
24
+ GPUS=()
25
+ PROMPT_START="${PROMPT_START:-0}"
26
+ PROMPT_END="${PROMPT_END:-100}"
27
+ NUM_FRAMES="${NUM_FRAMES:-}"
28
+ VERSIONS=(base mid distilled)
29
+ OUTPUT_ROOT="${OUTPUT_ROOT:-}"
30
+ PROMPT_FILE="${PROMPT_FILE:-${SCRIPT_DIR}/demo_data/MovieGenVideoBench_extended.txt}"
31
+ LOW_VRAM="${LOW_VRAM:-0}"
32
+
33
+ discover_gpus() {
34
+ if ! command -v nvidia-smi >/dev/null 2>&1; then
35
+ echo "nvidia-smi not found; use --gpus to specify GPU ids explicitly." >&2
36
+ exit 1
37
+ fi
38
+
39
+ mapfile -t GPUS < <(nvidia-smi --query-gpu=index --format=csv,noheader,nounits)
40
+ if [[ ${#GPUS[@]} -eq 0 ]]; then
41
+ echo "No GPUs found." >&2
42
+ exit 1
43
+ fi
44
+ }
45
+
46
+ while [[ $# -gt 0 ]]; do
47
+ case "$1" in
48
+ --gpus) shift; GPUS=(); while [[ $# -gt 0 && ! "$1" =~ ^-- ]]; do GPUS+=("$1"); shift; done ;;
49
+ --prompt_range)
50
+ if [[ ! "$2" =~ ^([0-9]+)-([0-9]+)$ ]]; then
51
+ echo "Invalid --prompt_range: $2 (expected START-END, e.g. 0-50)" >&2
52
+ exit 1
53
+ fi
54
+ PROMPT_START="${BASH_REMATCH[1]}"
55
+ PROMPT_END="${BASH_REMATCH[2]}"
56
+ shift 2
57
+ ;;
58
+ --prompt_start) PROMPT_START="$2"; shift 2 ;;
59
+ --prompt_end) PROMPT_END="$2"; shift 2 ;;
60
+ --num_frames) NUM_FRAMES="$2"; shift 2 ;;
61
+ --version) shift; VERSIONS=(); while [[ $# -gt 0 && ! "$1" =~ ^-- ]]; do VERSIONS+=("$1"); shift; done ;;
62
+ --output_root) OUTPUT_ROOT="$2"; shift 2 ;;
63
+ --prompt_file) PROMPT_FILE="$2"; shift 2 ;;
64
+ *) echo "Unknown option: $1"; exit 1 ;;
65
+ esac
66
+ done
67
+
68
+ if [[ ${#GPUS[@]} -eq 0 ]]; then
69
+ discover_gpus
70
+ fi
71
+
72
+ if [[ ${#VERSIONS[@]} -eq 0 ]]; then
73
+ echo "No versions specified. Use --version base [mid distilled]." >&2
74
+ exit 1
75
+ fi
76
+
77
+ if [[ ! "${PROMPT_START}" =~ ^[0-9]+$ ]] || [[ ! "${PROMPT_END}" =~ ^[0-9]+$ ]]; then
78
+ echo "prompt_start and prompt_end must be non-negative integers." >&2
79
+ exit 1
80
+ fi
81
+
82
+ if (( PROMPT_END <= PROMPT_START )); then
83
+ echo "prompt_end must be greater than prompt_start." >&2
84
+ exit 1
85
+ fi
86
+
87
+ if [[ -z "${OUTPUT_ROOT}" ]]; then
88
+ if [[ -n "${NUM_FRAMES}" ]]; then
89
+ OUTPUT_ROOT="${SCRIPT_DIR}/outputs/num_frames_${NUM_FRAMES}"
90
+ else
91
+ OUTPUT_ROOT="${SCRIPT_DIR}/outputs/num_frames_default"
92
+ fi
93
+ fi
94
+
95
+ echo "============================================================"
96
+ echo " Helios Benchmark Inference"
97
+ echo " $(date '+%Y-%m-%d %H:%M:%S')"
98
+ echo " Python: ${PYTHON_BIN}"
99
+ echo " GPUs: ${GPUS[*]} | Prompt range: ${PROMPT_START}-${PROMPT_END} | Versions: ${VERSIONS[*]}"
100
+ [[ -n "${NUM_FRAMES}" ]] && echo " Frames: ${NUM_FRAMES}"
101
+ echo " Prompt file: ${PROMPT_FILE}"
102
+ echo " Output: ${OUTPUT_ROOT}"
103
+ echo "============================================================"
104
+
105
+ mkdir -p "${OUTPUT_ROOT}"
106
+
107
+ if [[ ! -f "${PROMPT_FILE}" ]]; then
108
+ echo "Prompt file not found: ${PROMPT_FILE}" >&2
109
+ exit 1
110
+ fi
111
+
112
+ TOTAL_PROMPTS=$(awk 'NF {count++} END {print count + 0}' "${PROMPT_FILE}")
113
+ if (( PROMPT_START >= TOTAL_PROMPTS )); then
114
+ echo "prompt_start (${PROMPT_START}) is out of range; prompt file has ${TOTAL_PROMPTS} non-empty prompts." >&2
115
+ exit 1
116
+ fi
117
+
118
+ if (( PROMPT_END > TOTAL_PROMPTS )); then
119
+ echo "prompt_end (${PROMPT_END}) exceeds total prompts (${TOTAL_PROMPTS}); clamping to ${TOTAL_PROMPTS}."
120
+ PROMPT_END="${TOTAL_PROMPTS}"
121
+ fi
122
+
123
+ EXTRA=()
124
+ if [[ "${LOW_VRAM}" == "1" ]]; then
125
+ EXTRA+=(--enable_low_vram_mode)
126
+ fi
127
+ if [[ -n "${NUM_FRAMES}" ]]; then
128
+ EXTRA+=(--num_frames "${NUM_FRAMES}")
129
+ fi
130
+
131
+ EXIT_CODE=0
132
+ WORKER_PIDS=()
133
+ WORKER_GPUS=()
134
+ WORKER_SHARDS=()
135
+
136
+ prepare_missing_shards() {
137
+ local version="$1"
138
+ local shard_dir="${OUTPUT_ROOT}/shards/${version}_${PROMPT_START}_${PROMPT_END}_$$"
139
+ mkdir -p "${shard_dir}"
140
+
141
+ "${PYTHON_BIN}" - \
142
+ "${PROMPT_FILE}" \
143
+ "${OUTPUT_ROOT}" \
144
+ "${version}" \
145
+ "${PROMPT_START}" \
146
+ "${PROMPT_END}" \
147
+ "${#GPUS[@]}" \
148
+ "${shard_dir}" <<'PY'
149
+ import os
150
+ import re
151
+ import sys
152
+ from pathlib import Path
153
+
154
+ prompt_file = Path(sys.argv[1])
155
+ output_root = Path(sys.argv[2])
156
+ version = sys.argv[3]
157
+ prompt_start = int(sys.argv[4])
158
+ prompt_end = int(sys.argv[5])
159
+ gpu_count = int(sys.argv[6])
160
+ shard_dir = Path(sys.argv[7])
161
+
162
+ with prompt_file.open("r", encoding="utf-8") as f:
163
+ prompts = [line.strip() for line in f if line.strip()]
164
+
165
+ def sanitize_filename(text, max_len=80):
166
+ text = text.strip().lower()
167
+ text = re.sub(r"[^a-z0-9]+", "_", text)
168
+ text = text.strip("_")
169
+ return text[:max_len]
170
+
171
+ missing = []
172
+ existing = 0
173
+ version_dir = output_root / "by_version" / version
174
+ for idx in range(prompt_start, prompt_end):
175
+ slug = sanitize_filename(prompts[idx])
176
+ video_path = version_dir / f"{idx:04d}_{slug}.mp4"
177
+ if video_path.is_file() and video_path.stat().st_size > 0:
178
+ existing += 1
179
+ else:
180
+ missing.append(idx)
181
+
182
+ print(
183
+ f"[scan] version={version} range={prompt_start}-{prompt_end} "
184
+ f"existing={existing} missing={len(missing)} output={version_dir}",
185
+ file=sys.stderr,
186
+ )
187
+
188
+ if not missing:
189
+ sys.exit(0)
190
+
191
+ active_workers = min(gpu_count, len(missing))
192
+ base_chunk = len(missing) // active_workers
193
+ remainder = len(missing) % active_workers
194
+ offset = 0
195
+
196
+ for shard_idx in range(active_workers):
197
+ shard_size = base_chunk + (1 if shard_idx < remainder else 0)
198
+ shard_indices = missing[offset:offset + shard_size]
199
+ offset += shard_size
200
+ shard_path = shard_dir / f"shard_{shard_idx:02d}.txt"
201
+ shard_path.write_text(
202
+ "".join(f"{idx}\n" for idx in shard_indices),
203
+ encoding="utf-8",
204
+ )
205
+ print(shard_path)
206
+ print(
207
+ f"[shard] version={version} shard={shard_idx} count={len(shard_indices)} "
208
+ f"indices={shard_indices[0]}-{shard_indices[-1]} file={shard_path}",
209
+ file=sys.stderr,
210
+ )
211
+ PY
212
+ }
213
+
214
+ launch_job() {
215
+ local version="$1"
216
+ local gpu="$2"
217
+ local shard_file="$3"
218
+ local shard_id
219
+ shard_id="$(basename "${shard_file}" .txt)"
220
+ local timing_file="${OUTPUT_ROOT}/timing_${version}_${shard_id}.txt"
221
+
222
+ echo "[launch] version=${version} gpu=${gpu} shard=${shard_id} indices=${shard_file} output=${OUTPUT_ROOT}"
223
+ "${PYTHON_BIN}" "${SCRIPT_DIR}/bench_infer.py" \
224
+ --prompt_file "${PROMPT_FILE}" \
225
+ --prompt_start "${PROMPT_START}" \
226
+ --prompt_end "${PROMPT_END}" \
227
+ --prompt_indices_file "${shard_file}" \
228
+ --output_root "${OUTPUT_ROOT}" \
229
+ --timing_file "${timing_file}" \
230
+ --version "${version}" \
231
+ --gpu "${gpu}" \
232
+ "${EXTRA[@]}" &
233
+
234
+ WORKER_PIDS+=("$!")
235
+ WORKER_GPUS+=("${gpu}")
236
+ WORKER_SHARDS+=("${shard_id}")
237
+ }
238
+
239
+ wait_for_current_version() {
240
+ local version="$1"
241
+ for idx in "${!WORKER_PIDS[@]}"; do
242
+ local pid="${WORKER_PIDS[$idx]}"
243
+ local gpu="${WORKER_GPUS[$idx]}"
244
+ local shard_id="${WORKER_SHARDS[$idx]}"
245
+ if wait "${pid}"; then
246
+ echo "[done] ${version} finished on gpu=${gpu} shard=${shard_id}"
247
+ else
248
+ echo "[fail] ${version} failed on gpu=${gpu} shard=${shard_id}"
249
+ EXIT_CODE=1
250
+ fi
251
+ done
252
+ WORKER_PIDS=()
253
+ WORKER_GPUS=()
254
+ WORKER_SHARDS=()
255
+ }
256
+
257
+ for version in "${VERSIONS[@]}"; do
258
+ echo ""
259
+ echo "-------------------- version=${version} --------------------"
260
+ mapfile -t SHARD_FILES < <(prepare_missing_shards "${version}")
261
+ if (( ${#SHARD_FILES[@]} == 0 )); then
262
+ echo "[skip] version=${version} has no missing cases in ${PROMPT_START}-${PROMPT_END}"
263
+ continue
264
+ fi
265
+
266
+ for worker_idx in "${!SHARD_FILES[@]}"; do
267
+ launch_job "${version}" "${GPUS[$worker_idx]}" "${SHARD_FILES[$worker_idx]}"
268
+ done
269
+ wait_for_current_version "${version}"
270
+ done
271
+
272
+ echo ""
273
+ echo "Done. Per-shard timing reports are under ${OUTPUT_ROOT}/timing_<version>_shard_<id>.txt"
274
+
275
+ exit ${EXIT_CODE:-0}
Helios/_DEV3/train_helios.py ADDED
The diff for this file is too large to render. See raw diff
 
Helios/__pycache__/bench_infer.cpython-312.pyc ADDED
Binary file (27.4 kB). View file
 
Helios/app.py ADDED
@@ -0,0 +1,320 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import tempfile
2
+ import time
3
+
4
+ import gradio as gr
5
+ import spaces
6
+ import torch
7
+
8
+ from torch.utils._pytree import tree_map
9
+ from diffusers import AutoencoderKLWan, HeliosDMDScheduler, HeliosPyramidPipeline
10
+ from diffusers.utils import export_to_video, load_image, load_video
11
+
12
+
13
+ # ---------------------------------------------------------------------------
14
+ # Pre-load model
15
+ # ---------------------------------------------------------------------------
16
+ MODEL_ID = "BestWishYsh/Helios-Distilled"
17
+
18
+ vae = AutoencoderKLWan.from_pretrained(MODEL_ID, subfolder="vae", torch_dtype=torch.float32)
19
+ scheduler = HeliosDMDScheduler.from_pretrained(MODEL_ID, subfolder="scheduler")
20
+ pipe = HeliosPyramidPipeline.from_pretrained(
21
+ MODEL_ID, vae=vae, scheduler=scheduler, torch_dtype=torch.bfloat16, is_distilled=True
22
+ )
23
+ pipe.to("cuda")
24
+
25
+ cuda_major = torch.cuda.get_device_capability()[0]
26
+ if cuda_major >= 9:
27
+ # H100/H800 (SM90+) with FA3
28
+ try:
29
+ pipe.transformer.set_attention_backend("_flash_3_hub")
30
+ except Exception:
31
+ pipe.transformer.set_attention_backend("flash_hub")
32
+ else:
33
+ # 4090/A100 etc (SM89+) with FA2
34
+ pipe.transformer.set_attention_backend("flash_hub")
35
+
36
+ # ---------------------------------------------------------------------------
37
+ # AoTI
38
+ # ---------------------------------------------------------------------------
39
+
40
+ # Dynamic shapes: within a generation, only hidden_states H/W change across
41
+ # pyramid stages (history latents stay at full resolution). text_seq_length
42
+ # varies between different prompts.
43
+ _AUTO = torch.export.Dim.AUTO
44
+
45
+ TRANSFORMER_DYNAMIC_SHAPES = {
46
+ "hidden_states": {
47
+ 3: _AUTO, # H — doubles each pyramid stage
48
+ 4: _AUTO, # W — doubles each pyramid stage
49
+ },
50
+ "encoder_hidden_states": {
51
+ 1: _AUTO, # text_seq_length — varies with prompt
52
+ },
53
+ }
54
+
55
+ INDUCTOR_CONFIGS = {
56
+ "conv_1x1_as_mm": True,
57
+ "epilogue_fusion": False,
58
+ "coordinate_descent_tuning": True,
59
+ "coordinate_descent_check_all_directions": True,
60
+ # "max_autotune": True,
61
+ "triton.cudagraphs": True,
62
+ }
63
+
64
+ @spaces.GPU(duration=1500) # maximum duration allowed during startup
65
+ def compile_transformer():
66
+ with spaces.aoti_capture(pipe.transformer) as call:
67
+ pipe(
68
+ "arbitrary example prompt",
69
+ height=384,
70
+ width=640,
71
+ num_frames=33,
72
+ guidance_scale=1.0,
73
+ generator=torch.Generator(device="cuda").manual_seed(42),
74
+ pyramid_num_inference_steps_list=[2, 2, 2],
75
+ is_amplify_first_chunk=True,
76
+ )
77
+
78
+ dynamic_shapes = tree_map(lambda t: None, call.kwargs)
79
+ dynamic_shapes |= TRANSFORMER_DYNAMIC_SHAPES
80
+
81
+ with torch.no_grad():
82
+ exported = torch.export.export(
83
+ pipe.transformer,
84
+ args=call.args,
85
+ kwargs=call.kwargs,
86
+ dynamic_shapes=dynamic_shapes,
87
+ )
88
+
89
+ return spaces.aoti_compile(exported, INDUCTOR_CONFIGS)
90
+
91
+ compiled_transformer = compile_transformer()
92
+ spaces.aoti_apply(compiled_transformer, pipe.transformer)
93
+
94
+
95
+ # ---------------------------------------------------------------------------
96
+ # Generation
97
+ # ---------------------------------------------------------------------------
98
+ @spaces.GPU(duration=60)
99
+ def generate_video(
100
+ mode: str,
101
+ prompt: str,
102
+ image_input,
103
+ video_input,
104
+ height: int,
105
+ width: int,
106
+ num_frames: int,
107
+ num_inference_steps: int,
108
+ seed: int,
109
+ is_amplify_first_chunk: bool,
110
+ progress=gr.Progress(track_tqdm=True),
111
+ ):
112
+ if not prompt:
113
+ raise gr.Error("Please provide a prompt.")
114
+
115
+ generator = torch.Generator(device="cuda").manual_seed(int(seed))
116
+
117
+ kwargs = {
118
+ "prompt": prompt,
119
+ "height": int(height),
120
+ "width": int(width),
121
+ "num_frames": int(num_frames),
122
+ "guidance_scale": 1.0,
123
+ "generator": generator,
124
+ "output_type": "np",
125
+ "pyramid_num_inference_steps_list": [
126
+ int(num_inference_steps),
127
+ int(num_inference_steps),
128
+ int(num_inference_steps),
129
+ ],
130
+ "is_amplify_first_chunk": is_amplify_first_chunk,
131
+ }
132
+
133
+ if mode == "Image-to-Video" and image_input is not None:
134
+ img = load_image(image_input).resize((int(width), int(height)))
135
+ kwargs["image"] = img
136
+ elif mode == "Video-to-Video" and video_input is not None:
137
+ kwargs["video"] = load_video(video_input)
138
+
139
+ t0 = time.time()
140
+ output = pipe(**kwargs).frames[0]
141
+ elapsed = time.time() - t0
142
+
143
+ tmp = tempfile.NamedTemporaryFile(suffix=".mp4", delete=False)
144
+ export_to_video(output, tmp.name, fps=24)
145
+ info = f"Generated in {elapsed:.1f}s · {num_frames} frames · {height}×{width}"
146
+ return tmp.name, info
147
+
148
+
149
+ # ---------------------------------------------------------------------------
150
+ # UI Setup
151
+ # ---------------------------------------------------------------------------
152
+ def update_conditional_visibility(mode):
153
+ if mode == "Image-to-Video":
154
+ return gr.update(visible=True), gr.update(visible=False)
155
+ elif mode == "Video-to-Video":
156
+ return gr.update(visible=False), gr.update(visible=True)
157
+ else:
158
+ return gr.update(visible=False), gr.update(visible=False)
159
+
160
+
161
+ CSS = """
162
+ #header { text-align: center; margin-bottom: 1.5em; }
163
+ #header h1 { font-size: 2.2em; margin-bottom: 0.2em; }
164
+ .logo { max-height: 100px; margin: 0 auto 10px auto; display: block; }
165
+ .link-buttons { display: flex; justify-content: center; gap: 15px; margin-top: 10px; }
166
+ .link-buttons a {
167
+ background-color: #2b3137;
168
+ color: #ffffff !important;
169
+ padding: 8px 20px;
170
+ border-radius: 6px;
171
+ text-decoration: none;
172
+ font-weight: 600;
173
+ font-size: 1em;
174
+ transition: all 0.2s ease-in-out;
175
+ box-shadow: 0 2px 4px rgba(0,0,0,0.1);
176
+ }
177
+ .link-buttons a:hover { background-color: #4a535c; transform: translateY(-1px); }
178
+ .contain { max-width: 1350px; margin: 0 auto !important; }
179
+ """
180
+
181
+ with gr.Blocks(title="Helios Video Generation") as demo:
182
+ gr.HTML(
183
+ """
184
+ <div style='display: flex; align-items: center; justify-content: center; width: 100%;'>
185
+ <img src="https://raw.githubusercontent.com/SHYuanBest/shyuanbest_media/main/Helios/logo_white.png" style='width: 400px; height: auto;' />
186
+ </div>
187
+ <div id="header">
188
+ <h1>🎬 Helios 14B Distilled: Real Real-Time Long Video Generation Model</h1>
189
+ <p style="font-size: 1.1em; color: #666; margin-top: 0.5em; margin-bottom: 1em;">
190
+ If you like our project, please give us a star ⭐ on GitHub for the latest update.
191
+ </p>
192
+ <div class="link-buttons">
193
+ <a href="https://github.com/PKU-YuanGroup/Helios" target="_blank">💻 Code</a>
194
+ <a href="https://pku-yuangroup.github.io/Helios-Page" target="_blank">📄 Page</a>
195
+ <a href="https://www.youtube.com/watch?v=vd_AgHtOUFQ" target="_blank">🎥 Main Feature</a>
196
+ <a href="https://www.youtube.com/watch?v=1GeIU2Dn7UY" target="_blank">⚡ Inference Speed</a>
197
+ </div>
198
+ </div>
199
+ """
200
+ )
201
+
202
+ with gr.Row():
203
+ with gr.Column(scale=1):
204
+ mode = gr.Radio(
205
+ choices=["Text-to-Video", "Image-to-Video", "Video-to-Video"],
206
+ value="Text-to-Video",
207
+ label="Generation Mode",
208
+ )
209
+ image_input = gr.Image(label="Image (for I2V)", type="filepath", visible=False)
210
+ video_input = gr.Video(label="Video (for V2V)", visible=False)
211
+ prompt = gr.Textbox(
212
+ label="Prompt",
213
+ lines=4,
214
+ value=(
215
+ "A vibrant tropical fish swimming gracefully among colorful coral reefs in "
216
+ "a clear, turquoise ocean. The fish has bright blue and yellow scales with a "
217
+ "small, distinctive orange spot on its side, its fins moving fluidly. The coral "
218
+ "reefs are alive with a variety of marine life, including small schools of "
219
+ "colorful fish and sea turtles gliding by. The water is crystal clear, allowing "
220
+ "for a view of the sandy ocean floor below. The reef itself is adorned with a mix "
221
+ "of hard and soft corals in shades of red, orange, and green. The photo captures "
222
+ "the fish from a slightly elevated angle, emphasizing its lively movements and the "
223
+ "vivid colors of its surroundings. A close-up shot with dynamic movement."
224
+ ),
225
+ )
226
+ with gr.Accordion("Advanced Settings", open=False):
227
+ with gr.Row():
228
+ height = gr.Number(value=384, label="Height", precision=0, interactive=False)
229
+ width = gr.Number(value=640, label="Width", precision=0, interactive=False)
230
+ with gr.Row():
231
+ num_frames = gr.Slider(33, 231, value=231, step=33, label="Num Frames")
232
+ num_inference_steps = gr.Slider(1, 10, value=2, step=1, label="Steps per stage")
233
+ with gr.Row():
234
+ seed = gr.Number(value=42, label="Seed", precision=0)
235
+ is_amplify_first_chunk = gr.Checkbox(label="Amplify First Chunk", value=True)
236
+
237
+ generate_btn = gr.Button("🚀 Generate Video", variant="primary", size="lg")
238
+
239
+ with gr.Column(scale=1):
240
+ video_output = gr.Video(label="Generated Video", autoplay=True)
241
+ info_output = gr.Textbox(label="Info", interactive=False)
242
+
243
+ mode.change(fn=update_conditional_visibility, inputs=[mode], outputs=[image_input, video_input])
244
+ generate_btn.click(
245
+ fn=generate_video,
246
+ inputs=[
247
+ mode,
248
+ prompt,
249
+ image_input,
250
+ video_input,
251
+ height,
252
+ width,
253
+ num_frames,
254
+ num_inference_steps,
255
+ seed,
256
+ is_amplify_first_chunk,
257
+ ],
258
+ outputs=[video_output, info_output],
259
+ )
260
+
261
+ gr.Examples(
262
+ examples=[
263
+ [
264
+ "Text-to-Video",
265
+ "A vibrant tropical fish swimming gracefully among colorful coral reefs in "
266
+ "a clear, turquoise ocean. The fish has bright blue and yellow scales with a "
267
+ "small, distinctive orange spot on its side, its fins moving fluidly. The coral "
268
+ "reefs are alive with a variety of marine life, including small schools of "
269
+ "colorful fish and sea turtles gliding by. The water is crystal clear, allowing "
270
+ "for a view of the sandy ocean floor below. The reef itself is adorned with a mix "
271
+ "of hard and soft corals in shades of red, orange, and green. The photo captures "
272
+ "the fish from a slightly elevated angle, emphasizing its lively movements and the "
273
+ "vivid colors of its surroundings. A close-up shot with dynamic movement.",
274
+ None,
275
+ None,
276
+ ],
277
+ [
278
+ "Text-to-Video",
279
+ "An extreme close-up of an gray-haired man with a beard in his 60s, he is deep in "
280
+ "thought pondering the history of the universe as he sits at a cafe in Paris, his eyes "
281
+ "focus on people offscreen as they walk as he sits mostly motionless, he is dressed in "
282
+ "a wool coat suit coat with a button-down shirt , he wears a brown beret and glasses "
283
+ "and has a very professorial appearance, and the end he offers a subtle closed-mouth "
284
+ "smile as if he found the answer to the mystery of life, the lighting is very cinematic "
285
+ "with the golden light and the Parisian streets and city in the background, depth of "
286
+ "field, cinematic 35mm film.",
287
+ None,
288
+ None,
289
+ ],
290
+ [
291
+ "Text-to-Video",
292
+ "A drone camera circles around a beautiful historic church built on a rocky outcropping "
293
+ "along the Amalfi Coast, the view showcases historic and magnificent architectural "
294
+ "details and tiered pathways and patios, waves are seen crashing against the rocks "
295
+ "below as the view overlooks the horizon of the coastal waters and hilly landscapes "
296
+ "of the Amalfi Coast Italy, several distant people are seen walking and enjoying vistas "
297
+ "on patios of the dramatic ocean views, the warm glow of the afternoon sun creates a "
298
+ "magical and romantic feeling to the scene, the view is stunning captured with beautiful photography.",
299
+ None,
300
+ None,
301
+ ],
302
+ [
303
+ "Image-to-Video",
304
+ "A towering emerald wave surges forward, its crest curling with raw power and energy. Sunlight glints off the translucent water, illuminating the intricate textures and deep green hues within the wave’s body. A thick spray erupts from the breaking crest, casting a misty veil that dances above the churning surface. As the perspective widens, the immense scale of the wave becomes apparent, revealing the restless expanse of the ocean stretching beyond. The scene captures the ocean’s untamed beauty and relentless force, with every droplet and ripple shimmering in the light. The dynamic motion and vivid colors evoke both awe and respect for nature’s might.",
305
+ "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/helios/wave.jpg",
306
+ None,
307
+ ],
308
+ [
309
+ "Video-to-Video",
310
+ "A bright yellow Lamborghini Huracn Tecnica speeds along a curving mountain road, surrounded by lush green trees under a partly cloudy sky. The car's sleek design and vibrant color stand out against the natural backdrop, emphasizing its dynamic movement. The road curves gently, with a guardrail visible on one side, adding depth to the scene. The motion blur captures the sense of speed and energy, creating a thrilling and exhilarating atmosphere. A front-facing shot from a slightly elevated angle, highlighting the car's aggressive stance and the surrounding greenery.",
311
+ None,
312
+ "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/helios/car.mp4",
313
+ ],
314
+ ],
315
+ inputs=[mode, prompt, image_input, video_input],
316
+ label="Example Prompts",
317
+ )
318
+
319
+ if __name__ == "__main__":
320
+ demo.launch(share=True, css=CSS, theme=gr.themes.Soft())
Helios/bench_infer.py ADDED
@@ -0,0 +1,569 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Helios Benchmark Inference Script
3
+ - Runs T2V inference for a single model version on a single GPU
4
+ - Uses the first N prompts from a txt file
5
+ - Saves videos in two layouts: by_prompt/<slug>/<version>.mp4
6
+ by_version/<version>/<slug>.mp4
7
+ - Records per-video timing to timing_<version>.txt and computes summary stats
8
+ """
9
+
10
+ import importlib
11
+ import os
12
+ import re
13
+ import shutil
14
+ import sys
15
+ import time
16
+
17
+ os.environ["HF_ENABLE_PARALLEL_LOADING"] = "yes"
18
+ os.environ["HF_PARALLEL_LOADING_WORKERS"] = "8"
19
+
20
+ import argparse
21
+ import subprocess
22
+ from pathlib import Path
23
+
24
+
25
+ SCRIPT_DIR = Path(__file__).resolve().parent
26
+ DEFAULT_PROMPT_FILE = SCRIPT_DIR / "demo_data" / "MovieGenVideoBench_extended.txt"
27
+ DEFAULT_MODEL_ROOT = SCRIPT_DIR / "checkpoints"
28
+ DEFAULT_OUTPUT_ROOT = SCRIPT_DIR / "output_helios" / "bench"
29
+
30
+
31
+ def pick_gpu_by_free_vram(min_free_mib=20000):
32
+ """Pick physical GPU index with the most free memory (via nvidia-smi). No torch import."""
33
+ try:
34
+ out = subprocess.check_output(
35
+ [
36
+ "nvidia-smi",
37
+ "--query-gpu=index,memory.free",
38
+ "--format=csv,noheader,nounits",
39
+ ],
40
+ text=True,
41
+ stderr=subprocess.DEVNULL,
42
+ )
43
+ except (subprocess.CalledProcessError, FileNotFoundError) as e:
44
+ raise RuntimeError("nvidia-smi failed; specify --gpu explicitly") from e
45
+
46
+ best_idx, best_free = None, -1
47
+ for line in out.strip().splitlines():
48
+ parts = [p.strip() for p in line.split(",")]
49
+ if len(parts) < 2:
50
+ continue
51
+ idx, free = int(parts[0]), int(parts[1])
52
+ if free > best_free:
53
+ best_free, best_idx = free, idx
54
+ if best_idx is None:
55
+ raise RuntimeError("Could not parse nvidia-smi GPU list")
56
+ if best_free < min_free_mib:
57
+ print(
58
+ f"[warn] Best GPU {best_idx} has only {best_free} MiB free "
59
+ f"(<{min_free_mib} MiB); OOM risk — consider --enable_low_vram_mode",
60
+ file=sys.stderr,
61
+ )
62
+ return best_idx, best_free
63
+
64
+
65
+ def _apply_cuda_visible_devices_before_torch():
66
+ """CUDA_VISIBLE_DEVICES must be set before `import torch` (first CUDA init)."""
67
+ pre = argparse.ArgumentParser(add_help=False)
68
+ pre.add_argument("--gpu", type=str, default="auto")
69
+ known, _ = pre.parse_known_args()
70
+ g = known.gpu.strip().lower()
71
+ if g == "auto":
72
+ idx, free = pick_gpu_by_free_vram()
73
+ os.environ["CUDA_VISIBLE_DEVICES"] = str(idx)
74
+ os.environ["_BENCH_PHYSICAL_GPU"] = f"{idx} ({free} MiB free)"
75
+ else:
76
+ os.environ["CUDA_VISIBLE_DEVICES"] = known.gpu.strip()
77
+ os.environ["_BENCH_PHYSICAL_GPU"] = known.gpu.strip()
78
+ os.environ["_BENCH_GPU_ARG"] = known.gpu.strip()
79
+
80
+
81
+ _apply_cuda_visible_devices_before_torch()
82
+
83
+ import torch
84
+ from tqdm import tqdm
85
+
86
+ if importlib.util.find_spec("torch_npu") is not None:
87
+ import torch_npu # noqa: F401
88
+
89
+ from helios.diffusers_version.pipeline_helios_diffusers import HeliosPipeline
90
+ from helios.diffusers_version.scheduling_helios_diffusers import HeliosScheduler
91
+ from helios.diffusers_version.transformer_helios_diffusers import HeliosTransformer3DModel
92
+ from helios.modules.helios_kernels import (
93
+ replace_all_norms_with_flash_norms,
94
+ replace_rmsnorm_with_fp32,
95
+ replace_rope_with_flash_rope,
96
+ )
97
+ from diffusers.models import AutoencoderKLWan
98
+ from diffusers.utils import export_to_video
99
+
100
+ # ── per-version inference presets (matching official scripts) ─────────────────
101
+
102
+ MODEL_PRESETS = {
103
+ "base": dict(
104
+ model_dir="Helios-Base",
105
+ num_frames=99,
106
+ num_inference_steps=50,
107
+ guidance_scale=5.0,
108
+ is_enable_stage2=False,
109
+ pyramid_num_inference_steps_list=[20, 20, 20],
110
+ is_amplify_first_chunk=False,
111
+ use_zero_init=False,
112
+ zero_steps=1,
113
+ ),
114
+ "mid": dict(
115
+ model_dir="Helios-Mid",
116
+ num_frames=99,
117
+ num_inference_steps=50,
118
+ guidance_scale=5.0,
119
+ is_enable_stage2=True,
120
+ pyramid_num_inference_steps_list=[20, 20, 20],
121
+ is_amplify_first_chunk=False,
122
+ use_zero_init=True,
123
+ zero_steps=1,
124
+ ),
125
+ "distilled": dict(
126
+ model_dir="Helios-Distilled",
127
+ num_frames=240,
128
+ num_inference_steps=50,
129
+ guidance_scale=1.0,
130
+ is_enable_stage2=True,
131
+ pyramid_num_inference_steps_list=[2, 2, 2],
132
+ is_amplify_first_chunk=True,
133
+ use_zero_init=False,
134
+ zero_steps=1,
135
+ ),
136
+ }
137
+
138
+ NEGATIVE_PROMPT = (
139
+ "Bright tones, overexposed, static, blurred details, subtitles, style, "
140
+ "works, paintings, images, static, overall gray, worst quality, low quality, "
141
+ "JPEG compression residue, ugly, incomplete, extra fingers, poorly drawn hands, "
142
+ "poorly drawn faces, deformed, disfigured, misshapen limbs, fused fingers, "
143
+ "still picture, messy background, three legs, many people in the background, "
144
+ "walking backwards"
145
+ )
146
+
147
+
148
+ def sanitize_filename(text, max_len=80):
149
+ """Turn a prompt into a filesystem-safe slug."""
150
+ text = text.strip().lower()
151
+ text = re.sub(r"[^a-z0-9]+", "_", text)
152
+ text = text.strip("_")
153
+ return text[:max_len]
154
+
155
+
156
+ def load_prompt_indices(path):
157
+ indices = []
158
+ with open(path, "r", encoding="utf-8") as f:
159
+ for line_no, raw_line in enumerate(f, start=1):
160
+ line = raw_line.strip()
161
+ if not line or line.startswith("#"):
162
+ continue
163
+ try:
164
+ idx = int(line)
165
+ except ValueError as exc:
166
+ raise ValueError(
167
+ f"Invalid prompt index at {path}:{line_no}: {line!r}"
168
+ ) from exc
169
+ if idx < 0:
170
+ raise ValueError(f"Prompt index must be >= 0 at {path}:{line_no}")
171
+ indices.append(idx)
172
+ return indices
173
+
174
+
175
+ def load_prompts(path, prompt_start=0, prompt_end=None, prompt_indices=None):
176
+ with open(path, "r", encoding="utf-8") as f:
177
+ lines = [line.strip() for line in f if line.strip()]
178
+ if prompt_indices is not None:
179
+ selected = []
180
+ total = len(lines)
181
+ for idx in prompt_indices:
182
+ if idx >= total:
183
+ raise ValueError(
184
+ f"Prompt index {idx} is out of range; prompt file has {total} prompts"
185
+ )
186
+ selected.append((idx, lines[idx]))
187
+ return selected
188
+
189
+ if prompt_start < 0:
190
+ raise ValueError("prompt_start must be >= 0")
191
+ if prompt_end is not None and prompt_end < prompt_start:
192
+ raise ValueError("prompt_end must be >= prompt_start")
193
+
194
+ selected = lines[prompt_start:prompt_end]
195
+ return [(prompt_start + offset, prompt) for offset, prompt in enumerate(selected)]
196
+
197
+
198
+ def build_expected_outputs(prompts, version, by_version_dir):
199
+ version_dir = os.path.join(by_version_dir, version)
200
+ expected = []
201
+ for idx, prompt in prompts:
202
+ slug = sanitize_filename(prompt)
203
+ vid_name = f"{idx:04d}_{slug}"
204
+ expected.append((idx, slug, os.path.join(version_dir, f"{vid_name}.mp4")))
205
+ return version_dir, expected
206
+
207
+
208
+ def output_exists(path):
209
+ return os.path.isfile(path) and os.path.getsize(path) > 0
210
+
211
+
212
+ def find_missing_outputs(expected_outputs):
213
+ return [item for item in expected_outputs if not output_exists(item[2])]
214
+
215
+
216
+ def make_timing_line(version, idx, elapsed, slug):
217
+ return (
218
+ f" {version:10s} #{idx:04d} {elapsed:8.2f}s "
219
+ f"({elapsed / 60:5.2f}min) {slug[:50]}"
220
+ )
221
+
222
+
223
+ def load_existing_timing_records(timing_file, version):
224
+ if not os.path.exists(timing_file):
225
+ return {}
226
+
227
+ pattern = re.compile(
228
+ rf"^\s*{re.escape(version)}\s+#(\d+)\s+([0-9.]+)s\s+\([^)]+\)\s+(.*)$"
229
+ )
230
+ records = {}
231
+ with open(timing_file, "r", encoding="utf-8") as f:
232
+ for raw_line in f:
233
+ line = raw_line.rstrip("\n")
234
+ match = pattern.match(line)
235
+ if not match:
236
+ continue
237
+ idx = int(match.group(1))
238
+ elapsed = float(match.group(2))
239
+ slug = match.group(3)
240
+ records[idx] = (elapsed, slug)
241
+ return records
242
+
243
+
244
+ def build_pipeline(
245
+ model_path,
246
+ device,
247
+ weight_dtype,
248
+ enable_low_vram=False,
249
+ group_offloading_type="leaf_level",
250
+ num_blocks_per_group=4,
251
+ ):
252
+ transformer = HeliosTransformer3DModel.from_pretrained(
253
+ model_path, subfolder="transformer", torch_dtype=weight_dtype,
254
+ )
255
+ transformer = replace_rmsnorm_with_fp32(transformer)
256
+ transformer = replace_all_norms_with_flash_norms(transformer)
257
+ replace_rope_with_flash_rope()
258
+
259
+ cuda_major = torch.cuda.get_device_capability()[0]
260
+ if cuda_major >= 9:
261
+ try:
262
+ transformer.set_attention_backend("_flash_3_hub")
263
+ except Exception:
264
+ transformer.set_attention_backend("flash_hub")
265
+ else:
266
+ transformer.set_attention_backend("flash_hub")
267
+
268
+ vae = AutoencoderKLWan.from_pretrained(
269
+ model_path, subfolder="vae", torch_dtype=torch.float32,
270
+ )
271
+ scheduler = HeliosScheduler.from_pretrained(model_path, subfolder="scheduler")
272
+
273
+ pipe = HeliosPipeline.from_pretrained(
274
+ model_path,
275
+ transformer=transformer,
276
+ vae=vae,
277
+ scheduler=scheduler,
278
+ torch_dtype=weight_dtype,
279
+ )
280
+ if enable_low_vram:
281
+ nbg = int(num_blocks_per_group) if group_offloading_type == "block_level" else None
282
+ pipe.enable_group_offload(
283
+ onload_device=torch.device("cuda"),
284
+ offload_device=torch.device("cpu"),
285
+ offload_type=group_offloading_type,
286
+ num_blocks_per_group=nbg,
287
+ use_stream=True,
288
+ record_stream=True,
289
+ )
290
+ else:
291
+ pipe = pipe.to(device)
292
+ return pipe
293
+
294
+
295
+ def run_single(pipe, prompt, preset, height, width, seed):
296
+ gen = torch.Generator(device="cuda").manual_seed(seed)
297
+
298
+ t0 = time.time()
299
+ with torch.no_grad():
300
+ output = pipe(
301
+ prompt=prompt,
302
+ negative_prompt=NEGATIVE_PROMPT,
303
+ height=height,
304
+ width=width,
305
+ num_frames=preset["num_frames"],
306
+ num_inference_steps=preset["num_inference_steps"],
307
+ guidance_scale=preset["guidance_scale"],
308
+ generator=gen,
309
+ history_sizes=[16, 2, 1],
310
+ num_latent_frames_per_chunk=9,
311
+ keep_first_frame=True,
312
+ is_enable_stage2=preset["is_enable_stage2"],
313
+ pyramid_num_inference_steps_list=preset["pyramid_num_inference_steps_list"],
314
+ is_skip_first_chunk=False,
315
+ is_amplify_first_chunk=preset["is_amplify_first_chunk"],
316
+ use_zero_init=preset["use_zero_init"],
317
+ zero_steps=preset["zero_steps"],
318
+ ).frames[0]
319
+ elapsed = time.time() - t0
320
+ return output, elapsed
321
+
322
+
323
+ def _parse_gpu(s):
324
+ if isinstance(s, str) and s.lower() == "auto":
325
+ return "auto"
326
+ return int(s)
327
+
328
+
329
+ def parse_args():
330
+ p = argparse.ArgumentParser(description="Helios benchmark inference for one model version")
331
+ p.add_argument("--prompt_file", type=str,
332
+ default=str(DEFAULT_PROMPT_FILE))
333
+ p.add_argument("--prompt_start", type=int, default=0)
334
+ p.add_argument("--prompt_end", type=int, default=100,
335
+ help="Exclusive end index for prompts, e.g. 50 means up to #49")
336
+ p.add_argument("--prompt_indices_file", type=str, default=None,
337
+ help="Optional file containing exact prompt indices to run, one per line")
338
+ p.add_argument("--model_root", type=str, default=str(DEFAULT_MODEL_ROOT),
339
+ help="Parent dir containing Helios-Base / Helios-Mid / Helios-Distilled")
340
+ p.add_argument("--output_root", type=str, default=str(DEFAULT_OUTPUT_ROOT))
341
+ p.add_argument("--version", type=str, choices=sorted(MODEL_PRESETS.keys()), required=True,
342
+ help="Which model version to run")
343
+ p.add_argument("--timing_file", type=str, default=None,
344
+ help="Optional override for timing report path")
345
+ p.add_argument("--height", type=int, default=384)
346
+ p.add_argument("--width", type=int, default=640)
347
+ p.add_argument("--num_frames", type=int, default=None,
348
+ help="Override preset frame count for all selected versions")
349
+ p.add_argument("--seed", type=int, default=42)
350
+ p.add_argument(
351
+ "--gpu",
352
+ type=_parse_gpu,
353
+ default="auto",
354
+ help='Physical GPU id or "auto" (pick most free VRAM via nvidia-smi)',
355
+ )
356
+ p.add_argument(
357
+ "--enable_low_vram_mode",
358
+ action="store_true",
359
+ help="CPU group-offload (slower, less VRAM); use if GPU is shared or OOM",
360
+ )
361
+ p.add_argument(
362
+ "--group_offloading_type",
363
+ type=str,
364
+ choices=["leaf_level", "block_level"],
365
+ default="leaf_level",
366
+ )
367
+ p.add_argument("--num_blocks_per_group", type=int, default=4)
368
+ return p.parse_args()
369
+
370
+
371
+ def main():
372
+ args = parse_args()
373
+
374
+ if not os.path.isfile(args.prompt_file):
375
+ raise FileNotFoundError(f"Prompt file not found: {args.prompt_file}")
376
+ if not os.path.isdir(args.model_root):
377
+ raise FileNotFoundError(f"Model root not found: {args.model_root}")
378
+
379
+ os.environ["CUDA_VISIBLE_DEVICES"] = str(args.gpu)
380
+ device = torch.device("cuda")
381
+ weight_dtype = torch.bfloat16
382
+
383
+ prompt_indices = None
384
+ if args.prompt_indices_file:
385
+ if not os.path.isfile(args.prompt_indices_file):
386
+ raise FileNotFoundError(f"Prompt indices file not found: {args.prompt_indices_file}")
387
+ prompt_indices = load_prompt_indices(args.prompt_indices_file)
388
+
389
+ prompts = load_prompts(
390
+ args.prompt_file,
391
+ args.prompt_start,
392
+ args.prompt_end,
393
+ prompt_indices=prompt_indices,
394
+ )
395
+ prompt_map = dict(prompts)
396
+ if args.prompt_indices_file:
397
+ print(
398
+ f"Loaded {len(prompts)} prompts from {args.prompt_file} "
399
+ f"(indices: {args.prompt_indices_file})"
400
+ )
401
+ else:
402
+ print(
403
+ f"Loaded {len(prompts)} prompts from {args.prompt_file} "
404
+ f"(range: {args.prompt_start}:{args.prompt_end})"
405
+ )
406
+
407
+ if args.num_frames is not None:
408
+ MODEL_PRESETS[args.version]["num_frames"] = args.num_frames
409
+
410
+ by_prompt_dir = os.path.join(args.output_root, "by_prompt")
411
+ by_version_dir = os.path.join(args.output_root, "by_version")
412
+ timing_file = args.timing_file or os.path.join(args.output_root, f"timing_{args.version}.txt")
413
+ os.makedirs(args.output_root, exist_ok=True)
414
+
415
+ preset = MODEL_PRESETS[args.version]
416
+ model_path = os.path.join(args.model_root, preset["model_dir"])
417
+ timing_records = load_existing_timing_records(timing_file, args.version)
418
+ selected_indices = set(prompt_map)
419
+ timing_records = {
420
+ idx: record for idx, record in timing_records.items() if idx in selected_indices
421
+ }
422
+ ver_dir, expected_outputs = build_expected_outputs(prompts, args.version, by_version_dir)
423
+ missing_outputs = find_missing_outputs(expected_outputs)
424
+ if not os.path.isdir(model_path):
425
+ raise FileNotFoundError(f"Model not found: {model_path}")
426
+
427
+ peak_mem = None
428
+ if not missing_outputs:
429
+ print(
430
+ f"[SKIP] All outputs already exist for version={args.version} under {ver_dir}"
431
+ )
432
+ else:
433
+ header = (
434
+ f"\n{'=' * 60}\n"
435
+ f" Version: {args.version} | Model: {preset['model_dir']}\n"
436
+ f" Frames: {preset['num_frames']} | guidance_scale: {preset['guidance_scale']}\n"
437
+ f" stage2: {preset['is_enable_stage2']} | pyramid_steps: {preset['pyramid_num_inference_steps_list']}\n"
438
+ f"{'=' * 60}\n"
439
+ )
440
+ print(header)
441
+
442
+ pipe = build_pipeline(
443
+ model_path,
444
+ device,
445
+ weight_dtype,
446
+ enable_low_vram=args.enable_low_vram_mode,
447
+ group_offloading_type=args.group_offloading_type,
448
+ num_blocks_per_group=args.num_blocks_per_group,
449
+ )
450
+
451
+ os.makedirs(ver_dir, exist_ok=True)
452
+
453
+ print(
454
+ f"[resume] version={args.version} existing={len(expected_outputs) - len(missing_outputs)} "
455
+ f"missing={len(missing_outputs)} timed={len(timing_records)}"
456
+ )
457
+ for idx, slug, ver_out in tqdm(missing_outputs, desc=f"[{args.version}]"):
458
+ if os.path.exists(ver_out):
459
+ print(f" [skip] {ver_out}")
460
+ continue
461
+
462
+ try:
463
+ frames, elapsed = run_single(
464
+ pipe, prompt_map[idx], preset, args.height, args.width, args.seed,
465
+ )
466
+ except Exception as e:
467
+ msg = f" [FAIL] {args.version} #{idx:04d}: {e}"
468
+ print(msg)
469
+ continue
470
+
471
+ export_to_video(frames, ver_out, fps=24)
472
+
473
+ vid_name = os.path.splitext(os.path.basename(ver_out))[0]
474
+ prompt_dir = os.path.join(by_prompt_dir, vid_name)
475
+ os.makedirs(prompt_dir, exist_ok=True)
476
+ shutil.copy2(ver_out, os.path.join(prompt_dir, f"{args.version}.mp4"))
477
+
478
+ timing_records[idx] = (elapsed, slug)
479
+ print(make_timing_line(args.version, idx, elapsed, slug))
480
+
481
+ peak_mem = torch.cuda.max_memory_allocated() / 1024 ** 3
482
+ print(f" >> [{args.version}] peak GPU memory: {peak_mem:.2f} GB")
483
+
484
+ del pipe
485
+ torch.cuda.empty_cache()
486
+ torch.cuda.reset_peak_memory_stats()
487
+
488
+ sorted_records = [timing_records[idx] for idx in sorted(timing_records)]
489
+ all_timings = [elapsed for elapsed, _ in sorted_records]
490
+
491
+ with open(timing_file, "w", encoding="utf-8") as tf:
492
+ tf.write(f"{'=' * 80}\n")
493
+ tf.write(f" Helios Benchmark Inference Timing Report\n")
494
+ tf.write(f" {time.strftime('%Y-%m-%d %H:%M:%S')}\n")
495
+ tf.write(
496
+ f" Prompts: {len(prompts)} | Range: {args.prompt_start}:{args.prompt_end} "
497
+ f"| Version: {args.version}\n"
498
+ )
499
+ if args.prompt_indices_file:
500
+ tf.write(f" Prompt indices file: {args.prompt_indices_file}\n")
501
+ tf.write(
502
+ f" Resolution: {args.width}x{args.height} | Seed: {args.seed} | "
503
+ f"GPU: {args.gpu} | low_vram: {args.enable_low_vram_mode}\n"
504
+ )
505
+ tf.write(f"{'=' * 80}\n\n")
506
+
507
+ tf.write(
508
+ f"\n{'=' * 60}\n"
509
+ f" Version: {args.version} | Model: {preset['model_dir']}\n"
510
+ f" Frames: {preset['num_frames']} | guidance_scale: {preset['guidance_scale']}\n"
511
+ f" stage2: {preset['is_enable_stage2']} | pyramid_steps: {preset['pyramid_num_inference_steps_list']}\n"
512
+ f"{'=' * 60}\n"
513
+ )
514
+ tf.write(
515
+ f" Existing timing records: {len(timing_records)} / expected outputs: {len(expected_outputs)}\n"
516
+ )
517
+
518
+ for idx in sorted(timing_records):
519
+ elapsed, slug = timing_records[idx]
520
+ tf.write(make_timing_line(args.version, idx, elapsed, slug) + "\n")
521
+
522
+ if all_timings:
523
+ avg_t = sum(all_timings) / len(all_timings)
524
+ total_t = sum(all_timings)
525
+ summary = (
526
+ f"\n >> [{args.version}] completed {len(all_timings)} videos | "
527
+ f"avg: {avg_t:.2f}s ({avg_t / 60:.2f}min) | "
528
+ f"total: {total_t:.1f}s ({total_t / 60:.1f}min)\n"
529
+ )
530
+ else:
531
+ summary = f"\n >> [{args.version}] no timing records available\n"
532
+ print(summary)
533
+ tf.write(summary)
534
+
535
+ if peak_mem is not None:
536
+ mem_line = f" >> [{args.version}] peak GPU memory: {peak_mem:.2f} GB\n"
537
+ tf.write(mem_line)
538
+
539
+ sep = f"\n{'=' * 80}\n"
540
+ tf.write(sep)
541
+ tf.write(" FINAL SUMMARY\n")
542
+ tf.write(f"{'=' * 80}\n")
543
+ print(sep)
544
+ print(" FINAL SUMMARY")
545
+ print(f"{'=' * 80}")
546
+
547
+ fmt = " {ver:12s} | videos: {n:3d} | avg: {avg:8.2f}s ({avgm:5.2f}min) | min: {mn:8.2f}s | max: {mx:8.2f}s | total: {tot:8.1f}s ({totm:5.1f}min)"
548
+ if all_timings:
549
+ line = fmt.format(
550
+ ver=args.version, n=len(all_timings),
551
+ avg=sum(all_timings) / len(all_timings), avgm=sum(all_timings) / len(all_timings) / 60,
552
+ mn=min(all_timings), mx=max(all_timings),
553
+ tot=sum(all_timings), totm=sum(all_timings) / 60,
554
+ )
555
+ else:
556
+ line = f" {args.version:12s} | N/A (no timing records)"
557
+ print(line)
558
+ tf.write(line + "\n")
559
+
560
+ tf.write(f"{'=' * 80}\n")
561
+
562
+ print(f"{'=' * 80}")
563
+ print(f"\nTiming report: {timing_file}")
564
+ print(f"Videos: {by_prompt_dir}")
565
+ print(f" {by_version_dir}")
566
+
567
+
568
+ if __name__ == "__main__":
569
+ main()
Helios/infer_helios.py ADDED
@@ -0,0 +1,560 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import importlib
2
+ import os
3
+
4
+
5
+ os.environ["HF_ENABLE_PARALLEL_LOADING"] = "yes"
6
+ os.environ["HF_PARALLEL_LOADING_WORKERS"] = "8"
7
+
8
+ import argparse
9
+ import time
10
+
11
+ import pandas as pd
12
+ import torch
13
+ import torch.distributed as dist
14
+ from tqdm import tqdm
15
+
16
+
17
+ if importlib.util.find_spec("torch_npu") is not None:
18
+ import torch_npu
19
+ else:
20
+ torch_npu = None
21
+
22
+ from helios.diffusers_version.pipeline_helios_diffusers import HeliosPipeline
23
+ from helios.diffusers_version.scheduling_helios_diffusers import HeliosScheduler
24
+ from helios.diffusers_version.transformer_helios_diffusers import HeliosTransformer3DModel
25
+ from helios.modules.helios_kernels import (
26
+ replace_all_norms_with_flash_norms,
27
+ replace_rmsnorm_with_fp32,
28
+ replace_rope_with_flash_rope,
29
+ )
30
+ from helios.utils.utils_base import load_extra_components
31
+
32
+ from diffusers import ContextParallelConfig
33
+ from diffusers.models import AutoencoderKLWan
34
+ from diffusers.utils import export_to_video, load_image, load_video
35
+
36
+
37
+ def parse_args():
38
+ parser = argparse.ArgumentParser(description="Generate video with model")
39
+
40
+ # === Model paths ===
41
+ parser.add_argument("--base_model_path", type=str, default="BestWishYsh/Helios-Base")
42
+ parser.add_argument(
43
+ "--transformer_path",
44
+ type=str,
45
+ default="BestWishYsh/Helios-Base",
46
+ )
47
+ parser.add_argument(
48
+ "--lora_path",
49
+ type=str,
50
+ default=None,
51
+ )
52
+ parser.add_argument(
53
+ "--partial_path",
54
+ type=str,
55
+ default=None,
56
+ )
57
+ parser.add_argument("--output_folder", type=str, default="./output_helios")
58
+ parser.add_argument("--enable_compile", action="store_true")
59
+
60
+ # === Generation parameters ===
61
+ # environment
62
+ parser.add_argument(
63
+ "--sample_type",
64
+ type=str,
65
+ default="t2v",
66
+ choices=["t2v", "i2v", "v2v"],
67
+ )
68
+ parser.add_argument(
69
+ "--weight_dtype",
70
+ type=str,
71
+ default="bf16",
72
+ choices=["bf16", "fp16", "fp32"],
73
+ help="Data type for model weights.",
74
+ )
75
+ parser.add_argument("--seed", type=int, default=42, help="Seed for random number generator.")
76
+ # base
77
+ parser.add_argument("--height", type=int, default=384)
78
+ parser.add_argument("--width", type=int, default=640)
79
+ parser.add_argument("--num_frames", type=int, default=99)
80
+ parser.add_argument("--fps", type=int, default=24)
81
+ parser.add_argument("--num_inference_steps", type=int, default=50)
82
+ parser.add_argument("--guidance_scale", type=float, default=5.0)
83
+ # cfg zero
84
+ parser.add_argument("--use_zero_init", action="store_true")
85
+ parser.add_argument("--zero_steps", type=int, default=1)
86
+ # stage 1
87
+ parser.add_argument("--num_latent_frames_per_chunk", type=int, default=9)
88
+ # stage 2
89
+ parser.add_argument("--is_enable_stage2", action="store_true")
90
+ parser.add_argument("--pyramid_num_inference_steps_list", type=int, nargs="+", default=[20, 20, 20])
91
+ # stage 3
92
+ parser.add_argument("--is_skip_first_chunk", action="store_true")
93
+ parser.add_argument("--is_amplify_first_chunk", action="store_true")
94
+
95
+ # === Prompts ===
96
+ parser.add_argument("--use_interpolate_prompt", action="store_true")
97
+ parser.add_argument("--interpolation_steps", type=int, default=3)
98
+ parser.add_argument("--interpolate_time", type=int, default=7)
99
+ parser.add_argument(
100
+ "--image_path",
101
+ type=str,
102
+ default=None,
103
+ )
104
+ parser.add_argument(
105
+ "--image_noise_sigma_min", type=float, default=0.111, help="Balance motion amplitude and visual consistency"
106
+ )
107
+ parser.add_argument(
108
+ "--image_noise_sigma_max", type=float, default=0.135, help="Balance motion amplitude and visual consistency"
109
+ )
110
+ parser.add_argument(
111
+ "--video_path",
112
+ type=str,
113
+ default=None,
114
+ )
115
+ parser.add_argument(
116
+ "--video_noise_sigma_min", type=float, default=0.111, help="Balance motion amplitude and visual consistency"
117
+ )
118
+ parser.add_argument(
119
+ "--video_noise_sigma_max", type=float, default=0.135, help="Balance motion amplitude and visual consistency"
120
+ )
121
+ parser.add_argument(
122
+ "--prompt",
123
+ type=str,
124
+ default="A dynamic time-lapse video showing the rapidly moving scenery from the window of a speeding train. The camera captures various elements such as lush green fields, towering trees, quaint countryside houses, and distant mountain ranges passing by quickly. The train window frames the view, adding a sense of speed and motion as the landscape rushes past. The camera remains static but emphasizes the fast-paced movement outside. The overall atmosphere is serene yet exhilarating, capturing the essence of travel and exploration. Medium shot focusing on the train window and the rushing scenery beyond.",
125
+ )
126
+ parser.add_argument(
127
+ "--negative_prompt",
128
+ type=str,
129
+ default="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",
130
+ )
131
+ parser.add_argument(
132
+ "--prompt_txt_path",
133
+ type=str,
134
+ default=None,
135
+ )
136
+ parser.add_argument(
137
+ "--base_image_prompt_path",
138
+ type=str,
139
+ default=None,
140
+ )
141
+ parser.add_argument(
142
+ "--image_prompt_csv_path",
143
+ type=str,
144
+ default=None,
145
+ )
146
+ parser.add_argument(
147
+ "--interactive_prompt_csv_path",
148
+ type=str,
149
+ default=None,
150
+ )
151
+
152
+ # === Context parallelism ===
153
+ # Please refer to https://huggingface.co/docs/diffusers/main/en/training/distributed_inference#context-parallelism
154
+ parser.add_argument("--enable_parallelism", action="store_true")
155
+ parser.add_argument(
156
+ "--cp_backend",
157
+ type=str,
158
+ choices=["ring", "ulysses", "unified", "ulysses_anything"],
159
+ default="ulysses",
160
+ help="Context parallel backend to use.",
161
+ )
162
+
163
+ # === Group-Offloading ===
164
+ # Please refer to https://huggingface.co/docs/diffusers/main/en/optimization/memory#group-offloading
165
+ parser.add_argument("--enable_low_vram_mode", action="store_true")
166
+ parser.add_argument(
167
+ "--group_offloading_type",
168
+ type=str,
169
+ choices=["leaf_level", "block_level"],
170
+ default="leaf_level",
171
+ help="Specifies the granularity for group CPU offloading. Choose between 'leaf_level' (individual modules) or 'block_level' (entire blocks).",
172
+ )
173
+ parser.add_argument(
174
+ "--num_blocks_per_group",
175
+ type=str,
176
+ default="4",
177
+ help="The number of blocks to bundle together in each offloading group. Only relevant when using block-level offloading.",
178
+ )
179
+
180
+ return parser.parse_args()
181
+
182
+
183
+ def main():
184
+ args = parse_args()
185
+
186
+ assert not (args.enable_low_vram_mode and args.enable_compile), (
187
+ "enable_low_vram_mode and enable_compile cannot be used together."
188
+ )
189
+
190
+ if args.weight_dtype == "fp32":
191
+ args.weight_dtype = torch.float32
192
+ elif args.weight_dtype == "fp16":
193
+ args.weight_dtype = torch.float16
194
+ else:
195
+ args.weight_dtype = torch.bfloat16
196
+
197
+ os.makedirs(args.output_folder, exist_ok=True)
198
+
199
+ if dist.is_available() and "RANK" in os.environ:
200
+ if args.cp_backend == "ulysses_anything":
201
+ dist.init_process_group(backend="cpu:gloo,cuda:nccl")
202
+ else:
203
+ dist.init_process_group(backend="nccl")
204
+ rank = dist.get_rank()
205
+ device = torch.device("cuda", rank % torch.cuda.device_count())
206
+ world_size = dist.get_world_size()
207
+ torch.cuda.set_device(device)
208
+ assert world_size == 1 or not args.enable_low_vram_mode, "enable_low_vram_mode is only for single GPU."
209
+ else:
210
+ rank = 0
211
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
212
+ world_size = 1
213
+
214
+ prompt = None
215
+ image_path = None
216
+ video_path = None
217
+ interpolate_time_list = None
218
+ if args.sample_type == "t2v" and args.prompt is None:
219
+ prompt = "An extreme close-up of an gray-haired man with a beard in his 60s, he is deep in thought pondering the history of the universe as he sits at a cafe in Paris, his eyes focus on people offscreen as they walk as he sits mostly motionless, he is dressed in a wool coat suit coat with a button-down shirt , he wears a brown beret and glasses and has a very professorial appearance, and the end he offers a subtle closed-mouth smile as if he found the answer to the mystery of life, the lighting is very cinematic with the golden light and the Parisian streets and city in the background, depth of field, cinematic 35mm film."
220
+ elif args.sample_type == "i2v" and (args.image_path is None and args.prompt is None):
221
+ image_path = (
222
+ "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/astronaut.jpg"
223
+ )
224
+ prompt = "An astronaut hatching from an egg, on the surface of the moon, the darkness and depth of space realised in the background. High quality, ultrarealistic detail and breath-taking movie-like camera shot."
225
+ elif args.sample_type == "v2v" and (args.video_path is None and args.prompt is None):
226
+ video_path = (
227
+ "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/diffusers/hiker.mp4"
228
+ )
229
+ prompt = "A robot standing on a mountain top. The sun is setting in the background."
230
+ else:
231
+ image_path = args.image_path
232
+ video_path = args.video_path
233
+ prompt = args.prompt
234
+
235
+ transformer = HeliosTransformer3DModel.from_pretrained(
236
+ args.transformer_path,
237
+ subfolder="transformer",
238
+ torch_dtype=args.weight_dtype,
239
+ )
240
+ if not args.enable_compile:
241
+ transformer = replace_rmsnorm_with_fp32(transformer)
242
+ transformer = replace_all_norms_with_flash_norms(transformer)
243
+ replace_rope_with_flash_rope()
244
+ cuda_major = torch.cuda.get_device_capability()[0]
245
+ if cuda_major >= 9:
246
+ # H100/H800 (SM90+) with FA3
247
+ try:
248
+ transformer.set_attention_backend("_flash_3_hub")
249
+ except Exception:
250
+ transformer.set_attention_backend("flash_hub")
251
+ else:
252
+ # 4090/A100 etc (SM89+) with FA2
253
+ transformer.set_attention_backend("flash_hub")
254
+
255
+ vae = AutoencoderKLWan.from_pretrained(
256
+ args.base_model_path,
257
+ subfolder="vae",
258
+ torch_dtype=torch.float32,
259
+ )
260
+ scheduler = HeliosScheduler.from_pretrained(
261
+ args.base_model_path,
262
+ subfolder="scheduler",
263
+ )
264
+ pipe = HeliosPipeline.from_pretrained(
265
+ args.base_model_path,
266
+ transformer=transformer,
267
+ vae=vae,
268
+ scheduler=scheduler,
269
+ torch_dtype=args.weight_dtype,
270
+ )
271
+
272
+ if args.lora_path is not None:
273
+ pipe.load_lora_weights(args.lora_path, adapter_name="default")
274
+ pipe.set_adapters(["default"], adapter_weights=[1.0])
275
+
276
+ if args.partial_path is not None:
277
+ if not hasattr(args, "training_config"):
278
+ from argparse import Namespace
279
+
280
+ args.training_config = Namespace()
281
+ args.training_config.is_enable_stage1 = True
282
+ args.training_config.restrict_self_attn = True
283
+ args.training_config.is_amplify_history = True
284
+ args.training_config.is_use_gan = True
285
+ load_extra_components(args, transformer, args.partial_path)
286
+
287
+ if args.enable_compile:
288
+ torch.backends.cudnn.benchmark = True
289
+ pipe.text_encoder.compile(mode="max-autotune-no-cudagraphs", dynamic=False)
290
+ pipe.vae.compile(mode="max-autotune-no-cudagraphs", dynamic=False)
291
+ pipe.transformer.compile(mode="max-autotune-no-cudagraphs", dynamic=False)
292
+
293
+ if args.enable_low_vram_mode:
294
+ pipe.enable_group_offload(
295
+ onload_device=torch.device("cuda"),
296
+ offload_device=torch.device("cpu"),
297
+ offload_type=args.group_offloading_type,
298
+ num_blocks_per_group=args.num_blocks_per_group if args.group_offloading_type == "block_level" else None,
299
+ use_stream=True,
300
+ record_stream=True,
301
+ )
302
+ else:
303
+ pipe = pipe.to(device)
304
+
305
+ if world_size > 1 and args.enable_parallelism:
306
+ if args.cp_backend == "ring":
307
+ cp_config = ContextParallelConfig(ring_degree=world_size)
308
+ elif args.cp_backend == "unified":
309
+ cp_config = ContextParallelConfig(ring_degree=world_size // 2, ulysses_degree=world_size // 2)
310
+ elif args.cp_backend == "ulysses":
311
+ cp_config = ContextParallelConfig(ulysses_degree=world_size)
312
+ elif args.cp_backend == "ulysses_anything":
313
+ cp_config = ContextParallelConfig(ulysses_degree=world_size, ulysses_anything=True)
314
+ else:
315
+ raise ValueError(f"Unsupported cp_backend: {args.cp_backend}")
316
+
317
+ pipe.transformer.enable_parallelism(config=cp_config)
318
+
319
+ if args.prompt_txt_path is not None:
320
+ with open(args.prompt_txt_path, "r") as f:
321
+ prompt_list = [line.strip() for line in f.readlines() if line.strip()]
322
+ if not args.enable_parallelism:
323
+ prompt_list_with_idx = [(i, prompt) for i, prompt in enumerate(prompt_list)]
324
+ prompt_list_with_idx = prompt_list_with_idx[rank::world_size]
325
+ else:
326
+ prompt_list_with_idx = [(i, prompt) for i, prompt in enumerate(prompt_list)]
327
+
328
+ for idx, prompt in tqdm(prompt_list_with_idx, desc="Processing prompts"):
329
+ output_path = os.path.join(args.output_folder, f"{idx}.mp4")
330
+ if os.path.exists(output_path):
331
+ print("skipping!")
332
+ continue
333
+
334
+ with torch.no_grad():
335
+ try:
336
+ output = pipe(
337
+ prompt=prompt,
338
+ negative_prompt=args.negative_prompt,
339
+ height=args.height,
340
+ width=args.width,
341
+ num_frames=args.num_frames,
342
+ num_inference_steps=args.num_inference_steps,
343
+ guidance_scale=args.guidance_scale,
344
+ generator=torch.Generator(device="cuda").manual_seed(args.seed),
345
+ # stage 1
346
+ history_sizes=[16, 2, 1],
347
+ num_latent_frames_per_chunk=args.num_latent_frames_per_chunk,
348
+ keep_first_frame=True,
349
+ # stage 2
350
+ is_enable_stage2=args.is_enable_stage2,
351
+ pyramid_num_inference_steps_list=args.pyramid_num_inference_steps_list,
352
+ # stage 3
353
+ is_skip_first_chunk=args.is_skip_first_chunk,
354
+ is_amplify_first_chunk=args.is_amplify_first_chunk,
355
+ # cfg zero
356
+ use_zero_init=args.use_zero_init,
357
+ zero_steps=args.zero_steps,
358
+ # i2v
359
+ image=load_image(image_path).resize((args.width, args.height))
360
+ if image_path is not None
361
+ else None,
362
+ image_noise_sigma_min=args.image_noise_sigma_min,
363
+ image_noise_sigma_max=args.image_noise_sigma_max,
364
+ # v2v
365
+ video=load_video(video_path) if video_path is not None else None,
366
+ video_noise_sigma_min=args.video_noise_sigma_min,
367
+ video_noise_sigma_max=args.video_noise_sigma_max,
368
+ # interpolate_prompt
369
+ use_interpolate_prompt=args.use_interpolate_prompt,
370
+ interpolation_steps=args.interpolation_steps,
371
+ interpolate_time_list=interpolate_time_list,
372
+ ).frames[0]
373
+ except Exception:
374
+ continue
375
+ if not args.enable_parallelism or rank == 0:
376
+ export_to_video(output, output_path, fps=24)
377
+ elif args.image_prompt_csv_path is not None:
378
+ df = pd.read_csv(args.image_prompt_csv_path)
379
+ if not args.enable_parallelism:
380
+ df = df.iloc[rank::world_size]
381
+
382
+ for idx, row in tqdm(df.iterrows(), total=len(df), desc="Processing prompts"):
383
+ # output_path = os.path.join(args.output_folder, f"{idx}.mp4")
384
+ output_path = os.path.join(args.output_folder, f"{row['id']}.mp4")
385
+ if os.path.exists(output_path):
386
+ print("skipping!")
387
+ continue
388
+
389
+ prompt = row.get("refined_prompt") or row["prompt"]
390
+ image_path = os.path.join(args.base_image_prompt_path, row["image_name"])
391
+
392
+ with torch.no_grad():
393
+ try:
394
+ output = pipe(
395
+ prompt=prompt,
396
+ negative_prompt=args.negative_prompt,
397
+ height=args.height,
398
+ width=args.width,
399
+ num_frames=args.num_frames,
400
+ num_inference_steps=args.num_inference_steps,
401
+ guidance_scale=args.guidance_scale,
402
+ generator=torch.Generator(device="cuda").manual_seed(args.seed),
403
+ # stage 1
404
+ history_sizes=[16, 2, 1],
405
+ num_latent_frames_per_chunk=args.num_latent_frames_per_chunk,
406
+ keep_first_frame=True,
407
+ # stage 2
408
+ is_enable_stage2=args.is_enable_stage2,
409
+ pyramid_num_inference_steps_list=args.pyramid_num_inference_steps_list,
410
+ # stage 3
411
+ is_skip_first_chunk=args.is_skip_first_chunk,
412
+ is_amplify_first_chunk=args.is_amplify_first_chunk,
413
+ # cfg zero
414
+ use_zero_init=args.use_zero_init,
415
+ zero_steps=args.zero_steps,
416
+ # i2v
417
+ image=load_image(image_path).resize((args.width, args.height))
418
+ if image_path is not None
419
+ else None,
420
+ image_noise_sigma_min=args.image_noise_sigma_min,
421
+ image_noise_sigma_max=args.image_noise_sigma_max,
422
+ # v2v
423
+ video=load_video(video_path) if video_path is not None else None,
424
+ video_noise_sigma_min=args.video_noise_sigma_min,
425
+ video_noise_sigma_max=args.video_noise_sigma_max,
426
+ # interpolate_prompt
427
+ use_interpolate_prompt=args.use_interpolate_prompt,
428
+ interpolation_steps=args.interpolation_steps,
429
+ interpolate_time_list=interpolate_time_list,
430
+ ).frames[0]
431
+ except Exception:
432
+ continue
433
+ if not args.enable_parallelism or rank == 0:
434
+ export_to_video(output, output_path, fps=24)
435
+ elif args.interactive_prompt_csv_path is not None:
436
+ df = pd.read_csv(args.interactive_prompt_csv_path)
437
+
438
+ df = df.sort_values(by=["id", "prompt_index"])
439
+ all_video_ids = df["id"].unique()
440
+
441
+ if not args.enable_parallelism:
442
+ my_video_ids = all_video_ids[rank::world_size]
443
+ else:
444
+ my_video_ids = all_video_ids
445
+
446
+ for video_id in tqdm(my_video_ids, desc="Processing prompts"):
447
+ output_path = os.path.join(args.output_folder, f"{video_id}.mp4")
448
+
449
+ if os.path.exists(output_path):
450
+ print(f"skipping {output_path}!")
451
+ continue
452
+
453
+ group_df = df[df["id"] == video_id]
454
+
455
+ if "refined_prompt" in df.columns:
456
+ prompt_list = group_df["refined_prompt"].fillna(group_df["prompt"]).tolist()
457
+ else:
458
+ prompt_list = group_df["prompt"].tolist()
459
+ interpolate_time_list = [args.interpolate_time] * len(prompt_list)
460
+
461
+ with torch.no_grad():
462
+ try:
463
+ output = pipe(
464
+ prompt=prompt_list,
465
+ negative_prompt=args.negative_prompt,
466
+ height=args.height,
467
+ width=args.width,
468
+ num_frames=args.num_frames,
469
+ num_inference_steps=args.num_inference_steps,
470
+ guidance_scale=args.guidance_scale,
471
+ generator=torch.Generator(device="cuda").manual_seed(args.seed),
472
+ # stage 1
473
+ history_sizes=[16, 2, 1],
474
+ num_latent_frames_per_chunk=args.num_latent_frames_per_chunk,
475
+ keep_first_frame=True,
476
+ # stage 2
477
+ is_enable_stage2=args.is_enable_stage2,
478
+ pyramid_num_inference_steps_list=args.pyramid_num_inference_steps_list,
479
+ # stage 3
480
+ is_skip_first_chunk=args.is_skip_first_chunk,
481
+ is_amplify_first_chunk=args.is_amplify_first_chunk,
482
+ # cfg zero
483
+ use_zero_init=args.use_zero_init,
484
+ zero_steps=args.zero_steps,
485
+ # i2v
486
+ image=load_image(image_path).resize((args.width, args.height))
487
+ if image_path is not None
488
+ else None,
489
+ image_noise_sigma_min=args.image_noise_sigma_min,
490
+ image_noise_sigma_max=args.image_noise_sigma_max,
491
+ # v2v
492
+ video=load_video(video_path) if video_path is not None else None,
493
+ video_noise_sigma_min=args.video_noise_sigma_min,
494
+ video_noise_sigma_max=args.video_noise_sigma_max,
495
+ # interpolate_prompt
496
+ use_interpolate_prompt=args.use_interpolate_prompt,
497
+ interpolation_steps=args.interpolation_steps,
498
+ interpolate_time_list=interpolate_time_list,
499
+ ).frames[0]
500
+ except Exception:
501
+ continue
502
+ if not args.enable_parallelism or rank == 0:
503
+ export_to_video(output, output_path, fps=24)
504
+ else:
505
+ with torch.no_grad():
506
+ # import time
507
+ # for _ in range(20):
508
+ # start_time = time.time()
509
+ output = pipe(
510
+ prompt=prompt,
511
+ negative_prompt=args.negative_prompt,
512
+ height=args.height,
513
+ width=args.width,
514
+ num_frames=args.num_frames,
515
+ num_inference_steps=args.num_inference_steps,
516
+ guidance_scale=args.guidance_scale,
517
+ generator=torch.Generator(device="cuda").manual_seed(args.seed),
518
+ # stage 1
519
+ history_sizes=[16, 2, 1],
520
+ num_latent_frames_per_chunk=args.num_latent_frames_per_chunk,
521
+ keep_first_frame=True,
522
+ # stage 2
523
+ is_enable_stage2=args.is_enable_stage2,
524
+ pyramid_num_inference_steps_list=args.pyramid_num_inference_steps_list,
525
+ # stage 3
526
+ is_skip_first_chunk=args.is_skip_first_chunk,
527
+ is_amplify_first_chunk=args.is_amplify_first_chunk,
528
+ # cfg zero
529
+ use_zero_init=args.use_zero_init,
530
+ zero_steps=args.zero_steps,
531
+ # i2v
532
+ image=load_image(image_path).resize((args.width, args.height)) if image_path is not None else None,
533
+ image_noise_sigma_min=args.image_noise_sigma_min,
534
+ image_noise_sigma_max=args.image_noise_sigma_max,
535
+ # v2v
536
+ video=load_video(video_path) if video_path is not None else None,
537
+ video_noise_sigma_min=args.video_noise_sigma_min,
538
+ video_noise_sigma_max=args.video_noise_sigma_max,
539
+ # interpolate_prompt
540
+ use_interpolate_prompt=args.use_interpolate_prompt,
541
+ interpolation_steps=args.interpolation_steps,
542
+ interpolate_time_list=interpolate_time_list,
543
+ ).frames[0]
544
+ # elapsed_time = time.time() - start_time
545
+ # print(f"Inference time: {elapsed_time:.2f} seconds ({elapsed_time/60:.2f} minutes)")
546
+
547
+ if not args.enable_parallelism or rank == 0:
548
+ file_count = len(
549
+ [f for f in os.listdir(args.output_folder) if os.path.isfile(os.path.join(args.output_folder, f))]
550
+ )
551
+ output_path = os.path.join(
552
+ args.output_folder, f"{file_count:04d}_{args.sample_type}_{int(time.time())}.mp4"
553
+ )
554
+ export_to_video(output, output_path, fps=24)
555
+
556
+ print(f"Max memory: {torch.cuda.max_memory_allocated() / 1024**3:.3f} GB")
557
+
558
+
559
+ if __name__ == "__main__":
560
+ main()
Helios/install.sh ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ pip install -r requirements.txt
2
+
3
+ rm -rf ~/.triton/cache/
4
+ rm -rf /tmp/torchinductor_*
5
+
6
+ pip uninstall triton torchao xformers wandb tensorflow tensorflow-cpu -y
7
+ pip install wandb==0.23.0 triton==3.6.0
8
+
9
+ rm -rf ~/.triton/cache/
10
+ rm -rf /tmp/torchinductor_*
Helios/requirements.txt ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ torch==2.10.0
2
+ torchvision==0.25.0
3
+ torchaudio==2.10.0
4
+ triton==3.6.0
5
+ kernels==0.13.0
6
+ # diffusers==0.36.0
7
+ # transformers==4.57.6
8
+ git+https://github.com/huggingface/diffusers.git
9
+ transformers==5.3.0
10
+ sentence-transformers==5.2.3
11
+ accelerate==1.12.0
12
+ deepspeed==0.18.4
13
+ peft==0.18.1
14
+ huggingface-hub==1.4.1
15
+ zstandard==0.25.0
16
+ wandb==0.23.0
17
+ video-reader-rs==0.4.1
18
+ numpy<2.0.0
19
+ opencv-python
20
+ gradio
21
+ spaces
22
+ moviepy
23
+ imageio-ffmpeg
24
+ ftfy
25
+ Jinja2
26
+ einops
27
+ nvitop
28
+ packaging
29
+ ninja
30
+ omegaconf
31
+ mpi4py
32
+ hf-doc-builder
33
+ torchdata
34
+ loguru
35
+ tf_keras
Helios/requirements_npu.txt ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ # Please refer to here for installation the latest version: https://github.com/Ascend/pytorch?tab=readme-ov-file#ascend-auxiliary-software
2
+ torch==2.9.0
3
+ torchvision==0.24.0
4
+ torchaudio==2.9.0
5
+ torch_npu==2.9.0
6
+ triton==3.5.1
Helios/run_bench.sh ADDED
@@ -0,0 +1,275 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # =============================================================================
3
+ # Helios Benchmark Inference Runner
4
+ # 用法: bash run_bench.sh [--gpus 5 6 7] [--prompt_range 0-50] [--num_frames 240]
5
+ # [--version base] [--version mid distilled]
6
+ # 默认使用所有可见 GPU;默认跑全部版本(base/mid/distilled),也可手动指定版本
7
+ # 同一时刻只跑一个版本;若有多张卡,会先扫描输出目录,只把缺失 case 均分到多张卡并行
8
+ # 低显存: LOW_VRAM=1 bash run_bench.sh
9
+ # =============================================================================
10
+ set -euo pipefail
11
+
12
+ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
13
+ if [[ -n "${PYTHON:-}" ]]; then
14
+ PYTHON_BIN="${PYTHON}"
15
+ elif command -v python3 >/dev/null 2>&1; then
16
+ PYTHON_BIN="$(command -v python3)"
17
+ elif command -v python >/dev/null 2>&1; then
18
+ PYTHON_BIN="$(command -v python)"
19
+ else
20
+ echo "Python interpreter not found. Set PYTHON=/path/to/python." >&2
21
+ exit 1
22
+ fi
23
+
24
+ GPUS=()
25
+ PROMPT_START="${PROMPT_START:-0}"
26
+ PROMPT_END="${PROMPT_END:-100}"
27
+ NUM_FRAMES="${NUM_FRAMES:-}"
28
+ VERSIONS=(base mid distilled)
29
+ OUTPUT_ROOT="${OUTPUT_ROOT:-}"
30
+ PROMPT_FILE="${PROMPT_FILE:-${SCRIPT_DIR}/demo_data/MovieGenVideoBench_extended.txt}"
31
+ LOW_VRAM="${LOW_VRAM:-0}"
32
+
33
+ discover_gpus() {
34
+ if ! command -v nvidia-smi >/dev/null 2>&1; then
35
+ echo "nvidia-smi not found; use --gpus to specify GPU ids explicitly." >&2
36
+ exit 1
37
+ fi
38
+
39
+ mapfile -t GPUS < <(nvidia-smi --query-gpu=index --format=csv,noheader,nounits)
40
+ if [[ ${#GPUS[@]} -eq 0 ]]; then
41
+ echo "No GPUs found." >&2
42
+ exit 1
43
+ fi
44
+ }
45
+
46
+ while [[ $# -gt 0 ]]; do
47
+ case "$1" in
48
+ --gpus) shift; GPUS=(); while [[ $# -gt 0 && ! "$1" =~ ^-- ]]; do GPUS+=("$1"); shift; done ;;
49
+ --prompt_range)
50
+ if [[ ! "$2" =~ ^([0-9]+)-([0-9]+)$ ]]; then
51
+ echo "Invalid --prompt_range: $2 (expected START-END, e.g. 0-50)" >&2
52
+ exit 1
53
+ fi
54
+ PROMPT_START="${BASH_REMATCH[1]}"
55
+ PROMPT_END="${BASH_REMATCH[2]}"
56
+ shift 2
57
+ ;;
58
+ --prompt_start) PROMPT_START="$2"; shift 2 ;;
59
+ --prompt_end) PROMPT_END="$2"; shift 2 ;;
60
+ --num_frames) NUM_FRAMES="$2"; shift 2 ;;
61
+ --version) shift; VERSIONS=(); while [[ $# -gt 0 && ! "$1" =~ ^-- ]]; do VERSIONS+=("$1"); shift; done ;;
62
+ --output_root) OUTPUT_ROOT="$2"; shift 2 ;;
63
+ --prompt_file) PROMPT_FILE="$2"; shift 2 ;;
64
+ *) echo "Unknown option: $1"; exit 1 ;;
65
+ esac
66
+ done
67
+
68
+ if [[ ${#GPUS[@]} -eq 0 ]]; then
69
+ discover_gpus
70
+ fi
71
+
72
+ if [[ ${#VERSIONS[@]} -eq 0 ]]; then
73
+ echo "No versions specified. Use --version base [mid distilled]." >&2
74
+ exit 1
75
+ fi
76
+
77
+ if [[ ! "${PROMPT_START}" =~ ^[0-9]+$ ]] || [[ ! "${PROMPT_END}" =~ ^[0-9]+$ ]]; then
78
+ echo "prompt_start and prompt_end must be non-negative integers." >&2
79
+ exit 1
80
+ fi
81
+
82
+ if (( PROMPT_END <= PROMPT_START )); then
83
+ echo "prompt_end must be greater than prompt_start." >&2
84
+ exit 1
85
+ fi
86
+
87
+ if [[ -z "${OUTPUT_ROOT}" ]]; then
88
+ if [[ -n "${NUM_FRAMES}" ]]; then
89
+ OUTPUT_ROOT="${SCRIPT_DIR}/outputs/num_frames_${NUM_FRAMES}"
90
+ else
91
+ OUTPUT_ROOT="${SCRIPT_DIR}/outputs/num_frames_default"
92
+ fi
93
+ fi
94
+
95
+ echo "============================================================"
96
+ echo " Helios Benchmark Inference"
97
+ echo " $(date '+%Y-%m-%d %H:%M:%S')"
98
+ echo " Python: ${PYTHON_BIN}"
99
+ echo " GPUs: ${GPUS[*]} | Prompt range: ${PROMPT_START}-${PROMPT_END} | Versions: ${VERSIONS[*]}"
100
+ [[ -n "${NUM_FRAMES}" ]] && echo " Frames: ${NUM_FRAMES}"
101
+ echo " Prompt file: ${PROMPT_FILE}"
102
+ echo " Output: ${OUTPUT_ROOT}"
103
+ echo "============================================================"
104
+
105
+ mkdir -p "${OUTPUT_ROOT}"
106
+
107
+ if [[ ! -f "${PROMPT_FILE}" ]]; then
108
+ echo "Prompt file not found: ${PROMPT_FILE}" >&2
109
+ exit 1
110
+ fi
111
+
112
+ TOTAL_PROMPTS=$(awk 'NF {count++} END {print count + 0}' "${PROMPT_FILE}")
113
+ if (( PROMPT_START >= TOTAL_PROMPTS )); then
114
+ echo "prompt_start (${PROMPT_START}) is out of range; prompt file has ${TOTAL_PROMPTS} non-empty prompts." >&2
115
+ exit 1
116
+ fi
117
+
118
+ if (( PROMPT_END > TOTAL_PROMPTS )); then
119
+ echo "prompt_end (${PROMPT_END}) exceeds total prompts (${TOTAL_PROMPTS}); clamping to ${TOTAL_PROMPTS}."
120
+ PROMPT_END="${TOTAL_PROMPTS}"
121
+ fi
122
+
123
+ EXTRA=()
124
+ if [[ "${LOW_VRAM}" == "1" ]]; then
125
+ EXTRA+=(--enable_low_vram_mode)
126
+ fi
127
+ if [[ -n "${NUM_FRAMES}" ]]; then
128
+ EXTRA+=(--num_frames "${NUM_FRAMES}")
129
+ fi
130
+
131
+ EXIT_CODE=0
132
+ WORKER_PIDS=()
133
+ WORKER_GPUS=()
134
+ WORKER_SHARDS=()
135
+
136
+ prepare_missing_shards() {
137
+ local version="$1"
138
+ local shard_dir="${OUTPUT_ROOT}/shards/${version}_${PROMPT_START}_${PROMPT_END}_$$"
139
+ mkdir -p "${shard_dir}"
140
+
141
+ "${PYTHON_BIN}" - \
142
+ "${PROMPT_FILE}" \
143
+ "${OUTPUT_ROOT}" \
144
+ "${version}" \
145
+ "${PROMPT_START}" \
146
+ "${PROMPT_END}" \
147
+ "${#GPUS[@]}" \
148
+ "${shard_dir}" <<'PY'
149
+ import os
150
+ import re
151
+ import sys
152
+ from pathlib import Path
153
+
154
+ prompt_file = Path(sys.argv[1])
155
+ output_root = Path(sys.argv[2])
156
+ version = sys.argv[3]
157
+ prompt_start = int(sys.argv[4])
158
+ prompt_end = int(sys.argv[5])
159
+ gpu_count = int(sys.argv[6])
160
+ shard_dir = Path(sys.argv[7])
161
+
162
+ with prompt_file.open("r", encoding="utf-8") as f:
163
+ prompts = [line.strip() for line in f if line.strip()]
164
+
165
+ def sanitize_filename(text, max_len=80):
166
+ text = text.strip().lower()
167
+ text = re.sub(r"[^a-z0-9]+", "_", text)
168
+ text = text.strip("_")
169
+ return text[:max_len]
170
+
171
+ missing = []
172
+ existing = 0
173
+ version_dir = output_root / "by_version" / version
174
+ for idx in range(prompt_start, prompt_end):
175
+ slug = sanitize_filename(prompts[idx])
176
+ video_path = version_dir / f"{idx:04d}_{slug}.mp4"
177
+ if video_path.is_file() and video_path.stat().st_size > 0:
178
+ existing += 1
179
+ else:
180
+ missing.append(idx)
181
+
182
+ print(
183
+ f"[scan] version={version} range={prompt_start}-{prompt_end} "
184
+ f"existing={existing} missing={len(missing)} output={version_dir}",
185
+ file=sys.stderr,
186
+ )
187
+
188
+ if not missing:
189
+ sys.exit(0)
190
+
191
+ active_workers = min(gpu_count, len(missing))
192
+ base_chunk = len(missing) // active_workers
193
+ remainder = len(missing) % active_workers
194
+ offset = 0
195
+
196
+ for shard_idx in range(active_workers):
197
+ shard_size = base_chunk + (1 if shard_idx < remainder else 0)
198
+ shard_indices = missing[offset:offset + shard_size]
199
+ offset += shard_size
200
+ shard_path = shard_dir / f"shard_{shard_idx:02d}.txt"
201
+ shard_path.write_text(
202
+ "".join(f"{idx}\n" for idx in shard_indices),
203
+ encoding="utf-8",
204
+ )
205
+ print(shard_path)
206
+ print(
207
+ f"[shard] version={version} shard={shard_idx} count={len(shard_indices)} "
208
+ f"indices={shard_indices[0]}-{shard_indices[-1]} file={shard_path}",
209
+ file=sys.stderr,
210
+ )
211
+ PY
212
+ }
213
+
214
+ launch_job() {
215
+ local version="$1"
216
+ local gpu="$2"
217
+ local shard_file="$3"
218
+ local shard_id
219
+ shard_id="$(basename "${shard_file}" .txt)"
220
+ local timing_file="${OUTPUT_ROOT}/timing_${version}_${shard_id}.txt"
221
+
222
+ echo "[launch] version=${version} gpu=${gpu} shard=${shard_id} indices=${shard_file} output=${OUTPUT_ROOT}"
223
+ "${PYTHON_BIN}" "${SCRIPT_DIR}/bench_infer.py" \
224
+ --prompt_file "${PROMPT_FILE}" \
225
+ --prompt_start "${PROMPT_START}" \
226
+ --prompt_end "${PROMPT_END}" \
227
+ --prompt_indices_file "${shard_file}" \
228
+ --output_root "${OUTPUT_ROOT}" \
229
+ --timing_file "${timing_file}" \
230
+ --version "${version}" \
231
+ --gpu "${gpu}" \
232
+ "${EXTRA[@]}" &
233
+
234
+ WORKER_PIDS+=("$!")
235
+ WORKER_GPUS+=("${gpu}")
236
+ WORKER_SHARDS+=("${shard_id}")
237
+ }
238
+
239
+ wait_for_current_version() {
240
+ local version="$1"
241
+ for idx in "${!WORKER_PIDS[@]}"; do
242
+ local pid="${WORKER_PIDS[$idx]}"
243
+ local gpu="${WORKER_GPUS[$idx]}"
244
+ local shard_id="${WORKER_SHARDS[$idx]}"
245
+ if wait "${pid}"; then
246
+ echo "[done] ${version} finished on gpu=${gpu} shard=${shard_id}"
247
+ else
248
+ echo "[fail] ${version} failed on gpu=${gpu} shard=${shard_id}"
249
+ EXIT_CODE=1
250
+ fi
251
+ done
252
+ WORKER_PIDS=()
253
+ WORKER_GPUS=()
254
+ WORKER_SHARDS=()
255
+ }
256
+
257
+ for version in "${VERSIONS[@]}"; do
258
+ echo ""
259
+ echo "-------------------- version=${version} --------------------"
260
+ mapfile -t SHARD_FILES < <(prepare_missing_shards "${version}")
261
+ if (( ${#SHARD_FILES[@]} == 0 )); then
262
+ echo "[skip] version=${version} has no missing cases in ${PROMPT_START}-${PROMPT_END}"
263
+ continue
264
+ fi
265
+
266
+ for worker_idx in "${!SHARD_FILES[@]}"; do
267
+ launch_job "${version}" "${GPUS[$worker_idx]}" "${SHARD_FILES[$worker_idx]}"
268
+ done
269
+ wait_for_current_version "${version}"
270
+ done
271
+
272
+ echo ""
273
+ echo "Done. Per-shard timing reports are under ${OUTPUT_ROOT}/timing_<version>_shard_<id>.txt"
274
+
275
+ exit ${EXIT_CODE:-0}
Helios/temp.sh ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ for i in $(seq 1 10000); do
2
+ CUDA_VISIBLE_DEVICES=0 python infer_helios.py \
3
+ --base_model_path "./checkpoints/Helios-Base" \
4
+ --transformer_path "./checkpoints/Helios-Base" \
5
+ --sample_type "t2v" \
6
+ --num_frames 99 \
7
+ --fps 24 \
8
+ --prompt "A woman dancing." \
9
+ --guidance_scale 5.0 \
10
+ --enable_compile \
11
+ --output_folder "./temp/run_${i}"
12
+ done
Helios/train_helios.py ADDED
The diff for this file is too large to render. See raw diff