Cccccz commited on
Commit
153dd42
·
verified ·
1 Parent(s): e019a54

Add files using upload-large-folder tool

Browse files
Files changed (50) hide show
  1. FlowCache/.gitignore +8 -0
  2. FlowCache/FlowCache4MAGI-1-dev-V1/README.md +71 -0
  3. FlowCache/FlowCache4MAGI-1-dev-V1/requirements.txt +21 -0
  4. FlowCache/FlowCache4MAGI-1-dev-V1/sample_video.py +403 -0
  5. FlowCache/FlowCache4MAGI-1-dev-V2/README.md +71 -0
  6. FlowCache/FlowCache4MAGI-1-dev-V2/requirements.txt +21 -0
  7. FlowCache/FlowCache4MAGI-1-dev-V2/sample_video.py +429 -0
  8. FlowCache/FlowCache4MAGI-1-dev3-motion/README.md +71 -0
  9. FlowCache/FlowCache4MAGI-1-dev3-motion/README_MOTIONCACHE.md +92 -0
  10. FlowCache/FlowCache4MAGI-1-dev3-motion/requirements.txt +21 -0
  11. FlowCache/FlowCache4MAGI-1-dev3-motion/sample_video.py +429 -0
  12. FlowCache/FlowCache4MAGI-1-dev4-detail/README.md +71 -0
  13. FlowCache/FlowCache4MAGI-1-dev4-detail/README_MOTIONCACHE.md +92 -0
  14. FlowCache/FlowCache4MAGI-1-dev4-detail/README_MOTIONDETAIL.md +71 -0
  15. FlowCache/FlowCache4MAGI-1-dev4-detail/requirements.txt +21 -0
  16. FlowCache/FlowCache4MAGI-1-dev4-detail/sample_video.py +429 -0
  17. FlowCache/FlowCache4MAGI-1-dev5-history/README.md +71 -0
  18. FlowCache/FlowCache4MAGI-1-dev5-history/README_DEV5_HISTORY.md +218 -0
  19. FlowCache/FlowCache4MAGI-1-dev5-history/README_MOTIONCACHE.md +92 -0
  20. FlowCache/FlowCache4MAGI-1-dev5-history/README_MOTIONDETAIL.md +71 -0
  21. FlowCache/FlowCache4MAGI-1-dev5-history/requirements.txt +21 -0
  22. FlowCache/FlowCache4MAGI-1-dev5-history/sample_video.py +429 -0
  23. FlowCache/FlowCache4MAGI-1-dev6-adaptive/README.md +71 -0
  24. FlowCache/FlowCache4MAGI-1-dev6-adaptive/README_ADAPTIVE.md +66 -0
  25. FlowCache/FlowCache4MAGI-1-dev6-adaptive/README_MOTIONCACHE.md +92 -0
  26. FlowCache/FlowCache4MAGI-1-dev6-adaptive/README_MOTIONDETAIL.md +71 -0
  27. FlowCache/FlowCache4MAGI-1-dev6-adaptive/requirements.txt +21 -0
  28. FlowCache/FlowCache4MAGI-1-dev6-adaptive/sample_video.py +429 -0
  29. FlowCache/FlowCache4MAGI-1/README.md +71 -0
  30. FlowCache/FlowCache4MAGI-1/__pycache__/sample_video.cpython-312.pyc +0 -0
  31. FlowCache/FlowCache4MAGI-1/inference/__init__.py +0 -0
  32. FlowCache/FlowCache4MAGI-1/logs/flowcache_vbench_20260520_103113.log +181 -0
  33. FlowCache/FlowCache4MAGI-1/logs/flowcache_vbench_20260520_121944.log +208 -0
  34. FlowCache/FlowCache4MAGI-1/logs/flowcache_vbench_20260520_124220.log +195 -0
  35. FlowCache/FlowCache4MAGI-1/logs/flowcache_vbench_20260520_170603.log +298 -0
  36. FlowCache/FlowCache4MAGI-1/logs/flowcache_vbench_20260521_034016.log +109 -0
  37. FlowCache/FlowCache4MAGI-1/requirements.txt +21 -0
  38. FlowCache/FlowCache4MAGI-1/sample_video.py +429 -0
  39. FlowCache/FlowCache4MAGI-1/scripts/metric.sh +5 -0
  40. FlowCache/FlowCache4MAGI-1/tools/plot_l1_rel.py +152 -0
  41. FlowCache/FlowCache4MAGI-1/tools/plot_residual_norms.py +142 -0
  42. FlowCache/FlowCache4SkyReels-V2/FLOPs claculation.xlsx +0 -0
  43. FlowCache/FlowCache4SkyReels-V2/README.md +52 -0
  44. FlowCache/FlowCache4SkyReels-V2/generate_video.py +161 -0
  45. FlowCache/FlowCache4SkyReels-V2/generate_video_df.py +231 -0
  46. FlowCache/FlowCache4SkyReels-V2/requirements.txt +14 -0
  47. FlowCache/FlowCache4SkyReels-V2/run_flowcache_fast.sh +24 -0
  48. FlowCache/FlowCache4SkyReels-V2/run_flowcache_kvcompress.sh +24 -0
  49. FlowCache/FlowCache4SkyReels-V2/run_flowcache_slow.sh +22 -0
  50. FlowCache/README.md +228 -0
FlowCache/.gitignore ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ __pycache__
2
+ *.pyc
3
+ *.log
4
+ *.pt
5
+ *.mp4
6
+ ckpt
7
+ downloads
8
+ *.whl
FlowCache/FlowCache4MAGI-1-dev-V1/README.md ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # FLOW CACHING FOR AUTOREGRESSIVE VIDEO GENERATION
2
+
3
+ This repository provides the official implementation of **FlowCache** on **MAGI-1** model, a caching-based acceleration method for autoregressive video generation models.
4
+
5
+
6
+ ## 🚀 Installation
7
+
8
+ Please follow the installation instructions provided in the [MAGI-1](https://github.com/SandAI-org/MAGI-1), as this implementation is built on top of MAGI-1.
9
+
10
+ ---
11
+
12
+ ## ▶️ Usage
13
+
14
+ ### 1. Single Video Generation
15
+
16
+ Run accelerated generation using FlowCache:
17
+
18
+ ```bash
19
+ # FlowCache for text-to-video generation
20
+ bash scripts/single_run/flowcache_t2v.sh
21
+
22
+ # FlowCache for video-to-video generation
23
+ bash scripts/single_run/flowcache_v2v.sh
24
+
25
+ # Baseline acceleration method (TeaCache) for text-to-video
26
+ bash scripts/single_run/teacache_t2v.sh
27
+
28
+ # Baseline acceleration method (TeaCache) for video-to-video
29
+ bash scripts/single_run/teacache_v2v.sh
30
+ ```
31
+
32
+ ### 2. Benchmark Sampling
33
+
34
+ Generate videos for evaluation on standard benchmarks:
35
+
36
+ ```bash
37
+ # VBench
38
+ bash scripts/sample/flowcache_vbench.sh
39
+ bash scripts/sample/teacache_vbench.sh
40
+
41
+ # PhysicsIQ
42
+ bash scripts/sample/flowcache_physicsiq.sh
43
+ bash scripts/sample/teacache_physicsiq.sh
44
+ ```
45
+
46
+ ### 3. Quality Evaluation
47
+
48
+ Compute perceptual and structural similarity metrics between original and accelerated generations:
49
+
50
+ ```bash
51
+ bash scripts/metric.sh
52
+ ```
53
+
54
+ ---
55
+
56
+ ## ⚙️ Key Parameters
57
+
58
+ | Parameter | Description |
59
+ |----------|-------------|
60
+ | `rel_l1_thresh` | Relative L1 distance threshold for cache reuse decision |
61
+ | ` warmup_steps` | Number of denoising steps where reuse is disabled |
62
+ | `total_cache_chunk_nums` (`B_total`) | Total number of cache chunks maintained |
63
+ | `compress_strategy` | Granularity for selecting important KV caches: `token`, `frame`, or `chunk` |
64
+ | `query_granularity` | Granularity for importance scoring: `token`, `frame`, or `chunk` |
65
+ | `mix_lambda` | Weight balancing importance and redundancy (default: `0.07`) |
66
+ | `mode` | Generation mode: `t2v` (text-to-video), `i2v` (image-to-video), or `v2v` (video-to-video) |
67
+ | `prompt` | Input prompt for conditional generation |
68
+ | `output_path` | Path to save generated videos |
69
+ | `config_file` | Path to MAGI-1 model configuration |
70
+
71
+ ---
FlowCache/FlowCache4MAGI-1-dev-V1/requirements.txt ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ accelerate==0.32.1
2
+ beautifulsoup4==4.13.4
3
+ debugpy==1.8.14
4
+ diffusers==0.29.2
5
+ einops>=0.6.0
6
+ ffmpeg-python
7
+ # flash-attn==2.4.2
8
+ flashinfer-python==0.2.0.post2 --extra-index-url https://flashinfer.ai/whl/cu124/torch2.4/
9
+ ftfy==6.2.0
10
+ gpustat==1.1.1
11
+ imageio==2.34.0
12
+ imageio[ffmpeg]
13
+ matplotlib==3.10.1
14
+ numpy==1.26.4
15
+ protobuf==5.28.3
16
+ rich==14.0.0
17
+ sentencepiece==0.2.0
18
+ timm==1.0.15
19
+ torchdiffeq==0.2.4
20
+ transformers==4.42.3
21
+ tqdm
FlowCache/FlowCache4MAGI-1-dev-V1/sample_video.py ADDED
@@ -0,0 +1,403 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 MAGI Authors. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import os
16
+ import re
17
+ import sys
18
+ import argparse
19
+ import csv
20
+ import subprocess
21
+ from pathlib import Path
22
+
23
+ import multiprocessing as mp
24
+
25
+ # Constants
26
+ DEFAULT_BASE_PORT = 29510
27
+ PHYSICSIQ_FPS = 24
28
+
29
+
30
+ def load_yaml_config(yaml_path: str) -> dict:
31
+ """Load configuration from YAML file."""
32
+ import yaml
33
+
34
+ with open(yaml_path, "r") as f:
35
+ return yaml.safe_load(f)
36
+
37
+
38
+ def apply_slice(items: list, start: int | None, end: int | None) -> list:
39
+ """Apply start/end slice to a list with bounds checking."""
40
+ if start is None and end is None:
41
+ return items
42
+
43
+ slice_start = max(0, start if start is not None else 0)
44
+ slice_end = min(end if end is not None else len(items), len(items))
45
+ slice_end = max(slice_start, slice_end)
46
+
47
+ return items[slice_start:slice_end]
48
+
49
+
50
+ def configure_teacache(transport, config: dict) -> None:
51
+ """Configure TeaCache reuse strategy on SampleTransport."""
52
+ from inference.pipeline.teacache import (
53
+ teacache_forward_velocity,
54
+ teacache_integrate_velocity,
55
+ )
56
+
57
+ transport.rel_l1_thresh = config["rel_l1_thresh"]
58
+ transport.accumulated_rel_l1_distance = 0
59
+ transport.previous_modulated_input = None
60
+ transport.previous_residual = None
61
+ transport.cnt = 0
62
+ transport.forward_velocity = teacache_forward_velocity
63
+ transport.integrate_velocity = teacache_integrate_velocity
64
+ transport.reuse_times = 0
65
+ transport.warmup_steps = config["warmup_steps"]
66
+ transport.previous_output = None
67
+ transport.log = config.get("log", False)
68
+
69
+
70
+ def configure_kv_cache(transport, config: dict) -> None:
71
+ """Configure KV cache compression if enabled."""
72
+ if not config.get("compress_kv_cache", False):
73
+ transport.compress_kv_cache = False
74
+ return
75
+
76
+ print("KV cache compression is enabled.")
77
+ transport.compress_kv_cache = True
78
+
79
+ assert config.get("total_cache_chunk_nums") is not None
80
+
81
+ compression_config = {
82
+ "method_config": {
83
+ "compress_strategy": config["compress_strategy"],
84
+ "mix_lambda": config["mix_lambda"],
85
+ "query_granularity": config["query_granularity"],
86
+ "score_weighting_method": config.get("score_weighting_method"),
87
+ "power": config.get("power", 3),
88
+ },
89
+ }
90
+
91
+ from inference.pipeline.kvcompress import replace_magi
92
+
93
+ replace_magi(compression_config)
94
+
95
+
96
+ def configure_flowcache(transport, config: dict) -> None:
97
+ """Configure FlowCache reuse strategy on SampleTransport."""
98
+ from inference.pipeline.flowcache import (
99
+ flowcache_forward_velocity,
100
+ flowcache_integrate_velocity,
101
+ )
102
+
103
+ configure_kv_cache(transport, config)
104
+
105
+ transport.rel_l1_thresh = config["rel_l1_thresh"]
106
+ transport.chunk_accumulated_rel_l1 = 0
107
+ transport.previous_modulated_input = None
108
+ transport.previous_residual = None
109
+ transport.cnt = 0
110
+ transport.forward_velocity = flowcache_forward_velocity
111
+ transport.integrate_velocity = flowcache_integrate_velocity
112
+ transport.reuse_times = 0
113
+ transport.warmup_steps = config["warmup_steps"]
114
+ transport.previous_output = None
115
+ transport.discard_nearly_clean_chunk = config.get("discard_nearly_clean_chunk", False)
116
+ transport.chunk_accumulated_rel_l1 = None
117
+ transport.prev_chunk_features = None
118
+ transport.chunk_reuse_flags = None
119
+ transport.total_cache_chunk_nums = config.get("total_cache_chunk_nums")
120
+ transport.log = config.get("log", False)
121
+
122
+
123
+ def configure_reuse_strategy(config: dict) -> None:
124
+ """Configure the appropriate reuse strategy on SampleTransport."""
125
+ from inference.pipeline.video_generate import SampleTransport
126
+
127
+ strategy = config["reuse_strategy"]
128
+
129
+ if strategy == "original":
130
+ return
131
+ if strategy == "all":
132
+ configure_teacache(SampleTransport, config)
133
+ elif strategy == "chunkwise":
134
+ configure_flowcache(SampleTransport, config)
135
+ else:
136
+ raise ValueError(f"Unknown reuse strategy: {strategy}")
137
+
138
+
139
+ def setup_environment(gpu_id: int) -> None:
140
+ """Set up environment variables for a GPU worker process."""
141
+ os.environ["CUDA_VISIBLE_DEVICES"] = str(gpu_id)
142
+ os.environ["WORLD_SIZE"] = "1"
143
+ os.environ["RANK"] = "0"
144
+ os.environ["LOCAL_RANK"] = "0"
145
+ os.environ["MASTER_ADDR"] = "localhost"
146
+ os.environ["MASTER_PORT"] = str(DEFAULT_BASE_PORT + gpu_id)
147
+
148
+ # Enable pdb terminal debugging
149
+ sys.stdin = open(0)
150
+
151
+
152
+ def filter_existing_samples(samples: list, config: dict) -> list:
153
+ """Filter out samples whose output files already exist."""
154
+ if config["benchmark"] == "vbench":
155
+ return [
156
+ sample
157
+ for sample in samples
158
+ if not os.path.exists(os.path.abspath(os.path.join(config["save_path"], f"{sample}-0.mp4")))
159
+ ]
160
+ else: # physicsiq
161
+ return [
162
+ sample for sample in samples if not os.path.exists(sample["output_path"])
163
+ ]
164
+
165
+
166
+ def assign_samples_to_gpu(
167
+ samples: list, gpu_id: int, rank: int, num_gpus: int
168
+ ) -> list:
169
+ """Divide samples across GPUs and return the subset for this GPU."""
170
+ samples_per_gpu = (len(samples) + num_gpus - 1) // num_gpus
171
+ start_idx = rank * samples_per_gpu
172
+ end_idx = min(start_idx + samples_per_gpu, len(samples))
173
+ return samples[start_idx:end_idx]
174
+
175
+
176
+ def process_vbench_sample(pipeline, prompt: str, config: dict, gpu_id: int) -> None:
177
+ """Process a single vbench text-to-video sample."""
178
+ output_path = os.path.abspath(os.path.join(config["save_path"], f"{prompt}-0.mp4"))
179
+
180
+ if os.path.exists(output_path):
181
+ print(f"[SKIP GPU {gpu_id}] Already exists: {output_path}")
182
+ return
183
+
184
+ print(f"[GPU {gpu_id}] Generating T2V: '{prompt}' -> {output_path}")
185
+ pipeline.run_text_to_video(prompt=prompt, output_path=output_path)
186
+ print(f"[DONE GPU {gpu_id}] Saved: {output_path}")
187
+
188
+
189
+ def process_physicsiq_sample(pipeline, sample: dict, gpu_id: int) -> None:
190
+ """Process a single PhysicsIQ video-to-video sample."""
191
+ prompt = sample["description"]
192
+ prefix_video_path = sample["prefix_video_path"]
193
+ output_path = sample["output_path"]
194
+
195
+ if not os.path.exists(prefix_video_path):
196
+ print(f"[WARN GPU {gpu_id}] Conditioning video not found: {prefix_video_path}")
197
+ return
198
+
199
+ if os.path.exists(output_path):
200
+ print(f"[SKIP GPU {gpu_id}] Already exists: {output_path}")
201
+ return
202
+
203
+ print(f"[GPU {gpu_id}] Generating V2V: '{prompt}'")
204
+ print(f" Input: {prefix_video_path}")
205
+ print(f" Output: {output_path}")
206
+
207
+ pipeline.run_video_to_video(
208
+ prompt=prompt,
209
+ prefix_video_path=prefix_video_path,
210
+ output_path=output_path,
211
+ )
212
+ print(f"[DONE GPU {gpu_id}] Saved: {output_path}")
213
+
214
+
215
+ def worker_process(gpu_id: int, rank: int, config: dict, all_samples: list) -> None:
216
+ """Independent worker running on each GPU."""
217
+ setup_environment(gpu_id)
218
+ configure_reuse_strategy(config)
219
+
220
+ try:
221
+ magi_root = subprocess.check_output(
222
+ ["git", "rev-parse", "--show-toplevel"]
223
+ ).decode().strip()
224
+ os.environ["MAGI_ROOT"] = magi_root
225
+ os.environ["PYTHONPATH"] = f"{magi_root}:{os.environ.get('PYTHONPATH', '')}"
226
+ except Exception as e:
227
+ print(f"[GPU {gpu_id}] Failed to set MAGI_ROOT: {e}")
228
+ return
229
+
230
+ filtered_samples = filter_existing_samples(all_samples, config)
231
+
232
+ if not filtered_samples:
233
+ print(f"[GPU {gpu_id}] No samples need to be generated.")
234
+ return
235
+
236
+ print(f"Processing {len(filtered_samples)} samples.")
237
+
238
+ my_samples = assign_samples_to_gpu(
239
+ filtered_samples, gpu_id, rank, config["num_gpus"]
240
+ )
241
+
242
+ if not my_samples:
243
+ print(f"[GPU {gpu_id}] No samples assigned.")
244
+ return
245
+
246
+ print(f"[GPU {gpu_id}] Assigned {len(my_samples)} samples")
247
+
248
+ from inference.pipeline.entry import MagiPipeline
249
+
250
+ print(f"[GPU {gpu_id}] Loading model...")
251
+ pipeline = MagiPipeline(config["config_file"])
252
+ print(f"[GPU {gpu_id}] Model loaded.")
253
+
254
+ process_func = (
255
+ process_vbench_sample if config["benchmark"] == "vbench" else process_physicsiq_sample
256
+ )
257
+
258
+ for sample in my_samples:
259
+ process_func(pipeline, sample, config, gpu_id)
260
+
261
+ print(f"[GPU {gpu_id}] Completed.")
262
+
263
+
264
+ def build_conditioning_video_path(
265
+ data_root: str, vid_id: str, scenario: str, fps: int
266
+ ) -> str:
267
+ """Construct the path to the conditioning video file."""
268
+ conditioning_dir = os.path.join(
269
+ data_root, "physics-IQ-benchmark", "split-videos", "conditioning", f"{fps}FPS"
270
+ )
271
+ match_suffix = re.search(r"_(.*)", scenario)
272
+ suffix = match_suffix.group(1) if match_suffix else ""
273
+ filename = f"{vid_id}_conditioning-videos_{fps}FPS_{suffix}"
274
+ return os.path.join(conditioning_dir, filename)
275
+
276
+
277
+ def load_physicsiq_samples(config: dict) -> list[dict]:
278
+ """Load sample list from PhysicsIQ dataset."""
279
+ data_root = config["physicsiq_data_dir"]
280
+ descriptions_csv = os.path.join(data_root, "descriptions", "descriptions.csv")
281
+ output_dir = config["save_path"]
282
+
283
+ if not os.path.exists(descriptions_csv):
284
+ raise FileNotFoundError(f"descriptions.csv not found at {descriptions_csv}")
285
+
286
+ os.makedirs(output_dir, exist_ok=True)
287
+
288
+ samples = []
289
+ with open(descriptions_csv, mode="r") as f:
290
+ reader = csv.DictReader(f)
291
+ for row in reader:
292
+ scenario = row["scenario"].strip()
293
+ match_id = re.match(r"^(\d+)_", scenario)
294
+
295
+ if not match_id:
296
+ print(f"Cannot extract ID from scenario: {scenario}")
297
+ continue
298
+
299
+ vid_id = match_id.group(1).zfill(4)
300
+ description = row["description"]
301
+ generated_video_name = row["generated_video_name"]
302
+ prefix_video_path = build_conditioning_video_path(
303
+ data_root, vid_id, scenario, PHYSICSIQ_FPS
304
+ )
305
+ output_path = os.path.join(output_dir, generated_video_name)
306
+
307
+ os.makedirs(os.path.dirname(output_path), exist_ok=True)
308
+
309
+ samples.append({
310
+ "vid_id": vid_id,
311
+ "scenario": scenario,
312
+ "description": description,
313
+ "generated_video_name": generated_video_name,
314
+ "prefix_video_path": prefix_video_path,
315
+ "output_path": output_path,
316
+ })
317
+
318
+ # PhysicsIQ samples are duplicated; take only the first half
319
+ unique_count = len(samples) // 2
320
+ samples = samples[:unique_count]
321
+
322
+ print(f"Loaded {unique_count} PhysicsIQ samples.")
323
+
324
+ return apply_slice(samples, config.get("start"), config.get("end"))
325
+
326
+
327
+ def load_vbench_samples(config: dict) -> list[str]:
328
+ """Load prompt list from vbench dimension file."""
329
+ prompt_dir = config["vbench_prompt_dir"]
330
+ dimension = config.get("dimension")
331
+
332
+ if not dimension:
333
+ raise ValueError("For vbench, 'dimension' must be specified in config")
334
+
335
+ prompt_file = os.path.join(prompt_dir, f"{dimension}.txt")
336
+
337
+ if not os.path.exists(prompt_file):
338
+ raise FileNotFoundError(f"Prompt file not found: {prompt_file}")
339
+
340
+ with open(prompt_file, "r") as f:
341
+ prompts = [line.strip() for line in f if line.strip()]
342
+
343
+ return apply_slice(prompts, config.get("start"), config.get("end"))
344
+
345
+
346
+ def setup_save_path(config: dict) -> None:
347
+ """Configure the output save path based on benchmark type."""
348
+ base_path = config["base_save_path"]
349
+
350
+ if config["benchmark"] == "vbench":
351
+ dimension = config.get("dimension")
352
+ videos_dir = os.path.join(base_path, "videos", dimension) if dimension else None
353
+ config["save_path"] = videos_dir if videos_dir else os.path.join(base_path, "videos")
354
+ elif config["benchmark"] == "physicsiq":
355
+ config["save_path"] = os.path.join(base_path, "videos")
356
+
357
+ os.makedirs(config["save_path"], exist_ok=True)
358
+
359
+
360
+ def main() -> None:
361
+ """Entry point for video sampling script."""
362
+ parser = argparse.ArgumentParser(
363
+ description="Video sampling script using YAML configuration"
364
+ )
365
+ parser.add_argument("yaml_config", type=str, help="Path to YAML configuration file")
366
+ args = parser.parse_args()
367
+
368
+ config = load_yaml_config(args.yaml_config)
369
+ print(f"Loaded configuration from: {args.yaml_config}")
370
+
371
+ setup_save_path(config)
372
+
373
+ gpu_ids = list(map(int, config["gpus"].split(",")))
374
+ config["num_gpus"] = len(gpu_ids)
375
+
376
+ benchmark = config["benchmark"]
377
+ if benchmark == "vbench":
378
+ all_samples = load_vbench_samples(config)
379
+ elif benchmark == "physicsiq":
380
+ data_root = config["physicsiq_data_dir"]
381
+ if not os.path.exists(data_root):
382
+ raise FileNotFoundError(f"Data directory not found: {data_root}")
383
+ all_samples = load_physicsiq_samples(config)
384
+ else:
385
+ raise ValueError(f"Invalid benchmark: {benchmark}")
386
+
387
+ print(f"Total samples: {len(all_samples)}")
388
+ print(f"GPUs: {gpu_ids}")
389
+ print(f"Output: {config['save_path']}")
390
+ print(f"Config: {config['config_file']}")
391
+
392
+ processes = []
393
+ for rank, gpu_id in enumerate(gpu_ids):
394
+ p = mp.Process(target=worker_process, args=(gpu_id, rank, config, all_samples))
395
+ p.start()
396
+ processes.append(p)
397
+
398
+ for p in processes:
399
+ p.join()
400
+
401
+
402
+ if __name__ == "__main__":
403
+ main()
FlowCache/FlowCache4MAGI-1-dev-V2/README.md ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # FLOW CACHING FOR AUTOREGRESSIVE VIDEO GENERATION
2
+
3
+ This repository provides the official implementation of **FlowCache** on **MAGI-1** model, a caching-based acceleration method for autoregressive video generation models.
4
+
5
+
6
+ ## 🚀 Installation
7
+
8
+ Please follow the installation instructions provided in the [MAGI-1](https://github.com/SandAI-org/MAGI-1), as this implementation is built on top of MAGI-1.
9
+
10
+ ---
11
+
12
+ ## ▶️ Usage
13
+
14
+ ### 1. Single Video Generation
15
+
16
+ Run accelerated generation using FlowCache:
17
+
18
+ ```bash
19
+ # FlowCache for text-to-video generation
20
+ bash scripts/single_run/flowcache_t2v.sh
21
+
22
+ # FlowCache for video-to-video generation
23
+ bash scripts/single_run/flowcache_v2v.sh
24
+
25
+ # Baseline acceleration method (TeaCache) for text-to-video
26
+ bash scripts/single_run/teacache_t2v.sh
27
+
28
+ # Baseline acceleration method (TeaCache) for video-to-video
29
+ bash scripts/single_run/teacache_v2v.sh
30
+ ```
31
+
32
+ ### 2. Benchmark Sampling
33
+
34
+ Generate videos for evaluation on standard benchmarks:
35
+
36
+ ```bash
37
+ # VBench
38
+ bash scripts/sample/flowcache_vbench.sh
39
+ bash scripts/sample/teacache_vbench.sh
40
+
41
+ # PhysicsIQ
42
+ bash scripts/sample/flowcache_physicsiq.sh
43
+ bash scripts/sample/teacache_physicsiq.sh
44
+ ```
45
+
46
+ ### 3. Quality Evaluation
47
+
48
+ Compute perceptual and structural similarity metrics between original and accelerated generations:
49
+
50
+ ```bash
51
+ bash scripts/metric.sh
52
+ ```
53
+
54
+ ---
55
+
56
+ ## ⚙️ Key Parameters
57
+
58
+ | Parameter | Description |
59
+ |----------|-------------|
60
+ | `rel_l1_thresh` | Relative L1 distance threshold for cache reuse decision |
61
+ | ` warmup_steps` | Number of denoising steps where reuse is disabled |
62
+ | `total_cache_chunk_nums` (`B_total`) | Total number of cache chunks maintained |
63
+ | `compress_strategy` | Granularity for selecting important KV caches: `token`, `frame`, or `chunk` |
64
+ | `query_granularity` | Granularity for importance scoring: `token`, `frame`, or `chunk` |
65
+ | `mix_lambda` | Weight balancing importance and redundancy (default: `0.07`) |
66
+ | `mode` | Generation mode: `t2v` (text-to-video), `i2v` (image-to-video), or `v2v` (video-to-video) |
67
+ | `prompt` | Input prompt for conditional generation |
68
+ | `output_path` | Path to save generated videos |
69
+ | `config_file` | Path to MAGI-1 model configuration |
70
+
71
+ ---
FlowCache/FlowCache4MAGI-1-dev-V2/requirements.txt ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ accelerate==0.32.1
2
+ beautifulsoup4==4.13.4
3
+ debugpy==1.8.14
4
+ diffusers==0.29.2
5
+ einops>=0.6.0
6
+ ffmpeg-python
7
+ # flash-attn==2.4.2
8
+ flashinfer-python==0.2.0.post2 --extra-index-url https://flashinfer.ai/whl/cu124/torch2.4/
9
+ ftfy==6.2.0
10
+ gpustat==1.1.1
11
+ imageio==2.34.0
12
+ imageio[ffmpeg]
13
+ matplotlib==3.10.1
14
+ numpy==1.26.4
15
+ protobuf==5.28.3
16
+ rich==14.0.0
17
+ sentencepiece==0.2.0
18
+ timm==1.0.15
19
+ torchdiffeq==0.2.4
20
+ transformers==4.42.3
21
+ tqdm
FlowCache/FlowCache4MAGI-1-dev-V2/sample_video.py ADDED
@@ -0,0 +1,429 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 MAGI Authors. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import os
16
+ import re
17
+ import sys
18
+ import argparse
19
+ import csv
20
+ import subprocess
21
+ from pathlib import Path
22
+
23
+ import multiprocessing as mp
24
+
25
+ # Constants
26
+ DEFAULT_BASE_PORT = 29510
27
+ PHYSICSIQ_FPS = 24
28
+
29
+
30
+ def resolve_gpu_ids(gpus_config) -> list[int]:
31
+ """Resolve explicit GPU IDs or auto-detect all currently visible GPUs."""
32
+ if isinstance(gpus_config, int):
33
+ return [gpus_config]
34
+
35
+ gpus_text = str(gpus_config).strip()
36
+ if not gpus_text:
37
+ raise ValueError("'gpus' must not be empty")
38
+
39
+ if gpus_text.lower() not in {"all", "auto"}:
40
+ return [int(item.strip()) for item in gpus_text.split(",") if item.strip()]
41
+
42
+ visible_devices = os.environ.get("CUDA_VISIBLE_DEVICES")
43
+ if visible_devices:
44
+ visible = [item.strip() for item in visible_devices.split(",") if item.strip()]
45
+ if visible and all(item.isdigit() for item in visible):
46
+ return [int(item) for item in visible]
47
+
48
+ try:
49
+ output = subprocess.check_output(
50
+ ["nvidia-smi", "--query-gpu=index", "--format=csv,noheader,nounits"],
51
+ text=True,
52
+ timeout=10,
53
+ )
54
+ gpu_ids = [int(line.strip()) for line in output.splitlines() if line.strip()]
55
+ if gpu_ids:
56
+ return gpu_ids
57
+ except Exception:
58
+ pass
59
+
60
+ try:
61
+ import torch
62
+
63
+ count = torch.cuda.device_count()
64
+ if count > 0:
65
+ return list(range(count))
66
+ except Exception:
67
+ pass
68
+
69
+ raise RuntimeError("No CUDA GPUs detected for gpus: all")
70
+
71
+
72
+ def load_yaml_config(yaml_path: str) -> dict:
73
+ """Load configuration from YAML file."""
74
+ import yaml
75
+
76
+ with open(yaml_path, "r") as f:
77
+ return yaml.safe_load(f)
78
+
79
+
80
+ def apply_slice(items: list, start: int | None, end: int | None) -> list:
81
+ """Apply start/end slice to a list with bounds checking."""
82
+ if start is None and end is None:
83
+ return items
84
+
85
+ slice_start = max(0, start if start is not None else 0)
86
+ slice_end = min(end if end is not None else len(items), len(items))
87
+ slice_end = max(slice_start, slice_end)
88
+
89
+ return items[slice_start:slice_end]
90
+
91
+
92
+ def configure_teacache(transport, config: dict) -> None:
93
+ """Configure TeaCache reuse strategy on SampleTransport."""
94
+ from inference.pipeline.teacache import setup_teacache
95
+
96
+ setup_teacache(
97
+ rel_l1_thresh=config["rel_l1_thresh"],
98
+ warmup_steps=config["warmup_steps"],
99
+ log=config.get("log", False),
100
+ )
101
+
102
+
103
+ def configure_kv_cache(transport, config: dict) -> None:
104
+ """Configure KV cache compression if enabled."""
105
+ if not config.get("compress_kv_cache", False):
106
+ transport.compress_kv_cache = False
107
+ return
108
+
109
+ print("KV cache compression is enabled.")
110
+ transport.compress_kv_cache = True
111
+
112
+ assert config.get("total_cache_chunk_nums") is not None
113
+
114
+ compression_config = {
115
+ "method_config": {
116
+ "compress_strategy": config["compress_strategy"],
117
+ "mix_lambda": config["mix_lambda"],
118
+ "query_granularity": config["query_granularity"],
119
+ "score_weighting_method": config.get("score_weighting_method") or "no_weight",
120
+ "power": config.get("power", 3),
121
+ },
122
+ }
123
+
124
+ from inference.pipeline.kvcompress import replace_magi
125
+
126
+ replace_magi(compression_config)
127
+
128
+
129
+ def configure_flowcache(transport, config: dict) -> None:
130
+ """Configure FlowCache reuse strategy on SampleTransport."""
131
+ from inference.pipeline.flowcache import setup_flowcache
132
+
133
+ configure_kv_cache(transport, config)
134
+
135
+ setup_flowcache(
136
+ rel_l1_thresh=config["rel_l1_thresh"],
137
+ warmup_steps=config["warmup_steps"],
138
+ discard_nearly_clean_chunk=config.get("discard_nearly_clean_chunk", False),
139
+ log=config.get("log", False),
140
+ total_cache_chunk_nums=config.get("total_cache_chunk_nums", 5),
141
+ compress_kv_cache=config.get("compress_kv_cache", False),
142
+ )
143
+
144
+
145
+ def configure_reuse_strategy(config: dict) -> None:
146
+ """Configure the appropriate reuse strategy on SampleTransport."""
147
+ from inference.pipeline.video_generate import SampleTransport
148
+
149
+ strategy = config["reuse_strategy"]
150
+
151
+ if strategy == "original":
152
+ return
153
+ if strategy == "all":
154
+ configure_teacache(SampleTransport, config)
155
+ elif strategy == "chunkwise":
156
+ configure_flowcache(SampleTransport, config)
157
+ else:
158
+ raise ValueError(f"Unknown reuse strategy: {strategy}")
159
+
160
+
161
+ def setup_environment(gpu_id: int) -> None:
162
+ """Set up environment variables for a GPU worker process."""
163
+ os.environ["CUDA_VISIBLE_DEVICES"] = str(gpu_id)
164
+ os.environ["WORLD_SIZE"] = "1"
165
+ os.environ["RANK"] = "0"
166
+ os.environ["LOCAL_RANK"] = "0"
167
+ os.environ["MASTER_ADDR"] = "localhost"
168
+ os.environ["MASTER_PORT"] = str(DEFAULT_BASE_PORT + gpu_id)
169
+
170
+ # Enable pdb terminal debugging
171
+ sys.stdin = open(0)
172
+
173
+
174
+ def filter_existing_samples(samples: list, config: dict) -> list:
175
+ """Filter out samples whose output files already exist."""
176
+ if config["benchmark"] == "vbench":
177
+ return [
178
+ sample
179
+ for sample in samples
180
+ if not os.path.exists(os.path.abspath(os.path.join(config["save_path"], f"{sample}-0.mp4")))
181
+ ]
182
+ else: # physicsiq
183
+ return [
184
+ sample for sample in samples if not os.path.exists(sample["output_path"])
185
+ ]
186
+
187
+
188
+ def assign_samples_to_gpu(
189
+ samples: list, gpu_id: int, rank: int, num_gpus: int
190
+ ) -> list:
191
+ """Divide samples across GPUs and return the subset for this GPU."""
192
+ samples_per_gpu = (len(samples) + num_gpus - 1) // num_gpus
193
+ start_idx = rank * samples_per_gpu
194
+ end_idx = min(start_idx + samples_per_gpu, len(samples))
195
+ return samples[start_idx:end_idx]
196
+
197
+
198
+ def process_vbench_sample(pipeline, prompt: str, config: dict, gpu_id: int) -> None:
199
+ """Process a single vbench text-to-video sample."""
200
+ output_path = os.path.abspath(os.path.join(config["save_path"], f"{prompt}-0.mp4"))
201
+
202
+ if os.path.exists(output_path):
203
+ print(f"[SKIP GPU {gpu_id}] Already exists: {output_path}")
204
+ return
205
+
206
+ print(f"[GPU {gpu_id}] Generating T2V: '{prompt}' -> {output_path}")
207
+ pipeline.run_text_to_video(prompt=prompt, output_path=output_path)
208
+ print(f"[DONE GPU {gpu_id}] Saved: {output_path}")
209
+
210
+
211
+ def process_physicsiq_sample(pipeline, sample: dict, gpu_id: int) -> None:
212
+ """Process a single PhysicsIQ video-to-video sample."""
213
+ prompt = sample["description"]
214
+ prefix_video_path = sample["prefix_video_path"]
215
+ output_path = sample["output_path"]
216
+
217
+ if not os.path.exists(prefix_video_path):
218
+ print(f"[WARN GPU {gpu_id}] Conditioning video not found: {prefix_video_path}")
219
+ return
220
+
221
+ if os.path.exists(output_path):
222
+ print(f"[SKIP GPU {gpu_id}] Already exists: {output_path}")
223
+ return
224
+
225
+ print(f"[GPU {gpu_id}] Generating V2V: '{prompt}'")
226
+ print(f" Input: {prefix_video_path}")
227
+ print(f" Output: {output_path}")
228
+
229
+ pipeline.run_video_to_video(
230
+ prompt=prompt,
231
+ prefix_video_path=prefix_video_path,
232
+ output_path=output_path,
233
+ )
234
+ print(f"[DONE GPU {gpu_id}] Saved: {output_path}")
235
+
236
+
237
+ def worker_process(gpu_id: int, rank: int, config: dict, all_samples: list) -> None:
238
+ """Independent worker running on each GPU."""
239
+ setup_environment(gpu_id)
240
+ configure_reuse_strategy(config)
241
+
242
+ try:
243
+ magi_root = subprocess.check_output(
244
+ ["git", "rev-parse", "--show-toplevel"]
245
+ ).decode().strip()
246
+ os.environ["MAGI_ROOT"] = magi_root
247
+ os.environ["PYTHONPATH"] = f"{magi_root}:{os.environ.get('PYTHONPATH', '')}"
248
+ except Exception as e:
249
+ print(f"[GPU {gpu_id}] Failed to set MAGI_ROOT: {e}")
250
+ return
251
+
252
+ filtered_samples = filter_existing_samples(all_samples, config)
253
+
254
+ if not filtered_samples:
255
+ print(f"[GPU {gpu_id}] No samples need to be generated.")
256
+ return
257
+
258
+ print(f"Processing {len(filtered_samples)} samples.")
259
+
260
+ my_samples = assign_samples_to_gpu(
261
+ filtered_samples, gpu_id, rank, config["num_gpus"]
262
+ )
263
+
264
+ if not my_samples:
265
+ print(f"[GPU {gpu_id}] No samples assigned.")
266
+ return
267
+
268
+ print(f"[GPU {gpu_id}] Assigned {len(my_samples)} samples")
269
+
270
+ from inference.pipeline.entry import MagiPipeline
271
+
272
+ print(f"[GPU {gpu_id}] Loading model...")
273
+ pipeline = MagiPipeline(config["config_file"])
274
+ print(f"[GPU {gpu_id}] Model loaded.")
275
+
276
+ process_func = (
277
+ process_vbench_sample if config["benchmark"] == "vbench" else process_physicsiq_sample
278
+ )
279
+
280
+ for sample in my_samples:
281
+ process_func(pipeline, sample, config, gpu_id)
282
+
283
+ print(f"[GPU {gpu_id}] Completed.")
284
+
285
+
286
+ def build_conditioning_video_path(
287
+ data_root: str, vid_id: str, scenario: str, fps: int
288
+ ) -> str:
289
+ """Construct the path to the conditioning video file."""
290
+ conditioning_dir = os.path.join(
291
+ data_root, "physics-IQ-benchmark", "split-videos", "conditioning", f"{fps}FPS"
292
+ )
293
+ match_suffix = re.search(r"_(.*)", scenario)
294
+ suffix = match_suffix.group(1) if match_suffix else ""
295
+ filename = f"{vid_id}_conditioning-videos_{fps}FPS_{suffix}"
296
+ return os.path.join(conditioning_dir, filename)
297
+
298
+
299
+ def load_physicsiq_samples(config: dict) -> list[dict]:
300
+ """Load sample list from PhysicsIQ dataset."""
301
+ data_root = config["physicsiq_data_dir"]
302
+ descriptions_csv = os.path.join(data_root, "descriptions", "descriptions.csv")
303
+ output_dir = config["save_path"]
304
+
305
+ if not os.path.exists(descriptions_csv):
306
+ raise FileNotFoundError(f"descriptions.csv not found at {descriptions_csv}")
307
+
308
+ os.makedirs(output_dir, exist_ok=True)
309
+
310
+ samples = []
311
+ with open(descriptions_csv, mode="r") as f:
312
+ reader = csv.DictReader(f)
313
+ for row in reader:
314
+ scenario = row["scenario"].strip()
315
+ match_id = re.match(r"^(\d+)_", scenario)
316
+
317
+ if not match_id:
318
+ print(f"Cannot extract ID from scenario: {scenario}")
319
+ continue
320
+
321
+ vid_id = match_id.group(1).zfill(4)
322
+ description = row["description"]
323
+ generated_video_name = row["generated_video_name"]
324
+ prefix_video_path = build_conditioning_video_path(
325
+ data_root, vid_id, scenario, PHYSICSIQ_FPS
326
+ )
327
+ output_path = os.path.join(output_dir, generated_video_name)
328
+
329
+ os.makedirs(os.path.dirname(output_path), exist_ok=True)
330
+
331
+ samples.append({
332
+ "vid_id": vid_id,
333
+ "scenario": scenario,
334
+ "description": description,
335
+ "generated_video_name": generated_video_name,
336
+ "prefix_video_path": prefix_video_path,
337
+ "output_path": output_path,
338
+ })
339
+
340
+ # PhysicsIQ samples are duplicated; take only the first half
341
+ unique_count = len(samples) // 2
342
+ samples = samples[:unique_count]
343
+
344
+ print(f"Loaded {unique_count} PhysicsIQ samples.")
345
+
346
+ return apply_slice(samples, config.get("start"), config.get("end"))
347
+
348
+
349
+ def load_vbench_samples(config: dict) -> list[str]:
350
+ """Load prompt list from vbench dimension file."""
351
+ prompt_dir = config["vbench_prompt_dir"]
352
+ dimension = config.get("dimension")
353
+
354
+ if not dimension:
355
+ raise ValueError("For vbench, 'dimension' must be specified in config")
356
+
357
+ prompt_file = os.path.join(prompt_dir, f"{dimension}.txt")
358
+
359
+ if not os.path.exists(prompt_file):
360
+ raise FileNotFoundError(f"Prompt file not found: {prompt_file}")
361
+
362
+ with open(prompt_file, "r") as f:
363
+ prompts = [line.strip() for line in f if line.strip()]
364
+
365
+ return apply_slice(prompts, config.get("start"), config.get("end"))
366
+
367
+
368
+ def setup_save_path(config: dict) -> None:
369
+ """Configure the output save path based on benchmark type."""
370
+ base_path = config["base_save_path"]
371
+
372
+ if config["benchmark"] == "vbench":
373
+ dimension = config.get("dimension")
374
+ videos_dir = os.path.join(base_path, "videos", dimension) if dimension else None
375
+ config["save_path"] = videos_dir if videos_dir else os.path.join(base_path, "videos")
376
+ elif config["benchmark"] == "physicsiq":
377
+ config["save_path"] = os.path.join(base_path, "videos")
378
+
379
+ os.makedirs(config["save_path"], exist_ok=True)
380
+
381
+
382
+ def main() -> None:
383
+ """Entry point for video sampling script."""
384
+ parser = argparse.ArgumentParser(
385
+ description="Video sampling script using YAML configuration"
386
+ )
387
+ parser.add_argument("yaml_config", type=str, help="Path to YAML configuration file")
388
+ args = parser.parse_args()
389
+
390
+ config = load_yaml_config(args.yaml_config)
391
+ print(f"Loaded configuration from: {args.yaml_config}")
392
+
393
+ setup_save_path(config)
394
+
395
+ gpu_ids = resolve_gpu_ids(config["gpus"])
396
+ config["num_gpus"] = len(gpu_ids)
397
+
398
+ benchmark = config["benchmark"]
399
+ if benchmark == "vbench":
400
+ all_samples = load_vbench_samples(config)
401
+ elif benchmark == "physicsiq":
402
+ data_root = config["physicsiq_data_dir"]
403
+ if not os.path.exists(data_root):
404
+ raise FileNotFoundError(f"Data directory not found: {data_root}")
405
+ all_samples = load_physicsiq_samples(config)
406
+ else:
407
+ raise ValueError(f"Invalid benchmark: {benchmark}")
408
+
409
+ print(f"Total samples: {len(all_samples)}")
410
+ print(f"GPUs: {gpu_ids}")
411
+ print(f"Output: {config['save_path']}")
412
+ print(f"Config: {config['config_file']}")
413
+
414
+ processes = []
415
+ for rank, gpu_id in enumerate(gpu_ids):
416
+ p = mp.Process(target=worker_process, args=(gpu_id, rank, config, all_samples))
417
+ p.start()
418
+ processes.append(p)
419
+
420
+ for p in processes:
421
+ p.join()
422
+
423
+ failed = [p.exitcode for p in processes if p.exitcode != 0]
424
+ if failed:
425
+ raise RuntimeError(f"{len(failed)} worker process(es) failed with exit codes: {failed}")
426
+
427
+
428
+ if __name__ == "__main__":
429
+ main()
FlowCache/FlowCache4MAGI-1-dev3-motion/README.md ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # FLOW CACHING FOR AUTOREGRESSIVE VIDEO GENERATION
2
+
3
+ This repository provides the official implementation of **FlowCache** on **MAGI-1** model, a caching-based acceleration method for autoregressive video generation models.
4
+
5
+
6
+ ## 🚀 Installation
7
+
8
+ Please follow the installation instructions provided in the [MAGI-1](https://github.com/SandAI-org/MAGI-1), as this implementation is built on top of MAGI-1.
9
+
10
+ ---
11
+
12
+ ## ▶️ Usage
13
+
14
+ ### 1. Single Video Generation
15
+
16
+ Run accelerated generation using FlowCache:
17
+
18
+ ```bash
19
+ # FlowCache for text-to-video generation
20
+ bash scripts/single_run/flowcache_t2v.sh
21
+
22
+ # FlowCache for video-to-video generation
23
+ bash scripts/single_run/flowcache_v2v.sh
24
+
25
+ # Baseline acceleration method (TeaCache) for text-to-video
26
+ bash scripts/single_run/teacache_t2v.sh
27
+
28
+ # Baseline acceleration method (TeaCache) for video-to-video
29
+ bash scripts/single_run/teacache_v2v.sh
30
+ ```
31
+
32
+ ### 2. Benchmark Sampling
33
+
34
+ Generate videos for evaluation on standard benchmarks:
35
+
36
+ ```bash
37
+ # VBench
38
+ bash scripts/sample/flowcache_vbench.sh
39
+ bash scripts/sample/teacache_vbench.sh
40
+
41
+ # PhysicsIQ
42
+ bash scripts/sample/flowcache_physicsiq.sh
43
+ bash scripts/sample/teacache_physicsiq.sh
44
+ ```
45
+
46
+ ### 3. Quality Evaluation
47
+
48
+ Compute perceptual and structural similarity metrics between original and accelerated generations:
49
+
50
+ ```bash
51
+ bash scripts/metric.sh
52
+ ```
53
+
54
+ ---
55
+
56
+ ## ⚙️ Key Parameters
57
+
58
+ | Parameter | Description |
59
+ |----------|-------------|
60
+ | `rel_l1_thresh` | Relative L1 distance threshold for cache reuse decision |
61
+ | ` warmup_steps` | Number of denoising steps where reuse is disabled |
62
+ | `total_cache_chunk_nums` (`B_total`) | Total number of cache chunks maintained |
63
+ | `compress_strategy` | Granularity for selecting important KV caches: `token`, `frame`, or `chunk` |
64
+ | `query_granularity` | Granularity for importance scoring: `token`, `frame`, or `chunk` |
65
+ | `mix_lambda` | Weight balancing importance and redundancy (default: `0.07`) |
66
+ | `mode` | Generation mode: `t2v` (text-to-video), `i2v` (image-to-video), or `v2v` (video-to-video) |
67
+ | `prompt` | Input prompt for conditional generation |
68
+ | `output_path` | Path to save generated videos |
69
+ | `config_file` | Path to MAGI-1 model configuration |
70
+
71
+ ---
FlowCache/FlowCache4MAGI-1-dev3-motion/README_MOTIONCACHE.md ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # MotionCache on MAGI-1 (dev3-motion)
2
+
3
+ 基于 [FlowCache4MAGI-1](../FlowCache4MAGI-1) 的 **MotionCache** 复现分支,对应论文:
4
+
5
+ > Xu et al., 2026 — *Motion-Aware Caching for Efficient Autoregressive Video Generation*
6
+
7
+ 官方代码仓库 [ywlq/MotionCache](https://github.com/ywlq/MotionCache) 尚未发布实现,本目录依据论文方法在 MAGI-1 推理框架上完成首版复现。
8
+
9
+ ## 与 FlowCache 的核心差异
10
+
11
+ | 维度 | FlowCache | MotionCache |
12
+ |------|-----------|-------------|
13
+ | 粒度 | Chunk 级全有或全无 | Phase 2 为 Token(latent 帧×空间)级 |
14
+ | 跳过策略 | 相对 L1 累积阈值 | 运动重要性加权累积 |
15
+ | 调度 | 单一 chunk-wise 策略 | 两阶段 coarse-to-fine |
16
+
17
+ ### 算法概要
18
+
19
+ 1. **全局 Warm-up(m 步)**:前 `warmup_steps` 步禁止 cache reuse
20
+ 2. **Phase 1(K 步)**:chunk-wise 二值决策,与 FlowCache 相同
21
+ 3. **Phase 2**:基于帧间 latent 差计算运动重要性 `M`,经 soft-mapping 得到权重 `W ∈ [α, 1]`
22
+ 4. **Token 累积**:`A[p] += W[p] · Δ_chunk`,当 `A[p] > τ` 时该 token 触发 DiT 计算
23
+ 5. **Integrate**:active token 正常积分;inactive token 复用缓存 residual
24
+
25
+ ### MAGI-1 默认超参(论文 Appendix C)
26
+
27
+ | 参数 | 值 | 说明 |
28
+ |------|-----|------|
29
+ | `alpha` | 0.5 | 静态区域权重下限 |
30
+ | `phase1_steps` (K) | 9 | chunk-wise 阶段持续步数 |
31
+ | `warmup_steps` (m) | 5 | 全局禁止 reuse 的步数 |
32
+ | `rel_l1_thresh` (τ) | 0.015 (slow) / 0.025 (fast) | token 累积阈值 |
33
+
34
+ ## 快速运行
35
+
36
+ ```bash
37
+ cd FlowCache4MAGI-1-dev3-motion
38
+
39
+ # MotionCache-slow(论文 Table 1 配置)
40
+ bash scripts/single_run/motioncache_t2v.sh
41
+
42
+ # MotionCache-fast
43
+ MOTIONCACHE_CONFIG=yaml_config/single_run/motioncache_config_fast.yaml \
44
+ bash scripts/single_run/motioncache_t2v.sh
45
+ ```
46
+
47
+ 需先按 FlowCache4MAGI-1 说明安装依赖并下载 MAGI-1 权重(`downloads/` 目录可通过软链接指向原项目)。
48
+
49
+ ## 代码结构
50
+
51
+ ```
52
+ inference/pipeline/
53
+ ├── motioncache.py # 入口与 forward/integrate monkey-patch
54
+ └── cache/
55
+ ├── motioncache.py # MotionWiseCache 核心逻辑
56
+ └── sparse_utils.py # Phase 2 gather/scatter 与 sparse meta_args
57
+
58
+ inference/model/dit/dit_module.py # sparse KV cache 写入 + flash_attn 稀疏 q 分支
59
+ inference/common/dataclass.py # ModelMetaArgs.sparse_active_indices
60
+
61
+ yaml_config/single_run/
62
+ ├── motioncache_config.yaml # slow 配置
63
+ └── motioncache_config_fast.yaml
64
+ ```
65
+
66
+ ## 当前实现说明(严格对齐论文 §5.3 Phase 2)
67
+
68
+ - **Phase 1(前 K 个 denoise step / chunk)**:与 FlowCache 完全一致的 chunk-wise 策略(已验证 PSNR=∞)
69
+ - **Phase 2 入口**:每个 chunk 的第 K 步强制全量计算,建立 token-wise 阶段的 residual 基准
70
+ - **Phase 2 运动感知累积**:latent 帧间差 → soft-mapping 权重 W → 累积器 A;`A > τ` 的 token 为 active
71
+ - **Phase 2 稀疏 forward(论文 5.3)**:
72
+ - 全部 inactive → 跳过 DiT forward,复用 chunk residual
73
+ - 部分 active → **gather active patch tokens → compact DiT forward → scatter 回完整序列**
74
+ - KV cache 仅更新 active 位置(`_compresskv_adjust_key_and_value` sparse 分支)
75
+ - integrate 时 active token 正常积分,inactive token 复用 `previous_residual`
76
+ - **运动 proxy**:latent 空间帧间 L1 差(论文 Eq. 9-10)
77
+ - **跨 chunk 连续性**:chunk 首帧与上一 chunk 末帧比较
78
+
79
+ ### 验证结果(`a woman dancing.`,240×720×720,vs FlowCache baseline)
80
+
81
+ | 运行 | PSNR | 说明 |
82
+ |------|------|------|
83
+ | phase1only | ∞ | 与 FlowCache 逐像素一致 |
84
+ | sparse2(论文对齐 sparse forward) | **20.44 dB** | 无黑帧,reuse_rate≈15.6% |
85
+ | final(整 chunk fallback) | 20.48 dB | 画质等价,推理慢 ~14% |
86
+
87
+ sparse2 日志示例:`active_ratio=1.51%` 时仍走 gather/scatter 稀疏路径;`active_ratio=0%` 时 `skip_forward=True`。
88
+
89
+ ## 参考
90
+
91
+ - FlowCache: chunk-wise cache + KV compression
92
+ - MotionCache 论文预期 MAGI-1 加速:slow 1.64×,fast 2.07×(Table 1)
FlowCache/FlowCache4MAGI-1-dev3-motion/requirements.txt ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ accelerate==0.32.1
2
+ beautifulsoup4==4.13.4
3
+ debugpy==1.8.14
4
+ diffusers==0.29.2
5
+ einops>=0.6.0
6
+ ffmpeg-python
7
+ # flash-attn==2.4.2
8
+ flashinfer-python==0.2.0.post2 --extra-index-url https://flashinfer.ai/whl/cu124/torch2.4/
9
+ ftfy==6.2.0
10
+ gpustat==1.1.1
11
+ imageio==2.34.0
12
+ imageio[ffmpeg]
13
+ matplotlib==3.10.1
14
+ numpy==1.26.4
15
+ protobuf==5.28.3
16
+ rich==14.0.0
17
+ sentencepiece==0.2.0
18
+ timm==1.0.15
19
+ torchdiffeq==0.2.4
20
+ transformers==4.42.3
21
+ tqdm
FlowCache/FlowCache4MAGI-1-dev3-motion/sample_video.py ADDED
@@ -0,0 +1,429 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 MAGI Authors. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import os
16
+ import re
17
+ import sys
18
+ import argparse
19
+ import csv
20
+ import subprocess
21
+ from pathlib import Path
22
+
23
+ import multiprocessing as mp
24
+
25
+ # Constants
26
+ DEFAULT_BASE_PORT = 29510
27
+ PHYSICSIQ_FPS = 24
28
+
29
+
30
+ def resolve_gpu_ids(gpus_config) -> list[int]:
31
+ """Resolve explicit GPU IDs or auto-detect all currently visible GPUs."""
32
+ if isinstance(gpus_config, int):
33
+ return [gpus_config]
34
+
35
+ gpus_text = str(gpus_config).strip()
36
+ if not gpus_text:
37
+ raise ValueError("'gpus' must not be empty")
38
+
39
+ if gpus_text.lower() not in {"all", "auto"}:
40
+ return [int(item.strip()) for item in gpus_text.split(",") if item.strip()]
41
+
42
+ visible_devices = os.environ.get("CUDA_VISIBLE_DEVICES")
43
+ if visible_devices:
44
+ visible = [item.strip() for item in visible_devices.split(",") if item.strip()]
45
+ if visible and all(item.isdigit() for item in visible):
46
+ return [int(item) for item in visible]
47
+
48
+ try:
49
+ output = subprocess.check_output(
50
+ ["nvidia-smi", "--query-gpu=index", "--format=csv,noheader,nounits"],
51
+ text=True,
52
+ timeout=10,
53
+ )
54
+ gpu_ids = [int(line.strip()) for line in output.splitlines() if line.strip()]
55
+ if gpu_ids:
56
+ return gpu_ids
57
+ except Exception:
58
+ pass
59
+
60
+ try:
61
+ import torch
62
+
63
+ count = torch.cuda.device_count()
64
+ if count > 0:
65
+ return list(range(count))
66
+ except Exception:
67
+ pass
68
+
69
+ raise RuntimeError("No CUDA GPUs detected for gpus: all")
70
+
71
+
72
+ def load_yaml_config(yaml_path: str) -> dict:
73
+ """Load configuration from YAML file."""
74
+ import yaml
75
+
76
+ with open(yaml_path, "r") as f:
77
+ return yaml.safe_load(f)
78
+
79
+
80
+ def apply_slice(items: list, start: int | None, end: int | None) -> list:
81
+ """Apply start/end slice to a list with bounds checking."""
82
+ if start is None and end is None:
83
+ return items
84
+
85
+ slice_start = max(0, start if start is not None else 0)
86
+ slice_end = min(end if end is not None else len(items), len(items))
87
+ slice_end = max(slice_start, slice_end)
88
+
89
+ return items[slice_start:slice_end]
90
+
91
+
92
+ def configure_teacache(transport, config: dict) -> None:
93
+ """Configure TeaCache reuse strategy on SampleTransport."""
94
+ from inference.pipeline.teacache import setup_teacache
95
+
96
+ setup_teacache(
97
+ rel_l1_thresh=config["rel_l1_thresh"],
98
+ warmup_steps=config["warmup_steps"],
99
+ log=config.get("log", False),
100
+ )
101
+
102
+
103
+ def configure_kv_cache(transport, config: dict) -> None:
104
+ """Configure KV cache compression if enabled."""
105
+ if not config.get("compress_kv_cache", False):
106
+ transport.compress_kv_cache = False
107
+ return
108
+
109
+ print("KV cache compression is enabled.")
110
+ transport.compress_kv_cache = True
111
+
112
+ assert config.get("total_cache_chunk_nums") is not None
113
+
114
+ compression_config = {
115
+ "method_config": {
116
+ "compress_strategy": config["compress_strategy"],
117
+ "mix_lambda": config["mix_lambda"],
118
+ "query_granularity": config["query_granularity"],
119
+ "score_weighting_method": config.get("score_weighting_method") or "no_weight",
120
+ "power": config.get("power", 3),
121
+ },
122
+ }
123
+
124
+ from inference.pipeline.kvcompress import replace_magi
125
+
126
+ replace_magi(compression_config)
127
+
128
+
129
+ def configure_flowcache(transport, config: dict) -> None:
130
+ """Configure FlowCache reuse strategy on SampleTransport."""
131
+ from inference.pipeline.flowcache import setup_flowcache
132
+
133
+ configure_kv_cache(transport, config)
134
+
135
+ setup_flowcache(
136
+ rel_l1_thresh=config["rel_l1_thresh"],
137
+ warmup_steps=config["warmup_steps"],
138
+ discard_nearly_clean_chunk=config.get("discard_nearly_clean_chunk", False),
139
+ log=config.get("log", False),
140
+ total_cache_chunk_nums=config.get("total_cache_chunk_nums", 5),
141
+ compress_kv_cache=config.get("compress_kv_cache", False),
142
+ )
143
+
144
+
145
+ def configure_reuse_strategy(config: dict) -> None:
146
+ """Configure the appropriate reuse strategy on SampleTransport."""
147
+ from inference.pipeline.video_generate import SampleTransport
148
+
149
+ strategy = config["reuse_strategy"]
150
+
151
+ if strategy == "original":
152
+ return
153
+ if strategy == "all":
154
+ configure_teacache(SampleTransport, config)
155
+ elif strategy == "chunkwise":
156
+ configure_flowcache(SampleTransport, config)
157
+ else:
158
+ raise ValueError(f"Unknown reuse strategy: {strategy}")
159
+
160
+
161
+ def setup_environment(gpu_id: int) -> None:
162
+ """Set up environment variables for a GPU worker process."""
163
+ os.environ["CUDA_VISIBLE_DEVICES"] = str(gpu_id)
164
+ os.environ["WORLD_SIZE"] = "1"
165
+ os.environ["RANK"] = "0"
166
+ os.environ["LOCAL_RANK"] = "0"
167
+ os.environ["MASTER_ADDR"] = "localhost"
168
+ os.environ["MASTER_PORT"] = str(DEFAULT_BASE_PORT + gpu_id)
169
+
170
+ # Enable pdb terminal debugging
171
+ sys.stdin = open(0)
172
+
173
+
174
+ def filter_existing_samples(samples: list, config: dict) -> list:
175
+ """Filter out samples whose output files already exist."""
176
+ if config["benchmark"] == "vbench":
177
+ return [
178
+ sample
179
+ for sample in samples
180
+ if not os.path.exists(os.path.abspath(os.path.join(config["save_path"], f"{sample}-0.mp4")))
181
+ ]
182
+ else: # physicsiq
183
+ return [
184
+ sample for sample in samples if not os.path.exists(sample["output_path"])
185
+ ]
186
+
187
+
188
+ def assign_samples_to_gpu(
189
+ samples: list, gpu_id: int, rank: int, num_gpus: int
190
+ ) -> list:
191
+ """Divide samples across GPUs and return the subset for this GPU."""
192
+ samples_per_gpu = (len(samples) + num_gpus - 1) // num_gpus
193
+ start_idx = rank * samples_per_gpu
194
+ end_idx = min(start_idx + samples_per_gpu, len(samples))
195
+ return samples[start_idx:end_idx]
196
+
197
+
198
+ def process_vbench_sample(pipeline, prompt: str, config: dict, gpu_id: int) -> None:
199
+ """Process a single vbench text-to-video sample."""
200
+ output_path = os.path.abspath(os.path.join(config["save_path"], f"{prompt}-0.mp4"))
201
+
202
+ if os.path.exists(output_path):
203
+ print(f"[SKIP GPU {gpu_id}] Already exists: {output_path}")
204
+ return
205
+
206
+ print(f"[GPU {gpu_id}] Generating T2V: '{prompt}' -> {output_path}")
207
+ pipeline.run_text_to_video(prompt=prompt, output_path=output_path)
208
+ print(f"[DONE GPU {gpu_id}] Saved: {output_path}")
209
+
210
+
211
+ def process_physicsiq_sample(pipeline, sample: dict, gpu_id: int) -> None:
212
+ """Process a single PhysicsIQ video-to-video sample."""
213
+ prompt = sample["description"]
214
+ prefix_video_path = sample["prefix_video_path"]
215
+ output_path = sample["output_path"]
216
+
217
+ if not os.path.exists(prefix_video_path):
218
+ print(f"[WARN GPU {gpu_id}] Conditioning video not found: {prefix_video_path}")
219
+ return
220
+
221
+ if os.path.exists(output_path):
222
+ print(f"[SKIP GPU {gpu_id}] Already exists: {output_path}")
223
+ return
224
+
225
+ print(f"[GPU {gpu_id}] Generating V2V: '{prompt}'")
226
+ print(f" Input: {prefix_video_path}")
227
+ print(f" Output: {output_path}")
228
+
229
+ pipeline.run_video_to_video(
230
+ prompt=prompt,
231
+ prefix_video_path=prefix_video_path,
232
+ output_path=output_path,
233
+ )
234
+ print(f"[DONE GPU {gpu_id}] Saved: {output_path}")
235
+
236
+
237
+ def worker_process(gpu_id: int, rank: int, config: dict, all_samples: list) -> None:
238
+ """Independent worker running on each GPU."""
239
+ setup_environment(gpu_id)
240
+ configure_reuse_strategy(config)
241
+
242
+ try:
243
+ magi_root = subprocess.check_output(
244
+ ["git", "rev-parse", "--show-toplevel"]
245
+ ).decode().strip()
246
+ os.environ["MAGI_ROOT"] = magi_root
247
+ os.environ["PYTHONPATH"] = f"{magi_root}:{os.environ.get('PYTHONPATH', '')}"
248
+ except Exception as e:
249
+ print(f"[GPU {gpu_id}] Failed to set MAGI_ROOT: {e}")
250
+ return
251
+
252
+ filtered_samples = filter_existing_samples(all_samples, config)
253
+
254
+ if not filtered_samples:
255
+ print(f"[GPU {gpu_id}] No samples need to be generated.")
256
+ return
257
+
258
+ print(f"Processing {len(filtered_samples)} samples.")
259
+
260
+ my_samples = assign_samples_to_gpu(
261
+ filtered_samples, gpu_id, rank, config["num_gpus"]
262
+ )
263
+
264
+ if not my_samples:
265
+ print(f"[GPU {gpu_id}] No samples assigned.")
266
+ return
267
+
268
+ print(f"[GPU {gpu_id}] Assigned {len(my_samples)} samples")
269
+
270
+ from inference.pipeline.entry import MagiPipeline
271
+
272
+ print(f"[GPU {gpu_id}] Loading model...")
273
+ pipeline = MagiPipeline(config["config_file"])
274
+ print(f"[GPU {gpu_id}] Model loaded.")
275
+
276
+ process_func = (
277
+ process_vbench_sample if config["benchmark"] == "vbench" else process_physicsiq_sample
278
+ )
279
+
280
+ for sample in my_samples:
281
+ process_func(pipeline, sample, config, gpu_id)
282
+
283
+ print(f"[GPU {gpu_id}] Completed.")
284
+
285
+
286
+ def build_conditioning_video_path(
287
+ data_root: str, vid_id: str, scenario: str, fps: int
288
+ ) -> str:
289
+ """Construct the path to the conditioning video file."""
290
+ conditioning_dir = os.path.join(
291
+ data_root, "physics-IQ-benchmark", "split-videos", "conditioning", f"{fps}FPS"
292
+ )
293
+ match_suffix = re.search(r"_(.*)", scenario)
294
+ suffix = match_suffix.group(1) if match_suffix else ""
295
+ filename = f"{vid_id}_conditioning-videos_{fps}FPS_{suffix}"
296
+ return os.path.join(conditioning_dir, filename)
297
+
298
+
299
+ def load_physicsiq_samples(config: dict) -> list[dict]:
300
+ """Load sample list from PhysicsIQ dataset."""
301
+ data_root = config["physicsiq_data_dir"]
302
+ descriptions_csv = os.path.join(data_root, "descriptions", "descriptions.csv")
303
+ output_dir = config["save_path"]
304
+
305
+ if not os.path.exists(descriptions_csv):
306
+ raise FileNotFoundError(f"descriptions.csv not found at {descriptions_csv}")
307
+
308
+ os.makedirs(output_dir, exist_ok=True)
309
+
310
+ samples = []
311
+ with open(descriptions_csv, mode="r") as f:
312
+ reader = csv.DictReader(f)
313
+ for row in reader:
314
+ scenario = row["scenario"].strip()
315
+ match_id = re.match(r"^(\d+)_", scenario)
316
+
317
+ if not match_id:
318
+ print(f"Cannot extract ID from scenario: {scenario}")
319
+ continue
320
+
321
+ vid_id = match_id.group(1).zfill(4)
322
+ description = row["description"]
323
+ generated_video_name = row["generated_video_name"]
324
+ prefix_video_path = build_conditioning_video_path(
325
+ data_root, vid_id, scenario, PHYSICSIQ_FPS
326
+ )
327
+ output_path = os.path.join(output_dir, generated_video_name)
328
+
329
+ os.makedirs(os.path.dirname(output_path), exist_ok=True)
330
+
331
+ samples.append({
332
+ "vid_id": vid_id,
333
+ "scenario": scenario,
334
+ "description": description,
335
+ "generated_video_name": generated_video_name,
336
+ "prefix_video_path": prefix_video_path,
337
+ "output_path": output_path,
338
+ })
339
+
340
+ # PhysicsIQ samples are duplicated; take only the first half
341
+ unique_count = len(samples) // 2
342
+ samples = samples[:unique_count]
343
+
344
+ print(f"Loaded {unique_count} PhysicsIQ samples.")
345
+
346
+ return apply_slice(samples, config.get("start"), config.get("end"))
347
+
348
+
349
+ def load_vbench_samples(config: dict) -> list[str]:
350
+ """Load prompt list from vbench dimension file."""
351
+ prompt_dir = config["vbench_prompt_dir"]
352
+ dimension = config.get("dimension")
353
+
354
+ if not dimension:
355
+ raise ValueError("For vbench, 'dimension' must be specified in config")
356
+
357
+ prompt_file = os.path.join(prompt_dir, f"{dimension}.txt")
358
+
359
+ if not os.path.exists(prompt_file):
360
+ raise FileNotFoundError(f"Prompt file not found: {prompt_file}")
361
+
362
+ with open(prompt_file, "r") as f:
363
+ prompts = [line.strip() for line in f if line.strip()]
364
+
365
+ return apply_slice(prompts, config.get("start"), config.get("end"))
366
+
367
+
368
+ def setup_save_path(config: dict) -> None:
369
+ """Configure the output save path based on benchmark type."""
370
+ base_path = config["base_save_path"]
371
+
372
+ if config["benchmark"] == "vbench":
373
+ dimension = config.get("dimension")
374
+ videos_dir = os.path.join(base_path, "videos", dimension) if dimension else None
375
+ config["save_path"] = videos_dir if videos_dir else os.path.join(base_path, "videos")
376
+ elif config["benchmark"] == "physicsiq":
377
+ config["save_path"] = os.path.join(base_path, "videos")
378
+
379
+ os.makedirs(config["save_path"], exist_ok=True)
380
+
381
+
382
+ def main() -> None:
383
+ """Entry point for video sampling script."""
384
+ parser = argparse.ArgumentParser(
385
+ description="Video sampling script using YAML configuration"
386
+ )
387
+ parser.add_argument("yaml_config", type=str, help="Path to YAML configuration file")
388
+ args = parser.parse_args()
389
+
390
+ config = load_yaml_config(args.yaml_config)
391
+ print(f"Loaded configuration from: {args.yaml_config}")
392
+
393
+ setup_save_path(config)
394
+
395
+ gpu_ids = resolve_gpu_ids(config["gpus"])
396
+ config["num_gpus"] = len(gpu_ids)
397
+
398
+ benchmark = config["benchmark"]
399
+ if benchmark == "vbench":
400
+ all_samples = load_vbench_samples(config)
401
+ elif benchmark == "physicsiq":
402
+ data_root = config["physicsiq_data_dir"]
403
+ if not os.path.exists(data_root):
404
+ raise FileNotFoundError(f"Data directory not found: {data_root}")
405
+ all_samples = load_physicsiq_samples(config)
406
+ else:
407
+ raise ValueError(f"Invalid benchmark: {benchmark}")
408
+
409
+ print(f"Total samples: {len(all_samples)}")
410
+ print(f"GPUs: {gpu_ids}")
411
+ print(f"Output: {config['save_path']}")
412
+ print(f"Config: {config['config_file']}")
413
+
414
+ processes = []
415
+ for rank, gpu_id in enumerate(gpu_ids):
416
+ p = mp.Process(target=worker_process, args=(gpu_id, rank, config, all_samples))
417
+ p.start()
418
+ processes.append(p)
419
+
420
+ for p in processes:
421
+ p.join()
422
+
423
+ failed = [p.exitcode for p in processes if p.exitcode != 0]
424
+ if failed:
425
+ raise RuntimeError(f"{len(failed)} worker process(es) failed with exit codes: {failed}")
426
+
427
+
428
+ if __name__ == "__main__":
429
+ main()
FlowCache/FlowCache4MAGI-1-dev4-detail/README.md ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # FLOW CACHING FOR AUTOREGRESSIVE VIDEO GENERATION
2
+
3
+ This repository provides the official implementation of **FlowCache** on **MAGI-1** model, a caching-based acceleration method for autoregressive video generation models.
4
+
5
+
6
+ ## 🚀 Installation
7
+
8
+ Please follow the installation instructions provided in the [MAGI-1](https://github.com/SandAI-org/MAGI-1), as this implementation is built on top of MAGI-1.
9
+
10
+ ---
11
+
12
+ ## ▶️ Usage
13
+
14
+ ### 1. Single Video Generation
15
+
16
+ Run accelerated generation using FlowCache:
17
+
18
+ ```bash
19
+ # FlowCache for text-to-video generation
20
+ bash scripts/single_run/flowcache_t2v.sh
21
+
22
+ # FlowCache for video-to-video generation
23
+ bash scripts/single_run/flowcache_v2v.sh
24
+
25
+ # Baseline acceleration method (TeaCache) for text-to-video
26
+ bash scripts/single_run/teacache_t2v.sh
27
+
28
+ # Baseline acceleration method (TeaCache) for video-to-video
29
+ bash scripts/single_run/teacache_v2v.sh
30
+ ```
31
+
32
+ ### 2. Benchmark Sampling
33
+
34
+ Generate videos for evaluation on standard benchmarks:
35
+
36
+ ```bash
37
+ # VBench
38
+ bash scripts/sample/flowcache_vbench.sh
39
+ bash scripts/sample/teacache_vbench.sh
40
+
41
+ # PhysicsIQ
42
+ bash scripts/sample/flowcache_physicsiq.sh
43
+ bash scripts/sample/teacache_physicsiq.sh
44
+ ```
45
+
46
+ ### 3. Quality Evaluation
47
+
48
+ Compute perceptual and structural similarity metrics between original and accelerated generations:
49
+
50
+ ```bash
51
+ bash scripts/metric.sh
52
+ ```
53
+
54
+ ---
55
+
56
+ ## ⚙️ Key Parameters
57
+
58
+ | Parameter | Description |
59
+ |----------|-------------|
60
+ | `rel_l1_thresh` | Relative L1 distance threshold for cache reuse decision |
61
+ | ` warmup_steps` | Number of denoising steps where reuse is disabled |
62
+ | `total_cache_chunk_nums` (`B_total`) | Total number of cache chunks maintained |
63
+ | `compress_strategy` | Granularity for selecting important KV caches: `token`, `frame`, or `chunk` |
64
+ | `query_granularity` | Granularity for importance scoring: `token`, `frame`, or `chunk` |
65
+ | `mix_lambda` | Weight balancing importance and redundancy (default: `0.07`) |
66
+ | `mode` | Generation mode: `t2v` (text-to-video), `i2v` (image-to-video), or `v2v` (video-to-video) |
67
+ | `prompt` | Input prompt for conditional generation |
68
+ | `output_path` | Path to save generated videos |
69
+ | `config_file` | Path to MAGI-1 model configuration |
70
+
71
+ ---
FlowCache/FlowCache4MAGI-1-dev4-detail/README_MOTIONCACHE.md ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # MotionCache on MAGI-1 (dev3-motion)
2
+
3
+ 基于 [FlowCache4MAGI-1](../FlowCache4MAGI-1) 的 **MotionCache** 复现分支,对应论文:
4
+
5
+ > Xu et al., 2026 — *Motion-Aware Caching for Efficient Autoregressive Video Generation*
6
+
7
+ 官方代码仓库 [ywlq/MotionCache](https://github.com/ywlq/MotionCache) 尚未发布实现,本目录依据论文方法在 MAGI-1 推理框架上完成首版复现。
8
+
9
+ ## 与 FlowCache 的核心差异
10
+
11
+ | 维度 | FlowCache | MotionCache |
12
+ |------|-----------|-------------|
13
+ | 粒度 | Chunk 级全有或全无 | Phase 2 为 Token(latent 帧×空间)级 |
14
+ | 跳过策略 | 相对 L1 累积阈值 | 运动重要性加权累积 |
15
+ | 调度 | 单一 chunk-wise 策略 | 两阶段 coarse-to-fine |
16
+
17
+ ### 算法概要
18
+
19
+ 1. **全局 Warm-up(m 步)**:前 `warmup_steps` 步禁止 cache reuse
20
+ 2. **Phase 1(K 步)**:chunk-wise 二值决策,与 FlowCache 相同
21
+ 3. **Phase 2**:基于帧间 latent 差计算运动重要性 `M`,经 soft-mapping 得到权重 `W ∈ [α, 1]`
22
+ 4. **Token 累积**:`A[p] += W[p] · Δ_chunk`,当 `A[p] > τ` 时该 token 触发 DiT 计算
23
+ 5. **Integrate**:active token 正常积分;inactive token 复用缓存 residual
24
+
25
+ ### MAGI-1 默认超参(论文 Appendix C)
26
+
27
+ | 参数 | 值 | 说明 |
28
+ |------|-----|------|
29
+ | `alpha` | 0.5 | 静态区域权重下限 |
30
+ | `phase1_steps` (K) | 9 | chunk-wise 阶段持续步数 |
31
+ | `warmup_steps` (m) | 5 | 全局禁止 reuse 的步数 |
32
+ | `rel_l1_thresh` (τ) | 0.015 (slow) / 0.025 (fast) | token 累积阈值 |
33
+
34
+ ## 快速运行
35
+
36
+ ```bash
37
+ cd FlowCache4MAGI-1-dev3-motion
38
+
39
+ # MotionCache-slow(论文 Table 1 配置)
40
+ bash scripts/single_run/motioncache_t2v.sh
41
+
42
+ # MotionCache-fast
43
+ MOTIONCACHE_CONFIG=yaml_config/single_run/motioncache_config_fast.yaml \
44
+ bash scripts/single_run/motioncache_t2v.sh
45
+ ```
46
+
47
+ 需先按 FlowCache4MAGI-1 说明安装依赖并下载 MAGI-1 权重(`downloads/` 目录可通过软链接指向原项目)。
48
+
49
+ ## 代码结构
50
+
51
+ ```
52
+ inference/pipeline/
53
+ ├── motioncache.py # 入口与 forward/integrate monkey-patch
54
+ └── cache/
55
+ ├── motioncache.py # MotionWiseCache 核心逻辑
56
+ └── sparse_utils.py # Phase 2 gather/scatter 与 sparse meta_args
57
+
58
+ inference/model/dit/dit_module.py # sparse KV cache 写入 + flash_attn 稀疏 q 分支
59
+ inference/common/dataclass.py # ModelMetaArgs.sparse_active_indices
60
+
61
+ yaml_config/single_run/
62
+ ├── motioncache_config.yaml # slow 配置
63
+ └── motioncache_config_fast.yaml
64
+ ```
65
+
66
+ ## 当前实现说明(严格对齐论文 §5.3 Phase 2)
67
+
68
+ - **Phase 1(前 K 个 denoise step / chunk)**:与 FlowCache 完全一致的 chunk-wise 策略(已验证 PSNR=∞)
69
+ - **Phase 2 入口**:每个 chunk 的第 K 步强制全量计算,建立 token-wise 阶段的 residual 基准
70
+ - **Phase 2 运动感知累积**:latent 帧间差 → soft-mapping 权重 W → 累积器 A;`A > τ` 的 token 为 active
71
+ - **Phase 2 稀疏 forward(论文 5.3)**:
72
+ - 全部 inactive → 跳过 DiT forward,复用 chunk residual
73
+ - 部分 active → **gather active patch tokens → compact DiT forward → scatter 回完整序列**
74
+ - KV cache 仅更新 active 位置(`_compresskv_adjust_key_and_value` sparse 分支)
75
+ - integrate 时 active token 正常积分,inactive token 复用 `previous_residual`
76
+ - **运动 proxy**:latent 空间帧间 L1 差(论文 Eq. 9-10)
77
+ - **跨 chunk 连续性**:chunk 首帧与上一 chunk 末帧比较
78
+
79
+ ### 验证结果(`a woman dancing.`,240×720×720,vs FlowCache baseline)
80
+
81
+ | 运行 | PSNR | 说明 |
82
+ |------|------|------|
83
+ | phase1only | ∞ | 与 FlowCache 逐像素一致 |
84
+ | sparse2(论文对齐 sparse forward) | **20.44 dB** | 无黑帧,reuse_rate≈15.6% |
85
+ | final(整 chunk fallback) | 20.48 dB | 画质等价,推理慢 ~14% |
86
+
87
+ sparse2 日志示例:`active_ratio=1.51%` 时仍走 gather/scatter 稀疏路径;`active_ratio=0%` 时 `skip_forward=True`。
88
+
89
+ ## 参考
90
+
91
+ - FlowCache: chunk-wise cache + KV compression
92
+ - MotionCache 论文预期 MAGI-1 加速:slow 1.64×,fast 2.07×(Table 1)
FlowCache/FlowCache4MAGI-1-dev4-detail/README_MOTIONDETAIL.md ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # MotionDetailCache on MAGI-1 (dev4-detail)
2
+
3
+ 基于 [FlowCache4MAGI-1-dev3-motion](../FlowCache4MAGI-1-dev3-motion) 的扩展分支,在 MotionCache 的 **motion 度量** 之外,增加 **spatial detail 度量**,Phase 2 active token 由两者共同决定。
4
+
5
+ ## 与 dev3 (MotionCache) 的差异
6
+
7
+ | 维度 | dev3 MotionCache | dev4 MotionDetailCache |
8
+ |------|------------------|------------------------|
9
+ | Phase 2 权重 | 仅 motion 权重 W_m | motion W_m + detail W_d 融合 |
10
+ | Detail proxy | — | latent 局部 k×k 空间方差 |
11
+ | 适用场景 | 运动区域优先计算 | 静止纹理/边缘/语义细节也优先保留 |
12
+
13
+ ## Detail 度量
14
+
15
+ 对每个 latent 像素 `(t, h, w)`:
16
+
17
+ 1. 通道聚合幅度:`mag = mean(|x|, dim=C)` → `[N, T, H, W]`
18
+ 2. 局部空间方差:在 `detail_window_size×detail_window_size` 窗口内计算 `Var(mag)`
19
+ 3. Soft-mapping:帧内 min-max 归一化 → `W_d ∈ [detail_alpha, 1]`
20
+
21
+ 高方差区域对应边缘、纹理、物体边界等 heterogeneous 邻域。
22
+
23
+ ## Motion + Detail 融合
24
+
25
+ ```
26
+ W_combined = combine(W_motion, W_detail)
27
+ A[p] += W_combined[p] · Δ_chunk
28
+ active[p] = A[p] > τ
29
+ ```
30
+
31
+ `weight_combine_mode`(默认 `max`):
32
+
33
+ | 模式 | 公式 | 特点 |
34
+ |------|------|------|
35
+ | `max` | max(W_m, W_d) | 运动或细节任一显著即可加速累积(推荐) |
36
+ | `product` | W_m × W_d | 两者同时高才快速激活,更激进 reuse |
37
+ | `blend` | (1-λ)W_m + λW_d | 线性权衡,λ=`detail_lambda` |
38
+
39
+ ## 默认超参
40
+
41
+ 继承 dev3 的 motion 参数,并新增:
42
+
43
+ | 参数 | 默认值 | 说明 |
44
+ |------|--------|------|
45
+ | `detail_alpha` | 0.5 | detail 权重下限 |
46
+ | `detail_window_size` | 3 | 局部方差窗口(奇数) |
47
+ | `detail_lambda` | 0.5 | blend 模式下的 detail 权重 |
48
+ | `weight_combine_mode` | max | 融合方式 |
49
+
50
+ ## 快速运行
51
+
52
+ ```bash
53
+ cd FlowCache4MAGI-1-dev4-detail
54
+ conda activate magi
55
+ export CUDA_VISIBLE_DEVICES=0
56
+ export MASTER_ADDR=localhost
57
+ bash scripts/single_run/motiondetail_t2v.sh
58
+ ```
59
+
60
+ ## 代码结构
61
+
62
+ ```
63
+ inference/pipeline/cache/
64
+ ├── motioncache.py # dev3 基类 MotionWiseCache
65
+ └── motiondetailcache.py # dev4 MotionDetailCache
66
+
67
+ yaml_config/single_run/motiondetail_config.yaml
68
+ scripts/single_run/motiondetail_t2v.sh
69
+ ```
70
+
71
+ 其余 sparse forward、KV cache、integrate 逻辑与 dev3 完全一致。
FlowCache/FlowCache4MAGI-1-dev4-detail/requirements.txt ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ accelerate==0.32.1
2
+ beautifulsoup4==4.13.4
3
+ debugpy==1.8.14
4
+ diffusers==0.29.2
5
+ einops>=0.6.0
6
+ ffmpeg-python
7
+ # flash-attn==2.4.2
8
+ flashinfer-python==0.2.0.post2 --extra-index-url https://flashinfer.ai/whl/cu124/torch2.4/
9
+ ftfy==6.2.0
10
+ gpustat==1.1.1
11
+ imageio==2.34.0
12
+ imageio[ffmpeg]
13
+ matplotlib==3.10.1
14
+ numpy==1.26.4
15
+ protobuf==5.28.3
16
+ rich==14.0.0
17
+ sentencepiece==0.2.0
18
+ timm==1.0.15
19
+ torchdiffeq==0.2.4
20
+ transformers==4.42.3
21
+ tqdm
FlowCache/FlowCache4MAGI-1-dev4-detail/sample_video.py ADDED
@@ -0,0 +1,429 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 MAGI Authors. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import os
16
+ import re
17
+ import sys
18
+ import argparse
19
+ import csv
20
+ import subprocess
21
+ from pathlib import Path
22
+
23
+ import multiprocessing as mp
24
+
25
+ # Constants
26
+ DEFAULT_BASE_PORT = 29510
27
+ PHYSICSIQ_FPS = 24
28
+
29
+
30
+ def resolve_gpu_ids(gpus_config) -> list[int]:
31
+ """Resolve explicit GPU IDs or auto-detect all currently visible GPUs."""
32
+ if isinstance(gpus_config, int):
33
+ return [gpus_config]
34
+
35
+ gpus_text = str(gpus_config).strip()
36
+ if not gpus_text:
37
+ raise ValueError("'gpus' must not be empty")
38
+
39
+ if gpus_text.lower() not in {"all", "auto"}:
40
+ return [int(item.strip()) for item in gpus_text.split(",") if item.strip()]
41
+
42
+ visible_devices = os.environ.get("CUDA_VISIBLE_DEVICES")
43
+ if visible_devices:
44
+ visible = [item.strip() for item in visible_devices.split(",") if item.strip()]
45
+ if visible and all(item.isdigit() for item in visible):
46
+ return [int(item) for item in visible]
47
+
48
+ try:
49
+ output = subprocess.check_output(
50
+ ["nvidia-smi", "--query-gpu=index", "--format=csv,noheader,nounits"],
51
+ text=True,
52
+ timeout=10,
53
+ )
54
+ gpu_ids = [int(line.strip()) for line in output.splitlines() if line.strip()]
55
+ if gpu_ids:
56
+ return gpu_ids
57
+ except Exception:
58
+ pass
59
+
60
+ try:
61
+ import torch
62
+
63
+ count = torch.cuda.device_count()
64
+ if count > 0:
65
+ return list(range(count))
66
+ except Exception:
67
+ pass
68
+
69
+ raise RuntimeError("No CUDA GPUs detected for gpus: all")
70
+
71
+
72
+ def load_yaml_config(yaml_path: str) -> dict:
73
+ """Load configuration from YAML file."""
74
+ import yaml
75
+
76
+ with open(yaml_path, "r") as f:
77
+ return yaml.safe_load(f)
78
+
79
+
80
+ def apply_slice(items: list, start: int | None, end: int | None) -> list:
81
+ """Apply start/end slice to a list with bounds checking."""
82
+ if start is None and end is None:
83
+ return items
84
+
85
+ slice_start = max(0, start if start is not None else 0)
86
+ slice_end = min(end if end is not None else len(items), len(items))
87
+ slice_end = max(slice_start, slice_end)
88
+
89
+ return items[slice_start:slice_end]
90
+
91
+
92
+ def configure_teacache(transport, config: dict) -> None:
93
+ """Configure TeaCache reuse strategy on SampleTransport."""
94
+ from inference.pipeline.teacache import setup_teacache
95
+
96
+ setup_teacache(
97
+ rel_l1_thresh=config["rel_l1_thresh"],
98
+ warmup_steps=config["warmup_steps"],
99
+ log=config.get("log", False),
100
+ )
101
+
102
+
103
+ def configure_kv_cache(transport, config: dict) -> None:
104
+ """Configure KV cache compression if enabled."""
105
+ if not config.get("compress_kv_cache", False):
106
+ transport.compress_kv_cache = False
107
+ return
108
+
109
+ print("KV cache compression is enabled.")
110
+ transport.compress_kv_cache = True
111
+
112
+ assert config.get("total_cache_chunk_nums") is not None
113
+
114
+ compression_config = {
115
+ "method_config": {
116
+ "compress_strategy": config["compress_strategy"],
117
+ "mix_lambda": config["mix_lambda"],
118
+ "query_granularity": config["query_granularity"],
119
+ "score_weighting_method": config.get("score_weighting_method") or "no_weight",
120
+ "power": config.get("power", 3),
121
+ },
122
+ }
123
+
124
+ from inference.pipeline.kvcompress import replace_magi
125
+
126
+ replace_magi(compression_config)
127
+
128
+
129
+ def configure_flowcache(transport, config: dict) -> None:
130
+ """Configure FlowCache reuse strategy on SampleTransport."""
131
+ from inference.pipeline.flowcache import setup_flowcache
132
+
133
+ configure_kv_cache(transport, config)
134
+
135
+ setup_flowcache(
136
+ rel_l1_thresh=config["rel_l1_thresh"],
137
+ warmup_steps=config["warmup_steps"],
138
+ discard_nearly_clean_chunk=config.get("discard_nearly_clean_chunk", False),
139
+ log=config.get("log", False),
140
+ total_cache_chunk_nums=config.get("total_cache_chunk_nums", 5),
141
+ compress_kv_cache=config.get("compress_kv_cache", False),
142
+ )
143
+
144
+
145
+ def configure_reuse_strategy(config: dict) -> None:
146
+ """Configure the appropriate reuse strategy on SampleTransport."""
147
+ from inference.pipeline.video_generate import SampleTransport
148
+
149
+ strategy = config["reuse_strategy"]
150
+
151
+ if strategy == "original":
152
+ return
153
+ if strategy == "all":
154
+ configure_teacache(SampleTransport, config)
155
+ elif strategy == "chunkwise":
156
+ configure_flowcache(SampleTransport, config)
157
+ else:
158
+ raise ValueError(f"Unknown reuse strategy: {strategy}")
159
+
160
+
161
+ def setup_environment(gpu_id: int) -> None:
162
+ """Set up environment variables for a GPU worker process."""
163
+ os.environ["CUDA_VISIBLE_DEVICES"] = str(gpu_id)
164
+ os.environ["WORLD_SIZE"] = "1"
165
+ os.environ["RANK"] = "0"
166
+ os.environ["LOCAL_RANK"] = "0"
167
+ os.environ["MASTER_ADDR"] = "localhost"
168
+ os.environ["MASTER_PORT"] = str(DEFAULT_BASE_PORT + gpu_id)
169
+
170
+ # Enable pdb terminal debugging
171
+ sys.stdin = open(0)
172
+
173
+
174
+ def filter_existing_samples(samples: list, config: dict) -> list:
175
+ """Filter out samples whose output files already exist."""
176
+ if config["benchmark"] == "vbench":
177
+ return [
178
+ sample
179
+ for sample in samples
180
+ if not os.path.exists(os.path.abspath(os.path.join(config["save_path"], f"{sample}-0.mp4")))
181
+ ]
182
+ else: # physicsiq
183
+ return [
184
+ sample for sample in samples if not os.path.exists(sample["output_path"])
185
+ ]
186
+
187
+
188
+ def assign_samples_to_gpu(
189
+ samples: list, gpu_id: int, rank: int, num_gpus: int
190
+ ) -> list:
191
+ """Divide samples across GPUs and return the subset for this GPU."""
192
+ samples_per_gpu = (len(samples) + num_gpus - 1) // num_gpus
193
+ start_idx = rank * samples_per_gpu
194
+ end_idx = min(start_idx + samples_per_gpu, len(samples))
195
+ return samples[start_idx:end_idx]
196
+
197
+
198
+ def process_vbench_sample(pipeline, prompt: str, config: dict, gpu_id: int) -> None:
199
+ """Process a single vbench text-to-video sample."""
200
+ output_path = os.path.abspath(os.path.join(config["save_path"], f"{prompt}-0.mp4"))
201
+
202
+ if os.path.exists(output_path):
203
+ print(f"[SKIP GPU {gpu_id}] Already exists: {output_path}")
204
+ return
205
+
206
+ print(f"[GPU {gpu_id}] Generating T2V: '{prompt}' -> {output_path}")
207
+ pipeline.run_text_to_video(prompt=prompt, output_path=output_path)
208
+ print(f"[DONE GPU {gpu_id}] Saved: {output_path}")
209
+
210
+
211
+ def process_physicsiq_sample(pipeline, sample: dict, gpu_id: int) -> None:
212
+ """Process a single PhysicsIQ video-to-video sample."""
213
+ prompt = sample["description"]
214
+ prefix_video_path = sample["prefix_video_path"]
215
+ output_path = sample["output_path"]
216
+
217
+ if not os.path.exists(prefix_video_path):
218
+ print(f"[WARN GPU {gpu_id}] Conditioning video not found: {prefix_video_path}")
219
+ return
220
+
221
+ if os.path.exists(output_path):
222
+ print(f"[SKIP GPU {gpu_id}] Already exists: {output_path}")
223
+ return
224
+
225
+ print(f"[GPU {gpu_id}] Generating V2V: '{prompt}'")
226
+ print(f" Input: {prefix_video_path}")
227
+ print(f" Output: {output_path}")
228
+
229
+ pipeline.run_video_to_video(
230
+ prompt=prompt,
231
+ prefix_video_path=prefix_video_path,
232
+ output_path=output_path,
233
+ )
234
+ print(f"[DONE GPU {gpu_id}] Saved: {output_path}")
235
+
236
+
237
+ def worker_process(gpu_id: int, rank: int, config: dict, all_samples: list) -> None:
238
+ """Independent worker running on each GPU."""
239
+ setup_environment(gpu_id)
240
+ configure_reuse_strategy(config)
241
+
242
+ try:
243
+ magi_root = subprocess.check_output(
244
+ ["git", "rev-parse", "--show-toplevel"]
245
+ ).decode().strip()
246
+ os.environ["MAGI_ROOT"] = magi_root
247
+ os.environ["PYTHONPATH"] = f"{magi_root}:{os.environ.get('PYTHONPATH', '')}"
248
+ except Exception as e:
249
+ print(f"[GPU {gpu_id}] Failed to set MAGI_ROOT: {e}")
250
+ return
251
+
252
+ filtered_samples = filter_existing_samples(all_samples, config)
253
+
254
+ if not filtered_samples:
255
+ print(f"[GPU {gpu_id}] No samples need to be generated.")
256
+ return
257
+
258
+ print(f"Processing {len(filtered_samples)} samples.")
259
+
260
+ my_samples = assign_samples_to_gpu(
261
+ filtered_samples, gpu_id, rank, config["num_gpus"]
262
+ )
263
+
264
+ if not my_samples:
265
+ print(f"[GPU {gpu_id}] No samples assigned.")
266
+ return
267
+
268
+ print(f"[GPU {gpu_id}] Assigned {len(my_samples)} samples")
269
+
270
+ from inference.pipeline.entry import MagiPipeline
271
+
272
+ print(f"[GPU {gpu_id}] Loading model...")
273
+ pipeline = MagiPipeline(config["config_file"])
274
+ print(f"[GPU {gpu_id}] Model loaded.")
275
+
276
+ process_func = (
277
+ process_vbench_sample if config["benchmark"] == "vbench" else process_physicsiq_sample
278
+ )
279
+
280
+ for sample in my_samples:
281
+ process_func(pipeline, sample, config, gpu_id)
282
+
283
+ print(f"[GPU {gpu_id}] Completed.")
284
+
285
+
286
+ def build_conditioning_video_path(
287
+ data_root: str, vid_id: str, scenario: str, fps: int
288
+ ) -> str:
289
+ """Construct the path to the conditioning video file."""
290
+ conditioning_dir = os.path.join(
291
+ data_root, "physics-IQ-benchmark", "split-videos", "conditioning", f"{fps}FPS"
292
+ )
293
+ match_suffix = re.search(r"_(.*)", scenario)
294
+ suffix = match_suffix.group(1) if match_suffix else ""
295
+ filename = f"{vid_id}_conditioning-videos_{fps}FPS_{suffix}"
296
+ return os.path.join(conditioning_dir, filename)
297
+
298
+
299
+ def load_physicsiq_samples(config: dict) -> list[dict]:
300
+ """Load sample list from PhysicsIQ dataset."""
301
+ data_root = config["physicsiq_data_dir"]
302
+ descriptions_csv = os.path.join(data_root, "descriptions", "descriptions.csv")
303
+ output_dir = config["save_path"]
304
+
305
+ if not os.path.exists(descriptions_csv):
306
+ raise FileNotFoundError(f"descriptions.csv not found at {descriptions_csv}")
307
+
308
+ os.makedirs(output_dir, exist_ok=True)
309
+
310
+ samples = []
311
+ with open(descriptions_csv, mode="r") as f:
312
+ reader = csv.DictReader(f)
313
+ for row in reader:
314
+ scenario = row["scenario"].strip()
315
+ match_id = re.match(r"^(\d+)_", scenario)
316
+
317
+ if not match_id:
318
+ print(f"Cannot extract ID from scenario: {scenario}")
319
+ continue
320
+
321
+ vid_id = match_id.group(1).zfill(4)
322
+ description = row["description"]
323
+ generated_video_name = row["generated_video_name"]
324
+ prefix_video_path = build_conditioning_video_path(
325
+ data_root, vid_id, scenario, PHYSICSIQ_FPS
326
+ )
327
+ output_path = os.path.join(output_dir, generated_video_name)
328
+
329
+ os.makedirs(os.path.dirname(output_path), exist_ok=True)
330
+
331
+ samples.append({
332
+ "vid_id": vid_id,
333
+ "scenario": scenario,
334
+ "description": description,
335
+ "generated_video_name": generated_video_name,
336
+ "prefix_video_path": prefix_video_path,
337
+ "output_path": output_path,
338
+ })
339
+
340
+ # PhysicsIQ samples are duplicated; take only the first half
341
+ unique_count = len(samples) // 2
342
+ samples = samples[:unique_count]
343
+
344
+ print(f"Loaded {unique_count} PhysicsIQ samples.")
345
+
346
+ return apply_slice(samples, config.get("start"), config.get("end"))
347
+
348
+
349
+ def load_vbench_samples(config: dict) -> list[str]:
350
+ """Load prompt list from vbench dimension file."""
351
+ prompt_dir = config["vbench_prompt_dir"]
352
+ dimension = config.get("dimension")
353
+
354
+ if not dimension:
355
+ raise ValueError("For vbench, 'dimension' must be specified in config")
356
+
357
+ prompt_file = os.path.join(prompt_dir, f"{dimension}.txt")
358
+
359
+ if not os.path.exists(prompt_file):
360
+ raise FileNotFoundError(f"Prompt file not found: {prompt_file}")
361
+
362
+ with open(prompt_file, "r") as f:
363
+ prompts = [line.strip() for line in f if line.strip()]
364
+
365
+ return apply_slice(prompts, config.get("start"), config.get("end"))
366
+
367
+
368
+ def setup_save_path(config: dict) -> None:
369
+ """Configure the output save path based on benchmark type."""
370
+ base_path = config["base_save_path"]
371
+
372
+ if config["benchmark"] == "vbench":
373
+ dimension = config.get("dimension")
374
+ videos_dir = os.path.join(base_path, "videos", dimension) if dimension else None
375
+ config["save_path"] = videos_dir if videos_dir else os.path.join(base_path, "videos")
376
+ elif config["benchmark"] == "physicsiq":
377
+ config["save_path"] = os.path.join(base_path, "videos")
378
+
379
+ os.makedirs(config["save_path"], exist_ok=True)
380
+
381
+
382
+ def main() -> None:
383
+ """Entry point for video sampling script."""
384
+ parser = argparse.ArgumentParser(
385
+ description="Video sampling script using YAML configuration"
386
+ )
387
+ parser.add_argument("yaml_config", type=str, help="Path to YAML configuration file")
388
+ args = parser.parse_args()
389
+
390
+ config = load_yaml_config(args.yaml_config)
391
+ print(f"Loaded configuration from: {args.yaml_config}")
392
+
393
+ setup_save_path(config)
394
+
395
+ gpu_ids = resolve_gpu_ids(config["gpus"])
396
+ config["num_gpus"] = len(gpu_ids)
397
+
398
+ benchmark = config["benchmark"]
399
+ if benchmark == "vbench":
400
+ all_samples = load_vbench_samples(config)
401
+ elif benchmark == "physicsiq":
402
+ data_root = config["physicsiq_data_dir"]
403
+ if not os.path.exists(data_root):
404
+ raise FileNotFoundError(f"Data directory not found: {data_root}")
405
+ all_samples = load_physicsiq_samples(config)
406
+ else:
407
+ raise ValueError(f"Invalid benchmark: {benchmark}")
408
+
409
+ print(f"Total samples: {len(all_samples)}")
410
+ print(f"GPUs: {gpu_ids}")
411
+ print(f"Output: {config['save_path']}")
412
+ print(f"Config: {config['config_file']}")
413
+
414
+ processes = []
415
+ for rank, gpu_id in enumerate(gpu_ids):
416
+ p = mp.Process(target=worker_process, args=(gpu_id, rank, config, all_samples))
417
+ p.start()
418
+ processes.append(p)
419
+
420
+ for p in processes:
421
+ p.join()
422
+
423
+ failed = [p.exitcode for p in processes if p.exitcode != 0]
424
+ if failed:
425
+ raise RuntimeError(f"{len(failed)} worker process(es) failed with exit codes: {failed}")
426
+
427
+
428
+ if __name__ == "__main__":
429
+ main()
FlowCache/FlowCache4MAGI-1-dev5-history/README.md ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # FLOW CACHING FOR AUTOREGRESSIVE VIDEO GENERATION
2
+
3
+ This repository provides the official implementation of **FlowCache** on **MAGI-1** model, a caching-based acceleration method for autoregressive video generation models.
4
+
5
+
6
+ ## 🚀 Installation
7
+
8
+ Please follow the installation instructions provided in the [MAGI-1](https://github.com/SandAI-org/MAGI-1), as this implementation is built on top of MAGI-1.
9
+
10
+ ---
11
+
12
+ ## ▶️ Usage
13
+
14
+ ### 1. Single Video Generation
15
+
16
+ Run accelerated generation using FlowCache:
17
+
18
+ ```bash
19
+ # FlowCache for text-to-video generation
20
+ bash scripts/single_run/flowcache_t2v.sh
21
+
22
+ # FlowCache for video-to-video generation
23
+ bash scripts/single_run/flowcache_v2v.sh
24
+
25
+ # Baseline acceleration method (TeaCache) for text-to-video
26
+ bash scripts/single_run/teacache_t2v.sh
27
+
28
+ # Baseline acceleration method (TeaCache) for video-to-video
29
+ bash scripts/single_run/teacache_v2v.sh
30
+ ```
31
+
32
+ ### 2. Benchmark Sampling
33
+
34
+ Generate videos for evaluation on standard benchmarks:
35
+
36
+ ```bash
37
+ # VBench
38
+ bash scripts/sample/flowcache_vbench.sh
39
+ bash scripts/sample/teacache_vbench.sh
40
+
41
+ # PhysicsIQ
42
+ bash scripts/sample/flowcache_physicsiq.sh
43
+ bash scripts/sample/teacache_physicsiq.sh
44
+ ```
45
+
46
+ ### 3. Quality Evaluation
47
+
48
+ Compute perceptual and structural similarity metrics between original and accelerated generations:
49
+
50
+ ```bash
51
+ bash scripts/metric.sh
52
+ ```
53
+
54
+ ---
55
+
56
+ ## ⚙️ Key Parameters
57
+
58
+ | Parameter | Description |
59
+ |----------|-------------|
60
+ | `rel_l1_thresh` | Relative L1 distance threshold for cache reuse decision |
61
+ | ` warmup_steps` | Number of denoising steps where reuse is disabled |
62
+ | `total_cache_chunk_nums` (`B_total`) | Total number of cache chunks maintained |
63
+ | `compress_strategy` | Granularity for selecting important KV caches: `token`, `frame`, or `chunk` |
64
+ | `query_granularity` | Granularity for importance scoring: `token`, `frame`, or `chunk` |
65
+ | `mix_lambda` | Weight balancing importance and redundancy (default: `0.07`) |
66
+ | `mode` | Generation mode: `t2v` (text-to-video), `i2v` (image-to-video), or `v2v` (video-to-video) |
67
+ | `prompt` | Input prompt for conditional generation |
68
+ | `output_path` | Path to save generated videos |
69
+ | `config_file` | Path to MAGI-1 model configuration |
70
+
71
+ ---
FlowCache/FlowCache4MAGI-1-dev5-history/README_DEV5_HISTORY.md ADDED
@@ -0,0 +1,218 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # dev5-history:利用 AR 历史 Chunk 的改进方向
2
+
3
+ 基于 `FlowCache4MAGI-1-dev4-detail`(Motion + Detail 双度量),dev5 探索 **自回归(AR)已生成历史 chunk** 如何进一步改进 cache 决策与画质。
4
+
5
+ ## AR 场景下「历史」指什么?
6
+
7
+ MAGI-1 自回归生成时,在 denoise chunk `i` 的时刻,系统已经拥有:
8
+
9
+ | 历史信息 | 代码/机制中已有 | 当前 dev4 使用情况 |
10
+ |----------|----------------|-------------------|
11
+ | 前序 **clean chunk** 的 latent | `x` 前缀、KV cache | 仅 KV 压缩,未用于 token 策略 |
12
+ | 前一 chunk 末帧 | `prev_chunk_last_frame` | 仅算 chunk 首帧 motion |
13
+ | 各 chunk 上一步 latent | `prev_latent_chunks` | 存了但几乎未参与 Phase2 决策 |
14
+ | 各 chunk embedding 特征 | `prev_metric_chunks` | 仅与 **当前步** 比 Δ_chunk |
15
+ | 前序 clean 特征的 KV | `compress_kv` + tracker | Attention 用,reuse 策略未显式用 |
16
+ | 各 chunk residual / velocity | `previous_residual` | 仅 **本 chunk 内** 复用 |
17
+
18
+ **核心洞察**:AR 下历史 chunk 是 **已收敛的时空上下文**,比单步 Δ 或单帧 motion 更稳定,可用于:
19
+ - 更准的「该不该算」
20
+ - 更准的「算哪些 token」
21
+ - 更准的「inactive token 复用什么」
22
+
23
+ ---
24
+
25
+ ## Idea 分级(推荐实施顺序)
26
+
27
+ ### ★★★ Tier 1:实现成本低、与 dev4 正交、收益可期
28
+
29
+ #### Idea 1 — 跨 Chunk 时空累积器(History Accumulator)
30
+
31
+ **动机**:dev4 的 `A[p]` 在每个 chunk 内独立;AR 下同一空间位置在多 chunk 有连续轨迹。
32
+
33
+ **做法**:
34
+ ```
35
+ A_hist[p] = decay · A_hist[p] + W_combined[p] · Δ_step
36
+ ```
37
+ - 对 **空间对齐** 的 token(同 `(h,w)`,跨 chunk 用上一 chunk 对应列/网格对齐,首帧对齐 `prev_chunk_last_frame`)
38
+ - `decay ∈ (0,1)` 或 chunk 边界衰减
39
+ - active 判定:`A_hist[p] > τ` 替代或补充现有 `A[p]`
40
+
41
+ **预期**:运动物体沿时间「扫过」的空间位置会持续 active;长期静止背景更快 reuse。
42
+
43
+ **改动点**:`MotionDetailCache` → `HistoryAwareCache`,新增 `cross_chunk_accumulator` dict。
44
+
45
+ ---
46
+
47
+ #### Idea 2 — 历史 Clean Latent 锚定(Clean History Anchor)
48
+
49
+ **动机**:AR 中 chunk `i-k` 已 clean 的 latent 是 **真实生成结果**,可作为锚点。
50
+
51
+ **做法**:
52
+ - 维护每个 spatial token 最近 `H` 个 clean chunk 的 latent 统计(均值/最后一帧)
53
+ - 当前 denoise latent 与锚的距离:
54
+ ```
55
+ d_anchor[p] = ||x_current[p] - x_clean_hist[p]|| / (||x_clean_hist[p]|| + ε)
56
+ ```
57
+ - 权重:`W_anchor = soft_map(d_anchor)`,高距离 → 更需计算
58
+ - 融合:`W_final = combine(W_motion, W_detail, W_anchor)`
59
+
60
+ **预期**:减少「看起来不动但 latent 在 drift」区域的误 reuse;对 dancing 等场景尤其有用。
61
+
62
+ **改动点**:在 `store_latent_chunk` 时,若 chunk 刚 clean,写入 `clean_latent_history[chunk_id]`。
63
+
64
+ ---
65
+
66
+ #### Idea 3 — 历史 Active 轨迹传播(Active Streak Propagation)
67
+
68
+ **动机**:dev4 仅看当前步 motion/detail;AR 下「持续在变的区域」有惯性。
69
+
70
+ **做法**:
71
+ - 记录每个 token 最近 `S` 步是否 active(或 active 计数 streak)
72
+ - 传播权重:
73
+ ```
74
+ W_streak[p] = α_s + (1-α_s) · min(streak[p] / S_max, 1)
75
+ ```
76
+ - streak 高 → 提高 `W_combined` 或直接 pin active
77
+
78
+ **预期**:减少运动主体边缘的 flickering(时而算时而不算);略降 reuse,提 PSNR。
79
+
80
+ ---
81
+
82
+ ### ★★ Tier 2:中等工程量、需与 KV/Attention 协同
83
+
84
+ #### Idea 4 — 历史特征一致性门控(Embedding Consistency Gate)
85
+
86
+ **做法**:
87
+ - 不仅比较 `metric_chunks[i]` 与上一步,还与 **历史 clean chunk 的 embedding**(需存 `clean_metric_history`)比:
88
+ ```
89
+ Δ_hist = rel_L1(f_current, f_clean_ref)
90
+ ```
91
+ - 若与 clean 历史一致且 streak 低 → 允许 skip forward
92
+ - 若与 clean 历史偏离增大 → 强制 active
93
+
94
+ **与 FlowCache 关系**:FlowCache 的 Δ 是 step-wise;这是 **chunk-wise AR 锚定**。
95
+
96
+ ---
97
+
98
+ #### Idea 5 — 历史 Residual 外推(Historical Residual Extrapolation)
99
+
100
+ **动机**:inactive token 目前复用 `previous_residual`(本 chunk 上一步);AR 可提供更长上下文。
101
+
102
+ **做法**:
103
+ - 存每个 token 最近 `K` 次 **被计算时** 的 residual 序列
104
+ - inactive 时:
105
+ ```
106
+ r_reuse = (1-β)·r_prev_step + β·r_hist_extrap
107
+ ```
108
+ 其中 `r_hist_extrap` 可为线性外推或上一 clean chunk 同位置 residual
109
+
110
+ **风险**:外推错误会累积;建议仅对 **streak=0 且 anchor 距离小** 的 token 使用。
111
+
112
+ ---
113
+
114
+ #### Idea 6 — 多 Chunk Motion 场(Temporal Motion Field)
115
+
116
+ **做法**:
117
+ - 用 `{x_chunk[t] - x_chunk[t-1]}` 在多 chunk 上建 low-res motion field
118
+ - 当前 token 的 motion 不只看相邻帧,还看 **历史 motion 幅值的分位数**
119
+ - 高历史 motion 区域(舞台中央舞者)→ 永久提高 W;静态背景 → 降低
120
+
121
+ **与 dev4 区别**:dev4 motion 是 **单 chunk 内** 帧差;这是 **跨 chunk 运动先验**。
122
+
123
+ ---
124
+
125
+ ### ★ Tier 3:研究向 / 改动较大
126
+
127
+ #### Idea 7 — 历史 Conditioned Sparse Attention Mask
128
+
129
+ - 利用 KV 中 clean history 的 attention score 或 query-key 相似度,决定哪些 query token 必须重算
130
+ - 需改 DiT sparse forward,工程量大
131
+
132
+ #### Idea 8 — Chunk 级 AR 难度预测器
133
+
134
+ - 用前 `n` 个 chunk 的 reuse 率、平均 Δ、motion 统计,预测 chunk `i` 的「难度」
135
+ - 动态调节 τ、detail_lambda(简单 chunk 更激进 reuse)
136
+
137
+ #### Idea 9 — 显式 Warp 对齐历史 Token
138
+
139
+ - 对 camera motion 场景,用光流/块匹配将 chunk `i-1` token 对齐到 chunk `i` 网格再比特征
140
+ - 最准但最重;适合 v2v 或有 camera 运动的数据
141
+
142
+ ---
143
+
144
+ ## 推荐 dev5 首版实现路线(MVP)
145
+
146
+ 建议 **Idea 1 + Idea 2 + Idea 3** 组合为 `HistoryAwareCache`:
147
+
148
+ ```
149
+ W_final = blend( max(W_motion, W_detail), W_anchor, λ_a )
150
+ × (1 + γ · W_streak)
151
+
152
+ A_cross[p] += W_final[p] · Δ_chunk
153
+ active[p] = (A_cross[p] > τ) OR (A_local[p] > τ) # 双累积器 OR 逻辑
154
+ ```
155
+
156
+ **超参(新增 yaml)**:
157
+ ```yaml
158
+ history_decay: 0.7 # 跨 chunk 累积衰减
159
+ history_anchor_horizon: 3 # 参考最近 H 个 clean chunk
160
+ history_streak_len: 5 # streak 窗口
161
+ history_anchor_lambda: 0.3 # anchor 权重
162
+ history_streak_gamma: 0.2 # streak 加成
163
+ ```
164
+
165
+ **验证指标**(延续 dev3/dev4 sweep):
166
+ - PSNR vs FlowCache baseline(240f)
167
+ - reuse_rate / wall_time
168
+ - 运动区域 active 比例稳定性(方差↓更好)
169
+
170
+ ---
171
+
172
+ ## 代码结构规划(dev5)
173
+
174
+ ```
175
+ inference/pipeline/cache/
176
+ ├── motioncache.py # dev3 基类
177
+ ├── motiondetailcache.py # dev4
178
+ └── historycache.py # dev5 HistoryAwareCache(待实现)
179
+
180
+ yaml_config/single_run/
181
+ └── historycache_config.yaml # dev5 默认 + 历史相关超参
182
+
183
+ README_DEV5_HISTORY.md # 本文档
184
+ ```
185
+
186
+ ---
187
+
188
+ ## 与 dev4 最优配置的继承关系
189
+
190
+ dev5 默认继承 dev4 sweep 最优(τ=0.012, blend, detail_window=3, detail_lambda=0.3),在其上叠加 history 项;便于 ablation:
191
+
192
+ | 实验 | 配置 |
193
+ |------|------|
194
+ | A0 | dev4 best(对照) |
195
+ | A1 | dev5 仅 Idea1 跨 chunk 累积 |
196
+ | A2 | dev5 Idea1+2 |
197
+ | A3 | dev5 Idea1+2+3 全量 |
198
+
199
+ ---
200
+
201
+ ## 风险与注意点
202
+
203
+ 1. **Chunk 边界对齐**:latent 空间 `(h,w)` 在 chunk 间是否严格对齐需确认 patch/grid 一致
204
+ 2. **Clean 时机**:只有 `chunk_denoise_count == num_steps` 后的 latent 才能进 history anchor
205
+ 3. **内存**:存 H 个 clean chunk latent 会增加 CPU/GPU 缓存,可只存 downsampled 或 embedding
206
+ 4. **CFG**:batch=2 时 history 需 per-batch 维护
207
+ 5. **不要破坏 Phase1**:前 K 步仍 chunk-wise FlowCache,history 仅 Phase2 启用
208
+
209
+ ---
210
+
211
+ ## 下一步
212
+
213
+ 1. 确认优先实现的 Idea(建议 1+2+3)
214
+ 2. 在 `historycache.py` 实现 `HistoryAwareCache`
215
+ 3. 复用 dev4 sweep 脚本做 dev5 ablation
216
+ 4. 在 `a woman dancing.` + VBench 子集上对比 dev4 best
217
+
218
+ 如需我直接在 dev5 实现 **HistoryAwareCache MVP(Idea 1+2+3)**,可以指定优先哪几个 Idea。
FlowCache/FlowCache4MAGI-1-dev5-history/README_MOTIONCACHE.md ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # MotionCache on MAGI-1 (dev3-motion)
2
+
3
+ 基于 [FlowCache4MAGI-1](../FlowCache4MAGI-1) 的 **MotionCache** 复现分支,对应论文:
4
+
5
+ > Xu et al., 2026 — *Motion-Aware Caching for Efficient Autoregressive Video Generation*
6
+
7
+ 官方代码仓库 [ywlq/MotionCache](https://github.com/ywlq/MotionCache) 尚未发布实现,本目录依据论文方法在 MAGI-1 推理框架上完成首版复现。
8
+
9
+ ## 与 FlowCache 的核心差异
10
+
11
+ | 维度 | FlowCache | MotionCache |
12
+ |------|-----------|-------------|
13
+ | 粒度 | Chunk 级全有或全无 | Phase 2 为 Token(latent 帧×空间)级 |
14
+ | 跳过策略 | 相对 L1 累积阈值 | 运动重要性加权累积 |
15
+ | 调度 | 单一 chunk-wise 策略 | 两阶段 coarse-to-fine |
16
+
17
+ ### 算法概要
18
+
19
+ 1. **全局 Warm-up(m 步)**:前 `warmup_steps` 步禁止 cache reuse
20
+ 2. **Phase 1(K 步)**:chunk-wise 二值决策,与 FlowCache 相同
21
+ 3. **Phase 2**:基于帧间 latent 差计算运动重要性 `M`,经 soft-mapping 得到权重 `W ∈ [α, 1]`
22
+ 4. **Token 累积**:`A[p] += W[p] · Δ_chunk`,当 `A[p] > τ` 时该 token 触发 DiT 计算
23
+ 5. **Integrate**:active token 正常积分;inactive token 复用缓存 residual
24
+
25
+ ### MAGI-1 默认超参(论文 Appendix C)
26
+
27
+ | 参数 | 值 | 说明 |
28
+ |------|-----|------|
29
+ | `alpha` | 0.5 | 静态区域权重下限 |
30
+ | `phase1_steps` (K) | 9 | chunk-wise 阶段持续步数 |
31
+ | `warmup_steps` (m) | 5 | 全局禁止 reuse 的步数 |
32
+ | `rel_l1_thresh` (τ) | 0.015 (slow) / 0.025 (fast) | token 累积阈值 |
33
+
34
+ ## 快速运行
35
+
36
+ ```bash
37
+ cd FlowCache4MAGI-1-dev3-motion
38
+
39
+ # MotionCache-slow(论文 Table 1 配置)
40
+ bash scripts/single_run/motioncache_t2v.sh
41
+
42
+ # MotionCache-fast
43
+ MOTIONCACHE_CONFIG=yaml_config/single_run/motioncache_config_fast.yaml \
44
+ bash scripts/single_run/motioncache_t2v.sh
45
+ ```
46
+
47
+ 需先按 FlowCache4MAGI-1 说明安装依赖并下载 MAGI-1 权重(`downloads/` 目录可通过软链接指向原项目)。
48
+
49
+ ## 代码结构
50
+
51
+ ```
52
+ inference/pipeline/
53
+ ├── motioncache.py # 入口与 forward/integrate monkey-patch
54
+ └── cache/
55
+ ├── motioncache.py # MotionWiseCache 核心逻辑
56
+ └── sparse_utils.py # Phase 2 gather/scatter 与 sparse meta_args
57
+
58
+ inference/model/dit/dit_module.py # sparse KV cache 写入 + flash_attn 稀疏 q 分支
59
+ inference/common/dataclass.py # ModelMetaArgs.sparse_active_indices
60
+
61
+ yaml_config/single_run/
62
+ ├── motioncache_config.yaml # slow 配置
63
+ └── motioncache_config_fast.yaml
64
+ ```
65
+
66
+ ## 当前实现说明(严格对齐论文 §5.3 Phase 2)
67
+
68
+ - **Phase 1(前 K 个 denoise step / chunk)**:与 FlowCache 完全一致的 chunk-wise 策略(已验证 PSNR=∞)
69
+ - **Phase 2 入口**:每个 chunk 的第 K 步强制全量计算,建立 token-wise 阶段的 residual 基准
70
+ - **Phase 2 运动感知累积**:latent 帧间差 → soft-mapping 权重 W → 累积器 A;`A > τ` 的 token 为 active
71
+ - **Phase 2 稀疏 forward(论文 5.3)**:
72
+ - 全部 inactive → 跳过 DiT forward,复用 chunk residual
73
+ - 部分 active → **gather active patch tokens → compact DiT forward → scatter 回完整序列**
74
+ - KV cache 仅更新 active 位置(`_compresskv_adjust_key_and_value` sparse 分支)
75
+ - integrate 时 active token 正常积分,inactive token 复用 `previous_residual`
76
+ - **运动 proxy**:latent 空间帧间 L1 差(论文 Eq. 9-10)
77
+ - **跨 chunk 连续性**:chunk 首帧与上一 chunk 末帧比较
78
+
79
+ ### 验证结果(`a woman dancing.`,240×720×720,vs FlowCache baseline)
80
+
81
+ | 运行 | PSNR | 说明 |
82
+ |------|------|------|
83
+ | phase1only | ∞ | 与 FlowCache 逐像素一致 |
84
+ | sparse2(论文对齐 sparse forward) | **20.44 dB** | 无黑帧,reuse_rate≈15.6% |
85
+ | final(整 chunk fallback) | 20.48 dB | 画质等价,推理慢 ~14% |
86
+
87
+ sparse2 日志示例:`active_ratio=1.51%` 时仍走 gather/scatter 稀疏路径;`active_ratio=0%` 时 `skip_forward=True`。
88
+
89
+ ## 参考
90
+
91
+ - FlowCache: chunk-wise cache + KV compression
92
+ - MotionCache 论文预期 MAGI-1 加速:slow 1.64×,fast 2.07×(Table 1)
FlowCache/FlowCache4MAGI-1-dev5-history/README_MOTIONDETAIL.md ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # MotionDetailCache on MAGI-1 (dev4-detail)
2
+
3
+ 基于 [FlowCache4MAGI-1-dev3-motion](../FlowCache4MAGI-1-dev3-motion) 的扩展分支,在 MotionCache 的 **motion 度量** 之外,增加 **spatial detail 度量**,Phase 2 active token 由两者共同决定。
4
+
5
+ ## 与 dev3 (MotionCache) 的差异
6
+
7
+ | 维度 | dev3 MotionCache | dev4 MotionDetailCache |
8
+ |------|------------------|------------------------|
9
+ | Phase 2 权重 | 仅 motion 权重 W_m | motion W_m + detail W_d 融合 |
10
+ | Detail proxy | — | latent 局部 k×k 空间方差 |
11
+ | 适用场景 | 运动区域优先计算 | 静止纹理/边缘/语义细节也优先保留 |
12
+
13
+ ## Detail 度量
14
+
15
+ 对每个 latent 像素 `(t, h, w)`:
16
+
17
+ 1. 通道聚合幅度:`mag = mean(|x|, dim=C)` → `[N, T, H, W]`
18
+ 2. 局部空间方差:在 `detail_window_size×detail_window_size` 窗口内计算 `Var(mag)`
19
+ 3. Soft-mapping:帧内 min-max 归一化 → `W_d ∈ [detail_alpha, 1]`
20
+
21
+ 高方差区域对应边缘、纹理、物体边界等 heterogeneous 邻域。
22
+
23
+ ## Motion + Detail 融合
24
+
25
+ ```
26
+ W_combined = combine(W_motion, W_detail)
27
+ A[p] += W_combined[p] · Δ_chunk
28
+ active[p] = A[p] > τ
29
+ ```
30
+
31
+ `weight_combine_mode`(默认 `max`):
32
+
33
+ | 模式 | 公式 | 特点 |
34
+ |------|------|------|
35
+ | `max` | max(W_m, W_d) | 运动或细节任一显著即可加速累积(推荐) |
36
+ | `product` | W_m × W_d | 两者同时高才快速激活,更激进 reuse |
37
+ | `blend` | (1-λ)W_m + λW_d | 线性权衡,λ=`detail_lambda` |
38
+
39
+ ## 默认超参
40
+
41
+ 继承 dev3 的 motion 参数,并新增:
42
+
43
+ | 参数 | 默认值 | 说明 |
44
+ |------|--------|------|
45
+ | `detail_alpha` | 0.5 | detail 权重下限 |
46
+ | `detail_window_size` | 3 | 局部方差窗口(奇数) |
47
+ | `detail_lambda` | 0.5 | blend 模式下的 detail 权重 |
48
+ | `weight_combine_mode` | max | 融合方式 |
49
+
50
+ ## 快速运行
51
+
52
+ ```bash
53
+ cd FlowCache4MAGI-1-dev4-detail
54
+ conda activate magi
55
+ export CUDA_VISIBLE_DEVICES=0
56
+ export MASTER_ADDR=localhost
57
+ bash scripts/single_run/motiondetail_t2v.sh
58
+ ```
59
+
60
+ ## 代码结构
61
+
62
+ ```
63
+ inference/pipeline/cache/
64
+ ├── motioncache.py # dev3 基类 MotionWiseCache
65
+ └── motiondetailcache.py # dev4 MotionDetailCache
66
+
67
+ yaml_config/single_run/motiondetail_config.yaml
68
+ scripts/single_run/motiondetail_t2v.sh
69
+ ```
70
+
71
+ 其余 sparse forward、KV cache、integrate 逻辑与 dev3 完全一致。
FlowCache/FlowCache4MAGI-1-dev5-history/requirements.txt ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ accelerate==0.32.1
2
+ beautifulsoup4==4.13.4
3
+ debugpy==1.8.14
4
+ diffusers==0.29.2
5
+ einops>=0.6.0
6
+ ffmpeg-python
7
+ # flash-attn==2.4.2
8
+ flashinfer-python==0.2.0.post2 --extra-index-url https://flashinfer.ai/whl/cu124/torch2.4/
9
+ ftfy==6.2.0
10
+ gpustat==1.1.1
11
+ imageio==2.34.0
12
+ imageio[ffmpeg]
13
+ matplotlib==3.10.1
14
+ numpy==1.26.4
15
+ protobuf==5.28.3
16
+ rich==14.0.0
17
+ sentencepiece==0.2.0
18
+ timm==1.0.15
19
+ torchdiffeq==0.2.4
20
+ transformers==4.42.3
21
+ tqdm
FlowCache/FlowCache4MAGI-1-dev5-history/sample_video.py ADDED
@@ -0,0 +1,429 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 MAGI Authors. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import os
16
+ import re
17
+ import sys
18
+ import argparse
19
+ import csv
20
+ import subprocess
21
+ from pathlib import Path
22
+
23
+ import multiprocessing as mp
24
+
25
+ # Constants
26
+ DEFAULT_BASE_PORT = 29510
27
+ PHYSICSIQ_FPS = 24
28
+
29
+
30
+ def resolve_gpu_ids(gpus_config) -> list[int]:
31
+ """Resolve explicit GPU IDs or auto-detect all currently visible GPUs."""
32
+ if isinstance(gpus_config, int):
33
+ return [gpus_config]
34
+
35
+ gpus_text = str(gpus_config).strip()
36
+ if not gpus_text:
37
+ raise ValueError("'gpus' must not be empty")
38
+
39
+ if gpus_text.lower() not in {"all", "auto"}:
40
+ return [int(item.strip()) for item in gpus_text.split(",") if item.strip()]
41
+
42
+ visible_devices = os.environ.get("CUDA_VISIBLE_DEVICES")
43
+ if visible_devices:
44
+ visible = [item.strip() for item in visible_devices.split(",") if item.strip()]
45
+ if visible and all(item.isdigit() for item in visible):
46
+ return [int(item) for item in visible]
47
+
48
+ try:
49
+ output = subprocess.check_output(
50
+ ["nvidia-smi", "--query-gpu=index", "--format=csv,noheader,nounits"],
51
+ text=True,
52
+ timeout=10,
53
+ )
54
+ gpu_ids = [int(line.strip()) for line in output.splitlines() if line.strip()]
55
+ if gpu_ids:
56
+ return gpu_ids
57
+ except Exception:
58
+ pass
59
+
60
+ try:
61
+ import torch
62
+
63
+ count = torch.cuda.device_count()
64
+ if count > 0:
65
+ return list(range(count))
66
+ except Exception:
67
+ pass
68
+
69
+ raise RuntimeError("No CUDA GPUs detected for gpus: all")
70
+
71
+
72
+ def load_yaml_config(yaml_path: str) -> dict:
73
+ """Load configuration from YAML file."""
74
+ import yaml
75
+
76
+ with open(yaml_path, "r") as f:
77
+ return yaml.safe_load(f)
78
+
79
+
80
+ def apply_slice(items: list, start: int | None, end: int | None) -> list:
81
+ """Apply start/end slice to a list with bounds checking."""
82
+ if start is None and end is None:
83
+ return items
84
+
85
+ slice_start = max(0, start if start is not None else 0)
86
+ slice_end = min(end if end is not None else len(items), len(items))
87
+ slice_end = max(slice_start, slice_end)
88
+
89
+ return items[slice_start:slice_end]
90
+
91
+
92
+ def configure_teacache(transport, config: dict) -> None:
93
+ """Configure TeaCache reuse strategy on SampleTransport."""
94
+ from inference.pipeline.teacache import setup_teacache
95
+
96
+ setup_teacache(
97
+ rel_l1_thresh=config["rel_l1_thresh"],
98
+ warmup_steps=config["warmup_steps"],
99
+ log=config.get("log", False),
100
+ )
101
+
102
+
103
+ def configure_kv_cache(transport, config: dict) -> None:
104
+ """Configure KV cache compression if enabled."""
105
+ if not config.get("compress_kv_cache", False):
106
+ transport.compress_kv_cache = False
107
+ return
108
+
109
+ print("KV cache compression is enabled.")
110
+ transport.compress_kv_cache = True
111
+
112
+ assert config.get("total_cache_chunk_nums") is not None
113
+
114
+ compression_config = {
115
+ "method_config": {
116
+ "compress_strategy": config["compress_strategy"],
117
+ "mix_lambda": config["mix_lambda"],
118
+ "query_granularity": config["query_granularity"],
119
+ "score_weighting_method": config.get("score_weighting_method") or "no_weight",
120
+ "power": config.get("power", 3),
121
+ },
122
+ }
123
+
124
+ from inference.pipeline.kvcompress import replace_magi
125
+
126
+ replace_magi(compression_config)
127
+
128
+
129
+ def configure_flowcache(transport, config: dict) -> None:
130
+ """Configure FlowCache reuse strategy on SampleTransport."""
131
+ from inference.pipeline.flowcache import setup_flowcache
132
+
133
+ configure_kv_cache(transport, config)
134
+
135
+ setup_flowcache(
136
+ rel_l1_thresh=config["rel_l1_thresh"],
137
+ warmup_steps=config["warmup_steps"],
138
+ discard_nearly_clean_chunk=config.get("discard_nearly_clean_chunk", False),
139
+ log=config.get("log", False),
140
+ total_cache_chunk_nums=config.get("total_cache_chunk_nums", 5),
141
+ compress_kv_cache=config.get("compress_kv_cache", False),
142
+ )
143
+
144
+
145
+ def configure_reuse_strategy(config: dict) -> None:
146
+ """Configure the appropriate reuse strategy on SampleTransport."""
147
+ from inference.pipeline.video_generate import SampleTransport
148
+
149
+ strategy = config["reuse_strategy"]
150
+
151
+ if strategy == "original":
152
+ return
153
+ if strategy == "all":
154
+ configure_teacache(SampleTransport, config)
155
+ elif strategy == "chunkwise":
156
+ configure_flowcache(SampleTransport, config)
157
+ else:
158
+ raise ValueError(f"Unknown reuse strategy: {strategy}")
159
+
160
+
161
+ def setup_environment(gpu_id: int) -> None:
162
+ """Set up environment variables for a GPU worker process."""
163
+ os.environ["CUDA_VISIBLE_DEVICES"] = str(gpu_id)
164
+ os.environ["WORLD_SIZE"] = "1"
165
+ os.environ["RANK"] = "0"
166
+ os.environ["LOCAL_RANK"] = "0"
167
+ os.environ["MASTER_ADDR"] = "localhost"
168
+ os.environ["MASTER_PORT"] = str(DEFAULT_BASE_PORT + gpu_id)
169
+
170
+ # Enable pdb terminal debugging
171
+ sys.stdin = open(0)
172
+
173
+
174
+ def filter_existing_samples(samples: list, config: dict) -> list:
175
+ """Filter out samples whose output files already exist."""
176
+ if config["benchmark"] == "vbench":
177
+ return [
178
+ sample
179
+ for sample in samples
180
+ if not os.path.exists(os.path.abspath(os.path.join(config["save_path"], f"{sample}-0.mp4")))
181
+ ]
182
+ else: # physicsiq
183
+ return [
184
+ sample for sample in samples if not os.path.exists(sample["output_path"])
185
+ ]
186
+
187
+
188
+ def assign_samples_to_gpu(
189
+ samples: list, gpu_id: int, rank: int, num_gpus: int
190
+ ) -> list:
191
+ """Divide samples across GPUs and return the subset for this GPU."""
192
+ samples_per_gpu = (len(samples) + num_gpus - 1) // num_gpus
193
+ start_idx = rank * samples_per_gpu
194
+ end_idx = min(start_idx + samples_per_gpu, len(samples))
195
+ return samples[start_idx:end_idx]
196
+
197
+
198
+ def process_vbench_sample(pipeline, prompt: str, config: dict, gpu_id: int) -> None:
199
+ """Process a single vbench text-to-video sample."""
200
+ output_path = os.path.abspath(os.path.join(config["save_path"], f"{prompt}-0.mp4"))
201
+
202
+ if os.path.exists(output_path):
203
+ print(f"[SKIP GPU {gpu_id}] Already exists: {output_path}")
204
+ return
205
+
206
+ print(f"[GPU {gpu_id}] Generating T2V: '{prompt}' -> {output_path}")
207
+ pipeline.run_text_to_video(prompt=prompt, output_path=output_path)
208
+ print(f"[DONE GPU {gpu_id}] Saved: {output_path}")
209
+
210
+
211
+ def process_physicsiq_sample(pipeline, sample: dict, gpu_id: int) -> None:
212
+ """Process a single PhysicsIQ video-to-video sample."""
213
+ prompt = sample["description"]
214
+ prefix_video_path = sample["prefix_video_path"]
215
+ output_path = sample["output_path"]
216
+
217
+ if not os.path.exists(prefix_video_path):
218
+ print(f"[WARN GPU {gpu_id}] Conditioning video not found: {prefix_video_path}")
219
+ return
220
+
221
+ if os.path.exists(output_path):
222
+ print(f"[SKIP GPU {gpu_id}] Already exists: {output_path}")
223
+ return
224
+
225
+ print(f"[GPU {gpu_id}] Generating V2V: '{prompt}'")
226
+ print(f" Input: {prefix_video_path}")
227
+ print(f" Output: {output_path}")
228
+
229
+ pipeline.run_video_to_video(
230
+ prompt=prompt,
231
+ prefix_video_path=prefix_video_path,
232
+ output_path=output_path,
233
+ )
234
+ print(f"[DONE GPU {gpu_id}] Saved: {output_path}")
235
+
236
+
237
+ def worker_process(gpu_id: int, rank: int, config: dict, all_samples: list) -> None:
238
+ """Independent worker running on each GPU."""
239
+ setup_environment(gpu_id)
240
+ configure_reuse_strategy(config)
241
+
242
+ try:
243
+ magi_root = subprocess.check_output(
244
+ ["git", "rev-parse", "--show-toplevel"]
245
+ ).decode().strip()
246
+ os.environ["MAGI_ROOT"] = magi_root
247
+ os.environ["PYTHONPATH"] = f"{magi_root}:{os.environ.get('PYTHONPATH', '')}"
248
+ except Exception as e:
249
+ print(f"[GPU {gpu_id}] Failed to set MAGI_ROOT: {e}")
250
+ return
251
+
252
+ filtered_samples = filter_existing_samples(all_samples, config)
253
+
254
+ if not filtered_samples:
255
+ print(f"[GPU {gpu_id}] No samples need to be generated.")
256
+ return
257
+
258
+ print(f"Processing {len(filtered_samples)} samples.")
259
+
260
+ my_samples = assign_samples_to_gpu(
261
+ filtered_samples, gpu_id, rank, config["num_gpus"]
262
+ )
263
+
264
+ if not my_samples:
265
+ print(f"[GPU {gpu_id}] No samples assigned.")
266
+ return
267
+
268
+ print(f"[GPU {gpu_id}] Assigned {len(my_samples)} samples")
269
+
270
+ from inference.pipeline.entry import MagiPipeline
271
+
272
+ print(f"[GPU {gpu_id}] Loading model...")
273
+ pipeline = MagiPipeline(config["config_file"])
274
+ print(f"[GPU {gpu_id}] Model loaded.")
275
+
276
+ process_func = (
277
+ process_vbench_sample if config["benchmark"] == "vbench" else process_physicsiq_sample
278
+ )
279
+
280
+ for sample in my_samples:
281
+ process_func(pipeline, sample, config, gpu_id)
282
+
283
+ print(f"[GPU {gpu_id}] Completed.")
284
+
285
+
286
+ def build_conditioning_video_path(
287
+ data_root: str, vid_id: str, scenario: str, fps: int
288
+ ) -> str:
289
+ """Construct the path to the conditioning video file."""
290
+ conditioning_dir = os.path.join(
291
+ data_root, "physics-IQ-benchmark", "split-videos", "conditioning", f"{fps}FPS"
292
+ )
293
+ match_suffix = re.search(r"_(.*)", scenario)
294
+ suffix = match_suffix.group(1) if match_suffix else ""
295
+ filename = f"{vid_id}_conditioning-videos_{fps}FPS_{suffix}"
296
+ return os.path.join(conditioning_dir, filename)
297
+
298
+
299
+ def load_physicsiq_samples(config: dict) -> list[dict]:
300
+ """Load sample list from PhysicsIQ dataset."""
301
+ data_root = config["physicsiq_data_dir"]
302
+ descriptions_csv = os.path.join(data_root, "descriptions", "descriptions.csv")
303
+ output_dir = config["save_path"]
304
+
305
+ if not os.path.exists(descriptions_csv):
306
+ raise FileNotFoundError(f"descriptions.csv not found at {descriptions_csv}")
307
+
308
+ os.makedirs(output_dir, exist_ok=True)
309
+
310
+ samples = []
311
+ with open(descriptions_csv, mode="r") as f:
312
+ reader = csv.DictReader(f)
313
+ for row in reader:
314
+ scenario = row["scenario"].strip()
315
+ match_id = re.match(r"^(\d+)_", scenario)
316
+
317
+ if not match_id:
318
+ print(f"Cannot extract ID from scenario: {scenario}")
319
+ continue
320
+
321
+ vid_id = match_id.group(1).zfill(4)
322
+ description = row["description"]
323
+ generated_video_name = row["generated_video_name"]
324
+ prefix_video_path = build_conditioning_video_path(
325
+ data_root, vid_id, scenario, PHYSICSIQ_FPS
326
+ )
327
+ output_path = os.path.join(output_dir, generated_video_name)
328
+
329
+ os.makedirs(os.path.dirname(output_path), exist_ok=True)
330
+
331
+ samples.append({
332
+ "vid_id": vid_id,
333
+ "scenario": scenario,
334
+ "description": description,
335
+ "generated_video_name": generated_video_name,
336
+ "prefix_video_path": prefix_video_path,
337
+ "output_path": output_path,
338
+ })
339
+
340
+ # PhysicsIQ samples are duplicated; take only the first half
341
+ unique_count = len(samples) // 2
342
+ samples = samples[:unique_count]
343
+
344
+ print(f"Loaded {unique_count} PhysicsIQ samples.")
345
+
346
+ return apply_slice(samples, config.get("start"), config.get("end"))
347
+
348
+
349
+ def load_vbench_samples(config: dict) -> list[str]:
350
+ """Load prompt list from vbench dimension file."""
351
+ prompt_dir = config["vbench_prompt_dir"]
352
+ dimension = config.get("dimension")
353
+
354
+ if not dimension:
355
+ raise ValueError("For vbench, 'dimension' must be specified in config")
356
+
357
+ prompt_file = os.path.join(prompt_dir, f"{dimension}.txt")
358
+
359
+ if not os.path.exists(prompt_file):
360
+ raise FileNotFoundError(f"Prompt file not found: {prompt_file}")
361
+
362
+ with open(prompt_file, "r") as f:
363
+ prompts = [line.strip() for line in f if line.strip()]
364
+
365
+ return apply_slice(prompts, config.get("start"), config.get("end"))
366
+
367
+
368
+ def setup_save_path(config: dict) -> None:
369
+ """Configure the output save path based on benchmark type."""
370
+ base_path = config["base_save_path"]
371
+
372
+ if config["benchmark"] == "vbench":
373
+ dimension = config.get("dimension")
374
+ videos_dir = os.path.join(base_path, "videos", dimension) if dimension else None
375
+ config["save_path"] = videos_dir if videos_dir else os.path.join(base_path, "videos")
376
+ elif config["benchmark"] == "physicsiq":
377
+ config["save_path"] = os.path.join(base_path, "videos")
378
+
379
+ os.makedirs(config["save_path"], exist_ok=True)
380
+
381
+
382
+ def main() -> None:
383
+ """Entry point for video sampling script."""
384
+ parser = argparse.ArgumentParser(
385
+ description="Video sampling script using YAML configuration"
386
+ )
387
+ parser.add_argument("yaml_config", type=str, help="Path to YAML configuration file")
388
+ args = parser.parse_args()
389
+
390
+ config = load_yaml_config(args.yaml_config)
391
+ print(f"Loaded configuration from: {args.yaml_config}")
392
+
393
+ setup_save_path(config)
394
+
395
+ gpu_ids = resolve_gpu_ids(config["gpus"])
396
+ config["num_gpus"] = len(gpu_ids)
397
+
398
+ benchmark = config["benchmark"]
399
+ if benchmark == "vbench":
400
+ all_samples = load_vbench_samples(config)
401
+ elif benchmark == "physicsiq":
402
+ data_root = config["physicsiq_data_dir"]
403
+ if not os.path.exists(data_root):
404
+ raise FileNotFoundError(f"Data directory not found: {data_root}")
405
+ all_samples = load_physicsiq_samples(config)
406
+ else:
407
+ raise ValueError(f"Invalid benchmark: {benchmark}")
408
+
409
+ print(f"Total samples: {len(all_samples)}")
410
+ print(f"GPUs: {gpu_ids}")
411
+ print(f"Output: {config['save_path']}")
412
+ print(f"Config: {config['config_file']}")
413
+
414
+ processes = []
415
+ for rank, gpu_id in enumerate(gpu_ids):
416
+ p = mp.Process(target=worker_process, args=(gpu_id, rank, config, all_samples))
417
+ p.start()
418
+ processes.append(p)
419
+
420
+ for p in processes:
421
+ p.join()
422
+
423
+ failed = [p.exitcode for p in processes if p.exitcode != 0]
424
+ if failed:
425
+ raise RuntimeError(f"{len(failed)} worker process(es) failed with exit codes: {failed}")
426
+
427
+
428
+ if __name__ == "__main__":
429
+ main()
FlowCache/FlowCache4MAGI-1-dev6-adaptive/README.md ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # FLOW CACHING FOR AUTOREGRESSIVE VIDEO GENERATION
2
+
3
+ This repository provides the official implementation of **FlowCache** on **MAGI-1** model, a caching-based acceleration method for autoregressive video generation models.
4
+
5
+
6
+ ## 🚀 Installation
7
+
8
+ Please follow the installation instructions provided in the [MAGI-1](https://github.com/SandAI-org/MAGI-1), as this implementation is built on top of MAGI-1.
9
+
10
+ ---
11
+
12
+ ## ▶️ Usage
13
+
14
+ ### 1. Single Video Generation
15
+
16
+ Run accelerated generation using FlowCache:
17
+
18
+ ```bash
19
+ # FlowCache for text-to-video generation
20
+ bash scripts/single_run/flowcache_t2v.sh
21
+
22
+ # FlowCache for video-to-video generation
23
+ bash scripts/single_run/flowcache_v2v.sh
24
+
25
+ # Baseline acceleration method (TeaCache) for text-to-video
26
+ bash scripts/single_run/teacache_t2v.sh
27
+
28
+ # Baseline acceleration method (TeaCache) for video-to-video
29
+ bash scripts/single_run/teacache_v2v.sh
30
+ ```
31
+
32
+ ### 2. Benchmark Sampling
33
+
34
+ Generate videos for evaluation on standard benchmarks:
35
+
36
+ ```bash
37
+ # VBench
38
+ bash scripts/sample/flowcache_vbench.sh
39
+ bash scripts/sample/teacache_vbench.sh
40
+
41
+ # PhysicsIQ
42
+ bash scripts/sample/flowcache_physicsiq.sh
43
+ bash scripts/sample/teacache_physicsiq.sh
44
+ ```
45
+
46
+ ### 3. Quality Evaluation
47
+
48
+ Compute perceptual and structural similarity metrics between original and accelerated generations:
49
+
50
+ ```bash
51
+ bash scripts/metric.sh
52
+ ```
53
+
54
+ ---
55
+
56
+ ## ⚙️ Key Parameters
57
+
58
+ | Parameter | Description |
59
+ |----------|-------------|
60
+ | `rel_l1_thresh` | Relative L1 distance threshold for cache reuse decision |
61
+ | ` warmup_steps` | Number of denoising steps where reuse is disabled |
62
+ | `total_cache_chunk_nums` (`B_total`) | Total number of cache chunks maintained |
63
+ | `compress_strategy` | Granularity for selecting important KV caches: `token`, `frame`, or `chunk` |
64
+ | `query_granularity` | Granularity for importance scoring: `token`, `frame`, or `chunk` |
65
+ | `mix_lambda` | Weight balancing importance and redundancy (default: `0.07`) |
66
+ | `mode` | Generation mode: `t2v` (text-to-video), `i2v` (image-to-video), or `v2v` (video-to-video) |
67
+ | `prompt` | Input prompt for conditional generation |
68
+ | `output_path` | Path to save generated videos |
69
+ | `config_file` | Path to MAGI-1 model configuration |
70
+
71
+ ---
FlowCache/FlowCache4MAGI-1-dev6-adaptive/README_ADAPTIVE.md ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # AdaptiveDetailCache on MAGI-1 (dev6-adaptive)
2
+
3
+ 基于 [FlowCache4MAGI-1-dev4-detail](../FlowCache4MAGI-1-dev4-detail) 的扩展分支,在 MotionDetailCache(motion + detail 双度量)之上,增加 **chunk 级 AR 难度预测 → 动态阈值 τ**。
4
+
5
+ ## 与 dev4 的差异
6
+
7
+ | 维度 | dev4 MotionDetailCache | dev6 AdaptiveDetailCache |
8
+ |------|------------------------|--------------------------|
9
+ | Phase 2 阈值 | 全局固定 `τ` | 每个 chunk 独立 `τ_eff` |
10
+ | 难度信号 | — | motion / detail / delta / 历史 active / 历史 reuse |
11
+ | 调参方式 | 手动 sweep `rel_l1_thresh` | `τ_base` + `beta` + `[τ_min, τ_max]` |
12
+
13
+ ## 动态 τ 公式
14
+
15
+ 每个 chunk 进入 Phase2 时(chunk 内固定,避免 step 间抖动):
16
+
17
+ ```
18
+ d = weighted(motion, detail, delta, hist_active, hist_reuse) ∈ [0, 1]
19
+ τ_eff = clamp(τ_base * exp(-β * (d - 0.5)), τ_min, τ_max)
20
+ active[p] = A[p] > τ_eff
21
+ ```
22
+
23
+ 难度高 → τ 降低 → 更常计算;难度低 → τ 升高 → 更敢 reuse。
24
+
25
+ ## 默认超参
26
+
27
+ 继承 dev4 best,并新增:
28
+
29
+ | 参数 | 默认值 | 说明 |
30
+ |------|--------|------|
31
+ | `rel_l1_thresh` | 0.012 | τ 基准(dev4 best) |
32
+ | `use_adaptive_tau` | true | 开启动态 τ |
33
+ | `adaptive_tau_beta` | 0.8 | 难度→τ 灵敏度 |
34
+ | `adaptive_tau_min` | 0.008 | τ 下界 |
35
+ | `adaptive_tau_max` | 0.020 | τ 上界 |
36
+
37
+ ## 快速运行
38
+
39
+ ```bash
40
+ cd FlowCache4MAGI-1-dev6-adaptive
41
+ conda activate magi
42
+ export CUDA_VISIBLE_DEVICES=0
43
+ export MASTER_ADDR=localhost
44
+ bash scripts/single_run/adaptive_t2v.sh
45
+ ```
46
+
47
+ ## dev4 vs dev6 对比
48
+
49
+ ```bash
50
+ FRAMES=120 bash tools/run_compare_dev4_dev6.sh
51
+ FRAMES=240 bash tools/run_compare_dev4_dev6.sh
52
+ ```
53
+
54
+ ## 代码结构
55
+
56
+ ```
57
+ inference/pipeline/cache/
58
+ ├── motiondetailcache.py # dev4 基类(含 τ hook)
59
+ └── adaptivedetailcache.py # dev6 AdaptiveDetailCache
60
+
61
+ yaml_config/single_run/adaptive_config_best.yaml
62
+ scripts/single_run/adaptive_t2v.sh
63
+ tools/run_compare_dev4_dev6.sh
64
+ ```
65
+
66
+ 其余 sparse forward、KV cache、integrate 逻辑与 dev4 完全一致。
FlowCache/FlowCache4MAGI-1-dev6-adaptive/README_MOTIONCACHE.md ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # MotionCache on MAGI-1 (dev3-motion)
2
+
3
+ 基于 [FlowCache4MAGI-1](../FlowCache4MAGI-1) 的 **MotionCache** 复现分支,对应论文:
4
+
5
+ > Xu et al., 2026 — *Motion-Aware Caching for Efficient Autoregressive Video Generation*
6
+
7
+ 官方代码仓库 [ywlq/MotionCache](https://github.com/ywlq/MotionCache) 尚未发布实现,本目录依据论文方法在 MAGI-1 推理框架上完成首版复现。
8
+
9
+ ## 与 FlowCache 的核心差异
10
+
11
+ | 维度 | FlowCache | MotionCache |
12
+ |------|-----------|-------------|
13
+ | 粒度 | Chunk 级全有或全无 | Phase 2 为 Token(latent 帧×空间)级 |
14
+ | 跳过策略 | 相对 L1 累积阈值 | 运动重要性加权累积 |
15
+ | 调度 | 单一 chunk-wise 策略 | 两阶段 coarse-to-fine |
16
+
17
+ ### 算法概要
18
+
19
+ 1. **全局 Warm-up(m 步)**:前 `warmup_steps` 步禁止 cache reuse
20
+ 2. **Phase 1(K 步)**:chunk-wise 二值决策,与 FlowCache 相同
21
+ 3. **Phase 2**:基于帧间 latent 差计算运动重要性 `M`,经 soft-mapping 得到权重 `W ∈ [α, 1]`
22
+ 4. **Token 累积**:`A[p] += W[p] · Δ_chunk`,当 `A[p] > τ` 时该 token 触发 DiT 计算
23
+ 5. **Integrate**:active token 正常积分;inactive token 复用缓存 residual
24
+
25
+ ### MAGI-1 默认超参(论文 Appendix C)
26
+
27
+ | 参数 | 值 | 说明 |
28
+ |------|-----|------|
29
+ | `alpha` | 0.5 | 静态区域权重下限 |
30
+ | `phase1_steps` (K) | 9 | chunk-wise 阶段持续步数 |
31
+ | `warmup_steps` (m) | 5 | 全局禁止 reuse 的步数 |
32
+ | `rel_l1_thresh` (τ) | 0.015 (slow) / 0.025 (fast) | token 累积阈值 |
33
+
34
+ ## 快速运行
35
+
36
+ ```bash
37
+ cd FlowCache4MAGI-1-dev3-motion
38
+
39
+ # MotionCache-slow(论文 Table 1 配置)
40
+ bash scripts/single_run/motioncache_t2v.sh
41
+
42
+ # MotionCache-fast
43
+ MOTIONCACHE_CONFIG=yaml_config/single_run/motioncache_config_fast.yaml \
44
+ bash scripts/single_run/motioncache_t2v.sh
45
+ ```
46
+
47
+ 需先按 FlowCache4MAGI-1 说明安装依赖并下载 MAGI-1 权重(`downloads/` 目录可通过软链接指向原项目)。
48
+
49
+ ## 代码结构
50
+
51
+ ```
52
+ inference/pipeline/
53
+ ├── motioncache.py # 入口与 forward/integrate monkey-patch
54
+ └── cache/
55
+ ├── motioncache.py # MotionWiseCache 核心逻辑
56
+ └── sparse_utils.py # Phase 2 gather/scatter 与 sparse meta_args
57
+
58
+ inference/model/dit/dit_module.py # sparse KV cache 写入 + flash_attn 稀疏 q 分支
59
+ inference/common/dataclass.py # ModelMetaArgs.sparse_active_indices
60
+
61
+ yaml_config/single_run/
62
+ ├── motioncache_config.yaml # slow 配置
63
+ └── motioncache_config_fast.yaml
64
+ ```
65
+
66
+ ## 当前实现说明(严格对齐论文 §5.3 Phase 2)
67
+
68
+ - **Phase 1(前 K 个 denoise step / chunk)**:与 FlowCache 完全一致的 chunk-wise 策略(已验证 PSNR=∞)
69
+ - **Phase 2 入口**:每个 chunk 的第 K 步强制全量计算,建立 token-wise 阶段的 residual 基准
70
+ - **Phase 2 运动感知累积**:latent 帧间差 → soft-mapping 权重 W → 累积器 A;`A > τ` 的 token 为 active
71
+ - **Phase 2 稀疏 forward(论文 5.3)**:
72
+ - 全部 inactive → 跳过 DiT forward,复用 chunk residual
73
+ - 部分 active → **gather active patch tokens → compact DiT forward → scatter 回完整序列**
74
+ - KV cache 仅更新 active 位置(`_compresskv_adjust_key_and_value` sparse 分支)
75
+ - integrate 时 active token 正常积分,inactive token 复用 `previous_residual`
76
+ - **运动 proxy**:latent 空间帧间 L1 差(论文 Eq. 9-10)
77
+ - **跨 chunk 连续性**:chunk 首帧与上一 chunk 末帧比较
78
+
79
+ ### 验证结果(`a woman dancing.`,240×720×720,vs FlowCache baseline)
80
+
81
+ | 运行 | PSNR | 说明 |
82
+ |------|------|------|
83
+ | phase1only | ∞ | 与 FlowCache 逐像素一致 |
84
+ | sparse2(论文对齐 sparse forward) | **20.44 dB** | 无黑帧,reuse_rate≈15.6% |
85
+ | final(整 chunk fallback) | 20.48 dB | 画质等价,推理慢 ~14% |
86
+
87
+ sparse2 日志示例:`active_ratio=1.51%` 时仍走 gather/scatter 稀疏路径;`active_ratio=0%` 时 `skip_forward=True`。
88
+
89
+ ## 参考
90
+
91
+ - FlowCache: chunk-wise cache + KV compression
92
+ - MotionCache 论文预期 MAGI-1 加速:slow 1.64×,fast 2.07×(Table 1)
FlowCache/FlowCache4MAGI-1-dev6-adaptive/README_MOTIONDETAIL.md ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # MotionDetailCache on MAGI-1 (dev4-detail)
2
+
3
+ 基于 [FlowCache4MAGI-1-dev3-motion](../FlowCache4MAGI-1-dev3-motion) 的扩展分支,在 MotionCache 的 **motion 度量** 之外,增加 **spatial detail 度量**,Phase 2 active token 由两者共同决定。
4
+
5
+ ## 与 dev3 (MotionCache) 的差异
6
+
7
+ | 维度 | dev3 MotionCache | dev4 MotionDetailCache |
8
+ |------|------------------|------------------------|
9
+ | Phase 2 权重 | 仅 motion 权重 W_m | motion W_m + detail W_d 融合 |
10
+ | Detail proxy | — | latent 局部 k×k 空间方差 |
11
+ | 适用场景 | 运动区域优先计算 | 静止纹理/边缘/语义细节也优先保留 |
12
+
13
+ ## Detail 度量
14
+
15
+ 对每个 latent 像素 `(t, h, w)`:
16
+
17
+ 1. 通道聚合幅度:`mag = mean(|x|, dim=C)` → `[N, T, H, W]`
18
+ 2. 局部空间方差:在 `detail_window_size×detail_window_size` 窗口内计算 `Var(mag)`
19
+ 3. Soft-mapping:帧内 min-max 归一化 → `W_d ∈ [detail_alpha, 1]`
20
+
21
+ 高方差区域对应边缘、纹理、物体边界等 heterogeneous 邻域。
22
+
23
+ ## Motion + Detail 融合
24
+
25
+ ```
26
+ W_combined = combine(W_motion, W_detail)
27
+ A[p] += W_combined[p] · Δ_chunk
28
+ active[p] = A[p] > τ
29
+ ```
30
+
31
+ `weight_combine_mode`(默认 `max`):
32
+
33
+ | 模式 | 公式 | 特点 |
34
+ |------|------|------|
35
+ | `max` | max(W_m, W_d) | 运动或细节任一显著即可加速累积(推荐) |
36
+ | `product` | W_m × W_d | 两者同时高才快速激活,更激进 reuse |
37
+ | `blend` | (1-λ)W_m + λW_d | 线性权衡,λ=`detail_lambda` |
38
+
39
+ ## 默认超参
40
+
41
+ 继承 dev3 的 motion 参数,并新增:
42
+
43
+ | 参数 | 默认值 | 说明 |
44
+ |------|--------|------|
45
+ | `detail_alpha` | 0.5 | detail 权重下限 |
46
+ | `detail_window_size` | 3 | 局部方差窗口(奇数) |
47
+ | `detail_lambda` | 0.5 | blend 模式下的 detail 权重 |
48
+ | `weight_combine_mode` | max | 融合方式 |
49
+
50
+ ## 快速运行
51
+
52
+ ```bash
53
+ cd FlowCache4MAGI-1-dev4-detail
54
+ conda activate magi
55
+ export CUDA_VISIBLE_DEVICES=0
56
+ export MASTER_ADDR=localhost
57
+ bash scripts/single_run/motiondetail_t2v.sh
58
+ ```
59
+
60
+ ## 代码结构
61
+
62
+ ```
63
+ inference/pipeline/cache/
64
+ ├── motioncache.py # dev3 基类 MotionWiseCache
65
+ └── motiondetailcache.py # dev4 MotionDetailCache
66
+
67
+ yaml_config/single_run/motiondetail_config.yaml
68
+ scripts/single_run/motiondetail_t2v.sh
69
+ ```
70
+
71
+ 其余 sparse forward、KV cache、integrate 逻辑与 dev3 完全一致。
FlowCache/FlowCache4MAGI-1-dev6-adaptive/requirements.txt ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ accelerate==0.32.1
2
+ beautifulsoup4==4.13.4
3
+ debugpy==1.8.14
4
+ diffusers==0.29.2
5
+ einops>=0.6.0
6
+ ffmpeg-python
7
+ # flash-attn==2.4.2
8
+ flashinfer-python==0.2.0.post2 --extra-index-url https://flashinfer.ai/whl/cu124/torch2.4/
9
+ ftfy==6.2.0
10
+ gpustat==1.1.1
11
+ imageio==2.34.0
12
+ imageio[ffmpeg]
13
+ matplotlib==3.10.1
14
+ numpy==1.26.4
15
+ protobuf==5.28.3
16
+ rich==14.0.0
17
+ sentencepiece==0.2.0
18
+ timm==1.0.15
19
+ torchdiffeq==0.2.4
20
+ transformers==4.42.3
21
+ tqdm
FlowCache/FlowCache4MAGI-1-dev6-adaptive/sample_video.py ADDED
@@ -0,0 +1,429 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 MAGI Authors. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import os
16
+ import re
17
+ import sys
18
+ import argparse
19
+ import csv
20
+ import subprocess
21
+ from pathlib import Path
22
+
23
+ import multiprocessing as mp
24
+
25
+ # Constants
26
+ DEFAULT_BASE_PORT = 29510
27
+ PHYSICSIQ_FPS = 24
28
+
29
+
30
+ def resolve_gpu_ids(gpus_config) -> list[int]:
31
+ """Resolve explicit GPU IDs or auto-detect all currently visible GPUs."""
32
+ if isinstance(gpus_config, int):
33
+ return [gpus_config]
34
+
35
+ gpus_text = str(gpus_config).strip()
36
+ if not gpus_text:
37
+ raise ValueError("'gpus' must not be empty")
38
+
39
+ if gpus_text.lower() not in {"all", "auto"}:
40
+ return [int(item.strip()) for item in gpus_text.split(",") if item.strip()]
41
+
42
+ visible_devices = os.environ.get("CUDA_VISIBLE_DEVICES")
43
+ if visible_devices:
44
+ visible = [item.strip() for item in visible_devices.split(",") if item.strip()]
45
+ if visible and all(item.isdigit() for item in visible):
46
+ return [int(item) for item in visible]
47
+
48
+ try:
49
+ output = subprocess.check_output(
50
+ ["nvidia-smi", "--query-gpu=index", "--format=csv,noheader,nounits"],
51
+ text=True,
52
+ timeout=10,
53
+ )
54
+ gpu_ids = [int(line.strip()) for line in output.splitlines() if line.strip()]
55
+ if gpu_ids:
56
+ return gpu_ids
57
+ except Exception:
58
+ pass
59
+
60
+ try:
61
+ import torch
62
+
63
+ count = torch.cuda.device_count()
64
+ if count > 0:
65
+ return list(range(count))
66
+ except Exception:
67
+ pass
68
+
69
+ raise RuntimeError("No CUDA GPUs detected for gpus: all")
70
+
71
+
72
+ def load_yaml_config(yaml_path: str) -> dict:
73
+ """Load configuration from YAML file."""
74
+ import yaml
75
+
76
+ with open(yaml_path, "r") as f:
77
+ return yaml.safe_load(f)
78
+
79
+
80
+ def apply_slice(items: list, start: int | None, end: int | None) -> list:
81
+ """Apply start/end slice to a list with bounds checking."""
82
+ if start is None and end is None:
83
+ return items
84
+
85
+ slice_start = max(0, start if start is not None else 0)
86
+ slice_end = min(end if end is not None else len(items), len(items))
87
+ slice_end = max(slice_start, slice_end)
88
+
89
+ return items[slice_start:slice_end]
90
+
91
+
92
+ def configure_teacache(transport, config: dict) -> None:
93
+ """Configure TeaCache reuse strategy on SampleTransport."""
94
+ from inference.pipeline.teacache import setup_teacache
95
+
96
+ setup_teacache(
97
+ rel_l1_thresh=config["rel_l1_thresh"],
98
+ warmup_steps=config["warmup_steps"],
99
+ log=config.get("log", False),
100
+ )
101
+
102
+
103
+ def configure_kv_cache(transport, config: dict) -> None:
104
+ """Configure KV cache compression if enabled."""
105
+ if not config.get("compress_kv_cache", False):
106
+ transport.compress_kv_cache = False
107
+ return
108
+
109
+ print("KV cache compression is enabled.")
110
+ transport.compress_kv_cache = True
111
+
112
+ assert config.get("total_cache_chunk_nums") is not None
113
+
114
+ compression_config = {
115
+ "method_config": {
116
+ "compress_strategy": config["compress_strategy"],
117
+ "mix_lambda": config["mix_lambda"],
118
+ "query_granularity": config["query_granularity"],
119
+ "score_weighting_method": config.get("score_weighting_method") or "no_weight",
120
+ "power": config.get("power", 3),
121
+ },
122
+ }
123
+
124
+ from inference.pipeline.kvcompress import replace_magi
125
+
126
+ replace_magi(compression_config)
127
+
128
+
129
+ def configure_flowcache(transport, config: dict) -> None:
130
+ """Configure FlowCache reuse strategy on SampleTransport."""
131
+ from inference.pipeline.flowcache import setup_flowcache
132
+
133
+ configure_kv_cache(transport, config)
134
+
135
+ setup_flowcache(
136
+ rel_l1_thresh=config["rel_l1_thresh"],
137
+ warmup_steps=config["warmup_steps"],
138
+ discard_nearly_clean_chunk=config.get("discard_nearly_clean_chunk", False),
139
+ log=config.get("log", False),
140
+ total_cache_chunk_nums=config.get("total_cache_chunk_nums", 5),
141
+ compress_kv_cache=config.get("compress_kv_cache", False),
142
+ )
143
+
144
+
145
+ def configure_reuse_strategy(config: dict) -> None:
146
+ """Configure the appropriate reuse strategy on SampleTransport."""
147
+ from inference.pipeline.video_generate import SampleTransport
148
+
149
+ strategy = config["reuse_strategy"]
150
+
151
+ if strategy == "original":
152
+ return
153
+ if strategy == "all":
154
+ configure_teacache(SampleTransport, config)
155
+ elif strategy == "chunkwise":
156
+ configure_flowcache(SampleTransport, config)
157
+ else:
158
+ raise ValueError(f"Unknown reuse strategy: {strategy}")
159
+
160
+
161
+ def setup_environment(gpu_id: int) -> None:
162
+ """Set up environment variables for a GPU worker process."""
163
+ os.environ["CUDA_VISIBLE_DEVICES"] = str(gpu_id)
164
+ os.environ["WORLD_SIZE"] = "1"
165
+ os.environ["RANK"] = "0"
166
+ os.environ["LOCAL_RANK"] = "0"
167
+ os.environ["MASTER_ADDR"] = "localhost"
168
+ os.environ["MASTER_PORT"] = str(DEFAULT_BASE_PORT + gpu_id)
169
+
170
+ # Enable pdb terminal debugging
171
+ sys.stdin = open(0)
172
+
173
+
174
+ def filter_existing_samples(samples: list, config: dict) -> list:
175
+ """Filter out samples whose output files already exist."""
176
+ if config["benchmark"] == "vbench":
177
+ return [
178
+ sample
179
+ for sample in samples
180
+ if not os.path.exists(os.path.abspath(os.path.join(config["save_path"], f"{sample}-0.mp4")))
181
+ ]
182
+ else: # physicsiq
183
+ return [
184
+ sample for sample in samples if not os.path.exists(sample["output_path"])
185
+ ]
186
+
187
+
188
+ def assign_samples_to_gpu(
189
+ samples: list, gpu_id: int, rank: int, num_gpus: int
190
+ ) -> list:
191
+ """Divide samples across GPUs and return the subset for this GPU."""
192
+ samples_per_gpu = (len(samples) + num_gpus - 1) // num_gpus
193
+ start_idx = rank * samples_per_gpu
194
+ end_idx = min(start_idx + samples_per_gpu, len(samples))
195
+ return samples[start_idx:end_idx]
196
+
197
+
198
+ def process_vbench_sample(pipeline, prompt: str, config: dict, gpu_id: int) -> None:
199
+ """Process a single vbench text-to-video sample."""
200
+ output_path = os.path.abspath(os.path.join(config["save_path"], f"{prompt}-0.mp4"))
201
+
202
+ if os.path.exists(output_path):
203
+ print(f"[SKIP GPU {gpu_id}] Already exists: {output_path}")
204
+ return
205
+
206
+ print(f"[GPU {gpu_id}] Generating T2V: '{prompt}' -> {output_path}")
207
+ pipeline.run_text_to_video(prompt=prompt, output_path=output_path)
208
+ print(f"[DONE GPU {gpu_id}] Saved: {output_path}")
209
+
210
+
211
+ def process_physicsiq_sample(pipeline, sample: dict, gpu_id: int) -> None:
212
+ """Process a single PhysicsIQ video-to-video sample."""
213
+ prompt = sample["description"]
214
+ prefix_video_path = sample["prefix_video_path"]
215
+ output_path = sample["output_path"]
216
+
217
+ if not os.path.exists(prefix_video_path):
218
+ print(f"[WARN GPU {gpu_id}] Conditioning video not found: {prefix_video_path}")
219
+ return
220
+
221
+ if os.path.exists(output_path):
222
+ print(f"[SKIP GPU {gpu_id}] Already exists: {output_path}")
223
+ return
224
+
225
+ print(f"[GPU {gpu_id}] Generating V2V: '{prompt}'")
226
+ print(f" Input: {prefix_video_path}")
227
+ print(f" Output: {output_path}")
228
+
229
+ pipeline.run_video_to_video(
230
+ prompt=prompt,
231
+ prefix_video_path=prefix_video_path,
232
+ output_path=output_path,
233
+ )
234
+ print(f"[DONE GPU {gpu_id}] Saved: {output_path}")
235
+
236
+
237
+ def worker_process(gpu_id: int, rank: int, config: dict, all_samples: list) -> None:
238
+ """Independent worker running on each GPU."""
239
+ setup_environment(gpu_id)
240
+ configure_reuse_strategy(config)
241
+
242
+ try:
243
+ magi_root = subprocess.check_output(
244
+ ["git", "rev-parse", "--show-toplevel"]
245
+ ).decode().strip()
246
+ os.environ["MAGI_ROOT"] = magi_root
247
+ os.environ["PYTHONPATH"] = f"{magi_root}:{os.environ.get('PYTHONPATH', '')}"
248
+ except Exception as e:
249
+ print(f"[GPU {gpu_id}] Failed to set MAGI_ROOT: {e}")
250
+ return
251
+
252
+ filtered_samples = filter_existing_samples(all_samples, config)
253
+
254
+ if not filtered_samples:
255
+ print(f"[GPU {gpu_id}] No samples need to be generated.")
256
+ return
257
+
258
+ print(f"Processing {len(filtered_samples)} samples.")
259
+
260
+ my_samples = assign_samples_to_gpu(
261
+ filtered_samples, gpu_id, rank, config["num_gpus"]
262
+ )
263
+
264
+ if not my_samples:
265
+ print(f"[GPU {gpu_id}] No samples assigned.")
266
+ return
267
+
268
+ print(f"[GPU {gpu_id}] Assigned {len(my_samples)} samples")
269
+
270
+ from inference.pipeline.entry import MagiPipeline
271
+
272
+ print(f"[GPU {gpu_id}] Loading model...")
273
+ pipeline = MagiPipeline(config["config_file"])
274
+ print(f"[GPU {gpu_id}] Model loaded.")
275
+
276
+ process_func = (
277
+ process_vbench_sample if config["benchmark"] == "vbench" else process_physicsiq_sample
278
+ )
279
+
280
+ for sample in my_samples:
281
+ process_func(pipeline, sample, config, gpu_id)
282
+
283
+ print(f"[GPU {gpu_id}] Completed.")
284
+
285
+
286
+ def build_conditioning_video_path(
287
+ data_root: str, vid_id: str, scenario: str, fps: int
288
+ ) -> str:
289
+ """Construct the path to the conditioning video file."""
290
+ conditioning_dir = os.path.join(
291
+ data_root, "physics-IQ-benchmark", "split-videos", "conditioning", f"{fps}FPS"
292
+ )
293
+ match_suffix = re.search(r"_(.*)", scenario)
294
+ suffix = match_suffix.group(1) if match_suffix else ""
295
+ filename = f"{vid_id}_conditioning-videos_{fps}FPS_{suffix}"
296
+ return os.path.join(conditioning_dir, filename)
297
+
298
+
299
+ def load_physicsiq_samples(config: dict) -> list[dict]:
300
+ """Load sample list from PhysicsIQ dataset."""
301
+ data_root = config["physicsiq_data_dir"]
302
+ descriptions_csv = os.path.join(data_root, "descriptions", "descriptions.csv")
303
+ output_dir = config["save_path"]
304
+
305
+ if not os.path.exists(descriptions_csv):
306
+ raise FileNotFoundError(f"descriptions.csv not found at {descriptions_csv}")
307
+
308
+ os.makedirs(output_dir, exist_ok=True)
309
+
310
+ samples = []
311
+ with open(descriptions_csv, mode="r") as f:
312
+ reader = csv.DictReader(f)
313
+ for row in reader:
314
+ scenario = row["scenario"].strip()
315
+ match_id = re.match(r"^(\d+)_", scenario)
316
+
317
+ if not match_id:
318
+ print(f"Cannot extract ID from scenario: {scenario}")
319
+ continue
320
+
321
+ vid_id = match_id.group(1).zfill(4)
322
+ description = row["description"]
323
+ generated_video_name = row["generated_video_name"]
324
+ prefix_video_path = build_conditioning_video_path(
325
+ data_root, vid_id, scenario, PHYSICSIQ_FPS
326
+ )
327
+ output_path = os.path.join(output_dir, generated_video_name)
328
+
329
+ os.makedirs(os.path.dirname(output_path), exist_ok=True)
330
+
331
+ samples.append({
332
+ "vid_id": vid_id,
333
+ "scenario": scenario,
334
+ "description": description,
335
+ "generated_video_name": generated_video_name,
336
+ "prefix_video_path": prefix_video_path,
337
+ "output_path": output_path,
338
+ })
339
+
340
+ # PhysicsIQ samples are duplicated; take only the first half
341
+ unique_count = len(samples) // 2
342
+ samples = samples[:unique_count]
343
+
344
+ print(f"Loaded {unique_count} PhysicsIQ samples.")
345
+
346
+ return apply_slice(samples, config.get("start"), config.get("end"))
347
+
348
+
349
+ def load_vbench_samples(config: dict) -> list[str]:
350
+ """Load prompt list from vbench dimension file."""
351
+ prompt_dir = config["vbench_prompt_dir"]
352
+ dimension = config.get("dimension")
353
+
354
+ if not dimension:
355
+ raise ValueError("For vbench, 'dimension' must be specified in config")
356
+
357
+ prompt_file = os.path.join(prompt_dir, f"{dimension}.txt")
358
+
359
+ if not os.path.exists(prompt_file):
360
+ raise FileNotFoundError(f"Prompt file not found: {prompt_file}")
361
+
362
+ with open(prompt_file, "r") as f:
363
+ prompts = [line.strip() for line in f if line.strip()]
364
+
365
+ return apply_slice(prompts, config.get("start"), config.get("end"))
366
+
367
+
368
+ def setup_save_path(config: dict) -> None:
369
+ """Configure the output save path based on benchmark type."""
370
+ base_path = config["base_save_path"]
371
+
372
+ if config["benchmark"] == "vbench":
373
+ dimension = config.get("dimension")
374
+ videos_dir = os.path.join(base_path, "videos", dimension) if dimension else None
375
+ config["save_path"] = videos_dir if videos_dir else os.path.join(base_path, "videos")
376
+ elif config["benchmark"] == "physicsiq":
377
+ config["save_path"] = os.path.join(base_path, "videos")
378
+
379
+ os.makedirs(config["save_path"], exist_ok=True)
380
+
381
+
382
+ def main() -> None:
383
+ """Entry point for video sampling script."""
384
+ parser = argparse.ArgumentParser(
385
+ description="Video sampling script using YAML configuration"
386
+ )
387
+ parser.add_argument("yaml_config", type=str, help="Path to YAML configuration file")
388
+ args = parser.parse_args()
389
+
390
+ config = load_yaml_config(args.yaml_config)
391
+ print(f"Loaded configuration from: {args.yaml_config}")
392
+
393
+ setup_save_path(config)
394
+
395
+ gpu_ids = resolve_gpu_ids(config["gpus"])
396
+ config["num_gpus"] = len(gpu_ids)
397
+
398
+ benchmark = config["benchmark"]
399
+ if benchmark == "vbench":
400
+ all_samples = load_vbench_samples(config)
401
+ elif benchmark == "physicsiq":
402
+ data_root = config["physicsiq_data_dir"]
403
+ if not os.path.exists(data_root):
404
+ raise FileNotFoundError(f"Data directory not found: {data_root}")
405
+ all_samples = load_physicsiq_samples(config)
406
+ else:
407
+ raise ValueError(f"Invalid benchmark: {benchmark}")
408
+
409
+ print(f"Total samples: {len(all_samples)}")
410
+ print(f"GPUs: {gpu_ids}")
411
+ print(f"Output: {config['save_path']}")
412
+ print(f"Config: {config['config_file']}")
413
+
414
+ processes = []
415
+ for rank, gpu_id in enumerate(gpu_ids):
416
+ p = mp.Process(target=worker_process, args=(gpu_id, rank, config, all_samples))
417
+ p.start()
418
+ processes.append(p)
419
+
420
+ for p in processes:
421
+ p.join()
422
+
423
+ failed = [p.exitcode for p in processes if p.exitcode != 0]
424
+ if failed:
425
+ raise RuntimeError(f"{len(failed)} worker process(es) failed with exit codes: {failed}")
426
+
427
+
428
+ if __name__ == "__main__":
429
+ main()
FlowCache/FlowCache4MAGI-1/README.md ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # FLOW CACHING FOR AUTOREGRESSIVE VIDEO GENERATION
2
+
3
+ This repository provides the official implementation of **FlowCache** on **MAGI-1** model, a caching-based acceleration method for autoregressive video generation models.
4
+
5
+
6
+ ## 🚀 Installation
7
+
8
+ Please follow the installation instructions provided in the [MAGI-1](https://github.com/SandAI-org/MAGI-1), as this implementation is built on top of MAGI-1.
9
+
10
+ ---
11
+
12
+ ## ▶️ Usage
13
+
14
+ ### 1. Single Video Generation
15
+
16
+ Run accelerated generation using FlowCache:
17
+
18
+ ```bash
19
+ # FlowCache for text-to-video generation
20
+ bash scripts/single_run/flowcache_t2v.sh
21
+
22
+ # FlowCache for video-to-video generation
23
+ bash scripts/single_run/flowcache_v2v.sh
24
+
25
+ # Baseline acceleration method (TeaCache) for text-to-video
26
+ bash scripts/single_run/teacache_t2v.sh
27
+
28
+ # Baseline acceleration method (TeaCache) for video-to-video
29
+ bash scripts/single_run/teacache_v2v.sh
30
+ ```
31
+
32
+ ### 2. Benchmark Sampling
33
+
34
+ Generate videos for evaluation on standard benchmarks:
35
+
36
+ ```bash
37
+ # VBench
38
+ bash scripts/sample/flowcache_vbench.sh
39
+ bash scripts/sample/teacache_vbench.sh
40
+
41
+ # PhysicsIQ
42
+ bash scripts/sample/flowcache_physicsiq.sh
43
+ bash scripts/sample/teacache_physicsiq.sh
44
+ ```
45
+
46
+ ### 3. Quality Evaluation
47
+
48
+ Compute perceptual and structural similarity metrics between original and accelerated generations:
49
+
50
+ ```bash
51
+ bash scripts/metric.sh
52
+ ```
53
+
54
+ ---
55
+
56
+ ## ⚙️ Key Parameters
57
+
58
+ | Parameter | Description |
59
+ |----------|-------------|
60
+ | `rel_l1_thresh` | Relative L1 distance threshold for cache reuse decision |
61
+ | ` warmup_steps` | Number of denoising steps where reuse is disabled |
62
+ | `total_cache_chunk_nums` (`B_total`) | Total number of cache chunks maintained |
63
+ | `compress_strategy` | Granularity for selecting important KV caches: `token`, `frame`, or `chunk` |
64
+ | `query_granularity` | Granularity for importance scoring: `token`, `frame`, or `chunk` |
65
+ | `mix_lambda` | Weight balancing importance and redundancy (default: `0.07`) |
66
+ | `mode` | Generation mode: `t2v` (text-to-video), `i2v` (image-to-video), or `v2v` (video-to-video) |
67
+ | `prompt` | Input prompt for conditional generation |
68
+ | `output_path` | Path to save generated videos |
69
+ | `config_file` | Path to MAGI-1 model configuration |
70
+
71
+ ---
FlowCache/FlowCache4MAGI-1/__pycache__/sample_video.cpython-312.pyc ADDED
Binary file (19.7 kB). View file
 
FlowCache/FlowCache4MAGI-1/inference/__init__.py ADDED
File without changes
FlowCache/FlowCache4MAGI-1/logs/flowcache_vbench_20260520_103113.log ADDED
@@ -0,0 +1,181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 🚀 Starting multi-GPU benchmark sampling
2
+ 🔢 Total dimensions to process: 3
3
+ 📋 Dimensions: overall_consistency subject_consistency scene
4
+ 🔍 Processing dimension: overall_consistency
5
+ Loaded configuration from: yaml_config/sample/flowcache_vbench.yaml.tmp
6
+ Total samples: 93
7
+ GPUs: [0]
8
+ Output: outputs/vbench/videos/overall_consistency
9
+ Config: config/sample/vbench.json
10
+ /home/dyvm6xra/dyvm6xrauser11/miniforge3/envs/magi/lib/python3.10/site-packages/timm/models/layers/__init__.py:48: FutureWarning: Importing from timm.models.layers is deprecated, please import via timm.layers
11
+ warnings.warn(f"Importing from {__name__} is deprecated, please import via timm.layers", FutureWarning)
12
+ [W520 10:31:24.093345214 CUDAAllocatorConfig.h:28] Warning: expandable_segments not supported on this platform (function operator())
13
+ [2026-05-20 10:31:24,656 - INFO] Initialize torch distribution and model parallel successfully
14
+ [2026-05-20 10:31:24,656 - INFO] MagiConfig(model_config=ModelConfig(model_name='videodit_ardf', num_layers=34, hidden_size=3072, ffn_hidden_size=12288, num_attention_heads=24, num_query_groups=8, kv_channels=128, layernorm_epsilon=1e-06, apply_layernorm_1p=True, x_rescale_factor=1, half_channel_vae=False, params_dtype=torch.bfloat16, patch_size=2, t_patch_size=1, in_channels=16, out_channels=16, cond_hidden_ratio=0.25, caption_channels=4096, caption_max_length=800, xattn_cond_hidden_ratio=1.0, cond_gating_ratio=1.0, gated_linear_unit=False), runtime_config=RuntimeConfig(cfg_number=1, cfg_t_range=[0.0, 0.0217, 0.1, 0.3, 0.999], prev_chunk_scales=[1.5, 1.5, 1.5, 1.0, 1.0], text_scales=[7.5, 7.5, 7.5, 0.0, 0.0], noise2clean_kvrange=[], clean_chunk_kvrange=1, clean_t=0.9999, seed=1234, num_frames=240, video_size_h=720, video_size_w=720, num_steps=16, window_size=4, fps=24, chunk_width=6, t5_pretrained='./downloads/t5_pretrained', t5_device='cuda', vae_pretrained='./downloads/vae', scale_factor=0.18215, temporal_downsample_factor=4, load='./downloads/4.5B_distill'), engine_config=EngineConfig(distributed_backend='nccl', distributed_timeout_minutes=15, pp_size=1, cp_size=1, cp_strategy='none', ulysses_overlap_degree=1, fp8_quant=False, distill_nearly_clean_chunk_threshold=0.3, shortcut_mode='8,16,16', distill=True, kv_offload=True, enable_cuda_graph=False))
15
+ [2026-05-20 10:31:24,657 - INFO] Precompute validation prompt embeddings
16
+ You are using the default legacy behaviour of the <class 'transformers.models.t5.tokenization_t5.T5Tokenizer'>. This is expected, and simply means that the `legacy` (previous) behavior will be used so nothing changes for you. If you want to use the new behaviour, set `legacy=False`. This should only be set if you understand what it means, and thoroughly read the reason why this was added as explained in https://github.com/huggingface/transformers/pull/24565
17
+ KV cache compression is enabled.
18
+ Processing 93 samples.
19
+ [GPU 0] Assigned 93 samples
20
+ [GPU 0] Loading model...
21
+ [GPU 0] Model loaded.
22
+ [GPU 0] Generating T2V: 'Close up of grapes on a rotating table.' -> /home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/outputs/vbench/videos/overall_consistency/Close up of grapes on a rotating table.-0.mp4
23
+
24
+ [2026-05-20 10:32:58,161 - INFO] (cp, pp) rank (0, 0): param count 4459898128, model size 8.34 GB
25
+ [2026-05-20 10:32:58,161 - INFO] Build DiTModel successfully
26
+ [2026-05-20 10:32:58,161 - INFO] After build_dit_model, memory allocated: 0.04 GB, memory reserved: 0.08 GB
27
+ [2026-05-20 10:32:58,161 - INFO] load inference_weight.distill weight from ./downloads/4.5B_distill/inference_weight.distill
28
+
29
+ [2026-05-20 10:33:20,857 - INFO] Load Weight Missing Keys: []
30
+ [2026-05-20 10:33:20,857 - INFO] Load Weight Unexpected Keys: []
31
+ [2026-05-20 10:33:21,087 - INFO] After load_checkpoint, memory allocated: 8.39 GB, memory reserved: 8.40 GB
32
+ [2026-05-20 10:33:21,089 - INFO] After high_precision_promoter, memory allocated: 8.39 GB, memory reserved: 8.40 GB
33
+ [2026-05-20 10:33:21,184 - INFO] Load checkpoint successfully
34
+ [2026-05-20 10:33:21,184 - INFO] Begin to generate per chunk
35
+ [2026-05-20 10:33:21,184 - INFO] special_token = ['HQ_TOKEN', 'DURATION_TOKEN']
36
+
37
+ Process Process-1:
38
+ Traceback (most recent call last):
39
+ File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/envs/magi/lib/python3.10/multiprocessing/process.py", line 314, in _bootstrap
40
+ self.run()
41
+ File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/envs/magi/lib/python3.10/multiprocessing/process.py", line 108, in run
42
+ self._target(*self._args, **self._kwargs)
43
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 259, in worker_process
44
+ process_func(pipeline, sample, config, gpu_id)
45
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 185, in process_vbench_sample
46
+ pipeline.run_text_to_video(prompt=prompt, output_path=output_path)
47
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/pipeline.py", line 38, in run_text_to_video
48
+ self._run(prompt, None, output_path)
49
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/pipeline.py", line 52, in _run
50
+ [
51
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/pipeline.py", line 52, in <listcomp>
52
+ [
53
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/video_generate.py", line 1129, in generate_per_chunk
54
+ for _, _, chunk in sample_transport.walk():
55
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/video_generate.py", line 1079, in walk
56
+ velocity = self.forward_velocity(infer_idx, 0)
57
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/flowcache.py", line 93, in flowcache_forward_velocity
58
+ cache = SampleTransport.cache_reuse_manager
59
+ AttributeError: type object 'SampleTransport' has no attribute 'cache_reuse_manager'
60
+
61
+ ✅ Completed: overall_consistency
62
+ ---
63
+ 🔍 Processing dimension: subject_consistency
64
+ Loaded configuration from: yaml_config/sample/flowcache_vbench.yaml.tmp
65
+ Total samples: 72
66
+ GPUs: [0]
67
+ Output: outputs/vbench/videos/subject_consistency
68
+ Config: config/sample/vbench.json
69
+ /home/dyvm6xra/dyvm6xrauser11/miniforge3/envs/magi/lib/python3.10/site-packages/timm/models/layers/__init__.py:48: FutureWarning: Importing from timm.models.layers is deprecated, please import via timm.layers
70
+ warnings.warn(f"Importing from {__name__} is deprecated, please import via timm.layers", FutureWarning)
71
+ [W520 10:33:28.974731573 CUDAAllocatorConfig.h:28] Warning: expandable_segments not supported on this platform (function operator())
72
+ [2026-05-20 10:33:28,530 - INFO] Initialize torch distribution and model parallel successfully
73
+ [2026-05-20 10:33:28,530 - INFO] MagiConfig(model_config=ModelConfig(model_name='videodit_ardf', num_layers=34, hidden_size=3072, ffn_hidden_size=12288, num_attention_heads=24, num_query_groups=8, kv_channels=128, layernorm_epsilon=1e-06, apply_layernorm_1p=True, x_rescale_factor=1, half_channel_vae=False, params_dtype=torch.bfloat16, patch_size=2, t_patch_size=1, in_channels=16, out_channels=16, cond_hidden_ratio=0.25, caption_channels=4096, caption_max_length=800, xattn_cond_hidden_ratio=1.0, cond_gating_ratio=1.0, gated_linear_unit=False), runtime_config=RuntimeConfig(cfg_number=1, cfg_t_range=[0.0, 0.0217, 0.1, 0.3, 0.999], prev_chunk_scales=[1.5, 1.5, 1.5, 1.0, 1.0], text_scales=[7.5, 7.5, 7.5, 0.0, 0.0], noise2clean_kvrange=[], clean_chunk_kvrange=1, clean_t=0.9999, seed=1234, num_frames=240, video_size_h=720, video_size_w=720, num_steps=16, window_size=4, fps=24, chunk_width=6, t5_pretrained='./downloads/t5_pretrained', t5_device='cuda', vae_pretrained='./downloads/vae', scale_factor=0.18215, temporal_downsample_factor=4, load='./downloads/4.5B_distill'), engine_config=EngineConfig(distributed_backend='nccl', distributed_timeout_minutes=15, pp_size=1, cp_size=1, cp_strategy='none', ulysses_overlap_degree=1, fp8_quant=False, distill_nearly_clean_chunk_threshold=0.3, shortcut_mode='8,16,16', distill=True, kv_offload=True, enable_cuda_graph=False))
74
+ [2026-05-20 10:33:28,530 - INFO] Precompute validation prompt embeddings
75
+ You are using the default legacy behaviour of the <class 'transformers.models.t5.tokenization_t5.T5Tokenizer'>. This is expected, and simply means that the `legacy` (previous) behavior will be used so nothing changes for you. If you want to use the new behaviour, set `legacy=False`. This should only be set if you understand what it means, and thoroughly read the reason why this was added as explained in https://github.com/huggingface/transformers/pull/24565
76
+ KV cache compression is enabled.
77
+ Processing 72 samples.
78
+ [GPU 0] Assigned 72 samples
79
+ [GPU 0] Loading model...
80
+ [GPU 0] Model loaded.
81
+ [GPU 0] Generating T2V: 'a person swimming in ocean' -> /home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/outputs/vbench/videos/subject_consistency/a person swimming in ocean-0.mp4
82
+
83
+ [2026-05-20 10:33:49,537 - INFO] (cp, pp) rank (0, 0): param count 4459898128, model size 8.34 GB
84
+ [2026-05-20 10:33:49,537 - INFO] Build DiTModel successfully
85
+ [2026-05-20 10:33:49,538 - INFO] After build_dit_model, memory allocated: 0.04 GB, memory reserved: 0.08 GB
86
+ [2026-05-20 10:33:49,538 - INFO] load inference_weight.distill weight from ./downloads/4.5B_distill/inference_weight.distill
87
+
88
+ [2026-05-20 10:33:51,253 - INFO] Load Weight Missing Keys: []
89
+ [2026-05-20 10:33:51,253 - INFO] Load Weight Unexpected Keys: []
90
+ [2026-05-20 10:33:51,770 - INFO] After load_checkpoint, memory allocated: 8.39 GB, memory reserved: 8.40 GB
91
+ [2026-05-20 10:33:51,773 - INFO] After high_precision_promoter, memory allocated: 8.39 GB, memory reserved: 8.40 GB
92
+ [2026-05-20 10:33:51,875 - INFO] Load checkpoint successfully
93
+ [2026-05-20 10:33:51,875 - INFO] Begin to generate per chunk
94
+ [2026-05-20 10:33:51,875 - INFO] special_token = ['HQ_TOKEN', 'DURATION_TOKEN']
95
+
96
+ Process Process-1:
97
+ Traceback (most recent call last):
98
+ File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/envs/magi/lib/python3.10/multiprocessing/process.py", line 314, in _bootstrap
99
+ self.run()
100
+ File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/envs/magi/lib/python3.10/multiprocessing/process.py", line 108, in run
101
+ self._target(*self._args, **self._kwargs)
102
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 259, in worker_process
103
+ process_func(pipeline, sample, config, gpu_id)
104
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 185, in process_vbench_sample
105
+ pipeline.run_text_to_video(prompt=prompt, output_path=output_path)
106
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/pipeline.py", line 38, in run_text_to_video
107
+ self._run(prompt, None, output_path)
108
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/pipeline.py", line 52, in _run
109
+ [
110
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/pipeline.py", line 52, in <listcomp>
111
+ [
112
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/video_generate.py", line 1129, in generate_per_chunk
113
+ for _, _, chunk in sample_transport.walk():
114
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/video_generate.py", line 1079, in walk
115
+ velocity = self.forward_velocity(infer_idx, 0)
116
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/flowcache.py", line 93, in flowcache_forward_velocity
117
+ cache = SampleTransport.cache_reuse_manager
118
+ AttributeError: type object 'SampleTransport' has no attribute 'cache_reuse_manager'
119
+
120
+ ✅ Completed: subject_consistency
121
+ ---
122
+ 🔍 Processing dimension: scene
123
+ Loaded configuration from: yaml_config/sample/flowcache_vbench.yaml.tmp
124
+ Total samples: 86
125
+ GPUs: [0]
126
+ Output: outputs/vbench/videos/scene
127
+ Config: config/sample/vbench.json
128
+ /home/dyvm6xra/dyvm6xrauser11/miniforge3/envs/magi/lib/python3.10/site-packages/timm/models/layers/__init__.py:48: FutureWarning: Importing from timm.models.layers is deprecated, please import via timm.layers
129
+ warnings.warn(f"Importing from {__name__} is deprecated, please import via timm.layers", FutureWarning)
130
+ [W520 10:33:58.467950462 CUDAAllocatorConfig.h:28] Warning: expandable_segments not supported on this platform (function operator())
131
+ [2026-05-20 10:33:58,023 - INFO] Initialize torch distribution and model parallel successfully
132
+ [2026-05-20 10:33:58,023 - INFO] MagiConfig(model_config=ModelConfig(model_name='videodit_ardf', num_layers=34, hidden_size=3072, ffn_hidden_size=12288, num_attention_heads=24, num_query_groups=8, kv_channels=128, layernorm_epsilon=1e-06, apply_layernorm_1p=True, x_rescale_factor=1, half_channel_vae=False, params_dtype=torch.bfloat16, patch_size=2, t_patch_size=1, in_channels=16, out_channels=16, cond_hidden_ratio=0.25, caption_channels=4096, caption_max_length=800, xattn_cond_hidden_ratio=1.0, cond_gating_ratio=1.0, gated_linear_unit=False), runtime_config=RuntimeConfig(cfg_number=1, cfg_t_range=[0.0, 0.0217, 0.1, 0.3, 0.999], prev_chunk_scales=[1.5, 1.5, 1.5, 1.0, 1.0], text_scales=[7.5, 7.5, 7.5, 0.0, 0.0], noise2clean_kvrange=[], clean_chunk_kvrange=1, clean_t=0.9999, seed=1234, num_frames=240, video_size_h=720, video_size_w=720, num_steps=16, window_size=4, fps=24, chunk_width=6, t5_pretrained='./downloads/t5_pretrained', t5_device='cuda', vae_pretrained='./downloads/vae', scale_factor=0.18215, temporal_downsample_factor=4, load='./downloads/4.5B_distill'), engine_config=EngineConfig(distributed_backend='nccl', distributed_timeout_minutes=15, pp_size=1, cp_size=1, cp_strategy='none', ulysses_overlap_degree=1, fp8_quant=False, distill_nearly_clean_chunk_threshold=0.3, shortcut_mode='8,16,16', distill=True, kv_offload=True, enable_cuda_graph=False))
133
+ [2026-05-20 10:33:58,023 - INFO] Precompute validation prompt embeddings
134
+ You are using the default legacy behaviour of the <class 'transformers.models.t5.tokenization_t5.T5Tokenizer'>. This is expected, and simply means that the `legacy` (previous) behavior will be used so nothing changes for you. If you want to use the new behaviour, set `legacy=False`. This should only be set if you understand what it means, and thoroughly read the reason why this was added as explained in https://github.com/huggingface/transformers/pull/24565
135
+ KV cache compression is enabled.
136
+ Processing 86 samples.
137
+ [GPU 0] Assigned 86 samples
138
+ [GPU 0] Loading model...
139
+ [GPU 0] Model loaded.
140
+ [GPU 0] Generating T2V: 'alley' -> /home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/outputs/vbench/videos/scene/alley-0.mp4
141
+
142
+ [2026-05-20 10:34:17,215 - INFO] (cp, pp) rank (0, 0): param count 4459898128, model size 8.34 GB
143
+ [2026-05-20 10:34:17,216 - INFO] Build DiTModel successfully
144
+ [2026-05-20 10:34:17,216 - INFO] After build_dit_model, memory allocated: 0.04 GB, memory reserved: 0.08 GB
145
+ [2026-05-20 10:34:17,216 - INFO] load inference_weight.distill weight from ./downloads/4.5B_distill/inference_weight.distill
146
+
147
+ [2026-05-20 10:34:18,927 - INFO] Load Weight Missing Keys: []
148
+ [2026-05-20 10:34:18,927 - INFO] Load Weight Unexpected Keys: []
149
+ [2026-05-20 10:34:19,154 - INFO] After load_checkpoint, memory allocated: 8.39 GB, memory reserved: 8.40 GB
150
+ [2026-05-20 10:34:19,156 - INFO] After high_precision_promoter, memory allocated: 8.39 GB, memory reserved: 8.40 GB
151
+ [2026-05-20 10:34:19,251 - INFO] Load checkpoint successfully
152
+ [2026-05-20 10:34:19,251 - INFO] Begin to generate per chunk
153
+ [2026-05-20 10:34:19,252 - INFO] special_token = ['HQ_TOKEN', 'DURATION_TOKEN']
154
+
155
+ Process Process-1:
156
+ Traceback (most recent call last):
157
+ File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/envs/magi/lib/python3.10/multiprocessing/process.py", line 314, in _bootstrap
158
+ self.run()
159
+ File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/envs/magi/lib/python3.10/multiprocessing/process.py", line 108, in run
160
+ self._target(*self._args, **self._kwargs)
161
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 259, in worker_process
162
+ process_func(pipeline, sample, config, gpu_id)
163
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 185, in process_vbench_sample
164
+ pipeline.run_text_to_video(prompt=prompt, output_path=output_path)
165
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/pipeline.py", line 38, in run_text_to_video
166
+ self._run(prompt, None, output_path)
167
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/pipeline.py", line 52, in _run
168
+ [
169
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/pipeline.py", line 52, in <listcomp>
170
+ [
171
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/video_generate.py", line 1129, in generate_per_chunk
172
+ for _, _, chunk in sample_transport.walk():
173
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/video_generate.py", line 1079, in walk
174
+ velocity = self.forward_velocity(infer_idx, 0)
175
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/flowcache.py", line 93, in flowcache_forward_velocity
176
+ cache = SampleTransport.cache_reuse_manager
177
+ AttributeError: type object 'SampleTransport' has no attribute 'cache_reuse_manager'
178
+
179
+ ✅ Completed: scene
180
+ ---
181
+ 🎉 All sampling tasks completed.
FlowCache/FlowCache4MAGI-1/logs/flowcache_vbench_20260520_121944.log ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 🚀 Starting multi-GPU benchmark sampling
2
+ 🔢 Total dimensions to process: 3
3
+ 📋 Dimensions: overall_consistency subject_consistency scene
4
+ 🔍 Processing dimension: overall_consistency
5
+ Loaded configuration from: yaml_config/sample/flowcache_vbench.yaml.tmp
6
+ Total samples: 93
7
+ GPUs: [0]
8
+ Output: outputs/vbench/videos/overall_consistency
9
+ Config: config/sample/vbench.json
10
+ /home/dyvm6xra/dyvm6xrauser11/miniforge3/envs/magi/lib/python3.10/site-packages/timm/models/layers/__init__.py:48: FutureWarning: Importing from timm.models.layers is deprecated, please import via timm.layers
11
+ warnings.warn(f"Importing from {__name__} is deprecated, please import via timm.layers", FutureWarning)
12
+ [W520 12:19:50.307116267 CUDAAllocatorConfig.h:28] Warning: expandable_segments not supported on this platform (function operator())
13
+ [2026-05-20 12:19:50,862 - INFO] Initialize torch distribution and model parallel successfully
14
+ [2026-05-20 12:19:50,862 - INFO] MagiConfig(model_config=ModelConfig(model_name='videodit_ardf', num_layers=34, hidden_size=3072, ffn_hidden_size=12288, num_attention_heads=24, num_query_groups=8, kv_channels=128, layernorm_epsilon=1e-06, apply_layernorm_1p=True, x_rescale_factor=1, half_channel_vae=False, params_dtype=torch.bfloat16, patch_size=2, t_patch_size=1, in_channels=16, out_channels=16, cond_hidden_ratio=0.25, caption_channels=4096, caption_max_length=800, xattn_cond_hidden_ratio=1.0, cond_gating_ratio=1.0, gated_linear_unit=False), runtime_config=RuntimeConfig(cfg_number=1, cfg_t_range=[0.0, 0.0217, 0.1, 0.3, 0.999], prev_chunk_scales=[1.5, 1.5, 1.5, 1.0, 1.0], text_scales=[7.5, 7.5, 7.5, 0.0, 0.0], noise2clean_kvrange=[], clean_chunk_kvrange=1, clean_t=0.9999, seed=1234, num_frames=240, video_size_h=720, video_size_w=720, num_steps=16, window_size=4, fps=24, chunk_width=6, t5_pretrained='./downloads/t5_pretrained', t5_device='cuda', vae_pretrained='./downloads/vae', scale_factor=0.18215, temporal_downsample_factor=4, load='./downloads/4.5B_distill'), engine_config=EngineConfig(distributed_backend='nccl', distributed_timeout_minutes=15, pp_size=1, cp_size=1, cp_strategy='none', ulysses_overlap_degree=1, fp8_quant=False, distill_nearly_clean_chunk_threshold=0.3, shortcut_mode='8,16,16', distill=True, kv_offload=True, enable_cuda_graph=False))
15
+ [2026-05-20 12:19:50,862 - INFO] Precompute validation prompt embeddings
16
+ You are using the default legacy behaviour of the <class 'transformers.models.t5.tokenization_t5.T5Tokenizer'>. This is expected, and simply means that the `legacy` (previous) behavior will be used so nothing changes for you. If you want to use the new behaviour, set `legacy=False`. This should only be set if you understand what it means, and thoroughly read the reason why this was added as explained in https://github.com/huggingface/transformers/pull/24565
17
+ KV cache compression is enabled.
18
+ Processing 93 samples.
19
+ [GPU 0] Assigned 93 samples
20
+ [GPU 0] Loading model...
21
+ [GPU 0] Model loaded.
22
+ [GPU 0] Generating T2V: 'Close up of grapes on a rotating table.' -> /home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/outputs/vbench/videos/overall_consistency/Close up of grapes on a rotating table.-0.mp4
23
+
24
+ [2026-05-20 12:20:08,897 - INFO] (cp, pp) rank (0, 0): param count 4459898128, model size 8.34 GB
25
+ [2026-05-20 12:20:08,897 - INFO] Build DiTModel successfully
26
+ [2026-05-20 12:20:08,897 - INFO] After build_dit_model, memory allocated: 0.04 GB, memory reserved: 0.08 GB
27
+ [2026-05-20 12:20:08,897 - INFO] load inference_weight.distill weight from ./downloads/4.5B_distill/inference_weight.distill
28
+
29
+ [2026-05-20 12:20:10,748 - INFO] Load Weight Missing Keys: []
30
+ [2026-05-20 12:20:10,748 - INFO] Load Weight Unexpected Keys: []
31
+ [2026-05-20 12:20:10,952 - INFO] After load_checkpoint, memory allocated: 8.39 GB, memory reserved: 8.40 GB
32
+ [2026-05-20 12:20:10,954 - INFO] After high_precision_promoter, memory allocated: 8.39 GB, memory reserved: 8.40 GB
33
+ [2026-05-20 12:20:11,056 - INFO] Load checkpoint successfully
34
+ [2026-05-20 12:20:11,056 - INFO] Begin to generate per chunk
35
+ [2026-05-20 12:20:11,056 - INFO] special_token = ['HQ_TOKEN', 'DURATION_TOKEN']
36
+
37
+
38
+ Traceback (most recent call last):
39
+ File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/envs/magi/lib/python3.10/multiprocessing/process.py", line 314, in _bootstrap
40
+ self.run()
41
+ File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/envs/magi/lib/python3.10/multiprocessing/process.py", line 108, in run
42
+ self._target(*self._args, **self._kwargs)
43
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 239, in worker_process
44
+ process_func(pipeline, sample, config, gpu_id)
45
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 165, in process_vbench_sample
46
+ pipeline.run_text_to_video(prompt=prompt, output_path=output_path)
47
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/pipeline.py", line 38, in run_text_to_video
48
+ self._run(prompt, None, output_path)
49
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/pipeline.py", line 52, in _run
50
+ [
51
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/pipeline.py", line 52, in <listcomp>
52
+ [
53
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/video_generate.py", line 1129, in generate_per_chunk
54
+ for _, _, chunk in sample_transport.walk():
55
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/video_generate.py", line 1092, in walk
56
+ clean_chunk, chunk_idx = self.integrate_velocity(work_status.infer_idx, work_status.cur_denoise_step)
57
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/flowcache.py", line 530, in flowcache_integrate_velocity
58
+ _check_and_compress_kv(self, infer_idx, chunk_start, transport_input)
59
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/flowcache.py", line 570, in _check_and_compress_kv
60
+ compressor.compress(
61
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/cache/kv_compressor.py", line 158, in compress
62
+ layer_result = self._compress_layer(
63
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/cache/kv_compressor.py", line 251, in _compress_layer
64
+ key_compressed, value_compressed, indices = kv_cluster.update_kv(
65
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/kvcompress/kv_compressor.py", line 52, in update_kv
66
+ return self.update_kv_token(
67
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/kvcompress/kv_compressor.py", line 168, in update_kv_token
68
+ raise ValueError(f"Unknown score weighting method: {self.score_weighting_method}")
69
+ ValueError: Unknown score weighting method: None
70
+ ✅ Completed: overall_consistency
71
+ ---
72
+ 🔍 Processing dimension: subject_consistency
73
+ Loaded configuration from: yaml_config/sample/flowcache_vbench.yaml.tmp
74
+ Total samples: 72
75
+ GPUs: [0]
76
+ Output: outputs/vbench/videos/subject_consistency
77
+ Config: config/sample/vbench.json
78
+ /home/dyvm6xra/dyvm6xrauser11/miniforge3/envs/magi/lib/python3.10/site-packages/timm/models/layers/__init__.py:48: FutureWarning: Importing from timm.models.layers is deprecated, please import via timm.layers
79
+ warnings.warn(f"Importing from {__name__} is deprecated, please import via timm.layers", FutureWarning)
80
+ [W520 12:22:42.069407203 CUDAAllocatorConfig.h:28] Warning: expandable_segments not supported on this platform (function operator())
81
+ [2026-05-20 12:22:42,624 - INFO] Initialize torch distribution and model parallel successfully
82
+ [2026-05-20 12:22:42,624 - INFO] MagiConfig(model_config=ModelConfig(model_name='videodit_ardf', num_layers=34, hidden_size=3072, ffn_hidden_size=12288, num_attention_heads=24, num_query_groups=8, kv_channels=128, layernorm_epsilon=1e-06, apply_layernorm_1p=True, x_rescale_factor=1, half_channel_vae=False, params_dtype=torch.bfloat16, patch_size=2, t_patch_size=1, in_channels=16, out_channels=16, cond_hidden_ratio=0.25, caption_channels=4096, caption_max_length=800, xattn_cond_hidden_ratio=1.0, cond_gating_ratio=1.0, gated_linear_unit=False), runtime_config=RuntimeConfig(cfg_number=1, cfg_t_range=[0.0, 0.0217, 0.1, 0.3, 0.999], prev_chunk_scales=[1.5, 1.5, 1.5, 1.0, 1.0], text_scales=[7.5, 7.5, 7.5, 0.0, 0.0], noise2clean_kvrange=[], clean_chunk_kvrange=1, clean_t=0.9999, seed=1234, num_frames=240, video_size_h=720, video_size_w=720, num_steps=16, window_size=4, fps=24, chunk_width=6, t5_pretrained='./downloads/t5_pretrained', t5_device='cuda', vae_pretrained='./downloads/vae', scale_factor=0.18215, temporal_downsample_factor=4, load='./downloads/4.5B_distill'), engine_config=EngineConfig(distributed_backend='nccl', distributed_timeout_minutes=15, pp_size=1, cp_size=1, cp_strategy='none', ulysses_overlap_degree=1, fp8_quant=False, distill_nearly_clean_chunk_threshold=0.3, shortcut_mode='8,16,16', distill=True, kv_offload=True, enable_cuda_graph=False))
83
+ [2026-05-20 12:22:42,625 - INFO] Precompute validation prompt embeddings
84
+ You are using the default legacy behaviour of the <class 'transformers.models.t5.tokenization_t5.T5Tokenizer'>. This is expected, and simply means that the `legacy` (previous) behavior will be used so nothing changes for you. If you want to use the new behaviour, set `legacy=False`. This should only be set if you understand what it means, and thoroughly read the reason why this was added as explained in https://github.com/huggingface/transformers/pull/24565
85
+ KV cache compression is enabled.
86
+ Processing 72 samples.
87
+ [GPU 0] Assigned 72 samples
88
+ [GPU 0] Loading model...
89
+ [GPU 0] Model loaded.
90
+ [GPU 0] Generating T2V: 'a person swimming in ocean' -> /home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/outputs/vbench/videos/subject_consistency/a person swimming in ocean-0.mp4
91
+
92
+ [2026-05-20 12:23:01,301 - INFO] (cp, pp) rank (0, 0): param count 4459898128, model size 8.34 GB
93
+ [2026-05-20 12:23:01,301 - INFO] Build DiTModel successfully
94
+ [2026-05-20 12:23:01,301 - INFO] After build_dit_model, memory allocated: 0.04 GB, memory reserved: 0.08 GB
95
+ [2026-05-20 12:23:01,301 - INFO] load inference_weight.distill weight from ./downloads/4.5B_distill/inference_weight.distill
96
+
97
+ [2026-05-20 12:23:03,292 - INFO] Load Weight Missing Keys: []
98
+ [2026-05-20 12:23:03,292 - INFO] Load Weight Unexpected Keys: []
99
+ [2026-05-20 12:23:03,525 - INFO] After load_checkpoint, memory allocated: 8.39 GB, memory reserved: 8.40 GB
100
+ [2026-05-20 12:23:03,528 - INFO] After high_precision_promoter, memory allocated: 8.39 GB, memory reserved: 8.40 GB
101
+ [2026-05-20 12:23:03,637 - INFO] Load checkpoint successfully
102
+ [2026-05-20 12:23:03,637 - INFO] Begin to generate per chunk
103
+ [2026-05-20 12:23:03,637 - INFO] special_token = ['HQ_TOKEN', 'DURATION_TOKEN']
104
+
105
+
106
+ Traceback (most recent call last):
107
+ File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/envs/magi/lib/python3.10/multiprocessing/process.py", line 314, in _bootstrap
108
+ self.run()
109
+ File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/envs/magi/lib/python3.10/multiprocessing/process.py", line 108, in run
110
+ self._target(*self._args, **self._kwargs)
111
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 239, in worker_process
112
+ process_func(pipeline, sample, config, gpu_id)
113
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 165, in process_vbench_sample
114
+ pipeline.run_text_to_video(prompt=prompt, output_path=output_path)
115
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/pipeline.py", line 38, in run_text_to_video
116
+ self._run(prompt, None, output_path)
117
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/pipeline.py", line 52, in _run
118
+ [
119
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/pipeline.py", line 52, in <listcomp>
120
+ [
121
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/video_generate.py", line 1129, in generate_per_chunk
122
+ for _, _, chunk in sample_transport.walk():
123
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/video_generate.py", line 1092, in walk
124
+ clean_chunk, chunk_idx = self.integrate_velocity(work_status.infer_idx, work_status.cur_denoise_step)
125
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/flowcache.py", line 530, in flowcache_integrate_velocity
126
+ _check_and_compress_kv(self, infer_idx, chunk_start, transport_input)
127
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/flowcache.py", line 570, in _check_and_compress_kv
128
+ compressor.compress(
129
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/cache/kv_compressor.py", line 158, in compress
130
+ layer_result = self._compress_layer(
131
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/cache/kv_compressor.py", line 251, in _compress_layer
132
+ key_compressed, value_compressed, indices = kv_cluster.update_kv(
133
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/kvcompress/kv_compressor.py", line 52, in update_kv
134
+ return self.update_kv_token(
135
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/kvcompress/kv_compressor.py", line 168, in update_kv_token
136
+ raise ValueError(f"Unknown score weighting method: {self.score_weighting_method}")
137
+ ValueError: Unknown score weighting method: None
138
+ ✅ Completed: subject_consistency
139
+ ---
140
+ 🔍 Processing dimension: scene
141
+ Loaded configuration from: yaml_config/sample/flowcache_vbench.yaml.tmp
142
+ Total samples: 86
143
+ GPUs: [0]
144
+ Output: outputs/vbench/videos/scene
145
+ Config: config/sample/vbench.json
146
+ /home/dyvm6xra/dyvm6xrauser11/miniforge3/envs/magi/lib/python3.10/site-packages/timm/models/layers/__init__.py:48: FutureWarning: Importing from timm.models.layers is deprecated, please import via timm.layers
147
+ warnings.warn(f"Importing from {__name__} is deprecated, please import via timm.layers", FutureWarning)
148
+ [W520 12:25:23.550998312 CUDAAllocatorConfig.h:28] Warning: expandable_segments not supported on this platform (function operator())
149
+ [2026-05-20 12:25:23,106 - INFO] Initialize torch distribution and model parallel successfully
150
+ [2026-05-20 12:25:23,106 - INFO] MagiConfig(model_config=ModelConfig(model_name='videodit_ardf', num_layers=34, hidden_size=3072, ffn_hidden_size=12288, num_attention_heads=24, num_query_groups=8, kv_channels=128, layernorm_epsilon=1e-06, apply_layernorm_1p=True, x_rescale_factor=1, half_channel_vae=False, params_dtype=torch.bfloat16, patch_size=2, t_patch_size=1, in_channels=16, out_channels=16, cond_hidden_ratio=0.25, caption_channels=4096, caption_max_length=800, xattn_cond_hidden_ratio=1.0, cond_gating_ratio=1.0, gated_linear_unit=False), runtime_config=RuntimeConfig(cfg_number=1, cfg_t_range=[0.0, 0.0217, 0.1, 0.3, 0.999], prev_chunk_scales=[1.5, 1.5, 1.5, 1.0, 1.0], text_scales=[7.5, 7.5, 7.5, 0.0, 0.0], noise2clean_kvrange=[], clean_chunk_kvrange=1, clean_t=0.9999, seed=1234, num_frames=240, video_size_h=720, video_size_w=720, num_steps=16, window_size=4, fps=24, chunk_width=6, t5_pretrained='./downloads/t5_pretrained', t5_device='cuda', vae_pretrained='./downloads/vae', scale_factor=0.18215, temporal_downsample_factor=4, load='./downloads/4.5B_distill'), engine_config=EngineConfig(distributed_backend='nccl', distributed_timeout_minutes=15, pp_size=1, cp_size=1, cp_strategy='none', ulysses_overlap_degree=1, fp8_quant=False, distill_nearly_clean_chunk_threshold=0.3, shortcut_mode='8,16,16', distill=True, kv_offload=True, enable_cuda_graph=False))
151
+ [2026-05-20 12:25:23,106 - INFO] Precompute validation prompt embeddings
152
+ You are using the default legacy behaviour of the <class 'transformers.models.t5.tokenization_t5.T5Tokenizer'>. This is expected, and simply means that the `legacy` (previous) behavior will be used so nothing changes for you. If you want to use the new behaviour, set `legacy=False`. This should only be set if you understand what it means, and thoroughly read the reason why this was added as explained in https://github.com/huggingface/transformers/pull/24565
153
+ KV cache compression is enabled.
154
+ Processing 86 samples.
155
+ [GPU 0] Assigned 86 samples
156
+ [GPU 0] Loading model...
157
+ [GPU 0] Model loaded.
158
+ [GPU 0] Generating T2V: 'alley' -> /home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/outputs/vbench/videos/scene/alley-0.mp4
159
+
160
+ [2026-05-20 12:25:41,783 - INFO] (cp, pp) rank (0, 0): param count 4459898128, model size 8.34 GB
161
+ [2026-05-20 12:25:41,783 - INFO] Build DiTModel successfully
162
+ [2026-05-20 12:25:41,783 - INFO] After build_dit_model, memory allocated: 0.04 GB, memory reserved: 0.08 GB
163
+ [2026-05-20 12:25:41,783 - INFO] load inference_weight.distill weight from ./downloads/4.5B_distill/inference_weight.distill
164
+
165
+ [2026-05-20 12:25:43,563 - INFO] Load Weight Missing Keys: []
166
+ [2026-05-20 12:25:43,563 - INFO] Load Weight Unexpected Keys: []
167
+ [2026-05-20 12:25:43,770 - INFO] After load_checkpoint, memory allocated: 8.39 GB, memory reserved: 8.40 GB
168
+ [2026-05-20 12:25:43,773 - INFO] After high_precision_promoter, memory allocated: 8.39 GB, memory reserved: 8.40 GB
169
+ [2026-05-20 12:25:43,867 - INFO] Load checkpoint successfully
170
+ [2026-05-20 12:25:43,867 - INFO] Begin to generate per chunk
171
+ [2026-05-20 12:25:43,867 - INFO] special_token = ['HQ_TOKEN', 'DURATION_TOKEN']
172
+
173
+
174
+ Traceback (most recent call last):
175
+ File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/envs/magi/lib/python3.10/multiprocessing/process.py", line 314, in _bootstrap
176
+ self.run()
177
+ File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/envs/magi/lib/python3.10/multiprocessing/process.py", line 108, in run
178
+ self._target(*self._args, **self._kwargs)
179
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 239, in worker_process
180
+ process_func(pipeline, sample, config, gpu_id)
181
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 165, in process_vbench_sample
182
+ pipeline.run_text_to_video(prompt=prompt, output_path=output_path)
183
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/pipeline.py", line 38, in run_text_to_video
184
+ self._run(prompt, None, output_path)
185
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/pipeline.py", line 52, in _run
186
+ [
187
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/pipeline.py", line 52, in <listcomp>
188
+ [
189
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/video_generate.py", line 1129, in generate_per_chunk
190
+ for _, _, chunk in sample_transport.walk():
191
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/video_generate.py", line 1092, in walk
192
+ clean_chunk, chunk_idx = self.integrate_velocity(work_status.infer_idx, work_status.cur_denoise_step)
193
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/flowcache.py", line 530, in flowcache_integrate_velocity
194
+ _check_and_compress_kv(self, infer_idx, chunk_start, transport_input)
195
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/flowcache.py", line 570, in _check_and_compress_kv
196
+ compressor.compress(
197
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/cache/kv_compressor.py", line 158, in compress
198
+ layer_result = self._compress_layer(
199
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/cache/kv_compressor.py", line 251, in _compress_layer
200
+ key_compressed, value_compressed, indices = kv_cluster.update_kv(
201
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/kvcompress/kv_compressor.py", line 52, in update_kv
202
+ return self.update_kv_token(
203
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/kvcompress/kv_compressor.py", line 168, in update_kv_token
204
+ raise ValueError(f"Unknown score weighting method: {self.score_weighting_method}")
205
+ ValueError: Unknown score weighting method: None
206
+ ✅ Completed: scene
207
+ ---
208
+ 🎉 All sampling tasks completed.
FlowCache/FlowCache4MAGI-1/logs/flowcache_vbench_20260520_124220.log ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 🚀 Starting multi-GPU benchmark sampling
2
+ 🔢 Total dimensions to process: 3
3
+ 📋 Dimensions: overall_consistency subject_consistency scene
4
+ 🔍 Processing dimension: overall_consistency
5
+ Loaded configuration from: yaml_config/sample/flowcache_vbench.yaml.tmp
6
+ Total samples: 93
7
+ GPUs: [0]
8
+ Output: outputs/vbench/videos/overall_consistency
9
+ Config: config/sample/vbench.json
10
+ /home/dyvm6xra/dyvm6xrauser11/miniforge3/envs/magi/lib/python3.10/site-packages/timm/models/layers/__init__.py:48: FutureWarning: Importing from timm.models.layers is deprecated, please import via timm.layers
11
+ warnings.warn(f"Importing from {__name__} is deprecated, please import via timm.layers", FutureWarning)
12
+ [W520 12:42:27.778130826 CUDAAllocatorConfig.h:28] Warning: expandable_segments not supported on this platform (function operator())
13
+ [2026-05-20 12:42:27,333 - INFO] Initialize torch distribution and model parallel successfully
14
+ [2026-05-20 12:42:27,333 - INFO] MagiConfig(model_config=ModelConfig(model_name='videodit_ardf', num_layers=34, hidden_size=3072, ffn_hidden_size=12288, num_attention_heads=24, num_query_groups=8, kv_channels=128, layernorm_epsilon=1e-06, apply_layernorm_1p=True, x_rescale_factor=1, half_channel_vae=False, params_dtype=torch.bfloat16, patch_size=2, t_patch_size=1, in_channels=16, out_channels=16, cond_hidden_ratio=0.25, caption_channels=4096, caption_max_length=800, xattn_cond_hidden_ratio=1.0, cond_gating_ratio=1.0, gated_linear_unit=False), runtime_config=RuntimeConfig(cfg_number=1, cfg_t_range=[0.0, 0.0217, 0.1, 0.3, 0.999], prev_chunk_scales=[1.5, 1.5, 1.5, 1.0, 1.0], text_scales=[7.5, 7.5, 7.5, 0.0, 0.0], noise2clean_kvrange=[], clean_chunk_kvrange=1, clean_t=0.9999, seed=1234, num_frames=240, video_size_h=720, video_size_w=720, num_steps=16, window_size=4, fps=24, chunk_width=6, t5_pretrained='./downloads/t5_pretrained', t5_device='cuda', vae_pretrained='./downloads/vae', scale_factor=0.18215, temporal_downsample_factor=4, load='./downloads/4.5B_distill'), engine_config=EngineConfig(distributed_backend='nccl', distributed_timeout_minutes=15, pp_size=1, cp_size=1, cp_strategy='none', ulysses_overlap_degree=1, fp8_quant=False, distill_nearly_clean_chunk_threshold=0.3, shortcut_mode='8,16,16', distill=True, kv_offload=True, enable_cuda_graph=False))
15
+ [2026-05-20 12:42:27,333 - INFO] Precompute validation prompt embeddings
16
+ You are using the default legacy behaviour of the <class 'transformers.models.t5.tokenization_t5.T5Tokenizer'>. This is expected, and simply means that the `legacy` (previous) behavior will be used so nothing changes for you. If you want to use the new behaviour, set `legacy=False`. This should only be set if you understand what it means, and thoroughly read the reason why this was added as explained in https://github.com/huggingface/transformers/pull/24565
17
+ KV cache compression is enabled.
18
+ Processing 93 samples.
19
+ [GPU 0] Assigned 93 samples
20
+ [GPU 0] Loading model...
21
+ [GPU 0] Model loaded.
22
+ [GPU 0] Generating T2V: 'Close up of grapes on a rotating table.' -> /home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/outputs/vbench/videos/overall_consistency/Close up of grapes on a rotating table.-0.mp4
23
+
24
+ [2026-05-20 12:42:45,676 - INFO] (cp, pp) rank (0, 0): param count 4459898128, model size 8.34 GB
25
+ [2026-05-20 12:42:45,676 - INFO] Build DiTModel successfully
26
+ [2026-05-20 12:42:45,676 - INFO] After build_dit_model, memory allocated: 0.04 GB, memory reserved: 0.08 GB
27
+ [2026-05-20 12:42:45,676 - INFO] load inference_weight.distill weight from ./downloads/4.5B_distill/inference_weight.distill
28
+
29
+ [2026-05-20 12:42:47,225 - INFO] Load Weight Missing Keys: []
30
+ [2026-05-20 12:42:47,225 - INFO] Load Weight Unexpected Keys: []
31
+ [2026-05-20 12:42:47,431 - INFO] After load_checkpoint, memory allocated: 8.39 GB, memory reserved: 8.40 GB
32
+ [2026-05-20 12:42:47,434 - INFO] After high_precision_promoter, memory allocated: 8.39 GB, memory reserved: 8.40 GB
33
+ [2026-05-20 12:42:47,535 - INFO] Load checkpoint successfully
34
+ [2026-05-20 12:42:47,535 - INFO] Begin to generate per chunk
35
+ [2026-05-20 12:42:47,535 - INFO] special_token = ['HQ_TOKEN', 'DURATION_TOKEN']
36
+
37
+
38
+ [2026-05-20 12:48:01,557 - INFO] Finish MagiPipeline, max memory allocated: 44.77 GB, max memory reserved: 56.32 GB
39
+ [2026-05-20 12:48:01,557 - INFO] Precompute validation prompt embeddings
40
+ Using no weighting method
41
+ Using no weighting method
42
+ Using no weighting method
43
+ Using no weighting method
44
+ Using no weighting method
45
+ Using no weighting method
46
+ Using no weighting method
47
+ Using no weighting method
48
+ Using no weighting method
49
+ Using no weighting method
50
+ Using no weighting method
51
+ Using no weighting method
52
+ Using no weighting method
53
+ Using no weighting method
54
+ Using no weighting method
55
+ Using no weighting method
56
+ Using no weighting method
57
+ Using no weighting method
58
+ Using no weighting method
59
+ Using no weighting method
60
+ Using no weighting method
61
+ Using no weighting method
62
+ Using no weighting method
63
+ Using no weighting method
64
+ Using no weighting method
65
+ Using no weighting method
66
+ Using no weighting method
67
+ Using no weighting method
68
+ Using no weighting method
69
+ Using no weighting method
70
+ Using no weighting method
71
+ Using no weighting method
72
+ Using no weighting method
73
+ Using no weighting method
74
+ Using no weighting method
75
+ Using no weighting method
76
+ Using no weighting method
77
+ Using no weighting method
78
+ Using no weighting method
79
+ Using no weighting method
80
+ Using no weighting method
81
+ Using no weighting method
82
+ Using no weighting method
83
+ Using no weighting method
84
+ Using no weighting method
85
+ Using no weighting method
86
+ Using no weighting method
87
+ Using no weighting method
88
+ Using no weighting method
89
+ Using no weighting method
90
+ Using no weighting method
91
+ Using no weighting method
92
+ Using no weighting method
93
+ Using no weighting method
94
+ Using no weighting method
95
+ Using no weighting method
96
+ Using no weighting method
97
+ Using no weighting method
98
+ Using no weighting method
99
+ Using no weighting method
100
+ Using no weighting method
101
+ Using no weighting method
102
+ Using no weighting method
103
+ Using no weighting method
104
+ Using no weighting method
105
+ Using no weighting method
106
+ Using no weighting method
107
+ Using no weighting method
108
+ Using no weighting method
109
+ Using no weighting method
110
+ Using no weighting method
111
+ Using no weighting method
112
+ Using no weighting method
113
+ Using no weighting method
114
+ Using no weighting method
115
+ Using no weighting method
116
+ Using no weighting method
117
+ Using no weighting method
118
+ Using no weighting method
119
+ Using no weighting method
120
+ Using no weighting method
121
+ Using no weighting method
122
+ Using no weighting method
123
+ Using no weighting method
124
+ Using no weighting method
125
+ Using no weighting method
126
+ Using no weighting method
127
+ Using no weighting method
128
+ Using no weighting method
129
+ Using no weighting method
130
+ Using no weighting method
131
+ Using no weighting method
132
+ Using no weighting method
133
+ Using no weighting method
134
+ Using no weighting method
135
+ Using no weighting method
136
+ Using no weighting method
137
+ Using no weighting method
138
+ Using no weighting method
139
+ Using no weighting method
140
+ Using no weighting method
141
+ Using no weighting method
142
+ Using no weighting method
143
+ Using no weighting method
144
+ Using no weighting method
145
+ Using no weighting method
146
+ Using no weighting method
147
+ Using no weighting method
148
+ Using no weighting method
149
+ Using no weighting method
150
+ Using no weighting method
151
+ Using no weighting method
152
+ Using no weighting method
153
+ Using no weighting method
154
+ Using no weighting method
155
+ Using no weighting method
156
+ Using no weighting method
157
+ Using no weighting method
158
+ Using no weighting method
159
+ Using no weighting method
160
+ Using no weighting method
161
+ Using no weighting method
162
+ Using no weighting method
163
+ Using no weighting method
164
+ Using no weighting method
165
+ Using no weighting method
166
+ Using no weighting method
167
+ Using no weighting method
168
+ Using no weighting method
169
+ Using no weighting method
170
+ Using no weighting method
171
+ Using no weighting method
172
+ Using no weighting method
173
+ Using no weighting method
174
+ Using no weighting method
175
+ Using no weighting method
176
+ ✅ Video saved successfully.
177
+ [DONE GPU 0] Saved: /home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/outputs/vbench/videos/overall_consistency/Close up of grapes on a rotating table.-0.mp4
178
+ [GPU 0] Generating T2V: 'Turtle swimming in ocean.' -> /home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/outputs/vbench/videos/overall_consistency/Turtle swimming in ocean.-0.mp4
179
+
180
+ [2026-05-20 12:48:18,152 - INFO] (cp, pp) rank (0, 0): param count 4459898128, model size 8.34 GB
181
+ [2026-05-20 12:48:18,152 - INFO] Build DiTModel successfully
182
+ [2026-05-20 12:48:18,152 - INFO] After build_dit_model, memory allocated: 0.17 GB, memory reserved: 0.31 GB
183
+ [2026-05-20 12:48:18,152 - INFO] load inference_weight.distill weight from ./downloads/4.5B_distill/inference_weight.distill
184
+
185
+ [2026-05-20 12:48:19,731 - INFO] Load Weight Missing Keys: []
186
+ [2026-05-20 12:48:19,731 - INFO] Load Weight Unexpected Keys: []
187
+ [2026-05-20 12:48:19,940 - INFO] After load_checkpoint, memory allocated: 8.52 GB, memory reserved: 8.56 GB
188
+ [2026-05-20 12:48:19,943 - INFO] After high_precision_promoter, memory allocated: 8.52 GB, memory reserved: 8.56 GB
189
+ [2026-05-20 12:48:20,393 - INFO] Load checkpoint successfully
190
+ [2026-05-20 12:48:20,393 - INFO] Begin to generate per chunk
191
+ [2026-05-20 12:48:20,394 - INFO] special_token = ['HQ_TOKEN', 'DURATION_TOKEN']
192
+
193
+ [2026-05-20 12:48:20,402 - INFO]
194
+ Time Elapsed: [0:05:32.819959] From [begin_walk (2026-05-20 12:42:47.582387)] To [begin_walk (2026-05-20 12:48:20.402346)]
195
+
FlowCache/FlowCache4MAGI-1/logs/flowcache_vbench_20260520_170603.log ADDED
@@ -0,0 +1,298 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 🚀 Starting multi-GPU benchmark sampling
2
+ 🔢 Total dimensions to process: 3
3
+ 📋 Dimensions: overall_consistency subject_consistency scene
4
+ 🔍 Processing dimension: overall_consistency
5
+ Loaded configuration from: yaml_config/sample/flowcache_vbench.yaml.tmp
6
+ Total samples: 93
7
+ GPUs: [0, 1, 2, 3]
8
+ Output: outputs/vbench/videos/overall_consistency
9
+ Config: config/sample/vbench.json
10
+ Process Process-3:
11
+ Process Process-2:
12
+ Process Process-1:
13
+ Process Process-4:
14
+ Traceback (most recent call last):
15
+ Traceback (most recent call last):
16
+ Traceback (most recent call last):
17
+ Traceback (most recent call last):
18
+ File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/lib/python3.12/multiprocessing/process.py", line 314, in _bootstrap
19
+ self.run()
20
+ File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/lib/python3.12/multiprocessing/process.py", line 108, in run
21
+ self._target(*self._args, **self._kwargs)
22
+ File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/lib/python3.12/multiprocessing/process.py", line 314, in _bootstrap
23
+ self.run()
24
+ File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/lib/python3.12/multiprocessing/process.py", line 314, in _bootstrap
25
+ self.run()
26
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 240, in worker_process
27
+ configure_reuse_strategy(config)
28
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 147, in configure_reuse_strategy
29
+ from inference.pipeline.video_generate import SampleTransport
30
+ File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/lib/python3.12/multiprocessing/process.py", line 108, in run
31
+ self._target(*self._args, **self._kwargs)
32
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/__init__.py", line 15, in <module>
33
+ from .pipeline import MagiPipeline
34
+ File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/lib/python3.12/multiprocessing/process.py", line 108, in run
35
+ self._target(*self._args, **self._kwargs)
36
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 240, in worker_process
37
+ configure_reuse_strategy(config)
38
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/pipeline.py", line 21, in <module>
39
+ from inference.model.dit import get_dit
40
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 240, in worker_process
41
+ configure_reuse_strategy(config)
42
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 147, in configure_reuse_strategy
43
+ from inference.pipeline.video_generate import SampleTransport
44
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/__init__.py", line 15, in <module>
45
+ from .dit_model import get_dit, VideoDiTModel
46
+ File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/lib/python3.12/multiprocessing/process.py", line 314, in _bootstrap
47
+ self.run()
48
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 147, in configure_reuse_strategy
49
+ from inference.pipeline.video_generate import SampleTransport
50
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/dit_model.py", line 39, in <module>
51
+ from .dit_module import CaptionEmbedder, FinalLinear, LearnableRotaryEmbeddingCat, TimestepEmbedder, TransformerBlock
52
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/__init__.py", line 15, in <module>
53
+ from .pipeline import MagiPipeline
54
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/__init__.py", line 15, in <module>
55
+ from .pipeline import MagiPipeline
56
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/dit_module.py", line 19, in <module>
57
+ import flashinfer
58
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/pipeline.py", line 21, in <module>
59
+ from inference.model.dit import get_dit
60
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/pipeline.py", line 21, in <module>
61
+ from inference.model.dit import get_dit
62
+ File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/lib/python3.12/multiprocessing/process.py", line 108, in run
63
+ self._target(*self._args, **self._kwargs)
64
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/__init__.py", line 15, in <module>
65
+ from .dit_model import get_dit, VideoDiTModel
66
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/__init__.py", line 15, in <module>
67
+ from .dit_model import get_dit, VideoDiTModel
68
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 240, in worker_process
69
+ configure_reuse_strategy(config)
70
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/dit_model.py", line 39, in <module>
71
+ from .dit_module import CaptionEmbedder, FinalLinear, LearnableRotaryEmbeddingCat, TimestepEmbedder, TransformerBlock
72
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/dit_model.py", line 39, in <module>
73
+ from .dit_module import CaptionEmbedder, FinalLinear, LearnableRotaryEmbeddingCat, TimestepEmbedder, TransformerBlock
74
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 147, in configure_reuse_strategy
75
+ from inference.pipeline.video_generate import SampleTransport
76
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/dit_module.py", line 19, in <module>
77
+ import flashinfer
78
+ ModuleNotFoundError: No module named 'flashinfer'
79
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/dit_module.py", line 19, in <module>
80
+ import flashinfer
81
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/__init__.py", line 15, in <module>
82
+ from .pipeline import MagiPipeline
83
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/pipeline.py", line 21, in <module>
84
+ from inference.model.dit import get_dit
85
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/__init__.py", line 15, in <module>
86
+ from .dit_model import get_dit, VideoDiTModel
87
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/dit_model.py", line 39, in <module>
88
+ from .dit_module import CaptionEmbedder, FinalLinear, LearnableRotaryEmbeddingCat, TimestepEmbedder, TransformerBlock
89
+ ModuleNotFoundError: No module named 'flashinfer'
90
+ ModuleNotFoundError: No module named 'flashinfer'
91
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/dit_module.py", line 19, in <module>
92
+ import flashinfer
93
+ ModuleNotFoundError: No module named 'flashinfer'
94
+ Traceback (most recent call last):
95
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 429, in <module>
96
+ main()
97
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 425, in main
98
+ raise RuntimeError(f"{len(failed)} worker process(es) failed with exit codes: {failed}")
99
+ RuntimeError: 4 worker process(es) failed with exit codes: [1, 1, 1, 1]
100
+ ✅ Completed: overall_consistency
101
+ ---
102
+ 🔍 Processing dimension: subject_consistency
103
+ Loaded configuration from: yaml_config/sample/flowcache_vbench.yaml.tmp
104
+ Total samples: 72
105
+ GPUs: [0, 1, 2, 3]
106
+ Output: outputs/vbench/videos/subject_consistency
107
+ Config: config/sample/vbench.json
108
+ Process Process-3:
109
+ Traceback (most recent call last):
110
+ File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/lib/python3.12/multiprocessing/process.py", line 314, in _bootstrap
111
+ self.run()
112
+ File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/lib/python3.12/multiprocessing/process.py", line 108, in run
113
+ self._target(*self._args, **self._kwargs)
114
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 240, in worker_process
115
+ configure_reuse_strategy(config)
116
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 147, in configure_reuse_strategy
117
+ from inference.pipeline.video_generate import SampleTransport
118
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/__init__.py", line 15, in <module>
119
+ from .pipeline import MagiPipeline
120
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/pipeline.py", line 21, in <module>
121
+ from inference.model.dit import get_dit
122
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/__init__.py", line 15, in <module>
123
+ from .dit_model import get_dit, VideoDiTModel
124
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/dit_model.py", line 39, in <module>
125
+ from .dit_module import CaptionEmbedder, FinalLinear, LearnableRotaryEmbeddingCat, TimestepEmbedder, TransformerBlock
126
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/dit_module.py", line 19, in <module>
127
+ import flashinfer
128
+ ModuleNotFoundError: No module named 'flashinfer'
129
+ Process Process-1:
130
+ Process Process-2:
131
+ Traceback (most recent call last):
132
+ File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/lib/python3.12/multiprocessing/process.py", line 314, in _bootstrap
133
+ self.run()
134
+ File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/lib/python3.12/multiprocessing/process.py", line 108, in run
135
+ self._target(*self._args, **self._kwargs)
136
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 240, in worker_process
137
+ configure_reuse_strategy(config)
138
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 147, in configure_reuse_strategy
139
+ from inference.pipeline.video_generate import SampleTransport
140
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/__init__.py", line 15, in <module>
141
+ from .pipeline import MagiPipeline
142
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/pipeline.py", line 21, in <module>
143
+ from inference.model.dit import get_dit
144
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/__init__.py", line 15, in <module>
145
+ from .dit_model import get_dit, VideoDiTModel
146
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/dit_model.py", line 39, in <module>
147
+ from .dit_module import CaptionEmbedder, FinalLinear, LearnableRotaryEmbeddingCat, TimestepEmbedder, TransformerBlock
148
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/dit_module.py", line 19, in <module>
149
+ import flashinfer
150
+ ModuleNotFoundError: No module named 'flashinfer'
151
+ Traceback (most recent call last):
152
+ File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/lib/python3.12/multiprocessing/process.py", line 314, in _bootstrap
153
+ self.run()
154
+ File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/lib/python3.12/multiprocessing/process.py", line 108, in run
155
+ self._target(*self._args, **self._kwargs)
156
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 240, in worker_process
157
+ configure_reuse_strategy(config)
158
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 147, in configure_reuse_strategy
159
+ from inference.pipeline.video_generate import SampleTransport
160
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/__init__.py", line 15, in <module>
161
+ from .pipeline import MagiPipeline
162
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/pipeline.py", line 21, in <module>
163
+ from inference.model.dit import get_dit
164
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/__init__.py", line 15, in <module>
165
+ from .dit_model import get_dit, VideoDiTModel
166
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/dit_model.py", line 39, in <module>
167
+ from .dit_module import CaptionEmbedder, FinalLinear, LearnableRotaryEmbeddingCat, TimestepEmbedder, TransformerBlock
168
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/dit_module.py", line 19, in <module>
169
+ import flashinfer
170
+ ModuleNotFoundError: No module named 'flashinfer'
171
+ Process Process-4:
172
+ Traceback (most recent call last):
173
+ File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/lib/python3.12/multiprocessing/process.py", line 314, in _bootstrap
174
+ self.run()
175
+ File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/lib/python3.12/multiprocessing/process.py", line 108, in run
176
+ self._target(*self._args, **self._kwargs)
177
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 240, in worker_process
178
+ configure_reuse_strategy(config)
179
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 147, in configure_reuse_strategy
180
+ from inference.pipeline.video_generate import SampleTransport
181
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/__init__.py", line 15, in <module>
182
+ from .pipeline import MagiPipeline
183
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/pipeline.py", line 21, in <module>
184
+ from inference.model.dit import get_dit
185
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/__init__.py", line 15, in <module>
186
+ from .dit_model import get_dit, VideoDiTModel
187
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/dit_model.py", line 39, in <module>
188
+ from .dit_module import CaptionEmbedder, FinalLinear, LearnableRotaryEmbeddingCat, TimestepEmbedder, TransformerBlock
189
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/dit_module.py", line 19, in <module>
190
+ import flashinfer
191
+ ModuleNotFoundError: No module named 'flashinfer'
192
+ Traceback (most recent call last):
193
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 429, in <module>
194
+ main()
195
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 425, in main
196
+ raise RuntimeError(f"{len(failed)} worker process(es) failed with exit codes: {failed}")
197
+ RuntimeError: 4 worker process(es) failed with exit codes: [1, 1, 1, 1]
198
+ ✅ Completed: subject_consistency
199
+ ---
200
+ 🔍 Processing dimension: scene
201
+ Loaded configuration from: yaml_config/sample/flowcache_vbench.yaml.tmp
202
+ Total samples: 86
203
+ GPUs: [0, 1, 2, 3]
204
+ Output: outputs/vbench/videos/scene
205
+ Config: config/sample/vbench.json
206
+ Process Process-4:
207
+ Process Process-2:
208
+ Traceback (most recent call last):
209
+ File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/lib/python3.12/multiprocessing/process.py", line 314, in _bootstrap
210
+ self.run()
211
+ File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/lib/python3.12/multiprocessing/process.py", line 108, in run
212
+ self._target(*self._args, **self._kwargs)
213
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 240, in worker_process
214
+ configure_reuse_strategy(config)
215
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 147, in configure_reuse_strategy
216
+ from inference.pipeline.video_generate import SampleTransport
217
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/__init__.py", line 15, in <module>
218
+ from .pipeline import MagiPipeline
219
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/pipeline.py", line 21, in <module>
220
+ from inference.model.dit import get_dit
221
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/__init__.py", line 15, in <module>
222
+ from .dit_model import get_dit, VideoDiTModel
223
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/dit_model.py", line 39, in <module>
224
+ from .dit_module import CaptionEmbedder, FinalLinear, LearnableRotaryEmbeddingCat, TimestepEmbedder, TransformerBlock
225
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/dit_module.py", line 19, in <module>
226
+ import flashinfer
227
+ ModuleNotFoundError: No module named 'flashinfer'
228
+ Traceback (most recent call last):
229
+ File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/lib/python3.12/multiprocessing/process.py", line 314, in _bootstrap
230
+ self.run()
231
+ File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/lib/python3.12/multiprocessing/process.py", line 108, in run
232
+ self._target(*self._args, **self._kwargs)
233
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 240, in worker_process
234
+ configure_reuse_strategy(config)
235
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 147, in configure_reuse_strategy
236
+ from inference.pipeline.video_generate import SampleTransport
237
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/__init__.py", line 15, in <module>
238
+ from .pipeline import MagiPipeline
239
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/pipeline.py", line 21, in <module>
240
+ from inference.model.dit import get_dit
241
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/__init__.py", line 15, in <module>
242
+ from .dit_model import get_dit, VideoDiTModel
243
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/dit_model.py", line 39, in <module>
244
+ from .dit_module import CaptionEmbedder, FinalLinear, LearnableRotaryEmbeddingCat, TimestepEmbedder, TransformerBlock
245
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/dit_module.py", line 19, in <module>
246
+ import flashinfer
247
+ ModuleNotFoundError: No module named 'flashinfer'
248
+ Process Process-3:
249
+ Traceback (most recent call last):
250
+ File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/lib/python3.12/multiprocessing/process.py", line 314, in _bootstrap
251
+ self.run()
252
+ File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/lib/python3.12/multiprocessing/process.py", line 108, in run
253
+ self._target(*self._args, **self._kwargs)
254
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 240, in worker_process
255
+ configure_reuse_strategy(config)
256
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 147, in configure_reuse_strategy
257
+ from inference.pipeline.video_generate import SampleTransport
258
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/__init__.py", line 15, in <module>
259
+ from .pipeline import MagiPipeline
260
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/pipeline.py", line 21, in <module>
261
+ from inference.model.dit import get_dit
262
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/__init__.py", line 15, in <module>
263
+ from .dit_model import get_dit, VideoDiTModel
264
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/dit_model.py", line 39, in <module>
265
+ from .dit_module import CaptionEmbedder, FinalLinear, LearnableRotaryEmbeddingCat, TimestepEmbedder, TransformerBlock
266
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/dit_module.py", line 19, in <module>
267
+ import flashinfer
268
+ ModuleNotFoundError: No module named 'flashinfer'
269
+ Process Process-1:
270
+ Traceback (most recent call last):
271
+ File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/lib/python3.12/multiprocessing/process.py", line 314, in _bootstrap
272
+ self.run()
273
+ File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/lib/python3.12/multiprocessing/process.py", line 108, in run
274
+ self._target(*self._args, **self._kwargs)
275
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 240, in worker_process
276
+ configure_reuse_strategy(config)
277
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 147, in configure_reuse_strategy
278
+ from inference.pipeline.video_generate import SampleTransport
279
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/__init__.py", line 15, in <module>
280
+ from .pipeline import MagiPipeline
281
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/pipeline.py", line 21, in <module>
282
+ from inference.model.dit import get_dit
283
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/__init__.py", line 15, in <module>
284
+ from .dit_model import get_dit, VideoDiTModel
285
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/dit_model.py", line 39, in <module>
286
+ from .dit_module import CaptionEmbedder, FinalLinear, LearnableRotaryEmbeddingCat, TimestepEmbedder, TransformerBlock
287
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/dit_module.py", line 19, in <module>
288
+ import flashinfer
289
+ ModuleNotFoundError: No module named 'flashinfer'
290
+ Traceback (most recent call last):
291
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 429, in <module>
292
+ main()
293
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 425, in main
294
+ raise RuntimeError(f"{len(failed)} worker process(es) failed with exit codes: {failed}")
295
+ RuntimeError: 4 worker process(es) failed with exit codes: [1, 1, 1, 1]
296
+ ✅ Completed: scene
297
+ ---
298
+ 🎉 All sampling tasks completed.
FlowCache/FlowCache4MAGI-1/logs/flowcache_vbench_20260521_034016.log ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 🚀 Starting multi-GPU benchmark sampling
2
+ 🔢 Total dimensions to process: 3
3
+ 📋 Dimensions: overall_consistency subject_consistency scene
4
+ 🔍 Processing dimension: overall_consistency
5
+ Loaded configuration from: yaml_config/sample/flowcache_vbench.yaml.tmp
6
+ Total samples: 93
7
+ GPUs: [0]
8
+ Output: outputs/vbench/videos/overall_consistency
9
+ Config: config/sample/vbench.json
10
+ Process Process-1:
11
+ Traceback (most recent call last):
12
+ File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/lib/python3.12/multiprocessing/process.py", line 314, in _bootstrap
13
+ self.run()
14
+ File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/lib/python3.12/multiprocessing/process.py", line 108, in run
15
+ self._target(*self._args, **self._kwargs)
16
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 240, in worker_process
17
+ configure_reuse_strategy(config)
18
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 147, in configure_reuse_strategy
19
+ from inference.pipeline.video_generate import SampleTransport
20
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/__init__.py", line 15, in <module>
21
+ from .pipeline import MagiPipeline
22
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/pipeline.py", line 21, in <module>
23
+ from inference.model.dit import get_dit
24
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/__init__.py", line 15, in <module>
25
+ from .dit_model import get_dit, VideoDiTModel
26
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/dit_model.py", line 39, in <module>
27
+ from .dit_module import CaptionEmbedder, FinalLinear, LearnableRotaryEmbeddingCat, TimestepEmbedder, TransformerBlock
28
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/dit_module.py", line 19, in <module>
29
+ import flashinfer
30
+ ModuleNotFoundError: No module named 'flashinfer'
31
+ Traceback (most recent call last):
32
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 429, in <module>
33
+ main()
34
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 425, in main
35
+ raise RuntimeError(f"{len(failed)} worker process(es) failed with exit codes: {failed}")
36
+ RuntimeError: 1 worker process(es) failed with exit codes: [1]
37
+ ✅ Completed: overall_consistency
38
+ ---
39
+ 🔍 Processing dimension: subject_consistency
40
+ Loaded configuration from: yaml_config/sample/flowcache_vbench.yaml.tmp
41
+ Total samples: 72
42
+ GPUs: [0]
43
+ Output: outputs/vbench/videos/subject_consistency
44
+ Config: config/sample/vbench.json
45
+ Process Process-1:
46
+ Traceback (most recent call last):
47
+ File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/lib/python3.12/multiprocessing/process.py", line 314, in _bootstrap
48
+ self.run()
49
+ File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/lib/python3.12/multiprocessing/process.py", line 108, in run
50
+ self._target(*self._args, **self._kwargs)
51
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 240, in worker_process
52
+ configure_reuse_strategy(config)
53
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 147, in configure_reuse_strategy
54
+ from inference.pipeline.video_generate import SampleTransport
55
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/__init__.py", line 15, in <module>
56
+ from .pipeline import MagiPipeline
57
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/pipeline.py", line 21, in <module>
58
+ from inference.model.dit import get_dit
59
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/__init__.py", line 15, in <module>
60
+ from .dit_model import get_dit, VideoDiTModel
61
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/dit_model.py", line 39, in <module>
62
+ from .dit_module import CaptionEmbedder, FinalLinear, LearnableRotaryEmbeddingCat, TimestepEmbedder, TransformerBlock
63
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/dit_module.py", line 19, in <module>
64
+ import flashinfer
65
+ ModuleNotFoundError: No module named 'flashinfer'
66
+ Traceback (most recent call last):
67
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 429, in <module>
68
+ main()
69
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 425, in main
70
+ raise RuntimeError(f"{len(failed)} worker process(es) failed with exit codes: {failed}")
71
+ RuntimeError: 1 worker process(es) failed with exit codes: [1]
72
+ ✅ Completed: subject_consistency
73
+ ---
74
+ 🔍 Processing dimension: scene
75
+ Loaded configuration from: yaml_config/sample/flowcache_vbench.yaml.tmp
76
+ Total samples: 86
77
+ GPUs: [0]
78
+ Output: outputs/vbench/videos/scene
79
+ Config: config/sample/vbench.json
80
+ Process Process-1:
81
+ Traceback (most recent call last):
82
+ File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/lib/python3.12/multiprocessing/process.py", line 314, in _bootstrap
83
+ self.run()
84
+ File "/home/dyvm6xra/dyvm6xrauser11/miniforge3/lib/python3.12/multiprocessing/process.py", line 108, in run
85
+ self._target(*self._args, **self._kwargs)
86
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 240, in worker_process
87
+ configure_reuse_strategy(config)
88
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 147, in configure_reuse_strategy
89
+ from inference.pipeline.video_generate import SampleTransport
90
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/__init__.py", line 15, in <module>
91
+ from .pipeline import MagiPipeline
92
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/pipeline/pipeline.py", line 21, in <module>
93
+ from inference.model.dit import get_dit
94
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/__init__.py", line 15, in <module>
95
+ from .dit_model import get_dit, VideoDiTModel
96
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/dit_model.py", line 39, in <module>
97
+ from .dit_module import CaptionEmbedder, FinalLinear, LearnableRotaryEmbeddingCat, TimestepEmbedder, TransformerBlock
98
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/inference/model/dit/dit_module.py", line 19, in <module>
99
+ import flashinfer
100
+ ModuleNotFoundError: No module named 'flashinfer'
101
+ Traceback (most recent call last):
102
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 429, in <module>
103
+ main()
104
+ File "/home/dyvm6xra/dyvm6xrauser11/workspace/cz/FlowCache/FlowCache4MAGI-1/sample_video.py", line 425, in main
105
+ raise RuntimeError(f"{len(failed)} worker process(es) failed with exit codes: {failed}")
106
+ RuntimeError: 1 worker process(es) failed with exit codes: [1]
107
+ ✅ Completed: scene
108
+ ---
109
+ 🎉 All sampling tasks completed.
FlowCache/FlowCache4MAGI-1/requirements.txt ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ accelerate==0.32.1
2
+ beautifulsoup4==4.13.4
3
+ debugpy==1.8.14
4
+ diffusers==0.29.2
5
+ einops>=0.6.0
6
+ ffmpeg-python
7
+ # flash-attn==2.4.2
8
+ flashinfer-python==0.2.0.post2 --extra-index-url https://flashinfer.ai/whl/cu124/torch2.4/
9
+ ftfy==6.2.0
10
+ gpustat==1.1.1
11
+ imageio==2.34.0
12
+ imageio[ffmpeg]
13
+ matplotlib==3.10.1
14
+ numpy==1.26.4
15
+ protobuf==5.28.3
16
+ rich==14.0.0
17
+ sentencepiece==0.2.0
18
+ timm==1.0.15
19
+ torchdiffeq==0.2.4
20
+ transformers==4.42.3
21
+ tqdm
FlowCache/FlowCache4MAGI-1/sample_video.py ADDED
@@ -0,0 +1,429 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 MAGI Authors. All Rights Reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import os
16
+ import re
17
+ import sys
18
+ import argparse
19
+ import csv
20
+ import subprocess
21
+ from pathlib import Path
22
+
23
+ import multiprocessing as mp
24
+
25
+ # Constants
26
+ DEFAULT_BASE_PORT = 29510
27
+ PHYSICSIQ_FPS = 24
28
+
29
+
30
+ def resolve_gpu_ids(gpus_config) -> list[int]:
31
+ """Resolve explicit GPU IDs or auto-detect all currently visible GPUs."""
32
+ if isinstance(gpus_config, int):
33
+ return [gpus_config]
34
+
35
+ gpus_text = str(gpus_config).strip()
36
+ if not gpus_text:
37
+ raise ValueError("'gpus' must not be empty")
38
+
39
+ if gpus_text.lower() not in {"all", "auto"}:
40
+ return [int(item.strip()) for item in gpus_text.split(",") if item.strip()]
41
+
42
+ visible_devices = os.environ.get("CUDA_VISIBLE_DEVICES")
43
+ if visible_devices:
44
+ visible = [item.strip() for item in visible_devices.split(",") if item.strip()]
45
+ if visible and all(item.isdigit() for item in visible):
46
+ return [int(item) for item in visible]
47
+
48
+ try:
49
+ output = subprocess.check_output(
50
+ ["nvidia-smi", "--query-gpu=index", "--format=csv,noheader,nounits"],
51
+ text=True,
52
+ timeout=10,
53
+ )
54
+ gpu_ids = [int(line.strip()) for line in output.splitlines() if line.strip()]
55
+ if gpu_ids:
56
+ return gpu_ids
57
+ except Exception:
58
+ pass
59
+
60
+ try:
61
+ import torch
62
+
63
+ count = torch.cuda.device_count()
64
+ if count > 0:
65
+ return list(range(count))
66
+ except Exception:
67
+ pass
68
+
69
+ raise RuntimeError("No CUDA GPUs detected for gpus: all")
70
+
71
+
72
+ def load_yaml_config(yaml_path: str) -> dict:
73
+ """Load configuration from YAML file."""
74
+ import yaml
75
+
76
+ with open(yaml_path, "r") as f:
77
+ return yaml.safe_load(f)
78
+
79
+
80
+ def apply_slice(items: list, start: int | None, end: int | None) -> list:
81
+ """Apply start/end slice to a list with bounds checking."""
82
+ if start is None and end is None:
83
+ return items
84
+
85
+ slice_start = max(0, start if start is not None else 0)
86
+ slice_end = min(end if end is not None else len(items), len(items))
87
+ slice_end = max(slice_start, slice_end)
88
+
89
+ return items[slice_start:slice_end]
90
+
91
+
92
+ def configure_teacache(transport, config: dict) -> None:
93
+ """Configure TeaCache reuse strategy on SampleTransport."""
94
+ from inference.pipeline.teacache import setup_teacache
95
+
96
+ setup_teacache(
97
+ rel_l1_thresh=config["rel_l1_thresh"],
98
+ warmup_steps=config["warmup_steps"],
99
+ log=config.get("log", False),
100
+ )
101
+
102
+
103
+ def configure_kv_cache(transport, config: dict) -> None:
104
+ """Configure KV cache compression if enabled."""
105
+ if not config.get("compress_kv_cache", False):
106
+ transport.compress_kv_cache = False
107
+ return
108
+
109
+ print("KV cache compression is enabled.")
110
+ transport.compress_kv_cache = True
111
+
112
+ assert config.get("total_cache_chunk_nums") is not None
113
+
114
+ compression_config = {
115
+ "method_config": {
116
+ "compress_strategy": config["compress_strategy"],
117
+ "mix_lambda": config["mix_lambda"],
118
+ "query_granularity": config["query_granularity"],
119
+ "score_weighting_method": config.get("score_weighting_method") or "no_weight",
120
+ "power": config.get("power", 3),
121
+ },
122
+ }
123
+
124
+ from inference.pipeline.kvcompress import replace_magi
125
+
126
+ replace_magi(compression_config)
127
+
128
+
129
+ def configure_flowcache(transport, config: dict) -> None:
130
+ """Configure FlowCache reuse strategy on SampleTransport."""
131
+ from inference.pipeline.flowcache import setup_flowcache
132
+
133
+ configure_kv_cache(transport, config)
134
+
135
+ setup_flowcache(
136
+ rel_l1_thresh=config["rel_l1_thresh"],
137
+ warmup_steps=config["warmup_steps"],
138
+ discard_nearly_clean_chunk=config.get("discard_nearly_clean_chunk", False),
139
+ log=config.get("log", False),
140
+ total_cache_chunk_nums=config.get("total_cache_chunk_nums", 5),
141
+ compress_kv_cache=config.get("compress_kv_cache", False),
142
+ )
143
+
144
+
145
+ def configure_reuse_strategy(config: dict) -> None:
146
+ """Configure the appropriate reuse strategy on SampleTransport."""
147
+ from inference.pipeline.video_generate import SampleTransport
148
+
149
+ strategy = config["reuse_strategy"]
150
+
151
+ if strategy == "original":
152
+ return
153
+ if strategy == "all":
154
+ configure_teacache(SampleTransport, config)
155
+ elif strategy == "chunkwise":
156
+ configure_flowcache(SampleTransport, config)
157
+ else:
158
+ raise ValueError(f"Unknown reuse strategy: {strategy}")
159
+
160
+
161
+ def setup_environment(gpu_id: int) -> None:
162
+ """Set up environment variables for a GPU worker process."""
163
+ os.environ["CUDA_VISIBLE_DEVICES"] = str(gpu_id)
164
+ os.environ["WORLD_SIZE"] = "1"
165
+ os.environ["RANK"] = "0"
166
+ os.environ["LOCAL_RANK"] = "0"
167
+ os.environ["MASTER_ADDR"] = "localhost"
168
+ os.environ["MASTER_PORT"] = str(DEFAULT_BASE_PORT + gpu_id)
169
+
170
+ # Enable pdb terminal debugging
171
+ sys.stdin = open(0)
172
+
173
+
174
+ def filter_existing_samples(samples: list, config: dict) -> list:
175
+ """Filter out samples whose output files already exist."""
176
+ if config["benchmark"] == "vbench":
177
+ return [
178
+ sample
179
+ for sample in samples
180
+ if not os.path.exists(os.path.abspath(os.path.join(config["save_path"], f"{sample}-0.mp4")))
181
+ ]
182
+ else: # physicsiq
183
+ return [
184
+ sample for sample in samples if not os.path.exists(sample["output_path"])
185
+ ]
186
+
187
+
188
+ def assign_samples_to_gpu(
189
+ samples: list, gpu_id: int, rank: int, num_gpus: int
190
+ ) -> list:
191
+ """Divide samples across GPUs and return the subset for this GPU."""
192
+ samples_per_gpu = (len(samples) + num_gpus - 1) // num_gpus
193
+ start_idx = rank * samples_per_gpu
194
+ end_idx = min(start_idx + samples_per_gpu, len(samples))
195
+ return samples[start_idx:end_idx]
196
+
197
+
198
+ def process_vbench_sample(pipeline, prompt: str, config: dict, gpu_id: int) -> None:
199
+ """Process a single vbench text-to-video sample."""
200
+ output_path = os.path.abspath(os.path.join(config["save_path"], f"{prompt}-0.mp4"))
201
+
202
+ if os.path.exists(output_path):
203
+ print(f"[SKIP GPU {gpu_id}] Already exists: {output_path}")
204
+ return
205
+
206
+ print(f"[GPU {gpu_id}] Generating T2V: '{prompt}' -> {output_path}")
207
+ pipeline.run_text_to_video(prompt=prompt, output_path=output_path)
208
+ print(f"[DONE GPU {gpu_id}] Saved: {output_path}")
209
+
210
+
211
+ def process_physicsiq_sample(pipeline, sample: dict, gpu_id: int) -> None:
212
+ """Process a single PhysicsIQ video-to-video sample."""
213
+ prompt = sample["description"]
214
+ prefix_video_path = sample["prefix_video_path"]
215
+ output_path = sample["output_path"]
216
+
217
+ if not os.path.exists(prefix_video_path):
218
+ print(f"[WARN GPU {gpu_id}] Conditioning video not found: {prefix_video_path}")
219
+ return
220
+
221
+ if os.path.exists(output_path):
222
+ print(f"[SKIP GPU {gpu_id}] Already exists: {output_path}")
223
+ return
224
+
225
+ print(f"[GPU {gpu_id}] Generating V2V: '{prompt}'")
226
+ print(f" Input: {prefix_video_path}")
227
+ print(f" Output: {output_path}")
228
+
229
+ pipeline.run_video_to_video(
230
+ prompt=prompt,
231
+ prefix_video_path=prefix_video_path,
232
+ output_path=output_path,
233
+ )
234
+ print(f"[DONE GPU {gpu_id}] Saved: {output_path}")
235
+
236
+
237
+ def worker_process(gpu_id: int, rank: int, config: dict, all_samples: list) -> None:
238
+ """Independent worker running on each GPU."""
239
+ setup_environment(gpu_id)
240
+ configure_reuse_strategy(config)
241
+
242
+ try:
243
+ magi_root = subprocess.check_output(
244
+ ["git", "rev-parse", "--show-toplevel"]
245
+ ).decode().strip()
246
+ os.environ["MAGI_ROOT"] = magi_root
247
+ os.environ["PYTHONPATH"] = f"{magi_root}:{os.environ.get('PYTHONPATH', '')}"
248
+ except Exception as e:
249
+ print(f"[GPU {gpu_id}] Failed to set MAGI_ROOT: {e}")
250
+ return
251
+
252
+ filtered_samples = filter_existing_samples(all_samples, config)
253
+
254
+ if not filtered_samples:
255
+ print(f"[GPU {gpu_id}] No samples need to be generated.")
256
+ return
257
+
258
+ print(f"Processing {len(filtered_samples)} samples.")
259
+
260
+ my_samples = assign_samples_to_gpu(
261
+ filtered_samples, gpu_id, rank, config["num_gpus"]
262
+ )
263
+
264
+ if not my_samples:
265
+ print(f"[GPU {gpu_id}] No samples assigned.")
266
+ return
267
+
268
+ print(f"[GPU {gpu_id}] Assigned {len(my_samples)} samples")
269
+
270
+ from inference.pipeline.entry import MagiPipeline
271
+
272
+ print(f"[GPU {gpu_id}] Loading model...")
273
+ pipeline = MagiPipeline(config["config_file"])
274
+ print(f"[GPU {gpu_id}] Model loaded.")
275
+
276
+ process_func = (
277
+ process_vbench_sample if config["benchmark"] == "vbench" else process_physicsiq_sample
278
+ )
279
+
280
+ for sample in my_samples:
281
+ process_func(pipeline, sample, config, gpu_id)
282
+
283
+ print(f"[GPU {gpu_id}] Completed.")
284
+
285
+
286
+ def build_conditioning_video_path(
287
+ data_root: str, vid_id: str, scenario: str, fps: int
288
+ ) -> str:
289
+ """Construct the path to the conditioning video file."""
290
+ conditioning_dir = os.path.join(
291
+ data_root, "physics-IQ-benchmark", "split-videos", "conditioning", f"{fps}FPS"
292
+ )
293
+ match_suffix = re.search(r"_(.*)", scenario)
294
+ suffix = match_suffix.group(1) if match_suffix else ""
295
+ filename = f"{vid_id}_conditioning-videos_{fps}FPS_{suffix}"
296
+ return os.path.join(conditioning_dir, filename)
297
+
298
+
299
+ def load_physicsiq_samples(config: dict) -> list[dict]:
300
+ """Load sample list from PhysicsIQ dataset."""
301
+ data_root = config["physicsiq_data_dir"]
302
+ descriptions_csv = os.path.join(data_root, "descriptions", "descriptions.csv")
303
+ output_dir = config["save_path"]
304
+
305
+ if not os.path.exists(descriptions_csv):
306
+ raise FileNotFoundError(f"descriptions.csv not found at {descriptions_csv}")
307
+
308
+ os.makedirs(output_dir, exist_ok=True)
309
+
310
+ samples = []
311
+ with open(descriptions_csv, mode="r") as f:
312
+ reader = csv.DictReader(f)
313
+ for row in reader:
314
+ scenario = row["scenario"].strip()
315
+ match_id = re.match(r"^(\d+)_", scenario)
316
+
317
+ if not match_id:
318
+ print(f"Cannot extract ID from scenario: {scenario}")
319
+ continue
320
+
321
+ vid_id = match_id.group(1).zfill(4)
322
+ description = row["description"]
323
+ generated_video_name = row["generated_video_name"]
324
+ prefix_video_path = build_conditioning_video_path(
325
+ data_root, vid_id, scenario, PHYSICSIQ_FPS
326
+ )
327
+ output_path = os.path.join(output_dir, generated_video_name)
328
+
329
+ os.makedirs(os.path.dirname(output_path), exist_ok=True)
330
+
331
+ samples.append({
332
+ "vid_id": vid_id,
333
+ "scenario": scenario,
334
+ "description": description,
335
+ "generated_video_name": generated_video_name,
336
+ "prefix_video_path": prefix_video_path,
337
+ "output_path": output_path,
338
+ })
339
+
340
+ # PhysicsIQ samples are duplicated; take only the first half
341
+ unique_count = len(samples) // 2
342
+ samples = samples[:unique_count]
343
+
344
+ print(f"Loaded {unique_count} PhysicsIQ samples.")
345
+
346
+ return apply_slice(samples, config.get("start"), config.get("end"))
347
+
348
+
349
+ def load_vbench_samples(config: dict) -> list[str]:
350
+ """Load prompt list from vbench dimension file."""
351
+ prompt_dir = config["vbench_prompt_dir"]
352
+ dimension = config.get("dimension")
353
+
354
+ if not dimension:
355
+ raise ValueError("For vbench, 'dimension' must be specified in config")
356
+
357
+ prompt_file = os.path.join(prompt_dir, f"{dimension}.txt")
358
+
359
+ if not os.path.exists(prompt_file):
360
+ raise FileNotFoundError(f"Prompt file not found: {prompt_file}")
361
+
362
+ with open(prompt_file, "r") as f:
363
+ prompts = [line.strip() for line in f if line.strip()]
364
+
365
+ return apply_slice(prompts, config.get("start"), config.get("end"))
366
+
367
+
368
+ def setup_save_path(config: dict) -> None:
369
+ """Configure the output save path based on benchmark type."""
370
+ base_path = config["base_save_path"]
371
+
372
+ if config["benchmark"] == "vbench":
373
+ dimension = config.get("dimension")
374
+ videos_dir = os.path.join(base_path, "videos", dimension) if dimension else None
375
+ config["save_path"] = videos_dir if videos_dir else os.path.join(base_path, "videos")
376
+ elif config["benchmark"] == "physicsiq":
377
+ config["save_path"] = os.path.join(base_path, "videos")
378
+
379
+ os.makedirs(config["save_path"], exist_ok=True)
380
+
381
+
382
+ def main() -> None:
383
+ """Entry point for video sampling script."""
384
+ parser = argparse.ArgumentParser(
385
+ description="Video sampling script using YAML configuration"
386
+ )
387
+ parser.add_argument("yaml_config", type=str, help="Path to YAML configuration file")
388
+ args = parser.parse_args()
389
+
390
+ config = load_yaml_config(args.yaml_config)
391
+ print(f"Loaded configuration from: {args.yaml_config}")
392
+
393
+ setup_save_path(config)
394
+
395
+ gpu_ids = resolve_gpu_ids(config["gpus"])
396
+ config["num_gpus"] = len(gpu_ids)
397
+
398
+ benchmark = config["benchmark"]
399
+ if benchmark == "vbench":
400
+ all_samples = load_vbench_samples(config)
401
+ elif benchmark == "physicsiq":
402
+ data_root = config["physicsiq_data_dir"]
403
+ if not os.path.exists(data_root):
404
+ raise FileNotFoundError(f"Data directory not found: {data_root}")
405
+ all_samples = load_physicsiq_samples(config)
406
+ else:
407
+ raise ValueError(f"Invalid benchmark: {benchmark}")
408
+
409
+ print(f"Total samples: {len(all_samples)}")
410
+ print(f"GPUs: {gpu_ids}")
411
+ print(f"Output: {config['save_path']}")
412
+ print(f"Config: {config['config_file']}")
413
+
414
+ processes = []
415
+ for rank, gpu_id in enumerate(gpu_ids):
416
+ p = mp.Process(target=worker_process, args=(gpu_id, rank, config, all_samples))
417
+ p.start()
418
+ processes.append(p)
419
+
420
+ for p in processes:
421
+ p.join()
422
+
423
+ failed = [p.exitcode for p in processes if p.exitcode != 0]
424
+ if failed:
425
+ raise RuntimeError(f"{len(failed)} worker process(es) failed with exit codes: {failed}")
426
+
427
+
428
+ if __name__ == "__main__":
429
+ main()
FlowCache/FlowCache4MAGI-1/scripts/metric.sh ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ export CUDA_VISIBLE_DEVICES=3
2
+
3
+ python tools/video_metrics.py \
4
+ --original_video "/path/to/original_video.mp4" \
5
+ --generated_video "/path/to/generated_video.mp4"
FlowCache/FlowCache4MAGI-1/tools/plot_l1_rel.py ADDED
@@ -0,0 +1,152 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+
3
+ import argparse
4
+ import json
5
+ from collections import defaultdict
6
+ from pathlib import Path
7
+ from typing import Dict, List, Optional, Set, Tuple
8
+
9
+ import matplotlib
10
+
11
+ matplotlib.use("Agg")
12
+ import matplotlib.pyplot as plt
13
+
14
+
15
+ def parse_int_list(value: Optional[str]) -> Optional[Set[int]]:
16
+ if not value:
17
+ return None
18
+ return {int(item.strip()) for item in value.split(",") if item.strip()}
19
+
20
+
21
+ def load_l1_rel_records(json_path: Path) -> List[dict]:
22
+ with json_path.open("r") as f:
23
+ payload = json.load(f)
24
+ if isinstance(payload, list):
25
+ return payload
26
+ if isinstance(payload, dict) and isinstance(payload.get("records"), list):
27
+ return payload["records"]
28
+ raise ValueError(f"Cannot find records in {json_path}")
29
+
30
+
31
+ def collect_by_chunk(records: List[dict], chunk_ids: Optional[Set[int]], max_chunks: Optional[int]) -> Dict[int, List[dict]]:
32
+ chunks = defaultdict(list)
33
+ for record in records:
34
+ chunk_idx = int(record["chunk_idx"])
35
+ if chunk_ids is not None and chunk_idx not in chunk_ids:
36
+ continue
37
+ chunks[chunk_idx].append(record)
38
+
39
+ chunks = dict(sorted(chunks.items()))
40
+ if max_chunks is not None:
41
+ chunks = dict(list(chunks.items())[:max_chunks])
42
+ return chunks
43
+
44
+
45
+ def plot_l1_rel(
46
+ chunks: Dict[int, List[dict]],
47
+ output_path: Path,
48
+ x_field: str,
49
+ y_field: str,
50
+ reverse_x: bool,
51
+ title: Optional[str],
52
+ figsize: Tuple[float, float],
53
+ dpi: int,
54
+ ) -> None:
55
+ fig, ax = plt.subplots(figsize=figsize)
56
+
57
+ for chunk_idx, records in chunks.items():
58
+ points = []
59
+ for record in records:
60
+ if x_field not in record or y_field not in record:
61
+ continue
62
+ if record[x_field] is None or record[y_field] is None:
63
+ continue
64
+ points.append((float(record[x_field]), float(record[y_field])))
65
+ if not points:
66
+ continue
67
+
68
+ points.sort(key=lambda item: item[0])
69
+ xs, ys = zip(*points)
70
+ ax.plot(xs, ys, marker="o", linewidth=1.6, markersize=3, label=f"chunk {chunk_idx}")
71
+
72
+ ax.set_xlabel(x_field)
73
+ ax.set_ylabel(y_field)
74
+ ax.set_title(title or f"{y_field} by timestep")
75
+ ax.grid(True, alpha=0.3)
76
+ if reverse_x:
77
+ ax.invert_xaxis()
78
+ ax.legend(loc="best", fontsize="small", ncols=2)
79
+ fig.tight_layout()
80
+
81
+ output_path.parent.mkdir(parents=True, exist_ok=True)
82
+ fig.savefig(output_path, dpi=dpi)
83
+ plt.close(fig)
84
+
85
+
86
+ def parse_arguments():
87
+ parser = argparse.ArgumentParser(description="Plot per-chunk MAGI relative L1 change curves.")
88
+ parser.add_argument("json_path", type=Path, help="Path to L1 relative change JSON saved by --l1_rel_stats_path.")
89
+ parser.add_argument("-o", "--output", type=Path, help="Output image path. Defaults to <json stem>_plot.png.")
90
+ parser.add_argument("--chunks", type=str, help="Comma-separated chunk_idx list to plot, for example: 0,1,2.")
91
+ parser.add_argument("--max-chunks", type=int, help="Plot at most this many chunks after filtering.")
92
+ parser.add_argument(
93
+ "--x-field",
94
+ choices=["timestep", "next_timestep", "cur_denoise_step", "denoise_idx"],
95
+ default="next_timestep",
96
+ help="Record field used for the x axis. next_timestep is the cleaner MAGI step.",
97
+ )
98
+ parser.add_argument(
99
+ "--y-field",
100
+ choices=[
101
+ "l1_rel",
102
+ "l1_rel_ratio",
103
+ "delta_l1_norm",
104
+ "x_l1_norm",
105
+ "x_embedder_l1_rel",
106
+ "x_embedder_l1_rel_ratio",
107
+ "x_embedder_delta_l1_norm",
108
+ "x_embedder_x_l1_norm",
109
+ "flowcache_rel_l1",
110
+ "flowcache_rel_l1_ratio",
111
+ "flowcache_delta_l1_norm",
112
+ "flowcache_prev_feat_l1_norm",
113
+ "flowcache_accumulated_rel_l1",
114
+ "rel_l1_thresh",
115
+ ],
116
+ default="l1_rel",
117
+ help="Record field used for the y axis.",
118
+ )
119
+ parser.add_argument("--reverse-x", action="store_true", help="Reverse the x axis.")
120
+ parser.add_argument("--title", type=str, help="Figure title.")
121
+ parser.add_argument("--figsize", type=str, default="10,6", help="Figure size as width,height.")
122
+ parser.add_argument("--dpi", type=int, default=160, help="Output image DPI.")
123
+ return parser.parse_args()
124
+
125
+
126
+ def main():
127
+ args = parse_arguments()
128
+ output_path = args.output or args.json_path.with_name(f"{args.json_path.stem}_plot.png")
129
+ figsize = [float(part.strip()) for part in args.figsize.split(",")]
130
+ if len(figsize) != 2:
131
+ raise ValueError("--figsize must be formatted as width,height")
132
+
133
+ records = load_l1_rel_records(args.json_path)
134
+ chunks = collect_by_chunk(records, parse_int_list(args.chunks), args.max_chunks)
135
+ if not chunks:
136
+ raise ValueError("No records matched the requested chunks.")
137
+
138
+ plot_l1_rel(
139
+ chunks=chunks,
140
+ output_path=output_path,
141
+ x_field=args.x_field,
142
+ y_field=args.y_field,
143
+ reverse_x=args.reverse_x,
144
+ title=args.title,
145
+ figsize=(figsize[0], figsize[1]),
146
+ dpi=args.dpi,
147
+ )
148
+ print(f"Saved plot to {output_path}")
149
+
150
+
151
+ if __name__ == "__main__":
152
+ main()
FlowCache/FlowCache4MAGI-1/tools/plot_residual_norms.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+
3
+ import argparse
4
+ import json
5
+ from collections import defaultdict
6
+ from pathlib import Path
7
+ from typing import Dict, List, Optional, Set, Tuple
8
+
9
+ import matplotlib
10
+
11
+ matplotlib.use("Agg")
12
+ import matplotlib.pyplot as plt
13
+
14
+
15
+ def parse_int_list(value: Optional[str]) -> Optional[Set[int]]:
16
+ if not value:
17
+ return None
18
+ return {int(item.strip()) for item in value.split(",") if item.strip()}
19
+
20
+
21
+ def load_records(json_path: Path) -> List[dict]:
22
+ with json_path.open("r") as f:
23
+ payload = json.load(f)
24
+ if isinstance(payload, list):
25
+ return payload
26
+ if isinstance(payload, dict) and isinstance(payload.get("records"), list):
27
+ return payload["records"]
28
+ raise ValueError(f"Cannot find records in {json_path}")
29
+
30
+
31
+ def group_records(records: List[dict], chunk_ids: Optional[Set[int]], max_chunks: Optional[int]) -> Dict[int, List[dict]]:
32
+ grouped = defaultdict(list)
33
+ for record in records:
34
+ chunk_idx = int(record["chunk_idx"])
35
+ if chunk_ids is not None and chunk_idx not in chunk_ids:
36
+ continue
37
+ grouped[chunk_idx].append(record)
38
+
39
+ grouped = dict(sorted(grouped.items()))
40
+ if max_chunks is not None:
41
+ grouped = dict(list(grouped.items())[:max_chunks])
42
+ return grouped
43
+
44
+
45
+ def build_plot(
46
+ grouped_records: Dict[int, List[dict]],
47
+ output_path: Path,
48
+ x_field: str,
49
+ y_field: str,
50
+ title: Optional[str],
51
+ reverse_x: bool,
52
+ figsize: Tuple[float, float],
53
+ dpi: int,
54
+ ) -> None:
55
+ fig, ax = plt.subplots(figsize=figsize)
56
+
57
+ for chunk_idx, records in grouped_records.items():
58
+ points = []
59
+ for record in records:
60
+ if x_field not in record or y_field not in record:
61
+ continue
62
+ if record[x_field] is None or record[y_field] is None:
63
+ continue
64
+ points.append((float(record[x_field]), float(record[y_field])))
65
+ if not points:
66
+ continue
67
+
68
+ points.sort(key=lambda item: item[0])
69
+ xs, ys = zip(*points)
70
+ ax.plot(xs, ys, marker="o", linewidth=1.6, markersize=3, label=f"chunk {chunk_idx}")
71
+
72
+ ax.set_xlabel(x_field)
73
+ ax.set_ylabel(y_field)
74
+ ax.set_title(title or f"{y_field} by timestep")
75
+ ax.grid(True, alpha=0.3)
76
+ if reverse_x:
77
+ ax.invert_xaxis()
78
+ ax.legend(loc="best", fontsize="small", ncols=2)
79
+ fig.tight_layout()
80
+
81
+ output_path.parent.mkdir(parents=True, exist_ok=True)
82
+ fig.savefig(output_path, dpi=dpi)
83
+ plt.close(fig)
84
+
85
+
86
+ def parse_arguments():
87
+ parser = argparse.ArgumentParser(description="Plot per-chunk residual norm curves from MAGI residual stats JSON.")
88
+ parser.add_argument("json_path", type=Path, help="Path to residual stats JSON saved by --residual_stats_path.")
89
+ parser.add_argument(
90
+ "-o",
91
+ "--output",
92
+ type=Path,
93
+ help="Output image path. Defaults to <json_path stem>_residual_norms.png.",
94
+ )
95
+ parser.add_argument("--chunks", type=str, help="Comma-separated chunk_idx list to plot, for example: 0,1,2.")
96
+ parser.add_argument("--max-chunks", type=int, help="Plot at most this many chunks after filtering.")
97
+ parser.add_argument(
98
+ "--x-field",
99
+ choices=["timestep", "cur_denoise_step", "denoise_idx"],
100
+ default="timestep",
101
+ help="Record field used for the x axis.",
102
+ )
103
+ parser.add_argument(
104
+ "--y-field",
105
+ choices=["residual_norm", "residual_diff_norm"],
106
+ default="residual_norm",
107
+ help="Record field used for the y axis.",
108
+ )
109
+ parser.add_argument("--reverse-x", action="store_true", help="Reverse the x axis.")
110
+ parser.add_argument("--title", type=str, help="Figure title.")
111
+ parser.add_argument("--figsize", type=str, default="10,6", help="Figure size as width,height.")
112
+ parser.add_argument("--dpi", type=int, default=160, help="Output image DPI.")
113
+ return parser.parse_args()
114
+
115
+
116
+ def main():
117
+ args = parse_arguments()
118
+ output_path = args.output or args.json_path.with_name(f"{args.json_path.stem}_residual_norms.png")
119
+ figsize_parts = [float(part.strip()) for part in args.figsize.split(",")]
120
+ if len(figsize_parts) != 2:
121
+ raise ValueError("--figsize must be formatted as width,height")
122
+
123
+ records = load_records(args.json_path)
124
+ grouped_records = group_records(records, parse_int_list(args.chunks), args.max_chunks)
125
+ if not grouped_records:
126
+ raise ValueError("No records matched the requested chunks.")
127
+
128
+ build_plot(
129
+ grouped_records=grouped_records,
130
+ output_path=output_path,
131
+ x_field=args.x_field,
132
+ y_field=args.y_field,
133
+ title=args.title,
134
+ reverse_x=args.reverse_x,
135
+ figsize=(figsize_parts[0], figsize_parts[1]),
136
+ dpi=args.dpi,
137
+ )
138
+ print(f"Saved plot to {output_path}")
139
+
140
+
141
+ if __name__ == "__main__":
142
+ main()
FlowCache/FlowCache4SkyReels-V2/FLOPs claculation.xlsx ADDED
Binary file (18 kB). View file
 
FlowCache/FlowCache4SkyReels-V2/README.md ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # FLOW CACHING FOR AUTOREGRESSIVE VIDEO GENERATION
2
+
3
+ This repository provides the official implementation of **FlowCache** on **SkyReels-V2** model, a caching-based acceleration method for autoregressive video generation models.
4
+
5
+
6
+ ## 🚀 Installation
7
+
8
+ Please follow the installation instructions provided in the [SkyReels-V2](https://github.com/SkyworkAI/SkyReels-V2), as this implementation is built on top of SkyReels-V2.
9
+
10
+ ---
11
+
12
+ ## ▶️ Usage
13
+
14
+ ### 1. Video Generation
15
+
16
+ Run accelerated generation using FlowCache:
17
+
18
+ ```bash
19
+ # FlowCache with KV cache compression
20
+ bash run_flowcache_kvcompress.sh
21
+
22
+ # FlowCache without KV cache compression (fast)
23
+ bash run_flowcache_fast.sh
24
+
25
+ # FlowCache without KV cache compression (slow)
26
+ bash run_flowcache_slow.sh
27
+
28
+ ```
29
+ For the allreuse implementation of Teacache, please refer to the official SkyReels-V2 repository.
30
+
31
+ ---
32
+
33
+ ## ⚙️ Key Parameters
34
+
35
+ | Parameter | Description | Default |
36
+ |----------|-------------|---------|
37
+ | `--model_id` | Model identifier (e.g., `SkyReels-V2/SkyReels-V2-DF-1.3B-540P`) | `Skywork/SkyReels-V2-DF-1.3B-540P` |
38
+ | `--resolution` | Video resolution: `540P` or `720P` | `540P` |
39
+ | `--num_frames` | Total number of frames to generate | `97` |
40
+ | `--base_num_frames` | Base number of frames for autoregressive generation | `97` |
41
+ | `--overlap_history` | Number of overlapping frames between segments | `17` |
42
+ | `--ar_step` | Autoregressive step size for long video generation | `5` |
43
+ | `--causal_block_size` | Block size for causal attention | `5` |
44
+ | `--inference_steps` | Number of denoising steps | `50` |
45
+ | `--guidance_scale` | Classifier-free guidance scale | `6.0` |
46
+ | `--teacache_thresh` | TeaCache threshold for cache reuse (higher = faster) | `0.1` |
47
+ | `--use_compress` | Enable KV compression for KV cache | `False` |
48
+ | `--budget_block` | Number of blocks for KV cache budget | `1` |
49
+ | `--addnoise_condition` | Noise condition for long video consistency | `20` |
50
+ | `--seed` | Random seed for reproducible generation | `1024` |
51
+
52
+ ---
FlowCache/FlowCache4SkyReels-V2/generate_video.py ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import gc
3
+ import os
4
+ import random
5
+ import time
6
+
7
+ import imageio
8
+ import torch
9
+ from diffusers.utils import load_image
10
+
11
+ from skyreels_v2_infer.modules import download_model
12
+ from skyreels_v2_infer.pipelines import Image2VideoPipeline
13
+ from skyreels_v2_infer.pipelines import PromptEnhancer
14
+ from skyreels_v2_infer.pipelines import resizecrop
15
+ from skyreels_v2_infer.pipelines import Text2VideoPipeline
16
+
17
+ MODEL_ID_CONFIG = {
18
+ "text2video": [
19
+ "Skywork/SkyReels-V2-T2V-14B-540P",
20
+ "Skywork/SkyReels-V2-T2V-14B-720P",
21
+ ],
22
+ "image2video": [
23
+ "Skywork/SkyReels-V2-I2V-1.3B-540P",
24
+ "Skywork/SkyReels-V2-I2V-14B-540P",
25
+ "Skywork/SkyReels-V2-I2V-14B-720P",
26
+ ],
27
+ }
28
+
29
+
30
+ if __name__ == "__main__":
31
+
32
+ parser = argparse.ArgumentParser()
33
+ parser.add_argument("--outdir", type=str, default="video_out")
34
+ parser.add_argument("--model_id", type=str, default="Skywork/SkyReels-V2-T2V-14B-540P")
35
+ parser.add_argument("--resolution", type=str, choices=["540P", "720P"])
36
+ parser.add_argument("--num_frames", type=int, default=97)
37
+ parser.add_argument("--image", type=str, default=None)
38
+ parser.add_argument("--guidance_scale", type=float, default=6.0)
39
+ parser.add_argument("--shift", type=float, default=8.0)
40
+ parser.add_argument("--inference_steps", type=int, default=30)
41
+ parser.add_argument("--use_usp", action="store_true")
42
+ parser.add_argument("--offload", action="store_true")
43
+ parser.add_argument("--fps", type=int, default=24)
44
+ parser.add_argument("--seed", type=int, default=None)
45
+ parser.add_argument(
46
+ "--prompt",
47
+ type=str,
48
+ default="A serene lake surrounded by towering mountains, with a few swans gracefully gliding across the water and sunlight dancing on the surface.",
49
+ )
50
+ parser.add_argument("--prompt_enhancer", action="store_true")
51
+ parser.add_argument("--teacache", action="store_true")
52
+ parser.add_argument(
53
+ "--teacache_thresh",
54
+ type=float,
55
+ default=0.2,
56
+ help="Higher speedup will cause to worse quality -- 0.1 for 2.0x speedup -- 0.2 for 3.0x speedup")
57
+ parser.add_argument(
58
+ "--use_ret_steps",
59
+ action="store_true",
60
+ help="Using Retention Steps will result in faster generation speed and better generation quality.")
61
+ args = parser.parse_args()
62
+
63
+ args.model_id = download_model(args.model_id)
64
+ print("model_id:", args.model_id)
65
+
66
+ assert (args.use_usp and args.seed is not None) or (not args.use_usp), "usp mode need seed"
67
+ if args.seed is None:
68
+ random.seed(time.time())
69
+ args.seed = int(random.randrange(4294967294))
70
+
71
+ if args.resolution == "540P":
72
+ height = 544
73
+ width = 960
74
+ elif args.resolution == "720P":
75
+ height = 720
76
+ width = 1280
77
+ else:
78
+ raise ValueError(f"Invalid resolution: {args.resolution}")
79
+
80
+ image = load_image(args.image).convert("RGB") if args.image else None
81
+ 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"
82
+ local_rank = 0
83
+ if args.use_usp:
84
+ assert not args.prompt_enhancer, "`--prompt_enhancer` is not allowed if using `--use_usp`. We recommend running the skyreels_v2_infer/pipelines/prompt_enhancer.py script first to generate enhanced prompt before enabling the `--use_usp` parameter."
85
+ from xfuser.core.distributed import initialize_model_parallel, init_distributed_environment
86
+ import torch.distributed as dist
87
+
88
+ dist.init_process_group("nccl")
89
+ local_rank = dist.get_rank()
90
+ torch.cuda.set_device(dist.get_rank())
91
+ device = "cuda"
92
+
93
+ init_distributed_environment(rank=dist.get_rank(), world_size=dist.get_world_size())
94
+
95
+ initialize_model_parallel(
96
+ sequence_parallel_degree=dist.get_world_size(),
97
+ ring_degree=1,
98
+ ulysses_degree=dist.get_world_size(),
99
+ )
100
+
101
+ prompt_input = args.prompt
102
+ if args.prompt_enhancer and args.image is None:
103
+ print(f"init prompt enhancer")
104
+ prompt_enhancer = PromptEnhancer()
105
+ prompt_input = prompt_enhancer(prompt_input)
106
+ print(f"enhanced prompt: {prompt_input}")
107
+ del prompt_enhancer
108
+ gc.collect()
109
+ torch.cuda.empty_cache()
110
+
111
+ if image is None:
112
+ assert "T2V" in args.model_id, f"check model_id:{args.model_id}"
113
+ print("init text2video pipeline")
114
+ pipe = Text2VideoPipeline(
115
+ model_path=args.model_id, dit_path=args.model_id, use_usp=args.use_usp, offload=args.offload
116
+ )
117
+ else:
118
+ assert "I2V" in args.model_id, f"check model_id:{args.model_id}"
119
+ print("init img2video pipeline")
120
+ pipe = Image2VideoPipeline(
121
+ model_path=args.model_id, dit_path=args.model_id, use_usp=args.use_usp, offload=args.offload
122
+ )
123
+ args.image = load_image(args.image)
124
+ image_width, image_height = args.image.size
125
+ if image_height > image_width:
126
+ height, width = width, height
127
+ args.image = resizecrop(args.image, height, width)
128
+
129
+ if args.teacache:
130
+ pipe.transformer.initialize_teacache(enable_teacache=True, num_steps=args.inference_steps,
131
+ teacache_thresh=args.teacache_thresh, use_ret_steps=args.use_ret_steps,
132
+ ckpt_dir=args.model_id)
133
+
134
+
135
+ kwargs = {
136
+ "prompt": prompt_input,
137
+ "negative_prompt": negative_prompt,
138
+ "num_frames": args.num_frames,
139
+ "num_inference_steps": args.inference_steps,
140
+ "guidance_scale": args.guidance_scale,
141
+ "shift": args.shift,
142
+ "generator": torch.Generator(device="cuda").manual_seed(args.seed),
143
+ "height": height,
144
+ "width": width,
145
+ }
146
+
147
+ if image is not None:
148
+ kwargs["image"] = args.image.convert("RGB")
149
+
150
+ save_dir = os.path.join("result", args.outdir)
151
+ os.makedirs(save_dir, exist_ok=True)
152
+
153
+ with torch.cuda.amp.autocast(dtype=pipe.transformer.dtype), torch.no_grad():
154
+ print(f"infer kwargs:{kwargs}")
155
+ video_frames = pipe(**kwargs)[0]
156
+
157
+ if local_rank == 0:
158
+ current_time = time.strftime("%Y-%m-%d_%H-%M-%S", time.localtime())
159
+ video_out_file = f"{args.prompt[:100].replace('/','')}_{args.seed}_{current_time}.mp4"
160
+ output_path = os.path.join(save_dir, video_out_file)
161
+ imageio.mimwrite(output_path, video_frames, fps=args.fps, quality=8, output_params=["-loglevel", "error"])
FlowCache/FlowCache4SkyReels-V2/generate_video_df.py ADDED
@@ -0,0 +1,231 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import gc
3
+ import os
4
+ import random
5
+ import time
6
+
7
+ import imageio
8
+ import torch
9
+ from diffusers.utils import load_image
10
+
11
+ from skyreels_v2_infer import DiffusionForcingPipeline
12
+ from skyreels_v2_infer.modules import download_model
13
+ from skyreels_v2_infer.pipelines import PromptEnhancer
14
+ from skyreels_v2_infer.pipelines.image2video_pipeline import resizecrop
15
+ from moviepy.editor import VideoFileClip
16
+ # from moviepy import *
17
+
18
+
19
+ def get_video_num_frames_moviepy(video_path):
20
+ with VideoFileClip(video_path) as clip:
21
+ num_frames = 0
22
+ for _ in clip.iter_frames():
23
+ num_frames += 1
24
+ return clip.size, num_frames
25
+
26
+
27
+ if __name__ == "__main__":
28
+ parser = argparse.ArgumentParser()
29
+ parser.add_argument("--outdir", type=str, default="diffusion_forcing")
30
+ parser.add_argument("--model_id", type=str, default="Skywork/SkyReels-V2-DF-1.3B-540P")
31
+ parser.add_argument("--resolution", type=str, choices=["540P", "720P"])
32
+ parser.add_argument("--num_frames", type=int, default=97)
33
+ parser.add_argument("--image", type=str, default=None)
34
+ parser.add_argument("--end_image", type=str, default=None)
35
+ parser.add_argument("--video_path", type=str, default='')
36
+ parser.add_argument("--ar_step", type=int, default=0)
37
+ parser.add_argument("--causal_attention", action="store_true")
38
+ parser.add_argument("--causal_block_size", type=int, default=1)
39
+ parser.add_argument("--base_num_frames", type=int, default=97)
40
+ parser.add_argument("--overlap_history", type=int, default=None)
41
+ parser.add_argument("--addnoise_condition", type=int, default=0)
42
+ parser.add_argument("--guidance_scale", type=float, default=6.0)
43
+ parser.add_argument("--shift", type=float, default=8.0)
44
+ parser.add_argument("--inference_steps", type=int, default=30)
45
+ parser.add_argument("--use_usp", action="store_true")
46
+ parser.add_argument("--offload", action="store_true")
47
+ parser.add_argument("--fps", type=int, default=24)
48
+ parser.add_argument("--seed", type=int, default=None)
49
+ parser.add_argument(
50
+ "--prompt",
51
+ type=str,
52
+ default="A woman in a leather jacket and sunglasses riding a vintage motorcycle through a desert highway at sunset, her hair blowing wildly in the wind as the motorcycle kicks up dust, with the golden sun casting long shadows across the barren landscape.",
53
+ )
54
+ parser.add_argument("--prompt_enhancer", action="store_true")
55
+ parser.add_argument("--teacache", action="store_true")
56
+ parser.add_argument(
57
+ "--teacache_thresh",
58
+ type=float,
59
+ default=0.2,
60
+ help="Higher speedup will cause to worse quality -- 0.1 for 2.0x speedup -- 0.2 for 3.0x speedup")
61
+ parser.add_argument(
62
+ "--use_ret_steps",
63
+ action="store_true",
64
+ help="Using Retention Steps will result in faster generation speed and better generation quality.")
65
+ parser.add_argument("--expname", type=str)
66
+ parser.add_argument("--use_kvrange", action="store_true") # kvrange means using the latest clean KV cache
67
+ parser.add_argument("--kvrange", type=int, default=0)
68
+ parser.add_argument("--use_compress", action="store_true") # use KV compression to compress the KV cache
69
+ parser.add_argument("--budget_block", type=int, default=0) # number of blocks corresponding to buffer
70
+ args = parser.parse_args()
71
+
72
+ args.model_id = download_model(args.model_id)
73
+ print("model_id:", args.model_id)
74
+
75
+ assert (args.use_usp and args.seed is not None) or (not args.use_usp), "usp mode need seed"
76
+ if args.seed is None:
77
+ random.seed(time.time())
78
+ args.seed = int(random.randrange(4294967294))
79
+
80
+ if args.resolution == "540P":
81
+ height = 544
82
+ width = 960
83
+ elif args.resolution == "720P":
84
+ height = 720
85
+ width = 1280
86
+ else:
87
+ raise ValueError(f"Invalid resolution: {args.resolution}")
88
+
89
+ num_frames = args.num_frames
90
+ fps = args.fps
91
+
92
+ if num_frames > args.base_num_frames:
93
+ assert (
94
+ args.overlap_history is not None
95
+ ), 'You are supposed to specify the "overlap_history" to support the long video generation. 17 and 37 are recommanded to set.'
96
+ if args.addnoise_condition > 60:
97
+ print(
98
+ f'You have set "addnoise_condition" as {args.addnoise_condition}. The value is too large which can cause inconsistency in long video generation. The value is recommanded to set 20.'
99
+ )
100
+
101
+ guidance_scale = args.guidance_scale
102
+ shift = args.shift
103
+
104
+ negative_prompt = "色调艳丽,过曝,静态,细节模糊不清,字幕,风格,作品,画作,画面,静止,整体发灰,最差质量,低质量,JPEG压缩残留,丑陋的,残缺的,多余的手指,画得不好的手部,画得不好的脸部,畸形的,毁容的,形态畸形的肢体,手指融合,静止不动的画面,杂乱的背景,三条腿,背景人很多,倒着走"
105
+
106
+ # save_dir = os.path.join("result", args.outdir)
107
+ save_dir = args.outdir
108
+ os.makedirs(save_dir, exist_ok=True)
109
+ local_rank = 0
110
+ if args.use_usp:
111
+ assert not args.prompt_enhancer, "`--prompt_enhancer` is not allowed if using `--use_usp`. We recommend running the skyreels_v2_infer/pipelines/prompt_enhancer.py script first to generate enhanced prompt before enabling the `--use_usp` parameter."
112
+ from xfuser.core.distributed import initialize_model_parallel, init_distributed_environment
113
+ import torch.distributed as dist
114
+
115
+ dist.init_process_group("nccl")
116
+ local_rank = dist.get_rank()
117
+ torch.cuda.set_device(dist.get_rank())
118
+ device = "cuda"
119
+
120
+ init_distributed_environment(rank=dist.get_rank(), world_size=dist.get_world_size())
121
+
122
+ initialize_model_parallel(
123
+ sequence_parallel_degree=dist.get_world_size(),
124
+ ring_degree=1,
125
+ ulysses_degree=dist.get_world_size(),
126
+ )
127
+
128
+ prompt_input = args.prompt
129
+ if args.prompt_enhancer and args.image is None:
130
+ print(f"init prompt enhancer")
131
+ prompt_enhancer = PromptEnhancer()
132
+ prompt_input = prompt_enhancer(prompt_input)
133
+ print(f"enhanced prompt: {prompt_input}")
134
+ del prompt_enhancer
135
+ gc.collect()
136
+ torch.cuda.empty_cache()
137
+
138
+ pipe = DiffusionForcingPipeline(
139
+ args.model_id,
140
+ dit_path=args.model_id,
141
+ device=torch.device("cuda"),
142
+ weight_dtype=torch.bfloat16,
143
+ use_usp=args.use_usp,
144
+ offload=args.offload,
145
+ use_kvrange=args.use_kvrange,
146
+ )
147
+
148
+ if args.causal_attention:
149
+ pipe.transformer.set_ar_attention(args.causal_block_size)
150
+
151
+ if args.teacache:
152
+ if args.ar_step > 0:
153
+ num_steps = args.inference_steps + (((args.base_num_frames - 1) // 4 + 1) // args.causal_block_size - 1) * args.ar_step
154
+ print('num_steps:', num_steps)
155
+ else:
156
+ num_steps = args.inference_steps
157
+ pipe.transformer.initialize_asynchronous_teacache(enable_teacache=True, num_steps=num_steps,
158
+ teacache_thresh=args.teacache_thresh, use_ret_steps=args.use_ret_steps,
159
+ ckpt_dir=args.model_id, inference_steps=args.inference_steps)
160
+
161
+ print(f"prompt:{prompt_input}")
162
+ print(f"guidance_scale:{guidance_scale}")
163
+
164
+ if os.path.exists(args.video_path):
165
+ (v_width, v_height), input_num_frames = get_video_num_frames_moviepy(args.video_path)
166
+ assert input_num_frames >= args.overlap_history, "The input video is too short."
167
+
168
+ if v_height > v_width:
169
+ width, height = height, width
170
+
171
+ video_frames = pipe.extend_video(
172
+ prompt=prompt_input,
173
+ negative_prompt=negative_prompt,
174
+ prefix_video_path=args.video_path,
175
+ height=height,
176
+ width=width,
177
+ num_frames=num_frames,
178
+ num_inference_steps=args.inference_steps,
179
+ shift=shift,
180
+ guidance_scale=guidance_scale,
181
+ generator=torch.Generator(device="cuda").manual_seed(args.seed),
182
+ overlap_history=args.overlap_history,
183
+ addnoise_condition=args.addnoise_condition,
184
+ base_num_frames=args.base_num_frames,
185
+ ar_step=args.ar_step,
186
+ causal_block_size=args.causal_block_size,
187
+ fps=fps,
188
+ )[0]
189
+ else:
190
+ if args.image:
191
+ args.image = load_image(args.image)
192
+ image_width, image_height = args.image.size
193
+ if image_height > image_width:
194
+ height, width = width, height
195
+ args.image = resizecrop(args.image, height, width)
196
+ if args.end_image:
197
+ args.end_image = load_image(args.end_image)
198
+ args.end_image = resizecrop(args.end_image, height, width)
199
+
200
+ image = args.image.convert("RGB") if args.image else None
201
+ end_image = args.end_image.convert("RGB") if args.end_image else None
202
+
203
+ print(f"Saving to: {os.path.join(save_dir, f'{args.expname}-0.mp4')}")
204
+
205
+ with torch.cuda.amp.autocast(dtype=pipe.transformer.dtype), torch.no_grad():
206
+ video_frames = pipe(
207
+ prompt=prompt_input,
208
+ negative_prompt=negative_prompt,
209
+ image=image,
210
+ end_image=end_image,
211
+ height=height,
212
+ width=width,
213
+ num_frames=num_frames,
214
+ num_inference_steps=args.inference_steps,
215
+ shift=shift,
216
+ guidance_scale=guidance_scale,
217
+ generator=torch.Generator(device="cuda").manual_seed(args.seed),
218
+ overlap_history=args.overlap_history,
219
+ addnoise_condition=args.addnoise_condition,
220
+ base_num_frames=args.base_num_frames,
221
+ ar_step=args.ar_step,
222
+ causal_block_size=args.causal_block_size,
223
+ fps=fps,
224
+ args=args,
225
+ )[0]
226
+
227
+ if local_rank == 0:
228
+ current_time = time.strftime("%Y-%m-%d_%H-%M-%S", time.localtime())
229
+ video_out_file = f"{args.expname}-0.mp4"
230
+ output_path = os.path.join(save_dir, video_out_file)
231
+ imageio.mimwrite(output_path, video_frames, fps=fps, quality=8, output_params=["-loglevel", "error"])
FlowCache/FlowCache4SkyReels-V2/requirements.txt ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ opencv-python==4.10.0.84
2
+ diffusers>=0.31.0
3
+ transformers==4.49.0
4
+ tokenizers==0.21.1
5
+ accelerate==1.6.0
6
+ tqdm
7
+ imageio
8
+ easydict
9
+ ftfy
10
+ dashscope
11
+ imageio-ffmpeg
12
+ flash_attn
13
+ numpy>=1.23.5,<2
14
+ xfuser
FlowCache/FlowCache4SkyReels-V2/run_flowcache_fast.sh ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ export CUDA_VISIBLE_DEVICES=5
2
+ model_id="SkyReels-V2/SkyReels-V2-DF-1.3B-540P"
3
+
4
+ python3 generate_video_df.py \
5
+ --model_id ${model_id} \
6
+ --outdir ./result \
7
+ --expname "flowcache_fast" \
8
+ --resolution 540P \
9
+ --ar_step 5 \
10
+ --causal_block_size 5 \
11
+ --base_num_frames 97 \
12
+ --num_frames 177 \
13
+ --overlap_history 17 \
14
+ --prompt "In a still frame, a weathered stop sign stands prominently at a quiet intersection, its red paint slightly faded and edges rusted, evoking a sense of time passed. The sign is set against a backdrop of a serene suburban street, lined with tall, leafy trees whose branches gently sway in the breeze. The sky above is a soft gradient of twilight hues, transitioning from deep blue to a warm orange, suggesting the end of a peaceful day. The surrounding area is calm, with neatly trimmed lawns and quaint houses, their windows glowing softly with indoor lights, adding to the tranquil atmosphere." \
15
+ --addnoise_condition 20 \
16
+ --inference_steps 50 \
17
+ --seed 1024 \
18
+ --teacache \
19
+ --offload \
20
+ --use_ret_steps \
21
+ --guidance_scale 6 \
22
+ --teacache_thresh 0.15
23
+
24
+
FlowCache/FlowCache4SkyReels-V2/run_flowcache_kvcompress.sh ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ export CUDA_VISIBLE_DEVICES=5
2
+ model_id="SkyReels-V2/SkyReels-V2-DF-1.3B-540P"
3
+ # asynchronous inference
4
+ python3 generate_video_df.py \
5
+ --model_id ${model_id} \
6
+ --outdir ./result \
7
+ --expname "flowcache_kvcompress" \
8
+ --resolution 540P \
9
+ --ar_step 5 \
10
+ --causal_block_size 5 \
11
+ --base_num_frames 97 \
12
+ --num_frames 177 \
13
+ --overlap_history 17 \
14
+ --prompt "In a still frame, a weathered stop sign stands prominently at a quiet intersection, its red paint slightly faded and edges rusted, evoking a sense of time passed. The sign is set against a backdrop of a serene suburban street, lined with tall, leafy trees whose branches gently sway in the breeze. The sky above is a soft gradient of twilight hues, transitioning from deep blue to a warm orange, suggesting the end of a peaceful day. The surrounding area is calm, with neatly trimmed lawns and quaint houses, their windows glowing softly with indoor lights, adding to the tranquil atmosphere." \
15
+ --addnoise_condition 20 \
16
+ --inference_steps 50 \
17
+ --seed 1024 \
18
+ --teacache \
19
+ --offload \
20
+ --use_ret_steps \
21
+ --guidance_scale 6 \
22
+ --teacache_thresh 0.1 \
23
+ --use_compress \
24
+ --budget_block 1
FlowCache/FlowCache4SkyReels-V2/run_flowcache_slow.sh ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ export CUDA_VISIBLE_DEVICES=5
2
+ model_id="SkyReels-V2/SkyReels-V2-DF-1.3B-540P"
3
+
4
+ python3 generate_video_df.py \
5
+ --model_id ${model_id} \
6
+ --outdir ./result \
7
+ --expname "flowcache_slow" \
8
+ --resolution 540P \
9
+ --ar_step 5 \
10
+ --causal_block_size 5 \
11
+ --base_num_frames 97 \
12
+ --num_frames 177 \
13
+ --overlap_history 17 \
14
+ --prompt "In a still frame, a weathered stop sign stands prominently at a quiet intersection, its red paint slightly faded and edges rusted, evoking a sense of time passed. The sign is set against a backdrop of a serene suburban street, lined with tall, leafy trees whose branches gently sway in the breeze. The sky above is a soft gradient of twilight hues, transitioning from deep blue to a warm orange, suggesting the end of a peaceful day. The surrounding area is calm, with neatly trimmed lawns and quaint houses, their windows glowing softly with indoor lights, adding to the tranquil atmosphere." \
15
+ --addnoise_condition 20 \
16
+ --inference_steps 50 \
17
+ --seed 1024 \
18
+ --teacache \
19
+ --offload \
20
+ --use_ret_steps \
21
+ --guidance_scale 6 \
22
+ --teacache_thresh 0.1
FlowCache/README.md ADDED
@@ -0,0 +1,228 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <div align="center">
2
+
3
+ <div align="center">
4
+ <img src="assets/FlowCache1.png" width="50%">
5
+ </div>
6
+
7
+ # Flow Caching for Autoregressive Video Generation
8
+
9
+ ### ICLR 2026
10
+
11
+ **[Paper](https://openreview.net/forum?id=vko4DuhKbh)** | **[arXiv](https://arxiv.org/abs/2602.10825)** |
12
+
13
+ **The first caching framework specifically designed for autoregressive video generation**
14
+
15
+ Achieving **2.38× speedup on MAGI-1** and **6.7× on SkyReels-V2** with negligible quality degradation
16
+
17
+ [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)
18
+ [![Python 3.8+](https://img.shields.io/badge/python-3.8+-blue.svg)](https://www.python.org/downloads/)
19
+ [![PyTorch](https://img.shields.io/badge/PyTorch-2.0+-ee4c2c.svg)](https://pytorch.org/)
20
+
21
+ </div>
22
+
23
+ ## 📋 Table of Contents
24
+
25
+ - [News](#news)
26
+ - [Overview](#overview)
27
+ - [Method](#method)
28
+ - [Main Results](#main-results)
29
+ - [Installation](#installation)
30
+ - [Quick Start](#quick-start)
31
+ - [Supported Models](#supported-models)
32
+ - [Todo](#todo)
33
+ - [Contact](#contact)
34
+ - [Citation](#citation)
35
+ - [Acknowledgments](#acknowledgments)
36
+
37
+ ---
38
+
39
+ ## 📰 News
40
+
41
+ - 📄 **2026.02.12**: Paper available on [arXiv](https://arxiv.org/abs/2602.10825)!
42
+ - 🚀 **2026.02.10**: Code release for [MAGI-1](https://github.com/SandAI-org/MAGI-1) and [SkyReels-V2](https://github.com/SkyworkAI/SkyReels-V2)!
43
+ - 🎉 **2026.01.26**: Paper accepted by ICLR 2026!
44
+
45
+ ---
46
+
47
+ ## 🌟 Overview
48
+
49
+ FlowCache is a caching framework designed specifically for **autoregressive video generation models**. Unlike traditional caching methods that treat all frames uniformly, FlowCache introduces a **chunkwise caching strategy** where each video chunk maintains independent caching policies, complemented by **importance-based KV cache compression** that maintains fixed memory bounds while preserving generation quality.
50
+
51
+ <div align="center">
52
+ <img src="assets/visualization.jpg" alt="Overview" width="90%">
53
+ </div>
54
+
55
+ ---
56
+
57
+ ## 🔬 Method
58
+
59
+ ### Key Findings
60
+
61
+ <div align="center">
62
+ <img src="assets/key_findings.jpg" width="90%">
63
+ </div>
64
+
65
+ Our key insight: Different video chunks exhibit heterogeneous denoising states at identical timesteps, necessitating independent caching policies for optimal performance.
66
+
67
+
68
+ ### Framework Overview
69
+
70
+ <div align="center">
71
+ <img src="assets/method.jpg" width="90%">
72
+ </div>
73
+
74
+ FlowCache introduces three key innovations for training-free acceleration of autoregressive video generation:
75
+
76
+ - **Chunkwise Denoising Heterogeneity**: We identify and formalize that denoising progress varies significantly across video chunks—even at the same timestep—necessitating per-chunk caching decisions.
77
+
78
+ - **Chunkwise Adaptive Caching**: A novel design where each chunk independently decides whether to reuse or recompute based on its own similarity trajectory.
79
+
80
+ - **KV Cache Compression Tailored for Video**: We adapt importance–redundancy scoring to autoregressive video generation KV cache compression by introducing an efficient, equivalence-preserving similarity computation, thereby enhancing cache diversity without sacrificing efficiency.
81
+
82
+ These contributions collectively make FlowCache the first theoretically grounded, training-free caching framework for efficient autoregressive video generation.
83
+
84
+ For more details, please refer to the original paper.
85
+
86
+ ---
87
+
88
+ ## 📊 Main Results
89
+
90
+ ### Quantitative Performance
91
+
92
+ #### MAGI-1 (4.5B model)
93
+
94
+ | Method | PFLOPs | Speedup | Latency (s) | VBench | LPIPS | SSIM | PSNR |
95
+ |:------|:------:|:------:|:----------:|:-----:|:-----:|:----:|:----:|
96
+ | Vanilla | 306 | **1.0×** | 2873 | 77.06% | - | - | - |
97
+ | TeaCache-slow | 294 | 1.12× | 2579 | 77.50% | 0.6211 | 0.2801 | 13.26 |
98
+ | TeaCache-fast | 225 | 1.44× | 1998 | 70.11% | 0.8160 | 0.1138 | 8.94 |
99
+ | **FlowCache-slow** | 161 | **1.86×** | 1546 | **78.96%** | 0.3160 | 0.6497 | 22.34 |
100
+ | **FlowCache-fast** | 140 | **2.38×** | 1209 | **77.93%** | 0.4311 | 0.5140 | 19.27 |
101
+
102
+ #### SkyReels-V2 (1.3B model)
103
+
104
+ | Method | PFLOPs | Speedup | Latency (s) | VBench | LPIPS | SSIM | PSNR |
105
+ |:------|:------:|:------:|:----------:|:-----:|:-----:|:----:|:----:|
106
+ | Vanilla | 113 | **1.0×** | 1540 | 83.84% | - | - | - |
107
+ | TeaCache-slow | 58 | 1.89× | 814 | 82.67% | 0.1472 | 0.7501 | 21.96 |
108
+ | TeaCache-fast | 49 | 2.2× | 686 | 80.06% | 0.3063 | 0.6121 | 18.39 |
109
+ | **FlowCache-slow** | 36 | **5.88×** | 262 | **83.12%** | 0.1225 | 0.7890 | 23.74 |
110
+ | **FlowCache-fast** | 28 | **6.7×** | 230 | **83.05%** | 0.1467 | 0.7635 | 22.95 |
111
+
112
+ ---
113
+
114
+ ### Visualization
115
+
116
+ <div align="center">
117
+ <img src="assets/more_visualization1.jpg" width="90%">
118
+ <img src="assets/more_visualization2.jpg" width="90%">
119
+ </div>
120
+
121
+ ---
122
+
123
+ ## 🛠️ Installation
124
+
125
+ ### Prerequisites
126
+
127
+ - Python 3.8+
128
+ - CUDA 11.8+ (or 12.x)
129
+ - PyTorch 2.0+
130
+
131
+ ### MAGI-1 Setup
132
+
133
+ ```bash
134
+ cd FlowCache4MAGI-1
135
+ pip install -r requirements.txt
136
+ ```
137
+
138
+ ### SkyReels-V2 Setup
139
+
140
+ ```bash
141
+ cd FlowCache4SkyReels-V2
142
+ pip install -r requirements.txt
143
+ ```
144
+
145
+ ---
146
+
147
+ ## 🚀 Quick Start
148
+
149
+ ### MAGI-1
150
+
151
+ ```bash
152
+ cd FlowCache4MAGI-1
153
+
154
+ bash scripts/single_run/flowcache_t2v.sh
155
+ ```
156
+
157
+ ### SkyReels-V2
158
+
159
+ ```bash
160
+ cd FlowCache4SkyReels-V2
161
+
162
+ bash run_flowcache_fast.sh
163
+ ```
164
+
165
+ ---
166
+
167
+ ## 🎯 Supported Models
168
+
169
+ | Model | Type | Status |
170
+ |:------|:-----|:------:|
171
+ | **[MAGI-1](https://github.com/SandAI-org/MAGI-1)** | 4.5B-distill | ✅ |
172
+ | **[SkyReels-V2](https://github.com/SkyworkAI/SkyReels-V2)** | 1.3B | ✅ |
173
+
174
+ ---
175
+
176
+ ## 📝 Todo List
177
+
178
+ - [ ] Support more autoregressive video generation models (e.g., self-forcing, causal-forcing, etc.)
179
+ - [ ] Integrate other training-free acceleration methods (e.g., quantization, etc.)
180
+
181
+ ---
182
+
183
+ ## 📮 Contact
184
+
185
+ For questions and collaboration inquiries, please contact the co-first authors. The following are all **WeChat IDs**:
186
+
187
+ - Yuexiao Ma: `ma18640400169`
188
+ - Xuzhe Zheng: `zhengxuzhe_`
189
+ - Jing Xu: `a2665048215`
190
+
191
+ ---
192
+
193
+ ## 📚 Citation
194
+
195
+ If you find FlowCache useful for your research, please cite:
196
+
197
+ ```bibtex
198
+ @misc{ma2026flowcachingautoregressivevideo,
199
+ title={Flow caching for autoregressive video generation},
200
+ author={Yuexiao Ma and Xuzhe Zheng and Jing Xu and Xiwei Xu and Feng Ling and Xiawu Zheng and Huafeng Kuang and Huixia Li and Xing Wang and Xuefeng Xiao and Fei Chao and Rongrong Ji},
201
+ year={2026},
202
+ eprint={2602.10825},
203
+ archivePrefix={arXiv},
204
+ primaryClass={cs.CV},
205
+ url={https://arxiv.org/abs/2602.10825},
206
+ }
207
+ ```
208
+
209
+ ---
210
+
211
+ ## 🙏 Acknowledgments
212
+
213
+ We thank the authors of the following projects for their valuable contributions:
214
+
215
+ - [MAGI-1](https://github.com/SandAI-org/MAGI-1)
216
+ - [SkyReels-V2](https://github.com/SkyworkAI/SkyReels-V2)
217
+ - [TeaCache](https://github.com/ali-vilab/TeaCache)
218
+ - [R-KV](https://github.com/Zefan-Cai/R-KV)
219
+
220
+ ---
221
+
222
+ <div align="center">
223
+
224
+ **⭐ If you find this project useful, please consider giving it a star! ⭐**
225
+
226
+ For questions and feedback, please open an issue on GitHub.
227
+
228
+ </div>