Cccccz commited on
Commit
38a51ff
·
verified ·
1 Parent(s): 9bce1a6

Add files using upload-large-folder tool

Browse files
Experiment.md ADDED
@@ -0,0 +1,550 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Experiment: training-free caching on 4-step block-causal video DiTs
2
+
3
+ 四个 training-free 缓存方法(TeaCache / FlowCache / TaylorSeer / MotionCache)移植到两个 4-step 自回归视频 DiT(Self-Forcing、Causal-Forcing,均为 Wan2.1-1.3B block-causal)上,在匹配的 compute 预算下比较速度与质量。
4
+
5
+ ## 列定义
6
+
7
+ - **策略**:方法 + 调度 + 目标加速比。调度字符串按 chunk 内 4 个去噪步写,`F` = 必算完整 DiT,`x` = 允许方法从缓存服务。`FxxF` 是原始设定(等价于上游 `ret_steps=1` / `cutoff_steps=num_steps-1`),`FFxx` 让 TaylorSeer 在第一次预测前有两个已算点,`Fxxx` 去掉最后一步必算的限制,算术上限从 2.0× 提到 4.0×。
8
+ - **VBench-251 (%)**:Extended-251 协议的 VBench-8 selected 分(4×quality + semantic)/5,251 条 prompt(subject_consistency 72 / overall_consistency 93 / scene 86)。
9
+ - **Full**:一条视频(7 chunk × 4 步 = 28 次去噪 DiT forward)中实际执行的完整 DiT forward 等效数,251 条 prompt 的平均;MotionCache / FlowCache 这类部分重算的步按 compute-equivalent 折算。所有方法按这一列匹配 compute。
10
+ - **平均 P**:一条视频中被**缓存复用**的 forward 数 = 28 − Full。`naiveNstep` 基线走的是更短的去噪调度,缺的 forward 是**根本没有发起**而不是被复用,所以这一列对它们记为 —(它们的 Full 仍按 28 步的标尺给出,便于等算力对照)。Predictor 策略(`cfa_*`,Causal-Forcing-a)按记录里的 `full_forwards` / `predictor_forwards` 计:Full 为完整 DiT 次数,P 为 predictor 调用次数(每次约 0.03 个 forward,不计入 Full)。
11
+ - **模型路径耗时 (ms)**:251 条 prompt 上 denoise policy 路径的 GPU 平均耗时,含缓存方法自己的控制开销;不含 context/KV-cache 刷新 DiT(另计,~790 ms/视频)、文本编码、VAE 解码。
12
+ - **加速比**:matched FFFF 平均耗时 / 该策略平均耗时(同 prompt、同 seed、同一次运行内配对)。原始 26 个策略与 FFFF 同批生成;后加的策略由 `eval/retime_eval.py` 与 FFFF 在同一进程内逐 prompt 配对重新计时(只跑 denoise 路径),其"模型路径耗时"来自这次配对计时,绝对 ms 与首批不在同一争用条件下,只有加速比可跨行比较。首 chunk FFFF 变体(`_c0FFFF`,`teacache_x2_c0FFFF` 除外)的耗时来自 Sep 7 在空闲 GPU 上只重跑策略 denoise 路径的单次重计时(FFFF 不重跑,以各基模 FFFF 首批记录为分母;逐条核对算量一致,视频与质量指标不变)。
13
+ - **PSNR / SSIM / LPIPS**:相对同 prompt、同 seed 的 FFFF,在解码后的 81 帧 RGB 上计算,编码 MP4 之前。FFFF 对自身固定为 120 dB / 1.0 / 0.0。Sep 7 起新增的策略不再重新生成 FFFF,参考帧读自 FFFF 那次运行写出的 MP4(H.264),表中以 § 标出;在同一批视频上实测该替换使 PSNR +0.10 dB、SSIM −0.024、LPIPS +0.012(MP4 抹掉了参考的高频细节),与其它行比较时按此修正。
14
+ - 策略 id 与 `eval_out/` 目录一致(去掉 `sf_`/`cf_`/`cfa_` 前缀):不带调度后缀的是原始 `FxxF` 研究,`_FFxx_`/`_Fxxx_` 为放宽调度后的操作点,`_x<N>` 是搜索时的目标加速比,实际 compute 看 Full 列;`cfa_*` 为 Causal-Forcing-a 上的 Predictor 策略(DisCa / ATC-chunk / ATC-last-frame,均为 Stage-1 监督蒸馏;`atc_chunk_s2_*` 为 ATC-chunk 再经 Stage-2 随机出口 DMD(Wan-14B real score、LoRA rank-128 fake score,2000 步)后的 EMA 权重),后缀 `fppf`/`fppp` 是 chunk 内的调度模式(P = predictor 步)。
15
+
16
+ 视频规格:81 帧、480×832、16 FPS、seed 0、bf16、每 prompt 一个样本。
17
+
18
+ ## 1. Extended-251 评测结果(已完成)
19
+
20
+ ### Self-Forcing
21
+
22
+ | 策略 | VBench-251 (%) | 平均 P | Full | 模型路径耗时 (ms) | 加速比 | PSNR | SSIM | LPIPS |
23
+ |---|---:|---:|---:|---:|---:|---:|---:|---:|
24
+ | **原始调度(chunk 0 与其它 chunk 相同)** | | | | | | | | |
25
+ | `ffff` | 80.5372 | 0.000 | 28.000 | 3157.96 | 1.000× | 120.000 | 1.0000 | 0.0000 |
26
+ | `euler_FFFF` | 78.7741 | 0.000 | 28.000 | 3171.53 | 0.996× | 9.996 § | 0.3108 § | 0.6051 § |
27
+ | | | | | | | | | |
28
+ | *≈1.3×* | | | | | | | | |
29
+ | `teacache_x1.3` | 79.5878 | 5.633 | 22.367 | 2547.49 | 1.240× | 15.161 | 0.5325 | 0.3198 |
30
+ | `flowcache_x1.3` | 79.6210 | 6.076 | 21.924 | 2547.75 | 1.240× | 15.151 | 0.5325 | 0.3202 |
31
+ | `taylorseer_x1.3` | 79.8313 | 7.000 | 21.000 | 2439.16 | 1.295× | 13.315 | 0.4421 | 0.4469 |
32
+ | `taylorseer_FFxx_x1.3` | 79.2201 | 6.000 | 22.000 | 2588.89 | 1.226× | 13.128 | 0.4449 | 0.4290 |
33
+ | `motioncache_x1.3` | 79.2294 | 6.537 | 21.463 | 2762.30 | 1.143× | 13.264 | 0.4499 | 0.4431 |
34
+ | `reuse_FRFF` | 79.2460 | 7.000 | 21.000 | 2382.76 † | 1.325× † | 13.186 § | 0.4401 § | 0.4497 § |
35
+ | | | | | | | | | |
36
+ | *≈1.6×* | | | | | | | | |
37
+ | `teacache_x1.6` | 78.9947 | 8.757 | 19.243 | 2187.41 | 1.444× | 13.116 | 0.4428 | 0.4520 |
38
+ | `flowcache_x1.6` | 78.4997 | 9.255 | 18.745 | 2215.58 | 1.425× | 12.991 | 0.4339 | 0.4659 |
39
+ | `taylorseer_x1.6` | 79.0823 | 11.000 | 17.000 | 2008.93 | 1.572× | 13.398 | 0.4082 | 0.5029 |
40
+ | `taylorseer_FFxx_x1.6` | 66.3821 | 10.000 | 18.000 | 2102.06 | 1.509× | 11.321 | 0.3028 | 0.6140 |
41
+ | `motioncache_x1.6` | 79.4907 | 10.597 | 17.403 | 2126.98 | 1.485× | 13.127 | 0.4332 | 0.4722 |
42
+ | | | | | | | | | |
43
+ | *≈1.75×* | | | | | | | | |
44
+ | `teacache_x1.75` | 79.2788 | 7.725 | 20.275 | 3142.11 | 1.381× | 13.142 | 0.4471 | 0.4460 |
45
+ | `taylorseer_x1.75` | 78.6295 | 13.000 | 15.000 | 2379.43 | 1.823× | 13.479 | 0.4007 | 0.5163 |
46
+ | `motioncache_x1.75` | 79.0342 | 12.222 | 15.778 | 2713.77 | 1.599× | 13.046 | 0.4265 | 0.4823 |
47
+ | | | | | | | | | |
48
+ | *≈2×* | | | | | | | | |
49
+ | `teacache_x2` | 78.7743 | 14.000 | 14.000 | 1608.20 | 1.964× | 13.020 | 0.4222 | 0.4854 |
50
+ | `flowcache_x2` | 78.7743 | 14.000 | 14.000 | 1613.54 | 1.957× | 13.020 | 0.4222 | 0.4854 |
51
+ | `taylorseer_x2` | 78.2747 | 14.000 | 14.000 | 1667.04 | 1.894× | 13.486 | 0.3974 | 0.5240 |
52
+ | `taylorseer_FFxx_x2` | 57.1775 | 14.000 | 14.000 | 1687.69 | 1.880× | 9.626 | 0.1555 | 0.8272 |
53
+ | `motioncache_x2` | 78.7809 | 14.000 | 14.000 | 1621.06 | 1.948× | 13.020 | 0.4222 | 0.4854 |
54
+ | `reuse_FRRF` | 78.7743 | 14.000 | 14.000 | 1604.42 † | 1.968× † | 13.102 § | 0.4150 § | 0.4865 § |
55
+ | | | | | | | | | |
56
+ | *≈2.85–3×* | | | | | | | | |
57
+ | `teacache_Fxxx_x2.85` | 60.1481 | 14.000 | 14.000 | 2207.42 | 1.965× | 11.844 | 0.3029 | 0.6665 |
58
+ | `teacache_Fxxx_x3` | 58.6783 | 20.155 | 7.845 | 913.40 | 3.473× | 11.946 | 0.2851 | 0.7049 |
59
+ | `flowcache_Fxxx_x3` | 55.7999 | 19.851 | 8.149 | 987.12 | 3.214× | 12.013 | 0.2866 | 0.6946 |
60
+ | `taylorseer_Fxxx_x2.85` | 60.3007 | 19.000 | 9.000 | 1468.31 | 2.954× | 11.750 | 0.2608 | 0.7051 |
61
+ | `motioncache_Fxxx_x2.85` | 58.6018 | 20.344 | 7.656 | 1707.75 | 2.540× | 11.928 | 0.2649 | 0.7232 |
62
+ | `motioncache_Fxxx_x3` | 59.2793 | 18.785 | 9.215 | 1625.07 | 1.952× | 12.240 | 0.2860 | 0.6889 |
63
+ | | | | | | | | | |
64
+ | *≈3.3–4×* | | | | | | | | |
65
+ | `reuse_FRRR` | 58.1223 | 21.000 | 7.000 | 823.91 † | 3.833× † | 11.699 § | 0.2565 § | 0.7347 § |
66
+ | | | | | | | | | |
67
+ | **首 chunk FFFF(`_c0FFFF`)** | | | | | | | | |
68
+ | | | | | | | | | |
69
+ | *≈1.3×* | | | | | | | | |
70
+ | `teacache_x1.3_c0FFFF` | 80.3851 | 3.785 | 24.215 | 2721.09 | 1.161× | 20.370 | 0.8421 | 0.0866 |
71
+ | `taylorseer_x1.3_c0FFFF` | 80.4439 | 6.000 | 22.000 | 2517.09 | 1.255× | 17.312 | 0.6934 | 0.1524 |
72
+ | `motioncache_x1.3_c0FFFF` | 79.9742 | 5.490 | 22.510 | 2790.03 | 1.132× | 17.332 | 0.6934 | 0.1520 |
73
+ | | | | | | | | | |
74
+ | *≈1.6×* | | | | | | | | |
75
+ | `teacache_x1.6_c0FFFF` | 80.0586 | 7.179 | 20.821 | 2334.11 | 1.353× | 17.180 § | 0.6581 § | 0.1808 § |
76
+ | | | | | | | | | |
77
+ | *≈1.75×* | | | | | | | | |
78
+ | `taylorseer_x1.75_c0FFFF` | 79.4426 | 11.000 | 17.000 | 1930.29 | 1.636× | 16.752 | 0.6201 | 0.2132 |
79
+ | `motioncache_x1.75_c0FFFF` | 80.3427 | 10.328 | 17.672 | 2180.22 | 1.448× | 16.749 | 0.6578 | 0.1794 |
80
+ | | | | | | | | | |
81
+ | *≈2×* | | | | | | | | |
82
+ | `teacache_x2_c0FFFF` | 79.7515 | 12.000 | 16.000 | 1766.63 | 1.788× | 16.611 | 0.6511 | 0.1883 |
83
+ | | | | | | | | | |
84
+ | *≈2.85–3×* | | | | | | | | |
85
+ | `teacache_Fxxx_x3_c0FFFF` | 61.3078 | 17.713 | 10.287 | 1092.03 | 2.892× | 13.994 | 0.4180 | 0.5821 |
86
+ | `taylorseer_Fxxx_x2.85_c0FFFF` | 65.5397 | 16.000 | 12.000 | 1330.42 | 2.374× | 14.321 | 0.4627 | 0.4903 |
87
+ | `motioncache_Fxxx_x2.85_c0FFFF` | 62.0397 | 17.174 | 10.826 | 1650.77 | 1.913× | 14.279 | 0.4229 | 0.5744 |
88
+
89
+ ### Causal-Forcing
90
+
91
+ | 策略 | VBench-251 (%) | 平均 P | Full | 模型路径耗时 (ms) | 加速比 | PSNR | SSIM | LPIPS |
92
+ |---|---:|---:|---:|---:|---:|---:|---:|---:|
93
+ | **原始调度(chunk 0 与其它 chunk 相同)** | | | | | | | | |
94
+ | `ffff` | 81.1659 | 0.000 | 28.000 | 3156.09 | 1.000× | 120.000 | 1.0000 | 0.0000 |
95
+ | | | | | | | | | |
96
+ | *≈1.3×* | | | | | | | | |
97
+ | `teacache_x1.3` | 81.2244 | 6.088 | 21.912 | 2488.55 | 1.268× | 13.229 | 0.5272 | 0.3419 |
98
+ | `flowcache_x1.3` | 81.8224 | 5.145 | 22.855 | 2683.28 | 1.176× | 13.260 | 0.5272 | 0.3415 |
99
+ | `taylorseer_x1.3` | 81.6245 | 7.000 | 21.000 | 2437.75 | 1.295× | 11.994 | 0.4488 | 0.4509 |
100
+ | `taylorseer_FFxx_x1.3` | 80.2569 | 6.000 | 22.000 | 2569.62 | 1.223× | 11.395 | 0.4381 | 0.4580 |
101
+ | `motioncache_x1.3` | 81.2477 | 6.424 | 21.576 | 2716.36 | 1.162× | 12.068 | 0.4614 | 0.4450 |
102
+ | `naive3step` | 81.4017 | — | 21.000 | 2377.69 † | 1.327× † | 11.873 | 0.4393 | 0.4448 |
103
+ | `reuse_FRFF` | 81.3133 | 7.000 | 21.000 | 2387.76 † | 1.322× † | 11.845 | 0.4615 | 0.4467 |
104
+ | | | | | | | | | |
105
+ | *≈1.6×* | | | | | | | | |
106
+ | `teacache_x1.6` | 81.2088 | 9.781 | 18.219 | 2058.41 | 1.533× | 11.932 | 0.4590 | 0.4511 |
107
+ | `flowcache_x1.6` | 80.4213 | 10.631 | 17.369 | 2086.39 | 1.513× | 11.738 | 0.4424 | 0.4744 |
108
+ | `taylorseer_x1.6` | 80.4207 | 11.000 | 17.000 | 2008.23 | 1.572× | 12.175 | 0.4082 | 0.5063 |
109
+ | `taylorseer_FFxx_x1.6` | 65.8948 | 10.000 | 18.000 | 2092.15 | 1.502× | 9.924 | 0.3015 | 0.6262 |
110
+ | `motioncache_x1.6` | 80.8268 | 10.521 | 17.479 | 2243.38 | 1.407× | 11.911 | 0.4404 | 0.4737 |
111
+ | | | | | | | | | |
112
+ | *≈1.75×* | | | | | | | | |
113
+ | `teacache_x1.75` | 81.2378 | 9.127 | 18.873 | 2386.91 | 1.481× | 11.899 | 0.4596 | 0.4493 |
114
+ | `taylorseer_x1.75` | 79.9462 | 13.000 | 15.000 | 1977.36 | 1.788× | 12.178 | 0.4020 | 0.5182 |
115
+ | `motioncache_x1.75` | 80.6695 | 13.388 | 14.612 | 2270.46 | 1.557× | 11.936 | 0.4400 | 0.4824 |
116
+ | | | | | | | | | |
117
+ | *≈2×* | | | | | | | | |
118
+ | `teacache_x2` | 79.9681 | 14.000 | 14.000 | 1607.05 | 1.964× | 11.900 | 0.4402 | 0.4835 |
119
+ | `flowcache_x2` | 79.9681 | 14.000 | 14.000 | 1612.28 | 1.958× | 11.900 | 0.4402 | 0.4835 |
120
+ | `taylorseer_x2` | 79.7412 | 14.000 | 14.000 | 1666.32 | 1.894× | 12.160 | 0.3995 | 0.5260 |
121
+ | `taylorseer_FFxx_x2` | 57.3124 | 14.000 | 14.000 | 1673.11 | 1.879× | 8.788 | 0.1646 | 0.8242 |
122
+ | `motioncache_x2` | 79.9909 | 14.000 | 14.000 | 1618.55 | 1.950× | 11.901 | 0.4402 | 0.4835 |
123
+ | `naive2step` | 80.5679 | — | 14.000 | 1589.72 † | 1.985× † | 11.745 | 0.4131 | 0.4883 |
124
+ | `reuse_FRRF` | 80.0407 | 14.000 | 14.000 | 1607.58 † | 1.963× † | 11.900 | 0.4402 | 0.4835 |
125
+ | | | | | | | | | |
126
+ | *≈2.85–3×* | | | | | | | | |
127
+ | `teacache_Fxxx_x3` | 65.0186 | 18.378 | 9.622 | 1087.44 | 2.891× | 11.352 | 0.3356 | 0.6346 |
128
+ | `flowcache_Fxxx_x3` | 65.1726 | 18.073 | 9.927 | 1161.04 | 2.707× | 11.338 | 0.3387 | 0.6278 |
129
+ | `taylorseer_Fxxx_x2.85` | 60.9596 | 19.000 | 9.000 | 1217.30 | 2.904× | 10.339 | 0.2573 | 0.7044 |
130
+ | `motioncache_Fxxx_x2.85` | 59.5795 | 19.957 | 8.043 | 1706.05 | 2.072× | 10.619 | 0.2432 | 0.7114 |
131
+ | `motioncache_Fxxx_x3` | 60.9864 | 18.657 | 9.343 | 1698.44 | 1.849× | 10.941 | 0.2716 | 0.6802 |
132
+ | | | | | | | | | |
133
+ | *≈3.3–4×* | | | | | | | | |
134
+ | `naive1step` | 75.5181 | — | 7.000 | 797.85 † | 3.956× † | 11.470 | 0.4009 | 0.5506 |
135
+ | `reuse_FRRR` | 58.8612 | 21.000 | 7.000 | 825.80 † | 3.822× † | 10.148 | 0.2478 | 0.7408 |
136
+ | | | | | | | | | |
137
+ | **首 chunk FFFF(`_c0FFFF`)** | | | | | | | | |
138
+ | | | | | | | | | |
139
+ | *≈1.3×* | | | | | | | | |
140
+ | `teacache_x1.3_c0FFFF` | 81.0382 | 4.697 | 23.303 | 2611.40 | 1.209× | 16.495 | 0.7670 | 0.1410 |
141
+ | `taylorseer_x1.3_c0FFFF` | 81.3120 | 6.000 | 22.000 | 2522.30 | 1.251× | 14.728 | 0.6736 | 0.1983 |
142
+ | `motioncache_x1.3_c0FFFF` | 81.3863 | 5.410 | 22.590 | 2754.74 | 1.146× | 14.950 | 0.6803 | 0.1935 |
143
+ | `naive3step_c0FFFF` | 81.3914 | — | 22.000 | 2457.13 † | 1.284× † | 14.407 § | 0.6324 § | 0.2236 § |
144
+ | `reuse_FRFF_c0FFFF` | 81.3370 | 6.000 | 22.000 | 2467.84 † | 1.279× † | 14.775 § | 0.6624 § | 0.2046 § |
145
+ | | | | | | | | | |
146
+ | *≈1.75×* | | | | | | | | |
147
+ | `taylorseer_x1.75_c0FFFF` | 80.7431 | 11.000 | 17.000 | 1935.50 | 1.631× | 14.443 | 0.5972 | 0.2719 |
148
+ | `motioncache_x1.75_c0FFFF` | 81.1129 | 11.295 | 16.705 | 2173.89 | 1.452× | 14.454 | 0.6430 | 0.2301 |
149
+ | `naive2step_c0FFFF` | 81.7050 | — | 16.000 | 1746.77 † | 1.807× † | 14.259 § | 0.6122 § | 0.2437 § |
150
+ | `reuse_FRRF_c0FFFF` | 81.1816 | 12.000 | 16.000 | 1766.47 † | 1.787× † | 14.502 § | 0.6254 § | 0.2413 § |
151
+ | | | | | | | | | |
152
+ | *≈2×* | | | | | | | | |
153
+ | `teacache_x2_c0FFFF` | 81.1816 | 12.000 | 16.000 | 1764.22 | 1.789× | 14.431 § | 0.6423 § | 0.2327 § |
154
+ | | | | | | | | | |
155
+ | *≈2.85–3×* | | | | | | | | |
156
+ | `teacache_Fxxx_x3_c0FFFF` | 65.6584 | 16.558 | 11.442 | 1225.90 | 2.574× | 12.895 | 0.4612 | 0.5070 |
157
+ | `taylorseer_Fxxx_x2.85_c0FFFF` | 65.4647 | 16.000 | 12.000 | 1334.99 | 2.364× | 12.802 | 0.4509 | 0.5047 |
158
+ | `motioncache_Fxxx_x2.85_c0FFFF` | 64.0830 | 16.900 | 11.100 | 1792.95 | 1.760× | 12.959 | 0.4250 | 0.5596 |
159
+ | `naive1step_c0FFFF` | 79.1501 | — | 10.000 | 1035.46 † | 3.048× † | 14.104 § | 0.5977 § | 0.2779 § |
160
+ | `reuse_FRRR_c0FFFF` | 59.5377 | 18.000 | 10.000 | 1061.93 † | 2.972× † | 12.433 § | 0.3890 § | 0.6052 § |
161
+
162
+ ### Causal-Forcing-a(Predictor)
163
+
164
+ | 策略 | VBench-251 (%) | 平均 P | Full | 模型路径耗时 (ms) | 加速比 | PSNR | SSIM | LPIPS |
165
+ |---|---:|---:|---:|---:|---:|---:|---:|---:|
166
+ | **7 chunk(81 帧)** | | | | | | | | |
167
+ | `ffff` | 81.1659 | 0.000 | 28.000 | 3225.29 | 1.000× | 120.000 | 1.0000 | 0.0000 |
168
+ | | | | | | | | | |
169
+ | *≈1.3×* | | | | | | | | |
170
+ | `atc_chunk_s2_fpff` | 80.9902 | 6.000 | 22.000 | 2519.19 † | 1.280× † | 14.667 | 0.6761 | 0.1970 |
171
+ | | | | | | | | | |
172
+ | *≈1.75×* | | | | | | | | |
173
+ | `atc_chunk_fppf` | 81.5505 | 12.000 | 16.000 | 1900.49 | 1.697× | 14.635 | 0.6532 | 0.2215 |
174
+ | `atc_chunk_s2_fppf` | 81.2486 | 12.000 | 16.000 | 1871.26 † | 1.724× † | 14.452 | 0.6460 | 0.2260 |
175
+ | `atc_last_frame_fppf` | 81.2733 | 12.000 | 16.000 | 1897.37 | 1.700× | 14.622 | 0.6531 | 0.2217 |
176
+ | `disca_fppf` | 81.4375 | 12.000 | 16.000 | 1857.48 | 1.736× | 14.551 | 0.6516 | 0.2213 |
177
+ | `disca_s1000_fppf` | 81.2360 | 12.000 | 16.000 | 1824.35 ‡ | 1.768× ‡ | 14.830 § | 0.6229 § | 0.2380 § |
178
+ | `atc_chunk_fpf` | 81.2960 | 6.000 | 16.000 | 1819.13 | 1.773× | 14.523 § | 0.6117 § | 0.2419 § |
179
+ | | | | | | | | | |
180
+ | *≈2.85–3×* | | | | | | | | |
181
+ | `atc_chunk_fppp` | 77.3396 | 18.000 | 10.000 | 1238.59 | 2.604× | 14.328 | 0.6088 | 0.3012 |
182
+ | `atc_chunk_s2_fppp` | 78.6374 | 18.000 | 10.000 | 1221.75 † | 2.640× † | 14.135 | 0.5971 | 0.2976 |
183
+ | `atc_last_frame_fppp` | 77.3843 | 18.000 | 10.000 | 1234.61 | 2.612× | 14.298 | 0.6096 | 0.3005 |
184
+ | `disca_fppp` | 75.9581 | 18.000 | 10.000 | 1157.33 | 2.787× | 14.073 | 0.5782 | 0.3242 |
185
+ | `disca_s1000_fppp` | 72.2150 | 18.000 | 10.000 | 1153.31 ‡ | 2.797× ‡ | 13.858 § | 0.5182 § | 0.4040 § |
186
+ | | | | | | | | | |
187
+ | **14 chunk(165 帧)** | | | | | | | | |
188
+ | `14c_ffff` | 81.0061 | 0.000 | 56.000 | 7410.82 | 1.000× | 120.000 | 1.0000 | 0.0000 |
189
+ | | | | | | | | | |
190
+ | *≈1.75×* | | | | | | | | |
191
+ | `atc_chunk_14c_fppf` | 80.5734 | 26.000 | 30.000 | 4196.75 | 1.766× | 12.824 | 0.5568 | 0.3382 |
192
+ | `atc_chunk_s2_14c_fppf` | 80.9730 | 26.000 | 30.000 | 4196.14 | 1.766× | 12.715 | 0.5512 | 0.3452 |
193
+ | `atc_chunk_s2_s500_14c_fppf` | 81.0817 | 26.000 | 30.000 | 4167.73 | 1.778× | 12.817 § | 0.5299 § | 0.3522 § |
194
+ | `atc_chunk_s2_s1000_14c_fppf` | 81.1134 | 26.000 | 30.000 | 4167.71 | 1.778× | 12.748 § | 0.5311 § | 0.3524 § |
195
+ | `disca_14c_fppf` | 80.5953 | 26.000 | 30.000 | 4075.89 | 1.818× | 12.806 § | 0.5328 § | 0.3462 § |
196
+ | `disca_s500_14c_fppf` | 80.1191 | 26.000 | 30.000 | 4075.51 | 1.818× | 12.268 § | 0.5120 § | 0.3670 § |
197
+ | `disca_s1000_14c_fppf` | 80.5057 | 26.000 | 30.000 | 4075.84 | 1.818× | 13.040 § | 0.5250 § | 0.3631 § |
198
+ | `naive2step_14c` | 80.7865 | — | 30.000 | 3880.86 | 1.910× | 12.597 § | 0.5211 § | 0.3578 § |
199
+ | | | | | | | | | |
200
+ | **28 chunk(333 帧)** | | | | | | | | |
201
+ | `28c_ffff` | 77.9850 | 0.000 | 112.000 | 15832.56 | 1.000× | 120.000 | 1.0000 | 0.0000 |
202
+ | | | | | | | | | |
203
+ | *≈1.75×* | | | | | | | | |
204
+ | `atc_chunk_28c_fppf` | 77.4779 | 54.000 | 58.000 | 8831.55 | 1.793× | 11.004 | 0.4520 | 0.4727 |
205
+ | `atc_chunk_s2_28c_fppf` | 78.6544 | 54.000 | 58.000 | 8830.84 | 1.793× | 11.077 | 0.4412 | 0.4814 |
206
+ | `atc_chunk_s2_s500_28c_fppf` | 78.5516 | 54.000 | 58.000 | 8790.80 | 1.801× | 11.109 § | 0.4214 § | 0.4906 § |
207
+ | `atc_chunk_s2_s1000_28c_fppf` | 78.8416 | 54.000 | 58.000 | 8790.42 | 1.801× | 11.092 § | 0.4255 § | 0.4850 § |
208
+ | `disca_28c_fppf` | 77.8652 | 54.000 | 58.000 | 8598.80 | 1.841× | 10.985 § | 0.4235 § | 0.4813 § |
209
+ | `disca_s500_28c_fppf` | 75.4569 | 54.000 | 58.000 | 8599.47 | 1.841× | 10.342 § | 0.3920 § | 0.5037 § |
210
+ | `disca_s1000_28c_fppf` | 77.3960 | 54.000 | 58.000 | 8599.13 | 1.841× | 11.171 § | 0.4119 § | 0.5065 § |
211
+ | | | | | | | | | |
212
+ | *≈2×* | | | | | | | | |
213
+ | `naive2step_28c` | 78.7351 | — | 58.000 | 8139.14 | 1.945× | 11.024 § | 0.4163 § | 0.4844 § |
214
+
215
+ ### HY-WorldPlay(I2V,VBench-I2V-100)
216
+
217
+ 第三个基模:HY-WorldPlay 的 4-step 蒸馏自回归 I2V 模型(HunyuanVideo-1.5 架构,54 个 double-stream block,480×832,125 帧 = 8 chunk × 4 步 = **32 次去噪 forward**)。评测集为 DEV 项目的 validation25:25 张 VBench-I2V 图 × 4 组双向相机动作 = 100 个视频,seed 0。两列 VBench 都基于 `custom_input` 模式下的同一组 **Core5** 五个画质维度(subject_consistency、background_consistency、motion_smoothness、aesthetic_quality、imaging_quality,后者先除以 100):**原始**列是五项原始分的简单平均,口径与 HY-WorldPlay-DEV-Predictor 项目 experiment.md 第 8 节的 VBench Core5 一致,便于直接对照;**归一**列先按 VBench 官方 min-max 归一再平均,即 `((sc−0.1462)/0.8538 + (bc−0.2615)/0.7385 + (ms−0.7060)/0.2915 + aq + iq) / 5`,与 251 表的质量组口径一致。平均 P = 32 − Full。耗时列为去噪路径(32 次 forward)的 GPU 时间,不含每 chunk 一次的 context KV pass 和文本 KV pass;加速比与同进程内同一 job 的 FFFF 配对。
218
+
219
+ | 策略 | VBench-I2V-100 原始 (%) | VBench-I2V-100 归一 (%) | 平均 P | Full | 模型路径耗时 (ms) | 加速比 | PSNR | SSIM | LPIPS |
220
+ |---|---:|---:|---:|---:|---:|---:|---:|---:|---:|
221
+ | **原始调度(chunk 0 与其它 chunk 相同)** | | | | | | | | | |
222
+ | `ffff` | 84.2562 | 83.3246 | 0.000 | 32.000 | 26412.97 | 1.000× | 120.000 | 1.0000 | 0.0000 |
223
+ | | | | | | | | | | |
224
+ | *≈1.3×* | | | | | | | | | |
225
+ | `teacache_x1.3` | 84.3669 | 83.4689 | 8.000 | 24.000 | 19930.69 | 1.325× | 20.117 | 0.7697 | 0.1102 |
226
+ | `taylorseer_x1.3` | 84.2522 | 83.3337 | 7.000 | 25.000 | 22387.68 | 1.180× | 18.140 | 0.6780 | 0.1582 |
227
+ | `motioncache_x1.3` | 84.2313 | 83.3155 | 8.000 | 24.000 | 23101.18 | 1.143× | 17.845 | 0.6725 | 0.1642 |
228
+ | `naive3step` | 84.2911 | 83.3647 | — | 24.000 | 20351.22 | 1.330× | 19.353 | 0.7400 | 0.1261 |
229
+ | `reuse_FRFF` | 84.2897 | 83.3844 | 8.000 | 24.000 | 20673.89 | 1.309× | 18.187 | 0.6792 | 0.1575 |
230
+ | | | | | | | | | | |
231
+ | *≈1.75×* | | | | | | | | | |
232
+ | `teacache_x1.75` | 84.2693 | 83.3820 | 11.320 | 20.680 | 17177.16 | 1.538× | 17.638 | 0.6630 | 0.1781 |
233
+ | `taylorseer_x1.75` | 84.2668 | 83.3677 | 15.000 | 17.000 | 15685.12 | 1.684× | 16.903 | 0.6269 | 0.2090 |
234
+ | `motioncache_x1.75` | 84.2535 | 83.3566 | 14.382 | 17.618 | 17322.76 | 1.525× | 17.001 | 0.6305 | 0.2058 |
235
+ | | | | | | | | | | |
236
+ | *≈2×* | | | | | | | | | |
237
+ | `naive2step` | 84.2625 | 83.3436 | — | 16.000 | 13670.78 | 1.979× | 18.023 | 0.6641 | 0.1771 |
238
+ | `reuse_FRRF` | 84.2277 | 83.3291 | 16.000 | 16.000 | 13895.92 | 1.947× | 17.001 | 0.6288 | 0.2081 |
239
+ | | | | | | | | | | |
240
+ | *≈2.85–3×* | | | | | | | | | |
241
+ | `teacache_Fxxx_x2.85` | 82.8598 | 81.7531 | 19.380 | 12.620 | 10516.41 | 2.512× | 16.115 | 0.5980 | 0.2634 |
242
+ | `taylorseer_Fxxx_x2.85` | 82.4336 | 81.1889 | 21.000 | 11.000 | 10475.24 | 2.522× | 15.394 | 0.5608 | 0.3208 |
243
+ | `motioncache_Fxxx_x2.85` | 81.3278 | 79.9229 | 22.295 | 9.705 | 10594.27 | 2.494× | 15.160 | 0.5474 | 0.3761 |
244
+ | | | | | | | | | | |
245
+ | *≈3.3–4×* | | | | | | | | | |
246
+ | `naive1step` | 83.1146 | 82.0591 | — | 8.000 | 6940.58 | 3.899× | 16.096 | 0.5808 | 0.2998 |
247
+ | `reuse_FRRR` | 81.2746 | 79.8838 | 24.000 | 8.000 | 7182.47 | 3.767× | 15.043 | 0.5461 | 0.3698 |
248
+ | | | | | | | | | | |
249
+ | **首 chunk FFFF(`_c0FFFF`;Predictor 行 chunk 0 固定全算)** | | | | | | | | | |
250
+ | | | | | | | | | | |
251
+ | *≈1.3×* | | | | | | | | | |
252
+ | `naive3step_c0FFFF` | 84.2618 | 83.3402 | — | 25.000 | 20247.11 | 1.305× | 21.728 § | 0.7794 § | 0.1072 § |
253
+ | `reuse_FRFF_c0FFFF` | 84.2477 | 83.3293 | 7.000 | 25.000 | 20320.55 | 1.300× | 19.967 § | 0.7262 § | 0.1315 § |
254
+ | | | | | | | | | | |
255
+ | *≈1.75×* | | | | | | | | | |
256
+ | `teacache_x1.75_c0FFFF` | 84.2781 | 83.3869 | 14.000 | 18.000 | 14225.79 | 1.857× | 18.616 § | 0.6855 § | 0.1668 § |
257
+ | `taylorseer_x1.75_c0FFFF` | 84.2736 | 83.3736 | 14.000 | 18.000 | 15502.48 | 1.704× | 18.598 § | 0.6845 § | 0.1670 § |
258
+ | `motioncache_x1.75_c0FFFF` | 84.2630 | 83.3633 | 13.930 | 18.070 | 16165.60 | 1.634× | 18.587 § | 0.6843 § | 0.1672 § |
259
+ | `disca_s1_fppf` | 84.1670 | 83.2478 | 14.000 | 18.000 | 14662.50 ¶ | 1.801× ¶ | 19.668 | 0.7233 | 0.1346 |
260
+ | `disca_s500_fppf` | 待打分 | 待打分 | 14.000 | 18.000 | 14841.37 ¶ | 1.780× ¶ | 19.350 | 0.7120 | 0.1410 |
261
+ | `disca_s1000_fppf` | 84.1546 | 83.2336 | 14.000 | 18.000 | 14720.59 ¶ | 1.794× ¶ | 19.660 | 0.7216 | 0.1350 |
262
+ | `atc_s1_fppf` | 84.1847 | 83.2703 | 14.000 | 18.000 | 15812.57 ¶ | 1.670× ¶ | 20.056 | 0.7439 | 0.1257 |
263
+ | `atc_s2_s500_fppf_c0FFFF` | 84.2119 | 83.3056 | 14.000 | 18.000 | 20950.51 ¶ | 1.261× ¶ | 20.183 | 0.7480 | 0.1205 |
264
+ | `atc_s2_s800_fppf_c0FFFF` | 84.2323 | 83.3288 | 14.000 | 18.000 | 15629.35 ¶ | 1.690× ¶ | 20.457 | 0.7570 | 0.1163 |
265
+ | `atc_s2_s1000_fppf_c0FFFF` | 84.2230 | 83.3159 | 14.000 | 18.000 | 15566.46 ¶ | 1.697× ¶ | 20.265 | 0.7537 | 0.1176 |
266
+ | `atc_s2_s1500_fppf_c0FFFF` | 84.2264 | 83.3206 | 14.000 | 18.000 | 15546.63 ¶ | 1.699× ¶ | 20.581 | 0.7628 | 0.1137 |
267
+ | `atc_s2_s2000_fppf_c0FFFF` | 84.2402 | 83.3379 | 14.000 | 18.000 | 18191.28 ¶ | 1.452× ¶ | 20.519 | 0.7611 | 0.1144 |
268
+ | `naive2step_c0FFFF` | 84.2625 | 83.3447 | — | 18.000 | 14095.82 | 1.874× | 19.723 § | 0.7122 § | 0.1480 § |
269
+ | `reuse_FRRF_c0FFFF` | 84.2781 | 83.3869 | 14.000 | 18.000 | 14188.73 | 1.862× | 18.616 § | 0.6855 § | 0.1668 § |
270
+ | | | | | | | | | | |
271
+ | *≈2.85–3×* | | | | | | | | | |
272
+ | `teacache_Fxxx_x2.85_c0FFFF` | 82.6370 | 81.4356 | 18.320 | 13.680 | 10420.56 | 2.535× | 17.402 § | 0.6493 § | 0.2323 § |
273
+ | `taylorseer_Fxxx_x2.85_c0FFFF` | 81.6863 | 80.2616 | 21.000 | 11.000 | 9202.77 | 2.870× | 16.731 § | 0.6155 § | 0.2800 § |
274
+ | `motioncache_Fxxx_x2.85_c0FFFF` | 81.4090 | 79.9492 | 20.875 | 11.125 | 10491.83 | 2.517× | 16.788 § | 0.6167 § | 0.2840 § |
275
+ | `disca_s1_fppp` | 81.9808 | 80.7777 | 21.000 | 11.000 | 8802.08 ¶ | 3.001× ¶ | 18.980 | 0.6791 | 0.2445 |
276
+ | `disca_s1000_fppp` | 82.0229 | 80.8101 | 21.000 | 11.000 | 8728.97 ¶ | 3.026× ¶ | 18.891 | 0.6772 | 0.2430 |
277
+ | `atc_s1_fppp` | 81.9767 | 80.7813 | 21.000 | 11.000 | 10200.68 ¶ | 2.589× ¶ | 19.270 | 0.6931 | 0.2328 |
278
+ | `atc_s2_s500_fppp_c0FFFF` | 82.8711 | 81.7725 | 21.000 | 11.000 | 12327.93 ¶ | 2.143× ¶ | 19.203 | 0.6956 | 0.2063 |
279
+ | `atc_s2_s800_fppp_c0FFFF` | 82.7394 | 81.6377 | 21.000 | 11.000 | 9916.60 ¶ | 2.664× ¶ | 19.352 | 0.6991 | 0.2087 |
280
+ | `atc_s2_s1000_fppp_c0FFFF` | 82.7097 | 81.5668 | 21.000 | 11.000 | 10035.86 ¶ | 2.632× ¶ | 19.248 | 0.6952 | 0.2097 |
281
+ | `atc_s2_s1500_fppp_c0FFFF` | 82.7710 | 81.6625 | 21.000 | 11.000 | 9942.50 ¶ | 2.657× ¶ | 19.317 | 0.6989 | 0.2069 |
282
+ | `atc_s2_s2000_fppp_c0FFFF` | 82.7682 | 81.6582 | 21.000 | 11.000 | 11259.37 ¶ | 2.346× ¶ | 19.336 | 0.6989 | 0.2077 |
283
+ | `naive1step_c0FFFF` | 83.6264 | 82.6327 | — | 11.000 | 7928.52 | 3.331× | 17.717 § | 0.6393 § | 0.2345 § |
284
+ | `reuse_FRRR_c0FFFF` | 81.5309 | 80.0960 | 21.000 | 11.000 | 8070.78 | 3.273× | 16.796 § | 0.6174 § | 0.2812 § |
285
+
286
+ ### LingBot-World-V2-1.3B-Causal-Fast(I2V,VBench-I2V-100)
287
+
288
+ 第四个基模:LingBot-World-V2 的 1.3B causal-fast 蒸馏自回归 I2V 世界模型(Wan2.1-1.3B block-causal 架构,30 个 block,相机 Plucker 条件,480×832,16 fps,125 帧 = 8 chunk × 4 latent × 4 步 = **32 次去噪 forward**,KV 窗口 18 latent、sink 6)。评测协议与 HY-WorldPlay 完全相同:validation25 的 25 张图 × 4 组双向相机动作 = 100 个视频,seed 0,Core5 五维、原始/归一两列同上;相机动作把 HY 的逐 latent 位姿(前进 0.08 单位/latent、旋转 3°/latent,前半程正向、后半程反向)换算成 LingBot 需要的逐帧 OpenCV c2w 位姿(4 帧/latent),内参取模型 480×832 示例数据的 fx = fy ≈ 415.6。**这里的 `reuse_*` 复用的是 velocity 而不是 block 残差**:R 步完全不调用 DiT,直接把上一次算出的 flow 预测当作本步预测(`x0 = x_t − σ_t·v_prev`),再照常 renoise;因此 R 步耗时≈0,FRFF/FRRF/FRRR 的 Full 精确为 24/16/8。三个缓存方法(TeaCache / TaylorSeer / MotionCache)按 `cachelib` 的同一套移植接在 30 个 block 的循环上(block 级重实现与官方 forward 逐位一致,`lb_test_exact.py`),操作点沿用 HY 的流程:TeaCache 的 rescale 多项式用 3 个 case × 125 帧标定(`lb_coeff.json`,一次多项式,R² 0.63);`x1.3` 由 compute fraction 二分得到(`lb_sweep_*.json`,61 帧);`x1.75` / `Fxxx_x2.85` 及其 `_c0FFFF` 变体在 61 帧、配对 FFFF 的实测加速比网格上定点(`lb_point_v2.json` / `lb_point_c0.json`,选点规则与 HY 相同)。naive 减步按 Self-Forcing 的规则取 4 步网格的均匀子集(4 步网格 t = 999/937/833/624;3 步 = 999/833/624、2 步 = 999/624、1 步 = 999)。`atc_chunk_*` / `disca_*` 为 Layer-17 Predictor(`lingbot-world-v2-a`,Causal-Forcing-a 的同款移植:复制教师 block 17 + 融合模块,预测 head 输入的 final hidden;离线集 = 100 组 HY 训练图 × 4 动作 × 7 chunk × 3 相邻转移 = 8400 个样本,Stage-1 监督蒸馏 2000 步、全局 batch 64、fusion lr 1e-4 / block lr 1e-5,未做 Stage-2);chunk 0 固定 FFFF,FPPF / FPPP 中 P 步锚定同 chunk 上一步的 hidden,FPF 只走 t = 999 / 937 / 624 三步(P 锚定 t = 999);P 列为 Predictor 调用次数,Full 为完整 DiT 次数,Predictor 按 1/30 次 forward 计入算量。耗时列为去噪路径的 GPU 时间,不含每 chunk 一次的 context KV pass(t=0 的 KV 重写);加速比与同进程内同一 job 的 FFFF 配对。
289
+
290
+ | 策略 | VBench-I2V-100 原始 (%) | VBench-I2V-100 归一 (%) | 平均 P | Full | 模型路径耗时 (ms) | 加速比 | PSNR | SSIM | LPIPS |
291
+ |---|---:|---:|---:|---:|---:|---:|---:|---:|---:|
292
+ | **原始调度(chunk 0 与其它 chunk 相同)** | | | | | | | | | |
293
+ | `ffff` | 82.3539 | 80.2586 | 0.000 | 32.000 | 6093.68 | 1.000× | 120.000 | 1.0000 | 0.0000 |
294
+ | | | | | | | | | | |
295
+ | *≈1.3×* | | | | | | | | | |
296
+ | `teacache_x1.3` | 82.1485 | 80.1311 | 8.000 | 24.000 | 4645.01 | 1.313× | 15.926 | 0.5619 | 0.3094 |
297
+ | `taylorseer_x1.3` | 81.8251 | 79.8054 | 7.000 | 25.000 | 5023.59 | 1.214× | 16.037 | 0.5614 | 0.3130 |
298
+ | `motioncache_x1.3` | 81.2355 | 79.1397 | 7.286 | 24.714 | 5070.72 | 1.203× | 16.005 | 0.5622 | 0.3111 |
299
+ | `naive3step` | 82.1337 | 80.0778 | — | 24.000 | 4581.98 | 1.331× | 15.369 | 0.4767 | 0.3358 |
300
+ | `reuse_FRFF` | 82.0735 | 80.0272 | 8.000 | 24.000 | 4573.81 | 1.332× | 15.855 | 0.5632 | 0.3077 |
301
+ | | | | | | | | | | |
302
+ | *≈1.75×* | | | | | | | | | |
303
+ | `teacache_x1.75` | 80.9831 | 78.8059 | 9.930 | 22.070 | 4330.60 | 1.408× | 15.655 | 0.5365 | 0.3393 |
304
+ | `taylorseer_x1.75` | 76.6210 | 73.8544 | 16.000 | 16.000 | 3405.13 | 1.791× | 15.126 | 0.4776 | 0.4592 |
305
+ | `motioncache_x1.75` | 79.4888 | 77.0818 | 13.937 | 18.063 | 3835.59 | 1.590× | 15.496 | 0.5152 | 0.3733 |
306
+ | | | | | | | | | | |
307
+ | *≈2×* | | | | | | | | | |
308
+ | `naive2step` | 80.5176 | 78.3186 | — | 16.000 | 3061.56 | 1.992× | 14.945 | 0.4544 | 0.3699 |
309
+ | `reuse_FRRF` | 76.7683 | 73.5659 | 16.000 | 16.000 | 3059.20 | 1.992× | 14.869 | 0.4767 | 0.4288 |
310
+ | | | | | | | | | | |
311
+ | *≈2.85–3×* | | | | | | | | | |
312
+ | `teacache_Fxxx_x2.85` | 75.1360 | 71.6186 | 17.590 | 14.410 | 2895.33 | 2.106× | 13.435 | 0.4067 | 0.5503 |
313
+ | `taylorseer_Fxxx_x2.85` | 70.8612 | 65.4422 | 21.000 | 11.000 | 2534.78 | 2.406× | 11.432 | 0.2408 | 0.7647 |
314
+ | `motioncache_Fxxx_x2.85` | 71.0194 | 64.6213 | 23.623 | 8.377 | 2357.22 | 2.587× | 11.080 | 0.2028 | 0.7918 |
315
+ | | | | | | | | | | |
316
+ | *≈3.3–4×* | | | | | | | | | |
317
+ | `naive1step` | 75.1651 | 72.2501 | — | 8.000 | 1542.10 | 3.955× | 14.197 | 0.4394 | 0.4368 |
318
+ | `reuse_FRRR` | 71.5376 | 65.4500 | 24.000 | 8.000 | 1541.77 | 3.952× | 10.160 | 0.1762 | 0.8437 |
319
+ | | | | | | | | | | |
320
+ | **首 chunk FFFF(`_c0FFFF`;Predictor 行 chunk 0 固定全算)** | | | | | | | | | |
321
+ | | | | | | | | | | |
322
+ | *≈1.3×* | | | | | | | | | |
323
+ | `naive3step_c0FFFF` | 82.1607 | 80.1107 | — | 25.000 | 4720.24 | 1.292× | 16.469 | 0.5485 | 0.2759 |
324
+ | `reuse_FRFF_c0FFFF` | 82.1895 | 80.1582 | 7.000 | 25.000 | 4720.73 | 1.292× | 17.293 | 0.6455 | 0.2377 |
325
+ | | | | | | | | | | |
326
+ | *≈1.75×* | | | | | | | | | |
327
+ | `teacache_x1.75_c0FFFF` | 78.9073 | 76.3152 | 14.000 | 18.000 | 3439.77 | 1.773× | 16.656 | 0.5814 | 0.3268 |
328
+ | `taylorseer_x1.75_c0FFFF` | 77.4694 | 74.7649 | 13.000 | 19.000 | 3860.07 | 1.580× | 16.253 | 0.5518 | 0.3966 |
329
+ | `motioncache_x1.75_c0FFFF` | 78.9094 | 76.3180 | 13.992 | 18.008 | 3733.35 | 1.634× | 16.659 | 0.5815 | 0.3267 |
330
+ | `atc_chunk_fppf` | 80.0022 | 77.8061 | 14.000 | 18.000 | 3536.15 | 1.728× | 17.301 | 0.6297 | 0.2778 |
331
+ | `disca_fppf` | 80.0298 | 77.8495 | 14.000 | 18.000 | 3481.70 | 1.755× | 17.275 | 0.6279 | 0.2766 |
332
+ | `atc_chunk_fpf` | 80.2317 | 78.0594 | 7.000 | 18.000 | 3445.52 | 1.774× | 16.765 | 0.5490 | 0.2936 |
333
+ | `disca_fpf` | 80.3026 | 78.1454 | 7.000 | 18.000 | 3413.59 | 1.790× | 16.731 | 0.5497 | 0.2933 |
334
+ | `naive2step_c0FFFF` | 80.8730 | 78.7215 | — | 18.000 | 3342.15 | 1.825× | 16.162 | 0.5342 | 0.3007 |
335
+ | `reuse_FRRF_c0FFFF` | 76.9432 | 73.7413 | 14.000 | 18.000 | 3340.95 | 1.825× | 15.996 | 0.5476 | 0.3793 |
336
+ | | | | | | | | | | |
337
+ | *≈2.85–3×* | | | | | | | | | |
338
+ | `teacache_Fxxx_x2.85_c0FFFF` | 76.7028 | 73.5163 | 14.650 | 17.350 | 3323.93 | 1.835× | 15.709 | 0.5422 | 0.3865 |
339
+ | `taylorseer_Fxxx_x2.85_c0FFFF` | 62.0634 | 53.7016 | 21.000 | 11.000 | 2371.54 | 2.572× | 12.114 | 0.2968 | 0.7078 |
340
+ | `motioncache_Fxxx_x2.85_c0FFFF` | 62.0254 | 53.9066 | 20.996 | 11.004 | 2265.94 | 2.691× | 12.192 | 0.3137 | 0.6975 |
341
+ | `atc_chunk_fppp` | 73.6541 | 70.6632 | 21.000 | 11.000 | 2257.30 | 2.707× | 16.577 | 0.5786 | 0.3895 |
342
+ | `disca_fppp` | 73.6381 | 70.4325 | 21.000 | 11.000 | 2166.88 | 2.820× | 16.518 | 0.5565 | 0.3864 |
343
+ | `naive1step_c0FFFF` | 76.6593 | 73.9502 | — | 11.000 | 1960.37 | 3.111× | 15.430 | 0.5203 | 0.3572 |
344
+ | `reuse_FRRR_c0FFFF` | 62.1155 | 53.9646 | 21.000 | 11.000 | 1961.77 | 3.109× | 11.297 | 0.2748 | 0.7399 |
345
+
346
+ † 耗时来自该策略自己的生成运行(独占 GPU、单进程),与各基模 FFFF 首批记录相比得到加速比,未做同进程配对计时;按约定不再做 FFFF 重计时。其中 `atc_chunk_s2_fpff`(153/251 条)、`atc_chunk_s2_fppf`(155/251 条)、`atc_chunk_s2_fppp`(156/251 条) 的耗时只来自生成时计时未被破坏的那部分 prompt:其余记录的原始计时被一次中断且遭遇 GPU 争用的配对重计时覆盖,已在记录中标记 `latency_excluded` 并从耗时均值剔除,VBench 与像素指标仍用全部 251 条。
347
+
348
+ ‡ 该行有部分记录在生成时 GPU 被其他进程短暂共用(Sep 7 的 `disca_s1000_*`:GPU 4/7 上的 gpu_burn 占位,06:22–06:40,每策略约 84 条),这些记录事后在空闲 GPU 上只重跑策略路径重新计时(FFFF 不重跑,逐条核对算量一致,旧值保留在记录的 `generation_run_latency`);其余记录为独占 GPU 的生成运行值。所有记录均为单进程计时。
349
+
350
+ § 像素指标以 FFFF 运行写出的 MP4 解码帧为参考(其余行以 MP4 编码前的原始帧为参考);同一批视频上实测差异:PSNR +0.10 dB、SSIM −0.024、LPIPS +0.012。`cf_teacache_x2_c0FFFF` 为混合(75/251 条用 MP4 参考)。
351
+
352
+ ¶ `hy_atc_s1_*` / `hy_disca_s1_*` 来自 HY-WorldPlay-DEV-Predictor 的 validation25 评测(ATC Stage-1,`predictor_v4_atc-full_transport-global-chunk_…_4gpu_bs8x2_steps2000`,step 2000,FPPF/FPPP,chunk 0 四步全算——DEV 的 rollout 固定如此,Predictor 需要前一 chunk;FPPF = 18 full + 14 Predictor,FPPP = 11 + 21),耗时为该项目生成器的 host 端分段计时(`ar_step_transformer + ar_step_predictor`,即去噪路径,不含 context/history KV),与本表其它行的 CUDA event 计时口径接近但不完全相同;像素指标对照 DEV 项目 validation 的 FFFF 视频(与 `hy_ffff` 同源)。DisCa 为双 block Predictor(blocks [0,53],Sep 8 用 `--force_first_chunk_full` 重跑)。`hy_atc_s2_s<N>_*` 为同一 ATC Stage-1 再经 on-policy detached chunk+timestep FPPP rollout 微调(4 卡、每卡 1 条轨迹 × 累积 2、flr 5e-5 / blr 5e-6、2000 steps)后第 N 步的权重,Sep 10 评测(DEV experiment.md 第 12 节),生成设置与 `hy_atc_s1_*` 相同。Predictor 步按 1/54(DisCa 2/54)次 forward 计入 Full。
353
+
354
+ ### 读数备注
355
+
356
+ - 2.0× 是 `FxxF` 的算术上限(14/28),到了这一档 TeaCache / FlowCache / MotionCache 全部退化成"中间两步整体跳过、残差拷贝",走的是同一条代码路径,所以三者数字一致;TaylorSeer 在 2.0× 上不同(逐模块拷贝 + 当前步调制),且略差。
357
+ - `FxxF` 下 TaylorSeer 的一阶预测从未被触发:跳步前 chunk 内只算过 step 0,差分导数不存在,实际走的是 order-0(拷贝)。`FFxx` 调度就是为了让预测真正生效。
358
+ - 像素指标(PSNR 12–15 dB)与 VBench(掉 0–1.4 分)严重脱钩;在这个设定里 PSNR/SSIM 只能当"偏离 FFFF 的程度"读,不是质量代理。
359
+ - **第一个 chunk 不该被缓存。** `teacache_x2_c0FFFF` 与 `teacache_x2` 用同一个阈值,唯一区别是 chunk 0 走满 FFFF 四步(算力 16/28 vs 14/28)。Self-Forcing 上 VBench ��� 78.7743 升到 79.7515(**+0.98**,把相对 FFFF 的 1.76 分差距砍掉 55%),像素保真度改善更大:PSNR 13.02→16.61(**+3.59 dB**)、SSIM 0.4222→0.6511、LPIPS 0.4854→0.1883(几乎减半)。逐维增益集中在外观类(imaging_quality +0.021、aesthetic_quality +0.021、subject_consistency +0.014、scene +0.011),dynamic_degree −0.014(画面更稳)。机理很直接:第一个 chunk 没有前序 chunk 可复用,且整段视频的外观都继承自它,缓存它等于把误差灌进后面所有 chunk。值得注意的是它同时**又快又好于** `teacache_x1.3`(1.788× vs 1.240×,79.75 vs 79.59,PSNR 16.61 vs 15.16)——「首 chunk 全算 + 后续激进缓存」比「全程温和缓存」是更优的算力分配。
360
+ - **首 chunk FFFF 对三种方法、三个档位都成立(SF,`_c0FFFF` 行,Sep 6)。** 同参数下 VBench 一律上升:TeaCache 1.3× 79.59→80.39、1.6× 78.99→80.06(+1.07,1.353×)、`Fxxx` 3× 58.68→61.31;TaylorSeer 1.3× 79.83→80.44、1.75× 78.63→79.44、`Fxxx` 2.85× 60.30→65.54(**+5.2**);MotionCache 1.3× 79.23→79.97、1.75× 79.03→80.34(**+1.31**,已到 FFFF 的 80.54 只差 0.2)、`Fxxx` 2.85× 58.60→62.04。像素保真度更是整体抬升一个台阶:`FxxF` 各档 PSNR 从 13.0–15.2 dB 升到 16.7–20.4 dB、LPIPS 从 0.32–0.52 降到 0.09–0.21;`Fxxx` 档 PSNR 也从 11.7–11.9 升到 14.0–14.3。代价是首 chunk 多算 1–3 次 forward,实测加速比回落 0.08–0.6×(1.3× 档几乎不亏:1.24→1.16、1.30→1.26、1.14→1.13;3× 档亏最多:3.47→2.89、2.95→2.37、2.54→1.90)。两点值得写进论文:(i) `motioncache_x1.75_c0FFFF` 在 1.445× 上达到 80.34 / PSNR 16.75,是 SF 上所有非 FFFF 配置里最接近 FFFF 的一档;(ii) 即便首 chunk 全算,`Fxxx` 仍停在 61–66 分——最后一步的损失是逐 chunk 局部的,不是从首 chunk 传下来的,所以两条规则相互独立:首 chunk 全算、最后一步全算。
361
+ - **首 chunk FFFF 在 Causal-Forcing 上同样成立,但 1.3× 档没有余量。** CF 的 FFFF 是 81.17,而三种方法的 1.3× 原版已经在 81.2–81.6(与 FFFF 持平或更高,属评测噪声),所以 `_c0FFFF` 在这一档 VBench 变化在 ±0.3 内(TeaCache 81.22→81.04、TaylorSeer 81.62→81.31、MotionCache 81.25→81.39);但只要原版有损失,首 chunk 全算就把损失补回来:TeaCache 2× 79.97→**81.18**(+1.21,1.789× 下回到 FFFF 的 81.17;PSNR 11.90→14.43),1.75× TaylorSeer 79.95→80.74、MotionCache 80.67→81.11(回到 FFFF 水平),`Fxxx` 档 TaylorSeer 60.96→65.46、MotionCache 59.58→64.08(各 **+4.5**)、TeaCache 65.02→65.66。像素保真度则和 SF 一样全面抬升:`FxxF` 各档 PSNR 12.0–13.2→14.4–16.5、LPIPS 0.34–0.52→0.14–0.27。SF/CF 两个基模合起来,16 组同参数对照中 VBench 14 升 2 平(2 平的都是原本已到 FFFF 的 CF 1.3× 档),PSNR 16/16 上升。
362
+ - **naive 减步是很强的对照。** 在 Causal-Forcing 上按等算力配对(Full 完全相同):21/28 档 `naive3step` 81.40 vs `reuse_FRFF` 81.31,14/28 档 80.57 vs 80.04,7/28 档 **75.52 vs 58.86**——直接少走几步全面不输于、低算力时远好于固定位置的残差复用,因为 `FRRR` 只算首步、其余三步复用同一个残差,误差累积到崩溃。更关键的是 `naive2step`(14/28、80.57)优于所有缓存方法在同一算力下的成绩(`teacache_x2` / `motioncache_x2` 均为 79.97–79.99),即在这个基模上「直接少走两步」比「走满四步再缓存两步」更划算。
363
+ - **HY-WorldPlay 上 naive 减步几乎免费,直接复用不是(Sep 6,Core5 原始分)。** `naive3step` 84.29、`naive2step` 84.26 与 FFFF 84.26 持平,`naive1step` 83.11(−1.1)却拿到 **3.90×**;像素上 naive3/2/1 的 PSNR 19.4 / 18.0 / 16.1。等算力对照:24/32 档 `naive3step` 84.29 ≈ `reuse_FRFF` 84.29 ≈ `teacache_x1.3` 84.37;16/32 档 `naive2step` 84.26 ≈ `reuse_FRRF` 84.23;8/32 档 `naive1step` 83.11 vs `reuse_FRRR` 81.27(**+1.8**,PSNR 16.1 vs 15.0)。也就是说 HY 这类蒸馏 AR 模型对步数极不敏感(4 步→2 步无损、→1 步只掉 1 分),三种缓存方法在 `FxxF` 下做到的 1.5–1.7× 都被 `naive2step` 的 1.98× 无损覆盖;缓存方法唯一还能争的是 2.5–2.9× 那一档,而那一档它们(81.3–82.9)也输给 `naive1step`(83.1,3.9×)。把 Self-Forcing/Causal-Forcing 上「naive 减步强于缓存」的结论推广到 HY 是成立的,而且更极端。
364
+ - **首 chunk FFFF + naive 减步是 CF 上目前最强的算力分配(Sep 7)。** 后 6 个 chunk 减步、chunk 0 仍走 4 步:`naive3step_c0FFFF` 81.39(22/28,1.284×)、`naive2step_c0FFFF` **81.71**(16/28,1.807×,高于 FFFF 的 81.17)、`naive1step_c0FFFF` **79.15**(10/28,3.048×)。对比同算力的其它配置:16/28 档 `teacache_x2_c0FFFF` = `reuse_FRRF_c0FFFF` 81.18、`taylorseer_x1.75_c0FFFF`(17) 80.74;10/28 档所有 `Fxxx` 缓存方法 61–66、`reuse_FRRR_c0FFFF` 59.5,而 `naive1step_c0FFFF` 79.15 领先 13 分以上——原因同前:减步让最后一次预测仍在 t=1000 这一训练过的时间步上做(对 1 步就是唯一一步),而 `Fxxx` 是把最后一步换成过期残差。首 chunk FFFF 对 naive 的增益随减步幅度放大:3 步 −0.01、2 步 +1.14、1 步 **+3.63**(75.52→79.15),像素指标也从 11.5–11.9 dB 抬到 14.1–14.4 dB。直接复用(reuse)在同算力下始终不如减步:22/28 档 81.34 vs 81.39,16/28 档 81.18 vs 81.71,10/28 档 59.5 vs 79.2。
365
+ - **HY 上首 chunk FFFF 对基线的作用小得多(Sep 7)。** naive/reuse 六个 `_c0FFFF` 变体里,VBench 只有本来有损的两个动了:`naive1step` 83.11→83.63(+0.51,3.90×→3.33×)、`reuse_FRRR` 81.27→81.53(+0.26,3.77×→3.27×);已在 FFFF 水平的 3 步 / 2 步 / FRFF / FRRF 保持不变(±0.05)。像素指标仍全面上升(PSNR +1.6–2.4 dB,如 `naive2step` 18.0→19.7、`naive3step` 19.4→21.7)。这与 HY 是 I2V 一致:chunk 0 有输入图像做强条件,外观不像 T2V 那样完全由首 chunk 决定,所以 SF/CF 上 +1~+3.6 的 VBench 增益在 HY 上只剩零点几分。ATC Stage-1 predictor(`atc_s1_fppf`,DEV 项目 validation25)在 1.67× 下 84.18 / PSNR 20.1,像素保真度高于同速的 `teacache_x1.75`(PSNR 17.6)、与 `naive2step_c0FFFF`(1.87×,PSNR 19.7)相当。
366
+ - **HY 缓存方法在 c0FFFF 下重新搜参后达到了目标档位(Sep 8,`*_x1.75_c0FFFF` / `*_Fxxx_x2.85_c0FFFF`)。** 实测加速比 TeaCache 1.857× / 2.535×、TaylorSeer 1.704× / 2.870×、MotionCache 1.634× / 2.517×(之前为 1.54 / 2.51、1.68 / 2.52、1.53 / 2.49)。`FxxF` 档三者 VBench 全部保持 FFFF 水平(84.26–84.28 vs 84.26),像素指标比原版高 1–2 dB(PSNR 18.6 vs 16.9–17.6);但这一档 TeaCache 与 TaylorSeer 落到的都是「后 7 chunk 中间两步全跳」的量化上限点(Full = 18/32),与 `reuse_FRRF_c0FFFF` 算力等价、结果也几乎一样(84.28 / PSNR 18.6),只有 MotionCache 仍保留 27% 的 token 级活跃步。`Fxxx` 档 VBench 82.6 / 81.7 / 81.4,与原版持平或略低(TaylorSeer 82.43→81.69 是换了更激进的 interval 3.9 以换取 2.52×→2.87×),像素指标同样 +1.2–1.6 dB。同算力对照仍然是 naive 减步占优:16–18/32 档 `naive2step_c0FFFF` 84.26 / 1.87× / PSNR 19.7 不输任何缓存方法,11/32 档 `naive1step_c0FFFF` 83.63 / 3.33× 高出所有 `Fxxx` 缓存点 1–2 分。ATC Stage-1 predictor `atc_s1_fppp` 在 2.59× 下 81.98 / PSNR 19.3——VBench 与 `Fxxx` 缓存点相当,像素保真度高 2–3 dB。DisCa Stage-1(双 block,blocks [0,53],同样 chunk 0 全算)`disca_s1_fppf` 84.17 / PSNR 19.7 / LPIPS 0.135,1.80×:VBench 与 ATC 持平,像素保真度介于 ATC(20.1 / 0.126)与 naive2step_c0FFFF(19.7 / 0.148)之间,高于残差复用类(18.6 / 0.167)。FPPP 档 `disca_s1_fppp` 81.98 / PSNR 19.0(3.00×)与 `atc_s1_fppp` 81.98 / 19.3(2.59×)持平,仍低于 `naive1step_c0FFFF` 83.63。DisCa 的 step-1000 与 step-2000 checkpoint 几乎无差别(FPPF 84.15 vs 84.17,FPPP 82.02 vs 81.98,像素指标差 <0.1 dB)——HY 上 DisCa 在 1000 步已收敛,与 CF 上 DisCa 1000→2000 步 FPPP +3.7 的情况不同。
367
+ - **长视频(Sep 8,`*_14c_*` / `*_28c_*`:14 / 28 chunk = 165 / 333 帧,超过 21 帧训练上下文后 KV 走 21 帧滚动窗口)。** 14 chunk 时 FFFF 自身从 81.17 降到 81.01(`14c_ffff`;subject_consistency 95.7→92.7、background 95.8→94.1,scene 反而 56.0→61.3),说明滚动窗口下长程一致性本身在退化。ATC-chunk FPPF 在 14 chunk 上 1.766×:Stage-1 80.57(相对 `14c_ffff` −0.43,7 chunk 时是 +0.38)、Stage-2 **80.97**(−0.03);像素指标从 7 chunk 的 PSNR 14.6 / LPIPS 0.22 降到 12.8 / 0.34——Predictor 的误差随 chunk 累积(前 7 chunk 之后没有 FFFF 的「重锚定」),Stage-2(随机出口 DMD)在长视频上比 Stage-1 稳得多(VBench +0.40,主要是 subject/background consistency)。28 chunk(333 帧)时趋势放大:FFFF 自身掉到 **77.99**(subject 95.7→88.3、background 95.8→89.6、aesthetic 66.6→62.2——滚动窗口下的长程漂移是基模本身的问题),ATC Stage-1 FPPF 77.48(−0.51)、**Stage-2 78.65(+0.67,高于同长度 FFFF;subject 89.1 vs 88.3、background 91.3 vs 89.6)**,加速比 1.793×;像素指标继续下滑到 PSNR 11.0 / LPIPS 0.47–0.48。三种长度合起来:Stage-1 相对同长度 FFFF 为 +0.38 / −0.43 / −0.51,Stage-2 为 +0.08 / −0.03 / +0.67——随机出口 DMD 训练出来的 Predictor 不会随视频变长而退化,反而在 FFFF 自己漂移最严重的 28 chunk 上略优于 FFFF。
368
+ - **长视频上的 checkpoint 扫描(Sep 11–12,CF 14 / 28 chunk,FPPF,chunk 0 FFFF;HY 16 / 32 chunk 进行中)。** 对比 DisCa Stage-1 的 step 500 / 1000 / 2000、ATC Stage-2(��机出口 DMD,EMA)的 step 500 / 1000 / 2000 与 naive 2 步(`naive2step_<n>c`:chunk 0 四步全算,之后每 chunk 只走 t=1000 / 250,与 `cf_naive2step_c0FFFF` 同一子集),三者 Full 完全相同(14 chunk 30/56、28 chunk 58/112),参考帧读同长度 FFFF 的 MP4(§)。14 chunk:ATC Stage-2 s500 / s1000 / s2000 = 81.08 / **81.11** / 80.97(FFFF 81.01,1.77–1.78×),DisCa s500 / s1000 / s2000 = 80.12 / 80.51 / 80.60(1.82×),`naive2step_14c` 80.79(1.91×);28 chunk:ATC Stage-2 78.55 / **78.84** / 78.65(FFFF 77.99,1.80×),DisCa 75.46 / 77.40 / 77.87(1.84×),`naive2step_28c` 78.74(1.95×)。三点读数:(i) ATC Stage-2 三个 step 相差不到 0.15(14c)/ 0.3(28c),s500 就已经到达平台并且不低于同长度 FFFF——Stage-2 对长视频的增益来得很早,2000 步不是必要条件;(ii) DisCa 随步数单调上升,但 2000 步仍低于 FFFF 与 naive,且视频越长早期权重掉得越多(28c 的 s500 比 FFFF 低 2.5)——没有前一 chunk 通道的 Predictor 在长视频上误差累积更快;(iii) 等 Full 的 naive 2 步与最好的 ATC Stage-2 在 14c 只差 0.3、28c 持平(78.74 vs 78.84),像素指标也几乎相同(PSNR 12.6 vs 12.7–12.8、11.0 vs 11.1),而 naive 的实测加速比更高(Predictor 调用的真实开销高于按 1/30 forward 记的算量)——在 CF 的长视频上,ATC Stage-2 相对 naive 减步的优势只剩零点几分,主要收益是不低于 FFFF 的一致性指标(subject / background consistency)。HY 的 16 / 32 chunk 行(64 / 128 latent,相机动作等比拉长)生成中,完成后补入 HY 表。
369
+ - **`FPF`(Sep 8):chunk 内只走 3 个时间步——t=1000 全算、t=750 一步 Predictor(锚定 t=1000,与训练一致)、跳过 t=500、t=250 全算。** ATC-chunk Stage-1 的 `atc_chunk_fpf` 在 **1.773×** 下 81.30(FFFF 81.17,同算力 16 full 的 `atc_chunk_fppf` 81.55 / 1.697×,`naive3step` 81.40 / 1.327×),像素指标 PSNR 14.5 / LPIPS 0.24 与 FPPF 相当。也就是说少调用一次 Predictor、直接跳过一个时间步,质量几乎不变而更快——和 naive 减步同一逻辑:中间步的价值主要在于让最后一步有一个好的 起点,而不在于步数本身。
370
+ - MotionCache 在 1.3×/1.6× 的实测加速比明显低于 compute 折算(差 9–11 个百分点):逐 token 选择与 selective forward 的簿记开销是真实存在的;`Fxxx` 下更甚,compute 3.0× 只换来 实测 1.85–1.95×。
371
+ - **最后一步不能缓存。** 凡是让 step 3 走缓存的配置——`Fxxx` 全部、`FFxx` 在 ≥1.6× 时——VBench 掉 15–25 分:imaging/aesthetic 从 ~0.66 掉到 0.41–0.50,scene 从 ~0.57 掉到 0.03–0.37,而 dynamic_degree 从 0.69–0.82 **升**到 0.89–0.96,即残留噪声没有被去掉、画面在抖。`FFxx ×1.3` 实际是 FFxF(最后一步仍算),质量与 `FxxF ×1.3` 相当。
372
+ - TaylorSeer 的一阶预测在 `FFxx` 下确实被触发了,但 ≥1.6× 时把预测用在了最后一步,"预测 vs 拷贝"与"跳不跳最后一步"在这组数据里是混在一起的;要单独检验预测本身,需要最后一步必算、中间步用一阶预测的调度(如 FFxF,上限 1.33×)。
373
+ - `Fxxx` 下 TeaCache/FlowCache 的阈值在 3 条 prompt 上搜到 ~3.0× compute,251 条上实际为 3.4–3.6×(Self-Forcing)/ 2.8–2.9×(Causal-Forcing):indicator 跨 chunk 几乎不变,可达点是 {1, 2, 4}× 的台阶,中间值靠少数 chunk 落在台阶另一侧凑出,随 prompt 集漂移。MotionCache(逐 token)和 TaylorSeer(确定性调度)不漂。
374
+
375
+ ## 2. 各策略的配置参数
376
+
377
+ 阈值类方法(TeaCache / FlowCache / MotionCache)的 `thresh` 作用在**重标定后**的累计相对 L1 距离上(`calibrate.py` 按 TeaCache 的拟合流程得到的 1 次多项式,见下方系数),indicator 为时间步调制后的噪声输入(TeaCache 原始定义,非 Wan 移植的 `e0`)。TaylorSeer 的 `interval` 为平均刷新间隔,小数部分用 Bresenham 交替在相邻整数间隔间实现,`max_order=1`。固定超参:FlowCache `group_size=1`(3 帧组/chunk);MotionCache `weight_norm=mean`、`min_update_ratio=0`、无 temporal consistency。"搜索时 Full"是定参数时在搜索/配对 prompt 上的 compute,251 条上的实际值见第 1 节。
378
+
379
+ ### Self-Forcing
380
+
381
+ 重标定多项式系数(最高次在前):`0.611279, -0.168851`
382
+
383
+ | 策略 | 方法 | 调度 | 参数 | 取值 | 目标加速比 | 搜索时 Full | 来源 |
384
+ |---|---|---|---|---:|---:|---:|---|
385
+ | `ffff` | 无缓存 | FFFF | — | — | 1.0× | 28.000 | — |
386
+ | `teacache_x1.3` | TeaCache | FxxF | `thresh` | 0.634766 | 1.3× | 21.600 | final_self_forcing.json,held-out 漂移 -0.079 |
387
+ | `teacache_x1.3` | TeaCache | FxxF(首 chunk FFFF) | `thresh` | 0.634766 | 1.3× | nan | final_self_forcing_c0full_more.json,3-prompt 搜索点,未经 finalize |
388
+ | `teacache_x1.6` | TeaCache | FxxF | `thresh` | 1.25065 | 1.6× | 19.200 | final_self_forcing.json,held-out 漂移 -0.032 |
389
+ | `teacache_x1.6` | TeaCache | FxxF(首 chunk FFFF) | `thresh` | 1.25065 | 1.6× | nan | final_self_forcing_c0full_more.json,3-prompt 搜索点,未经 finalize |
390
+ | `teacache_x1.75` | TeaCache | FxxF | `thresh` | 1.2496 | 1.75× | 21.000 | final_self_forcing_v2.json,按实测加速比定点(扫描 1.337×);below band (reachable speedups are quantised) |
391
+ | `teacache_x2` | TeaCache | FxxF | `thresh` | 1.29167 | 2× | 14.000 | final_self_forcing.json,held-out 漂移 +0.000 |
392
+ | `teacache_x2` | TeaCache | FxxF(首 chunk FFFF) | `thresh` | 1.29167 | 2× | nan | final_self_forcing_c0full.json,3-prompt 搜索点,未经 finalize |
393
+ | `teacache_Fxxx_x2.85` | TeaCache | Fxxx | `thresh` | 0.9 | 2.85× | 14.000 | final_self_forcing_v2.json,按实测加速比定点(扫描 1.969×);below band (reachable speedups are quantised) |
394
+ | `teacache_Fxxx_x3` | TeaCache | Fxxx(首 chunk FFFF) | `thresh` | 1.72656 | 3× | nan | final_self_forcing_c0full_more.json,3-prompt 搜索点,未经 finalize |
395
+ | `teacache_Fxxx_x3` | TeaCache | Fxxx | `thresh` | 1.72656 | 3× | 9.667 | final_self_forcing_newsched.json,3-prompt 搜索点,未经 finalize |
396
+ | `flowcache_x1.3` | FlowCache | FxxF | `thresh` | 0.635946 | 1.3× | 21.433 | final_self_forcing.json,held-out 漂移 -0.038 |
397
+ | `flowcache_x1.6` | FlowCache | FxxF | `thresh` | 1.25 | 1.6× | 18.333 | final_self_forcing.json,held-out 漂移 -0.070 |
398
+ | `flowcache_x2` | FlowCache | FxxF | `thresh` | 1.29167 | 2× | 14.000 | final_self_forcing.json,held-out 漂移 +0.000 |
399
+ | `flowcache_Fxxx_x3` | FlowCache | Fxxx | `thresh` | 1.72461 | 3× | 10.111 | final_self_forcing_newsched.json,3-prompt 搜索点,未经 finalize |
400
+ | `taylorseer_x1.3` | TaylorSeer | FxxF | `interval` | 2.08333 | 1.3× | 21.000 | final_self_forcing.json,held-out 漂移 +0.000 |
401
+ | `taylorseer_x1.3` | TaylorSeer | FxxF(首 chunk FFFF) | `interval` | 2.08333 | 1.3× | nan | final_self_forcing_c0full_more.json,3-prompt 搜索点,未经 finalize |
402
+ | `taylorseer_x1.6` | TaylorSeer | FxxF | `interval` | 2.58333 | 1.6× | 17.000 | final_self_forcing.json,held-out 漂移 +0.000 |
403
+ | `taylorseer_x1.75` | TaylorSeer | FxxF(首 chunk FFFF) | `interval` | 2.75 | 1.75× | nan | final_self_forcing_c0full_more.json,3-prompt 搜索点,未经 finalize |
404
+ | `taylorseer_x1.75` | TaylorSeer | FxxF | `interval` | 2.75 | 1.75× | 15.000 | final_self_forcing_v2.json,按实测加速比定点(扫描 1.777×) |
405
+ | `taylorseer_x2` | TaylorSeer | FxxF | `interval` | 2.91667 | 2× | 14.000 | final_self_forcing.json,held-out 漂移 +0.000 |
406
+ | `taylorseer_FFxx_x1.3` | TaylorSeer | FFxx | `interval` | 1.8125 | 1.3× | 22.000 | final_self_forcing_newsched.json,3-prompt 搜索点,未经 finalize |
407
+ | `taylorseer_FFxx_x1.6` | TaylorSeer | FFxx | `interval` | 2.375 | 1.6× | 18.000 | final_self_forcing_newsched.json,3-prompt 搜索点,未经 finalize |
408
+ | `taylorseer_FFxx_x2` | TaylorSeer | FFxx | `interval` | 2.875 | 2× | 14.000 | final_self_forcing_newsched.json,3-prompt 搜索点,未经 finalize |
409
+ | `taylorseer_Fxxx_x2.85` | TaylorSeer | Fxxx(首 chunk FFFF) | `interval` | 3.65 | 2.85× | nan | final_self_forcing_c0full_more.json,3-prompt 搜索点,未经 finalize |
410
+ | `taylorseer_Fxxx_x2.85` | TaylorSeer | Fxxx | `interval` | 3.65 | 2.85× | 9.000 | final_self_forcing_v2.json,按实测加速比定点(扫描 2.870×) |
411
+ | `motioncache_x1.3` | MotionCache | FxxF(首 chunk FFFF) | `thresh` | 0.755981 | 1.3× | nan | final_self_forcing_c0full_more.json,3-prompt 搜索点,未经 finalize |
412
+ | `motioncache_x1.3` | MotionCache | FxxF | `thresh` | 0.755981 | 1.3× | 21.574 | final_self_forcing_mc.json,held-out 漂移 +0.003 |
413
+ | `motioncache_x1.6` | MotionCache | FxxF | `thresh` | 1.24609 | 1.6× | 17.333 | final_self_forcing_mc.json,held-out 漂移 -0.008 |
414
+ | `motioncache_x1.75` | MotionCache | FxxF(首 chunk FFFF) | `thresh` | 1.35 | 1.75× | nan | final_self_forcing_c0full_more.json,3-prompt 搜索点,未经 finalize |
415
+ | `motioncache_x1.75` | MotionCache | FxxF | `thresh` | 1.35 | 1.75× | 16.023 | final_self_forcing_v2.json,按实测加速比定点(扫描 1.536×,活跃步 50%,选中 28%);below band (token-wise decision goes vacuous above this point) |
416
+ | `motioncache_x2` | MotionCache | FxxF | `thresh` | 2.5 | 2× | 14.000 | final_self_forcing_mc.json,held-out 漂移 +0.000 |
417
+ | `motioncache_Fxxx_x2.85` | MotionCache | Fxxx(首 chunk FFFF) | `thresh` | 1.95 | 2.85× | nan | final_self_forcing_c0full_more.json,3-prompt 搜索点,未经 finalize |
418
+ | `motioncache_Fxxx_x2.85` | MotionCache | Fxxx | `thresh` | 1.95 | 2.85× | 7.550 | final_self_forcing_v2.json,按实测加速比定点(扫描 2.537×,活跃步 43%,选中 8%);below band (token-wise decision goes vacuous above this point) |
419
+ | `motioncache_Fxxx_x3` | MotionCache | Fxxx | `thresh` | 1.79297 | 3× | 9.342 | final_self_forcing_newsched.json,3-prompt 搜索点,未经 finalize |
420
+ | `euler_FFFF` | euler | FFFF | — | — | — | — | 基线(无搜索参数) |
421
+ | `reuse_FRFF` | reuse | FRFF | — | — | — | — | 基线(无搜索参数) |
422
+ | `reuse_FRRF` | reuse | FRRF | — | — | — | — | 基线(无搜索参数) |
423
+ | `reuse_FRRR` | reuse | FRRR | — | — | — | — | 基线(无搜索参数) |
424
+
425
+ ### Causal-Forcing
426
+
427
+ 重标定多项式系数(最高次在前):`0.807724, -0.413696`
428
+
429
+ | 策略 | 方法 | 调度 | 参数 | 取值 | 目标加速比 | 搜索时 Full | 来源 |
430
+ |---|---|---|---|---:|---:|---:|---|
431
+ | `ffff` | 无缓存 | FFFF | — | — | 1.0× | 28.000 | — |
432
+ | `teacache_x1.3` | TeaCache | FxxF | `thresh` | 0.649089 | 1.3× | 21.400 | final_causal_forcing.json,held-out 漂移 +0.025 |
433
+ | `teacache_x1.3` | TeaCache | FxxF(首 chunk FFFF) | `thresh` | 0.649089 | 1.3× | nan | final_causal_forcing_c0full.json,3-prompt 搜索点,未经 finalize |
434
+ | `teacache_x1.6` | TeaCache | FxxF | `thresh` | 1.27604 | 1.6× | 17.900 | final_causal_forcing.json,held-out 漂移 +0.024 |
435
+ | `teacache_x1.75` | TeaCache | FxxF | `thresh` | 1.2754 | 1.75× | 16.000 | final_causal_forcing_v2.json,按实测加速比定点(扫描 1.785×) |
436
+ | `teacache_x2` | TeaCache | FxxF | `thresh` | 1.29167 | 2× | 14.000 | final_causal_forcing.json,held-out 漂移 +0.000 |
437
+ | `teacache_x2` | TeaCache | FxxF(首 chunk FFFF) | `thresh` | 1.29167 | 2× | nan | final_causal_forcing_c0full_more.json,3-prompt 搜索点,未经 finalize |
438
+ | `teacache_Fxxx_x3` | TeaCache | Fxxx(首 chunk FFFF) | `thresh` | 1.70117 | 3× | nan | final_causal_forcing_c0full_more.json,3-prompt 搜索点,未经 finalize |
439
+ | `teacache_Fxxx_x3` | TeaCache | Fxxx | `thresh` | 1.70117 | 3× | 9.000 | final_causal_forcing_newsched.json,3-prompt 搜索点,未经 finalize |
440
+ | `flowcache_x1.3` | FlowCache | FxxF | `thresh` | 0.648763 | 1.3× | 22.083 | final_causal_forcing.json,held-out 漂移 +0.005 |
441
+ | `flowcache_x1.6` | FlowCache | FxxF | `thresh` | 1.27604 | 1.6× | 17.125 | final_causal_forcing.json,held-out 漂移 +0.004 |
442
+ | `flowcache_x2` | FlowCache | FxxF | `thresh` | 1.29167 | 2× | 14.000 | final_causal_forcing.json,held-out 漂移 +0.000 |
443
+ | `flowcache_Fxxx_x3` | FlowCache | Fxxx | `thresh` | 1.69922 | 3× | 9.556 | final_causal_forcing_newsched.json,3-prompt 搜索点,未经 finalize |
444
+ | `taylorseer_x1.3` | TaylorSeer | FxxF(首 chunk FFFF) | `interval` | 2.08333 | 1.3× | nan | final_causal_forcing_c0full_more.json,3-prompt 搜索点,未经 finalize |
445
+ | `taylorseer_x1.3` | TaylorSeer | FxxF | `interval` | 2.08333 | 1.3× | 21.000 | final_causal_forcing_ts.json,held-out 漂移 +0.000 |
446
+ | `taylorseer_x1.6` | TaylorSeer | FxxF | `interval` | 2.58333 | 1.6× | 17.000 | final_causal_forcing_ts.json,held-out 漂移 +0.000 |
447
+ | `taylorseer_x1.75` | TaylorSeer | FxxF(首 chunk FFFF) | `interval` | 2.75 | 1.75× | nan | final_causal_forcing_c0full_more.json,3-prompt 搜索点,未经 finalize |
448
+ | `taylorseer_x1.75` | TaylorSeer | FxxF | `interval` | 2.75 | 1.75× | 15.000 | final_causal_forcing_v2.json,按实测加速比定点(扫描 1.779×) |
449
+ | `taylorseer_x2` | TaylorSeer | FxxF | `interval` | 2.91667 | 2× | 14.000 | final_causal_forcing_ts.json,held-out 漂移 +0.000 |
450
+ | `taylorseer_FFxx_x1.3` | TaylorSeer | FFxx | `interval` | 1.8125 | 1.3× | 22.000 | final_causal_forcing_newsched.json,3-prompt 搜索点,未经 finalize |
451
+ | `taylorseer_FFxx_x1.6` | TaylorSeer | FFxx | `interval` | 2.375 | 1.6× | 18.000 | final_causal_forcing_newsched.json,3-prompt 搜索点,未经 finalize |
452
+ | `taylorseer_FFxx_x2` | TaylorSeer | FFxx | `interval` | 2.875 | 2× | 14.000 | final_causal_forcing_newsched.json,3-prompt 搜索点,未经 finalize |
453
+ | `taylorseer_Fxxx_x2.85` | TaylorSeer | Fxxx(首 chunk FFFF) | `interval` | 3.65 | 2.85× | nan | final_causal_forcing_c0full_more.json,3-prompt 搜索点,未经 finalize |
454
+ | `taylorseer_Fxxx_x2.85` | TaylorSeer | Fxxx | `interval` | 3.65 | 2.85× | 9.000 | final_causal_forcing_v2.json,按实测加速比定点(扫描 2.866×) |
455
+ | `motioncache_x1.3` | MotionCache | FxxF(首 chunk FFFF) | `thresh` | 0.769531 | 1.3× | nan | final_causal_forcing_c0full_more.json,3-prompt 搜索点,未经 finalize |
456
+ | `motioncache_x1.3` | MotionCache | FxxF | `thresh` | 0.769531 | 1.3× | 21.450 | final_causal_forcing_mc.json,held-out 漂移 -0.007 |
457
+ | `motioncache_x1.6` | MotionCache | FxxF | `thresh` | 1.26471 | 1.6× | 17.612 | final_causal_forcing_mc.json,held-out 漂移 +0.006 |
458
+ | `motioncache_x1.75` | MotionCache | FxxF(首 chunk FFFF) | `thresh` | 1.55 | 1.75× | nan | final_causal_forcing_c0full_more.json,3-prompt 搜索点,未经 finalize |
459
+ | `motioncache_x1.75` | MotionCache | FxxF | `thresh` | 1.55 | 1.75× | 14.393 | final_causal_forcing_v2.json,按实测加速比定点(扫描 1.550×,活跃步 52%,选中 7%);below band (token-wise decision goes vacuous above this point) |
460
+ | `motioncache_x2` | MotionCache | FxxF | `thresh` | 2.875 | 2× | 14.000 | final_causal_forcing_mc.json,held-out 漂移 +0.000 |
461
+ | `motioncache_Fxxx_x2.85` | MotionCache | Fxxx(首 chunk FFFF) | `thresh` | 1.9 | 2.85× | nan | final_causal_forcing_c0full_more.json,3-prompt 搜索点,未经 finalize |
462
+ | `motioncache_Fxxx_x2.85` | MotionCache | Fxxx | `thresh` | 1.9 | 2.85× | 8.043 | final_causal_forcing_v2.json,按实测加速比定点(扫描 2.316×,活跃步 65%,选中 8%);below band (token-wise decision goes vacuous above this point) |
463
+ | `motioncache_Fxxx_x3` | MotionCache | Fxxx | `thresh` | 1.76953 | 3× | 9.308 | final_causal_forcing_newsched.json,3-prompt 搜索点,未经 finalize |
464
+ | `naive3step` | FFFF | FFF | — | — | — | — | 基线(无搜索参数) |
465
+ | `naive2step` | FFFF | FF | — | — | — | — | 基线(无搜索参数) |
466
+ | `naive1step` | FFFF | F | — | — | — | — | 基线(无搜索参数) |
467
+ | `reuse_FRFF` | reuse | FRFF | — | — | — | — | 基线(无搜索参数) |
468
+ | `reuse_FRRF` | reuse | FRRF | — | — | — | — | 基线(无搜索参数) |
469
+ | `reuse_FRRR` | reuse | FRRR | — | — | — | — | 基线(无搜索参数) |
470
+ | `naive3step_c0FFFF` | FFFF | FFF | — | — | — | — | 基线(无搜索参数) |
471
+ | `naive2step_c0FFFF` | FFFF | FF | — | — | — | — | 基线(无搜索参数) |
472
+ | `naive1step_c0FFFF` | FFFF | F | — | — | — | — | 基线(无搜索参数) |
473
+ | `reuse_FRFF_c0FFFF` | reuse | FRFF | — | — | — | — | 基线(无搜索参数) |
474
+ | `reuse_FRRF_c0FFFF` | reuse | FRRF | — | — | — | — | 基线(无搜索参数) |
475
+ | `reuse_FRRR_c0FFFF` | reuse | FRRR | — | — | — | — | 基线(无搜索参数) |
476
+
477
+ ### HY-WorldPlay
478
+
479
+ | 策略 | 方法 | 调度 | 参数 | 取值 | 目标加速比 | 来源 |
480
+ |---|---|---|---|---:|---:|---|
481
+ | `ffff` | 无缓存 | FxxF | — | — | 1× | — |
482
+ | `teacache_x1.3` | TeaCache | FxxF | `thresh` | 0.242188 | 1.3× | hy_sweep_teacache.json;rescale 系数 hy_coeff.json |
483
+ | `teacache_x1.75` | TeaCache | FxxF | `thresh` | 0.4767 | 1.75× | hy_point_v2.json;rescale 系数 hy_coeff.json |
484
+ | `teacache_x1.75_c0FFFF` | TeaCache | FxxF(首 chunk FFFF) | `thresh` | 0.55 | 1.75× | hy_point_c0.json;rescale 系数 hy_coeff.json |
485
+ | `teacache_Fxxx_x2.85` | TeaCache | Fxxx | `thresh` | 0.655 | 2.85× | hy_point_v2.json;rescale 系数 hy_coeff.json |
486
+ | `teacache_Fxxx_x2.85_c0FFFF` | TeaCache | Fxxx(首 chunk FFFF) | `thresh` | 0.665 | 2.85× | hy_point_c0.json;rescale 系数 hy_coeff.json |
487
+ | `taylorseer_x1.3` | TaylorSeer | FxxF | `interval` | 1.83333 | 1.3× | hy_sweep_taylorseer.json |
488
+ | `taylorseer_x1.75` | TaylorSeer | FxxF | `interval` | 2.85 | 1.75× | hy_point_v2.json |
489
+ | `taylorseer_x1.75_c0FFFF` | TaylorSeer | FxxF(首 chunk FFFF) | `interval` | 3 | 1.75× | hy_point_c0.json |
490
+ | `taylorseer_Fxxx_x2.85` | TaylorSeer | Fxxx | `interval` | 3.65 | 2.85× | hy_point_v2.json |
491
+ | `taylorseer_Fxxx_x2.85_c0FFFF` | TaylorSeer | Fxxx(首 chunk FFFF) | `interval` | 3.9 | 2.85× | hy_point_c0.json |
492
+ | `motioncache_x1.3` | MotionCache | FxxF | `thresh` | 0.09375 | 1.3× | hy_sweep_motioncache.json |
493
+ | `motioncache_x1.75` | MotionCache | FxxF | `thresh` | 0.2 | 1.75× | hy_point_v2.json |
494
+ | `motioncache_x1.75_c0FFFF` | MotionCache | FxxF(首 chunk FFFF) | `thresh` | 0.36 | 1.75× | hy_point_c0.json |
495
+ | `motioncache_Fxxx_x2.85` | MotionCache | Fxxx | `thresh` | 0.6 | 2.85× | hy_point_v2.json |
496
+ | `motioncache_Fxxx_x2.85_c0FFFF` | MotionCache | Fxxx(首 chunk FFFF) | `thresh` | 0.9 | 2.85× | hy_point_c0.json |
497
+ | `naive3step` | 无缓存 | FFF | — | — | — | naive baseline |
498
+ | `naive2step` | 无缓存 | FF | — | — | — | naive baseline |
499
+ | `naive1step` | 无缓存 | F | — | — | — | naive baseline |
500
+ | `reuse_FRFF` | reuse | FRFF | — | — | — | naive cache baseline |
501
+ | `reuse_FRRF` | reuse | FRRF | — | — | — | naive cache baseline |
502
+ | `reuse_FRRR` | reuse | FRRR | — | — | — | naive cache baseline |
503
+ | `naive3step_c0FFFF` | 无缓存 | FFF(首 chunk FFFF) | — | — | — | naive baseline (chunk 0 FFFF) |
504
+ | `naive2step_c0FFFF` | 无缓存 | FF(首 chunk FFFF) | — | — | — | naive baseline (chunk 0 FFFF) |
505
+ | `naive1step_c0FFFF` | 无缓存 | F(首 chunk FFFF) | — | — | — | naive baseline (chunk 0 FFFF) |
506
+ | `reuse_FRFF_c0FFFF` | reuse | FRFF(首 chunk FFFF) | — | — | — | naive cache baseline (chunk 0 FFFF) |
507
+ | `reuse_FRRF_c0FFFF` | reuse | FRRF(首 chunk FFFF) | — | — | — | naive cache baseline (chunk 0 FFFF) |
508
+ | `reuse_FRRR_c0FFFF` | reuse | FRRR(首 chunk FFFF) | — | — | — | naive cache baseline (chunk 0 FFFF) |
509
+ | `atc_s1_fppf` / `atc_s1_fppp` | ATC Stage-1 predictor | FPPF / FPPP | — | — | — | HY-WorldPlay-DEV-Predictor validation25(¶) |
510
+ | `atc_s2_s{500,800,1000,1500,2000}_fppf` / `_fppp` | ATC Stage-1 + on-policy detached chunk+timestep FPPP rollout(step 500/800/1000/1500/2000) | FPPF / FPPP | — | — | — | HY-WorldPlay-DEV-Predictor validation25(¶) |
511
+ | `disca_s1_fppf` / `disca_s1_fppp` | DisCa Stage-1 predictor(双 block,step 2000) | FPPF / FPPP | — | — | — | HY-WorldPlay-DEV-Predictor validation25(¶) |
512
+ | `disca_s1000_fppf` / `disca_s1000_fppp` | DisCa Stage-1 predictor(step 1000) | FPPF / FPPP | — | — | — | HY-WorldPlay-DEV-Predictor validation25(¶) |
513
+ | `disca_s500_fppf` | DisCa Stage-1 predictor(step 500) | FPPF | — | — | — | HY-WorldPlay-DEV-Predictor validation25(¶) |
514
+ | `<n>c_ffff` / `naive2step_<n>c_c0FFFF`(n = 16 / 32) | 长视频 FFFF 参考 / naive 2 步(首 chunk FFFF),253 / 509 帧 | FFFF / FF | — | — | — | hycache,同进程配对 FFFF |
515
+ | `atc_s2_s{500,1000,2000}_<n>c_fppf_c0FFFF`、`disca_s{500,1000,2000}_<n>c_fppf`(n = 16 / 32) | ATC rollout / DisCa Stage-1 predictor 各 step 的长视频行(64 / 128 latent,相机动作等比拉长,pose-retrieved memory 上限 20 latent) | FPPF | — | — | — | HY-WorldPlay-DEV-Predictor 生成器(`hy_dev_gen_long.py`,¶),像素指标对照 `<n>c_ffff` 的 MP4 |
516
+
517
+ ### LingBot-World-V2-1.3B-Causal-Fast
518
+
519
+ | 策略 | 方法 | 调度 | 参数 | 取值 | 目标加速比 | 来源 |
520
+ |---|---|---|---|---:|---:|---|
521
+ | `ffff` | 无缓存 | FxxF | — | — | 1× | — |
522
+ | `teacache_x1.3` | TeaCache | FxxF | `thresh` | 1 | 1.3× | lb_sweep_teacache.json;rescale 系数 lb_coeff.json |
523
+ | `teacache_x1.75` | TeaCache | FxxF | `thresh` | 1.395 | 1.75× | lb_point_v2.json;rescale 系数 lb_coeff.json |
524
+ | `teacache_x1.75_c0FFFF` | TeaCache | FxxF(首 chunk FFFF) | `thresh` | 1.48 | 1.75× | lb_point_c0.json;rescale 系数 lb_coeff.json |
525
+ | `teacache_Fxxx_x2.85` | TeaCache | Fxxx | `thresh` | 1.905 | 2.85× | lb_point_v2.json;rescale 系数 lb_coeff.json |
526
+ | `teacache_Fxxx_x2.85_c0FFFF` | TeaCache | Fxxx(首 chunk FFFF) | `thresh` | 1.9 | 2.85× | lb_point_c0.json;rescale 系数 lb_coeff.json |
527
+ | `taylorseer_x1.3` | TaylorSeer | FxxF | `interval` | 1.83333 | 1.3× | lb_sweep_taylorseer.json |
528
+ | `taylorseer_x1.75` | TaylorSeer | FxxF | `interval` | 3 | 1.75× | lb_point_v2.json |
529
+ | `taylorseer_x1.75_c0FFFF` | TaylorSeer | FxxF(首 chunk FFFF) | `interval` | 2.85 | 1.75× | lb_point_c0.json |
530
+ | `taylorseer_Fxxx_x2.85` | TaylorSeer | Fxxx | `interval` | 3.65 | 2.85× | lb_point_v2.json |
531
+ | `taylorseer_Fxxx_x2.85_c0FFFF` | TaylorSeer | Fxxx(首 chunk FFFF) | `interval` | 3.9 | 2.85× | lb_point_c0.json |
532
+ | `motioncache_x1.3` | MotionCache | FxxF | `thresh` | 1.40625 | 1.3× | lb_sweep_motioncache.json |
533
+ | `motioncache_x1.75` | MotionCache | FxxF | `thresh` | 2.6 | 1.75× | lb_point_v2.json |
534
+ | `motioncache_x1.75_c0FFFF` | MotionCache | FxxF(首 chunk FFFF) | `thresh` | 3.6 | 1.75× | lb_point_c0.json |
535
+ | `motioncache_Fxxx_x2.85` | MotionCache | Fxxx | `thresh` | 3.9 | 2.85× | lb_point_v2.json |
536
+ | `motioncache_Fxxx_x2.85_c0FFFF` | MotionCache | Fxxx(首 chunk FFFF) | `thresh` | 5 | 2.85× | lb_point_c0.json |
537
+ | `naive3step` | 无缓存 | FFF | — | — | — | naive baseline |
538
+ | `naive2step` | 无缓存 | FF | — | — | — | naive baseline |
539
+ | `naive1step` | 无缓存 | F | — | — | — | naive baseline |
540
+ | `reuse_FRFF` | reuse(velocity) | FRFF | — | — | — | naive cache baseline (velocity reuse) |
541
+ | `reuse_FRRF` | reuse(velocity) | FRRF | — | — | — | naive cache baseline (velocity reuse) |
542
+ | `reuse_FRRR` | reuse(velocity) | FRRR | — | — | — | naive cache baseline (velocity reuse) |
543
+ | `naive3step_c0FFFF` | 无缓存 | FFF(首 chunk FFFF) | — | — | — | naive baseline (chunk 0 FFFF) |
544
+ | `naive2step_c0FFFF` | 无缓存 | FF(首 chunk FFFF) | — | — | — | naive baseline (chunk 0 FFFF) |
545
+ | `naive1step_c0FFFF` | 无缓存 | F(首 chunk FFFF) | — | — | — | naive baseline (chunk 0 FFFF) |
546
+ | `reuse_FRFF_c0FFFF` | reuse(velocity) | FRFF(首 chunk FFFF) | — | — | — | naive cache baseline (velocity reuse) (chunk 0 FFFF) |
547
+ | `reuse_FRRF_c0FFFF` | reuse(velocity) | FRRF(首 chunk FFFF) | — | — | — | naive cache baseline (velocity reuse) (chunk 0 FFFF) |
548
+ | `reuse_FRRR_c0FFFF` | reuse(velocity) | FRRR(首 chunk FFFF) | — | — | — | naive cache baseline (velocity reuse) (chunk 0 FFFF) |
549
+ | `atc_chunk_fpf` / `atc_chunk_fppf` / `atc_chunk_fppp` | ATC Stage-1 predictor(block 17,previous_scope=chunk) | FPF / FPPF / FPPP(首 chunk FFFF) | — | — | — | lingbot-world-v2-a Stage-1,100 组图 × 4 动作离线集,2000 步 |
550
+ | `disca_fpf` / `disca_fppf` / `disca_fppp` | DisCa Stage-1 predictor(block 17,无 previous-chunk 通道) | FPF / FPPF / FPPP(首 chunk FFFF) | — | — | — | lingbot-world-v2-a Stage-1,100 组图 × 4 动作离线集,2000 步 |
README.md ADDED
@@ -0,0 +1,418 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Cache-method comparison on 4-step block-causal video DiTs
2
+
3
+ Four training-free caching methods (TeaCache, TaylorSeer, FlowCache, MotionCache)
4
+ implemented on two 4-step autoregressive video base models (Self-Forcing and
5
+ Causal-Forcing), swept to matched denoise-DiT speedups.
6
+
7
+ ## Layout
8
+
9
+ ```
10
+ repos/ the six upstream clones (reference implementations + base models)
11
+ Self-Forcing/ base model 1 (guandeh17/Self-Forcing)
12
+ Causal-Forcing/ base model 2 (thu-ml/Causal-Forcing)
13
+ TeaCache/ ali-vilab/TeaCache
14
+ TaylorSeer/ Shenyi-Z/TaylorSeer
15
+ FlowCache/ mikeallen39/FlowCache (ICLR 2026)
16
+ MotionCache/ MAC-AutoML/MotionCache (ICML 2026)
17
+ cachelib/ the ports -- one implementation, both base models
18
+ methods.py the four cache methods + baseline + calibration probe
19
+ selective.py token-subset forward for the KV-cached causal DiT
20
+ patch.py routes CausalWanModel._forward_inference through a method
21
+ runner.py chunked denoising loop with cache hooks and denoise-only timing
22
+ harness.py model loading, prompt loading, paired A/B measurement
23
+ calibrate.py fits the TeaCache rescale polynomial for a base model
24
+ sweep.py finds the parameter that hits a target speedup
25
+ finalize.py re-targets on the timed prompts + held-out check (authoritative)
26
+ overhead_bench.py per-step cost of a cached vs a full step (contention-robust)
27
+ retime.py plain stopwatch re-measurement of the settled points
28
+ verify.py re-measures operating points on held-out prompts
29
+ run_compare.py single-configuration CLI
30
+ summarize.py collects everything into one table
31
+ results/ JSON output, plus SUMMARY.md / SUMMARY.csv
32
+ videos/ generated mp4s per operating point, plus *_baseline references
33
+ ```
34
+
35
+ Pipeline order: `calibrate.py` -> `sweep.py` -> `finalize.py` -> `overhead_bench.py`
36
+ -> `retime.py` -> `summarize.py`.
37
+
38
+ Weights are symlinked from the pre-existing checkouts rather than re-downloaded:
39
+
40
+ | base | checkpoint | source |
41
+ |---|---|---|
42
+ | self_forcing | `checkpoints/self_forcing_dmd.pt` (`generator_ema`) | `../Self-Forcing` |
43
+ | causal_forcing | `checkpoints/chunkwise/causal_forcing.pt` (`generator`) | `../Causal-Forcing` |
44
+
45
+ Both also symlink `wan_models/` (Wan2.1-T2V-1.3B backbone, VAE, UMT5 text encoder).
46
+
47
+ ## The setting
48
+
49
+ Both base models are the same architecture: a block-causal Wan2.1-1.3B DiT that
50
+ generates a video chunk at a time. With `num_frame_per_block=3` and 21 latent
51
+ frames, a video is **7 chunks x 4 denoising steps = 28 DiT forwards**, plus one
52
+ untimed KV-cache refresh pass per chunk (`context_noise`) that rewrites the
53
+ chunk's KV entries from the clean latent.
54
+
55
+ The experiment fixes the schedule to **`F ? ? F`**: step 0 and step 3 always run
56
+ the full DiT, steps 1 and 2 are the ones a cache method may skip. This is
57
+ equivalent to the upstream `ret_steps=1` / `cutoff_steps=num_steps-1` guards.
58
+
59
+ **Speedup is measured on denoise-DiT time only** — the sum of the 28 denoising
60
+ forwards, timed with CUDA events. Text encoding, VAE decode and the per-chunk
61
+ KV-refresh pass are excluded. That makes 2.0x the arithmetic ceiling (14 of 28
62
+ forwards), which is why the 2.0x target is exactly "skip both middle steps
63
+ everywhere".
64
+
65
+ ## How each method was ported
66
+
67
+ All four hook the same place: the 30-block loop inside
68
+ `CausalWanModel._forward_inference`. The DiT preamble and the head/unpatchify tail
69
+ always run.
70
+
71
+ | method | decision granularity | what a skipped step reuses | knob |
72
+ |---|---|---|---|
73
+ | TeaCache | whole forward | the 30-block residual `x_out - x_in` from the last computed step | `thresh` |
74
+ | FlowCache | per frame group inside the chunk | the same residual, banked per group | `thresh`, `group_size` |
75
+ | TaylorSeer | whole forward | a **Taylor forecast** of each block's self-attn / cross-attn / FFN output | `interval`, `max_order` |
76
+ | MotionCache | per token, motion-weighted | cached rows for un-selected tokens; selected tokens are recomputed | `thresh`, `weight_norm` |
77
+
78
+ Skipping the block stack leaves the chunk's KV-cache entries holding the previous
79
+ computed step's keys/values. That is safe here: every later step of the chunk
80
+ overwrites the same slots, and the per-chunk KV-refresh pass rewrites them from
81
+ the clean latent before the next chunk reads them.
82
+
83
+ ### Selective (partial-token) forward
84
+
85
+ FlowCache and MotionCache recompute only part of the chunk. On a KV-cached causal
86
+ model that means, per self-attention layer: compute q/k/v for the selected rows
87
+ only, scatter their fresh k/v into the slots the chunk owns (leaving unselected
88
+ slots holding the previous step's k/v), and attend the selected queries against
89
+ the full cache. This mirrors MotionCache's `forward_selective`, moved from
90
+ SkyReels' persistent buffers onto Self-Forcing's rolling `kv_cache`.
91
+
92
+ Validated: with *all* tokens selected the selective path is **bit-exact** against
93
+ the stock full forward (max abs latent difference 0.0). The same check passes for
94
+ TaylorSeer's recording path at `interval=1`.
95
+
96
+ ### Deviations from upstream, and why
97
+
98
+ 1. **Indicator.** `TeaCache4Wan2.1` derives its indicator from `e0` (the timestep
99
+ modulation) alone. That is fine for bidirectional Wan, where one forward covers
100
+ the whole video at a single timestep, but it *degenerates* here: every chunk
101
+ runs the same four timesteps, so an `e0` indicator is bit-identical across
102
+ chunks and the threshold cannot adapt to content at all. The default is
103
+ therefore TeaCache's original definition — the relative L1 distance of the
104
+ **timestep-modulated noisy input**, the tensor block 0 feeds to its
105
+ self-attention, which is what TeaCache uses on HunyuanVideo and FLUX.
106
+ `--indicator e0` restores the literal Wan port.
107
+
108
+ 2. **Rescale polynomial.** TeaCache's shipped 4th-degree coefficients were fitted
109
+ for a different model, schedule and indicator, so `calibrate.py` reruns
110
+ TeaCache's own fitting procedure here. The fit is **degree 1, not 4**: on this
111
+ model the input distance only spans ~[1.19, 1.36], where a degree-4 fit is
112
+ ill-conditioned (coefficients ~10^3 with alternating signs) and MotionCache,
113
+ which evaluates the polynomial *per token*, would extrapolate it far outside
114
+ the fitted domain. Degree 1 is monotone and safe. All degrees are recorded in
115
+ the coefficient JSON.
116
+
117
+ 3. **FlowCache granularity.** FlowCache's contribution is that the units covered
118
+ by one forward denoise at different rates and need independent policies. In
119
+ SkyReels-V2 those units are the chunks of the diffusion-forcing window; here a
120
+ forward covers exactly one chunk, so the corresponding units are the frame
121
+ groups inside it (`group_size=1`, i.e. 3 groups). Its KV-cache-compression
122
+ component is not ported: Self-Forcing already bounds its KV cache by local
123
+ attention, so there is no growing cache to compress.
124
+
125
+ 4. **TaylorSeer fractional interval.** TaylorSeer's schedule is a uniform integer
126
+ refresh interval, which on an `F ? ? F` schedule can only produce 1.0x, 1.33x
127
+ and 2.0x. `interval` is accepted as a float and realised as a deterministic
128
+ per-chunk alternation between the two bracketing integer intervals
129
+ (Bresenham-style), giving the requested *average* interval. This keeps
130
+ TaylorSeer's content-independent schedule rather than bolting a threshold onto
131
+ it.
132
+
133
+ 5. **Fused forecast.** TaylorSeer's cached step is ~90 bandwidth-bound elementwise
134
+ ops per forward. Upstream puts `@torch.compile` on the equivalent
135
+ `wan_attention_cache_forward`; the port does the same. Without it the forecast
136
+ ate most of the saving (1.72x measured at a 2.0x FLOPs setting); with it, it
137
+ does not. Set `CACHELIB_NO_COMPILE=1` to disable.
138
+
139
+ ## Scope change (Sep 4)
140
+
141
+ FlowCache is frozen: its finished operating points stay in the tables, nothing new
142
+ is generated for it. The continuing study is **three methods** (TeaCache,
143
+ TaylorSeer, MotionCache) x **three base models** (Self-Forcing, Causal-Forcing,
144
+ HY-WorldPlay) x **three points**: `FxxF` at ~1.3x, `FxxF` at 1.7-1.8x, and `Fxxx`
145
+ at 2.7-3.0x -- all targeted on **measured** wall-clock speedup, not on the compute
146
+ fraction. The reason is MotionCache: matching compute at 2.0x under `FxxF` forces
147
+ its per-token selection to pick *zero* tokens, which makes it bit-identical to
148
+ TeaCache and reproduces nothing. Operating points are now chosen as the fastest
149
+ setting that still keeps the token-level decision active (>=25% of cacheable steps
150
+ partial, >=5% of tokens selected on those steps); the activity statistics are
151
+ recorded per video in ``cache_diagnostics``.
152
+
153
+ ## Schedules beyond `FxxF`
154
+
155
+ Every entry point takes `--schedule` (`sweep.py`, `finalize.py`, `run_compare.py`;
156
+ the evaluation reads it from the `final_*.json` rows). `F` marks a step that always
157
+ runs the full DiT, `x` one the method may serve from cache: `FxxF` is the study
158
+ above and the default; `FFxx` gives TaylorSeer two computed points before its first
159
+ forecast so the first-order term is actually exercised; `Fxxx` lifts the cool-down
160
+ guard and raises the arithmetic ceiling to 4x. Operating points for `FFxx`
161
+ (TaylorSeer, 1.3/1.6/2.0x) and `Fxxx` (the other three, ~3x) were searched on
162
+ 3 prompts (`results/sweep_*_{FFxx,Fxxx}.json`, collected in
163
+ `results/final_<base>_newsched.json`) and evaluated on Extended-251.
164
+
165
+ **All results, speed and quality, are collected in `Experiment.md`**
166
+ (regenerate with `python experiment_md.py`). The headline of the second round:
167
+ caching the *last* denoising step -- which every `Fxxx` point and every `FFxx`
168
+ point at >= 1.6x does -- costs 15-25 VBench points on both base models, while
169
+ `FxxF` at the same compute costs 1-2. On a 4-step distilled model the final step
170
+ is not optional.
171
+
172
+ ## Measurement protocol
173
+
174
+ This is a **shared node** and it was busy throughout. Other tenants' jobs move
175
+ absolute timings by 30%+ and drift them *within* a single sweep, so a baseline
176
+ measured once at the start silently inflates every later configuration. Four
177
+ things follow, and they are the difference between numbers worth reading and
178
+ numbers that are noise:
179
+
180
+ 1. **Search on compute, not on time.** The parameter search runs on the compute
181
+ fraction (how many of the 28 DiT forwards were actually computed), which is
182
+ exactly deterministic given the prompt set and immune to contention. Targets
183
+ are aimed at the compute budget directly, which also puts all four methods on
184
+ identical compute — the right basis for a later quality comparison. Correcting
185
+ the target by a measured overhead ratio was tried and abandoned: that ratio is
186
+ itself a timing measurement, one probe returned 1.110 (physically impossible),
187
+ and it dragged a whole method's operating points below target.
188
+
189
+ 2. **Paired A/B.** Baseline and method run back to back on the same prompt, so
190
+ drift between them is seconds rather than minutes.
191
+
192
+ 3. **Minimum, not median, as the headline.** Contention is one-sided — a
193
+ neighbour can only make a run slower — so the fastest observed run is the best
194
+ estimate of the uncontended time, and the headline speedup is
195
+ `min(baseline) / min(method)` over the pairs. The paired median is reported
196
+ alongside but is biased *upward*, because the baseline run is longer and so
197
+ more exposed to being hit by a spike; that is why it sometimes exceeded a
198
+ method's arithmetic ceiling.
199
+
200
+ 4. **Compute fraction from the timed runs.** A threshold tuned on one prompt
201
+ subset and timed on another silently disagrees whenever it sits near a decision
202
+ boundary. `finalize.py` reports the compute fraction of the very runs it timed,
203
+ and re-tunes on those prompts if it misses.
204
+
205
+ `finalize.py` also re-checks every point on a disjoint prompt slice, so a
206
+ threshold that only hit its target by sitting inside a narrow band of the
207
+ indicator distribution shows up as held-out drift. `verify.py` does the same
208
+ check standalone against a sweep file.
209
+
210
+ ## Reproducing
211
+
212
+ ```bash
213
+ PY=/local/zoubin/cz/envs/self_forcing/bin/python
214
+
215
+ # 1. fit the rescale polynomial (once per base model)
216
+ CUDA_VISIBLE_DEVICES=0 $PY calibrate.py --base self_forcing \
217
+ --num-prompts 12 --out results/coeff_self_forcing.json
218
+
219
+ # 2. sweep one method to the three target speedups
220
+ CUDA_VISIBLE_DEVICES=0 $PY sweep.py --base self_forcing --method teacache \
221
+ --coefficients results/coeff_self_forcing.json \
222
+ --targets 1.3,1.6,2.0 --save-video-dir videos \
223
+ --out results/sweep_self_forcing_teacache.json
224
+
225
+ # 3. check the settings transfer to unseen prompts
226
+ CUDA_VISIBLE_DEVICES=0 $PY verify.py \
227
+ --sweep results/sweep_self_forcing_teacache.json --prompt-offset 64 \
228
+ --out results/verify_self_forcing_teacache.json
229
+
230
+ # 4. collect everything
231
+ $PY summarize.py
232
+ ```
233
+
234
+ `run_compare.py` runs a single configuration if you just want one number:
235
+
236
+ ```bash
237
+ CUDA_VISIBLE_DEVICES=0 $PY run_compare.py --base causal_forcing \
238
+ --method taylorseer --interval 2.5 --num-prompts 8
239
+ ```
240
+
241
+ ## Environment note
242
+
243
+ **Sep 3:** the machine was restored again -- `/mnt/local_nvme` became `/local`,
244
+ both environments lost their executable bits a second time (1632 files restored),
245
+ the `vbench_eval` venv's `pyvenv.cfg`/interpreter links pointed at the old path
246
+ (now symlinks into `/local/.../self_forcing`), and the caches moved to
247
+ `/local/zoubin/cz/.cache/`. Paths in `eval/*.sh`, `eval/aggregate.py` and the
248
+ per-prompt records were updated accordingly. The node is shared: other tenants'
249
+ launches have repeatedly killed GPU processes of ours, so long runs go through
250
+ `eval/retime_until_clean.sh`-style loops that only use quiet GPUs and resume.
251
+
252
+ The conda environment at `/mnt/local_nvme/zoubin/cz/envs/self_forcing` had lost
253
+ every executable bit (a bad restore left all files `rw-rw-r--`), so nothing in it
254
+ could run — including Triton's bundled `ptxas`, which broke `torch.compile`. The
255
+ exec bits were restored on files that are ELF binaries or start with `#!`
256
+ (1772 files). No package contents were changed.
257
+
258
+ ## Results
259
+
260
+ Full tables: `results/SUMMARY.md` (regenerate with `python summarize.py`), machine
261
+ readable in `results/SUMMARY.csv` and the per-stage JSONs.
262
+
263
+ **Headline speedup** is the denoise-DiT speedup implied by the measured compute
264
+ fraction and the measured per-step cost model (see Measurement protocol). The
265
+ `stopwatch` column is the plain paired whole-video ratio; it agrees within its
266
+ (large) spread but is not the number to quote from this node.
267
+
268
+ ### Operating points found
269
+
270
+ | base | method | knob | 1.3x | 1.6x | 2.0x |
271
+ |---|---|---|---|---|---|
272
+ | Self-Forcing | TeaCache | `thresh` | 0.6348 → **1.30x** | 1.2507 → **1.48x** | 1.2917 → **1.96x** |
273
+ | Self-Forcing | FlowCache | `thresh` | 0.6360 → **1.30x** | 1.2500 → **1.51x** | 1.2917 → **1.96x** |
274
+ | Self-Forcing | TaylorSeer | `interval` | 2.083 → **1.31x** | 2.583 → **1.59x** | 2.917 → **1.89x** |
275
+ | Self-Forcing | MotionCache | `thresh` | 0.7560 → **1.29x** | 1.2461 → **1.60x** | 2.5000 → **1.96x** |
276
+ | Causal-Forcing | TeaCache | `thresh` | 0.6491 → **1.30x** | 1.2760 → **1.51x** | 1.2917 → **1.96x** |
277
+ | Causal-Forcing | FlowCache | `thresh` | 0.6488 → **1.26x** | 1.2760 → **1.61x** | 1.2917 → **1.95x** |
278
+ | Causal-Forcing | TaylorSeer | `interval` | 2.083 → **1.31x** | 2.583 → **1.59x** | 2.917 → **1.89x** |
279
+ | Causal-Forcing | MotionCache | `thresh` | 0.7695 → **1.30x** | 1.2647 → **1.57x** | 2.8750 → **1.96x** |
280
+
281
+ ### What a cached step actually costs
282
+
283
+ Minima over ~1900 per-step samples per base, so these are solid:
284
+
285
+ | method | cached step, as a fraction of a full step | ceiling at 14/28 forwards |
286
+ |---|---|---|
287
+ | TeaCache | 1.9% | 1.96x |
288
+ | MotionCache | 2.0% | 1.96x |
289
+ | FlowCache | 2.3% | 1.96x |
290
+ | TaylorSeer | 5.6 - 5.8% | 1.89x |
291
+
292
+ A full denoising forward costs 76-77 ms uncontended (1 chunk = 3 latent frames,
293
+ 4680 tokens, Wan2.1-1.3B, H100). **2.0x is the arithmetic ceiling** of this
294
+ schedule, and the achievable ceiling is ~1.96x for three of the methods.
295
+ TaylorSeer pays more because its cached step is a Taylor *forecast*, not a copy:
296
+ 30 layers x 3 module features have to be extrapolated and re-modulated. That is
297
+ already with the `torch.compile` fusion upstream uses; without it the same step
298
+ costs ~25% of a full one and the method tops out near 1.7x.
299
+
300
+ ### Three findings
301
+
302
+ 1. **The TeaCache-family indicator carries almost no signal on a 4-step distilled
303
+ model.** Calibration over 252 (chunk, step) pairs: at a given denoising step the
304
+ indicator's spread *across chunks* is a standard deviation of 0.0013 on a mean
305
+ of 1.35 (0.1%), while the gaps *between* steps are 0.04-0.10. So the threshold
306
+ is really choosing *which step index* to skip, not adapting per chunk. Worse,
307
+ within a step the indicator is *negatively* correlated with the actual reuse
308
+ error (r = -0.54 / -0.58 at steps 1 and 2); the +0.49 overall correlation is
309
+ entirely a between-step effect, and a degree-4 fit only reaches R^2 = 0.26.
310
+
311
+ 2. **That makes 1.6x hard to hit for the threshold methods and easy for the other
312
+ two.** TeaCache's reachable points on Self-Forcing are essentially quantised to
313
+ {1.0, 1.33, ~1.48, 2.0} — the requested 1.6x falls in a gap, and the closest
314
+ honest point is 1.48x. FlowCache, deciding per frame group, does slightly better
315
+ (1.51x on Self-Forcing, 1.61x on Causal-Forcing). TaylorSeer (fractional
316
+ interval) and MotionCache (per token) land on 1.59x / 1.60x directly, because
317
+ both have a genuinely continuous knob.
318
+
319
+ 3. **Generalisation splits the methods the same way.** Re-running each setting on
320
+ 64 prompts it was never tuned on, the compute fraction drifts by:
321
+
322
+ | method | worst held-out drift |
323
+ |---|---|
324
+ | TaylorSeer | 0.000 |
325
+ | MotionCache | 0.008 |
326
+ | TeaCache | 0.079 |
327
+ | FlowCache | 0.070 |
328
+
329
+ TeaCache's and FlowCache's 1.3x and 1.6x settings sit inside a razor-thin band
330
+ of the indicator distribution, so they do not transfer; their 2.0x settings
331
+ (where everything skips regardless) transfer perfectly. TaylorSeer's schedule is
332
+ content-independent by construction, and MotionCache's per-token thresholding
333
+ averages over 4680 decisions per step instead of one.
334
+
335
+ ### Artifacts for a quality comparison
336
+
337
+ `videos/<base>_<method>_x<target>/NNNN.mp4` holds 7-10 clips per operating point,
338
+ and `videos/<base>_baseline/NNNN.mp4` the matching all-full references (same
339
+ prompts, same seed, indices align). The quality numbers are in `Experiment.md`
340
+ (Extended-251 evaluation, next section).
341
+
342
+ ---
343
+
344
+ # Self-Forcing Extended-251 Full Evaluation
345
+
346
+ VBench-8 + FFFF-relative pixel metrics + matched-prompt policy latency, following
347
+ `self_forcing_extended_full_evaluation_protocol.md`, with the protocol's paths
348
+ remapped to this machine.
349
+
350
+ ## Path remapping
351
+
352
+ | Protocol path | Here |
353
+ |---|---|
354
+ | `/data3/chenzhuo/anaconda3/envs/self_forcing` | `/mnt/local_nvme/zoubin/cz/envs/self_forcing` |
355
+ | `$SELF_FORCING_REPO/.evaluation_env/vbench_site2` | absent -> `/mnt/local_nvme/zoubin/cz/projects/VBench` on `PYTHONPATH` |
356
+ | `/data3/chenzhuo/.cache/vbench` | `/mnt/local_nvme/zoubin/cache/vbench` |
357
+ | `prompts/vbench/all_dimension{,_extended}.txt` | `../Self-Forcing/prompts/vbench/` |
358
+ | `assets/vbench8_extended_subset_mapping.json` | absent -> rebuilt by `eval/build_mapping.py` |
359
+
360
+ ## Files
361
+
362
+ ```
363
+ assets/vbench8_extended_subset_mapping.json the 251-row mapping (built + validated here)
364
+ eval/build_mapping.py 946 -> 251 selection, with the protocol's validation gate
365
+ eval/strategies.py FFFF + the 12 settled operating points, per base model
366
+ eval/generate_eval.py video generation, latency split, pixel metrics
367
+ eval/pixel_metrics.py PSNR / SSIM / LPIPS on decoded frames, pre-encode
368
+ eval/run_vbench.py the eight dimensions, stock VBench metric code
369
+ eval/aggregate.py normalize -> Quality/Semantic/Selected, latency, final tables
370
+ eval/test_protocol.py the section 12 unit tests
371
+ eval/run_generation.sh / run_vbench_all.sh / run_all_phases.sh 8-GPU drivers
372
+ eval_out/ generated_videos/ per_prompt/ vbench/ summaries/
373
+ ```
374
+
375
+ ## Strategies
376
+
377
+ 26 = 2 base models x (FFFF + 4 cache methods x 3 speed targets). FFFF is the
378
+ all-full 4-step baseline and is each base model's own reference for both the
379
+ pixel metrics and the latency speedup. Cache parameters are read back from
380
+ `results/final_<base>*.json`, so the evaluation scores exactly the operating
381
+ points the speed study settled on.
382
+
383
+ ## Two environments, on purpose
384
+
385
+ Generation runs in the **base `self_forcing` env** -- the same interpreter and
386
+ package set the speed study used, so the evaluated videos come from exactly the
387
+ benchmarked stack. The only addition to that env is `lpips`.
388
+
389
+ VBench runs in the **`vbench_eval` venv**. It has to: the base env carries
390
+ `torchao 0.17.0`, which is unimportable under `torch 2.5.1` (it references
391
+ `torch.int1`), and `transformers.modeling_utils` pulls torchao in through its
392
+ quantizer registry -- so `BertModel`, and therefore Tag2Text and the `scene`
393
+ dimension, cannot load there. The venv pins `torchao==0.7.0`,
394
+ `transformers==4.46.3` and adds `fairscale`. This is a deviation from protocol
395
+ section 2.1 (one environment for everything); it does not touch generation.
396
+
397
+ The venv itself needed repair first: a bad restore had flattened its `bin/python`
398
+ symlinks into text files and stripped every executable bit.
399
+
400
+ ## Protocol conformance
401
+
402
+ Verified before the run:
403
+
404
+ * mapping is 251 rows = 72 / 93 / 86, `global_index` unique, `suite_index`
405
+ contiguous, all 86 scene rows keep `auxiliary_info`, and the 946 short prompts
406
+ match `VBench_full_info.json` in order exactly (selection is by index -- two
407
+ prompt texts are duplicated, so text matching is unsafe and is forbidden);
408
+ * SHA256 recorded for the short prompts, extended prompts, `VBench_full_info.json`
409
+ and the mapping;
410
+ * videos are 81 frames, 480x832, 16 FPS, seed 0, one sample per prompt;
411
+ * `prompt_en` handed to VBench is the **extended** prompt actually generated from;
412
+ * each dimension scores only its own suite (72 / 93 / 86), driven by the mapping;
413
+ * `policy_latency_ms` covers the denoise path only; the context/KV-cache DiT is
414
+ timed separately into `excluded_context_kv_latency_ms` (~790 ms/video) and never
415
+ added in;
416
+ * pixel metrics run on the decoded RGB tensors before MP4 encoding, over all 81
417
+ frames, with FFFF-vs-itself pinned to 120 dB / 1.0 / 0.0;
418
+ * `eval/test_protocol.py` covers the section 12 checklist and passes.
activity_pass.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """Backfill token-activity statistics into per-prompt records generated before the
3
+ controller recorded them.
4
+
5
+ Re-runs only the denoising loop (no VAE decode, no video write) for the given
6
+ strategies, which is deterministic, and merges ``active_step_ratio`` /
7
+ ``empty_step_ratio`` / ``full_step_ratio`` / ``mean_selected_fraction_active``
8
+ into each record's ``cache_diagnostics``.
9
+
10
+ CUDA_VISIBLE_DEVICES=4 python activity_pass.py --base self_forcing \
11
+ --strategies sf_motioncache_x1.75,sf_motioncache_Fxxx_x2.85 --shard 0 --num-shards 4
12
+ """
13
+ import argparse, json, os, sys, time
14
+
15
+ ROOT = os.path.dirname(os.path.abspath(__file__))
16
+ sys.path.insert(0, ROOT)
17
+ from eval.strategies import load_strategies # noqa: E402
18
+ from harness import BASES, enter_base, load_pipeline # noqa: E402
19
+
20
+ MAPPING = os.path.join(ROOT, "assets/vbench8_extended_subset_mapping.json")
21
+ ap = argparse.ArgumentParser()
22
+ ap.add_argument("--base", choices=sorted(BASES), required=True)
23
+ ap.add_argument("--strategies", required=True)
24
+ ap.add_argument("--shard", type=int, default=0)
25
+ ap.add_argument("--num-shards", type=int, default=1)
26
+ ap.add_argument("--out-root", default="eval_out")
27
+ ap.add_argument("--seed", type=int, default=0)
28
+ ap.add_argument("--num-latent-frames", type=int, default=21)
29
+ args = ap.parse_args()
30
+ out_root = args.out_root if os.path.isabs(args.out_root) else os.path.join(ROOT, args.out_root)
31
+
32
+ rows = json.load(open(MAPPING))["rows"][args.shard::args.num_shards]
33
+ wanted = set(args.strategies.split(","))
34
+ strategies = [s for s in load_strategies(args.base) if s["name"] in wanted]
35
+ if not strategies:
36
+ sys.exit(f"no strategies matched {sorted(wanted)}")
37
+ print(f"shard {args.shard}/{args.num_shards}: {len(rows)} prompts x {len(strategies)} strategies", flush=True)
38
+
39
+ base = enter_base(args.base)
40
+ import torch
41
+ from utils.misc import set_seed
42
+ from cachelib import CacheController, build_method, cached_inference, install, parse_schedule
43
+
44
+ torch.set_grad_enabled(False)
45
+ pipe = load_pipeline(base)
46
+ num_steps = len(pipe.denoising_step_list)
47
+ t0 = time.time()
48
+ for n, row in enumerate(rows):
49
+ for s in strategies:
50
+ rp = os.path.join(out_root, "per_prompt", s["name"],
51
+ f"{row['prompt_suite']}_{row['suite_index']:03d}.json")
52
+ if not os.path.exists(rp):
53
+ continue
54
+ rec = json.load(open(rp))
55
+ if "active_step_ratio" in rec.get("cache_diagnostics", {}):
56
+ continue
57
+ kw = dict(indicator=s["indicator"], coefficients=s["coefficients"])
58
+ if s["method"] != "none":
59
+ kw[s["param"]] = s["value"]
60
+ ctrl = CacheController(build_method(s["method"], **kw), num_steps=num_steps,
61
+ forced_steps=parse_schedule(s.get("schedule", "FxxF"), num_steps))
62
+ install(pipe.generator.model, ctrl)
63
+ set_seed(args.seed)
64
+ noise = torch.randn([1, args.num_latent_frames, 16, 60, 104],
65
+ device=torch.device("cuda"), dtype=torch.bfloat16)
66
+ cached_inference(pipe, ctrl, noise, [rec["prompt"]], decode=False)
67
+ summary = ctrl.summary()
68
+ assert abs(summary["compute_equivalent_forwards"]
69
+ - rec["cache_diagnostics"]["compute_equivalent_forwards"]) < 1e-6, \
70
+ f"compute mismatch on {rp}"
71
+ rec["cache_diagnostics"] = dict(summary)
72
+ tmp = rp + ".tmp"
73
+ json.dump(rec, open(tmp, "w"), indent=2)
74
+ os.replace(tmp, rp)
75
+ if (n + 1) % 20 == 0:
76
+ rate = (time.time() - t0) / (n + 1)
77
+ print(f"[{args.base} activity shard {args.shard}] {n+1}/{len(rows)} "
78
+ f"{rate:.1f}s/prompt eta {(len(rows)-n-1)*rate/60:.0f} min", flush=True)
79
+ print(f"shard {args.shard} done in {(time.time()-t0)/60:.1f} min", flush=True)
calibrate.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """Fit the TeaCache rescale polynomial for a base model.
3
+
4
+ TeaCache ships per-model 4th-degree coefficients that map the cheap input-side
5
+ relative L1 distance onto the output-side distance. Those were fitted for
6
+ bidirectional Wan on a 50-step schedule with an ``e0``-only indicator, so they do
7
+ not transfer to a 4-step block-causal model with the modulated-input indicator.
8
+ This script reruns TeaCache's own fitting procedure on the target model.
9
+
10
+ python calibrate.py --base self_forcing --num-prompts 8 \
11
+ --out results/coeff_self_forcing.json
12
+ """
13
+
14
+ import argparse
15
+ import json
16
+ import os
17
+ import sys
18
+
19
+ ROOT = os.path.dirname(os.path.abspath(__file__))
20
+ sys.path.insert(0, ROOT)
21
+
22
+ from harness import BASES, enter_base, load_pipeline # noqa: E402
23
+
24
+
25
+ def main():
26
+ p = argparse.ArgumentParser()
27
+ p.add_argument("--base", choices=sorted(BASES), required=True)
28
+ p.add_argument("--indicator", default="modulated_input",
29
+ choices=["modulated_input", "e0"])
30
+ p.add_argument("--num-prompts", type=int, default=8)
31
+ p.add_argument("--num-output-frames", type=int, default=21)
32
+ p.add_argument("--degree", type=int, default=1,
33
+ help="Degree 4 (TeaCache default) is ill-conditioned on the narrow "
34
+ "distance range a 4-step schedule produces; degree 1 stays "
35
+ "monotone and is safe to extrapolate per token.")
36
+ p.add_argument("--seed", type=int, default=0)
37
+ p.add_argument("--out", required=True)
38
+ args = p.parse_args()
39
+
40
+ out_path = args.out if os.path.isabs(args.out) else os.path.join(ROOT, args.out)
41
+ base = enter_base(args.base)
42
+
43
+ import numpy as np
44
+ import torch
45
+
46
+ from utils.dataset import TextDataset
47
+ from utils.misc import set_seed
48
+
49
+ from cachelib import CacheController, build_method, cached_inference, install
50
+
51
+ set_seed(args.seed)
52
+ torch.set_grad_enabled(False)
53
+ device = torch.device("cuda")
54
+ pipeline = load_pipeline(base)
55
+
56
+ method = build_method("calibrate", indicator=args.indicator)
57
+ num_steps = len(pipeline.denoising_step_list)
58
+ controller = CacheController(method, num_steps=num_steps,
59
+ forced_steps=(0, num_steps - 1))
60
+ install(pipeline.generator.model, controller)
61
+
62
+ prompt_file = ("prompts/MovieGenVideoBench.txt"
63
+ if os.path.exists("prompts/MovieGenVideoBench.txt")
64
+ else "prompts/demos.txt")
65
+ dataset = TextDataset(prompt_path=prompt_file)
66
+
67
+ for i in range(min(args.num_prompts, len(dataset))):
68
+ set_seed(args.seed)
69
+ noise = torch.randn([1, args.num_output_frames, 16, 60, 104],
70
+ device=device, dtype=torch.bfloat16)
71
+ cached_inference(pipeline, controller, noise, [dataset[i]["prompts"]],
72
+ decode=False)
73
+ print(f"[{i}] samples={len(method.samples)}", flush=True)
74
+
75
+ xs = np.array([s["x"] for s in method.samples], dtype=np.float64)
76
+ ys = np.array([s["y"] for s in method.samples], dtype=np.float64)
77
+ coeffs = np.polyfit(xs, ys, args.degree)
78
+ pred = np.poly1d(coeffs)(xs)
79
+
80
+ result = {
81
+ "base": args.base,
82
+ "indicator": args.indicator,
83
+ "degree": args.degree,
84
+ "num_samples": int(xs.size),
85
+ "coefficients": [float(c) for c in coeffs],
86
+ "x_range": [float(xs.min()), float(xs.max())],
87
+ "y_range": [float(ys.min()), float(ys.max())],
88
+ "fit_r2": float(1 - ((ys - pred) ** 2).sum() / ((ys - ys.mean()) ** 2).sum()),
89
+ "per_step_mean_x": {
90
+ str(k): float(xs[[s["step"] == k for s in method.samples]].mean())
91
+ for k in sorted({s["step"] for s in method.samples})
92
+ },
93
+ "per_step_mean_y": {
94
+ str(k): float(ys[[s["step"] == k for s in method.samples]].mean())
95
+ for k in sorted({s["step"] for s in method.samples})
96
+ },
97
+ "samples": method.samples,
98
+ }
99
+ print(json.dumps({k: v for k, v in result.items() if k != "samples"}, indent=2))
100
+
101
+ os.makedirs(os.path.dirname(out_path), exist_ok=True)
102
+ with open(out_path, "w") as f:
103
+ json.dump(result, f, indent=2)
104
+ print(f"wrote {out_path}")
105
+
106
+
107
+ if __name__ == "__main__":
108
+ main()
experiment_md.py ADDED
@@ -0,0 +1,770 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """Build Experiment.md from the evaluation summary and the settled operating points.
3
+
4
+ Sections:
5
+ 1. the Extended-251 evaluation table for every strategy that has been fully
6
+ scored (eval_out/summaries/final_summary.csv);
7
+ 2. operating points found but not yet evaluated (results/sweep_*_<schedule>.json
8
+ for the non-default schedules), with search-stage speed numbers only.
9
+
10
+ python experiment_md.py # writes Experiment.md
11
+ """
12
+
13
+ import csv
14
+ import glob
15
+ import json
16
+ import os
17
+ import re
18
+ import sys
19
+
20
+ ROOT = os.path.dirname(os.path.abspath(__file__))
21
+ SUMMARY = os.path.join(ROOT, "eval_out/summaries/final_summary.csv")
22
+ OUT = os.path.join(ROOT, "Experiment.md")
23
+
24
+ BASE_LABEL = {"self_forcing": "Self-Forcing", "causal_forcing": "Causal-Forcing",
25
+ "causal_forcing_a": "Causal-Forcing-a(Predictor)"}
26
+ BASES = ["self_forcing", "causal_forcing", "causal_forcing_a"]
27
+ PREFIX = {"self_forcing": "sf_", "causal_forcing": "cf_", "causal_forcing_a": "cfa_"}
28
+ METHOD_LABEL = {"none": "FFFF", "teacache": "TeaCache", "flowcache": "FlowCache",
29
+ "taylorseer": "TaylorSeer", "motioncache": "MotionCache"}
30
+ METHOD_ORDER = ["none", "teacache", "flowcache", "taylorseer", "motioncache"]
31
+ FORWARDS = 28
32
+ CHUNKS = 7
33
+ STEPS = 4
34
+
35
+ HEADER = ("| 策略 | VBench-251 (%) | 平均 P | Full | 模型路径耗时 (ms) | 加速比 "
36
+ "| PSNR | SSIM | LPIPS |\n|---|---:|---:|---:|---:|---:|---:|---:|---:|")
37
+
38
+
39
+ def strategy_label(method, schedule, target):
40
+ if target in (None, 0.0): # naive / reuse baselines carry no target
41
+ return f"`{method}_{schedule}`" if method != "none" else f"`naive_{schedule}`"
42
+ """Strategy id as used in eval_out/, minus the base prefix: ``ffff``,
43
+ ``teacache_x1.3`` (FxxF study), ``taylorseer_FFxx_x1.6``."""
44
+ if method == "none":
45
+ return "`ffff`"
46
+ tag = "" if schedule.upper() == "FXXF" else f"_{schedule}"
47
+ return f"`{method}{tag}_x{target:g}`"
48
+
49
+
50
+ def eval_rows():
51
+ if not os.path.exists(SUMMARY):
52
+ return {}
53
+ rows = list(csv.DictReader(open(SUMMARY)))
54
+ by_base = {}
55
+ for r in rows:
56
+ # schedule is not in the summary; the FxxF study has unsuffixed names
57
+ m = re.match(r"^(sf|cf)_(\w+?)(?:_(F[Fx]{3}))?_x([\d.]+)$", r["strategy"])
58
+ if r.get("schedule"):
59
+ sched = r["schedule"]
60
+ elif r["method"] == "none":
61
+ sched = "FFFF"
62
+ elif r["strategy"].startswith("cfa_"):
63
+ sched = r["strategy"].rsplit("_", 1)[-1].upper() # cfa_disca_fppf -> FPPF
64
+ else:
65
+ sched = (m.group(3) if m and m.group(3) else "FxxF")
66
+ r["schedule"] = sched
67
+ # naive / naive-cache rows are baselines, not operating points of a method
68
+ r["is_baseline"] = ("naive" in r["strategy"]) or ("_reuse_" in r["strategy"])
69
+ r["id"] = r["strategy"].split("_", 1)[1]
70
+ by_base.setdefault(r["base_model"], []).append(r)
71
+ return by_base
72
+
73
+
74
+ def forward_counts(strategy):
75
+ """(Full, P) for one strategy. Predictor strategies record full_forwards /
76
+ predictor_forwards per prompt and are counted that way (a predictor call is
77
+ ~0.03 of a forward and is not folded into Full); cache strategies use the
78
+ compute-equivalent forwards, P = 28 - Full."""
79
+ recs = [json.load(open(p)) for p in
80
+ glob.glob(os.path.join(ROOT, "eval_out/per_prompt", strategy, "*.json"))]
81
+ diag = [r.get("cache_diagnostics", {}) for r in recs]
82
+ if diag and all("full_forwards" in d for d in diag):
83
+ full = sum(d["full_forwards"] for d in diag) / len(diag)
84
+ pred = sum(d["predictor_forwards"] for d in diag) / len(diag)
85
+ return full, pred
86
+ ce = sum(d["compute_equivalent_forwards"] for d in diag) / len(diag)
87
+ return ce, FORWARDS - ce
88
+
89
+
90
+ PARTIAL_LATENCY = [] # (strategy id, timed prompts, total prompts) collected while formatting
91
+
92
+
93
+ # ---- row grouping: sections (schedule family / chunk count) x speed tiers ----
94
+ TIERS = [(1.3, "≈1.3×"), (1.6, "≈1.6×"), (1.75, "≈1.75×"), (2.0, "≈2×"), (2.85, "≈2.85–3×"), (4.0, "≈3.3–4×")]
95
+
96
+
97
+ def tier_label(r, n_full_steps):
98
+ """Nominal speed tier of a row: the search target for cache operating points,
99
+ otherwise the compute ratio (full forwards for Predictor rows) snapped to the
100
+ nearest tier. FFFF rows get their own label."""
101
+ if r["strategy"].endswith("_ffff"):
102
+ return "FFFF"
103
+ target = float(r.get("target_speedup") or 0)
104
+ is_pred = r["method"].startswith("predictor_")
105
+ if target > 0 and not r.get("is_baseline") and not is_pred:
106
+ x = target
107
+ else:
108
+ full = float(r.get("mean_full_forwards") or 0) if is_pred else 0.0
109
+ ce = full if full > 0 else float(r.get("mean_compute_equivalent_forwards") or 0)
110
+ x = n_full_steps / ce if ce > 0 else 1.0
111
+ if x < 1.15: # e.g. a full-compute variant (euler_FFFF): no speed tier
112
+ return "FFFF"
113
+ return min(TIERS, key=lambda t: abs(t[0] - x))[1]
114
+
115
+
116
+ TIER_ORDER = ["FFFF"] + [lab for _, lab in TIERS]
117
+
118
+
119
+ def grouped(rows, section_of, section_order, n_full_steps, row_key, ncols):
120
+ """Yield table lines: a blank spacer row + bold section row, then per tier a
121
+ spacer + italic tier row, then the rows (ordered by row_key)."""
122
+ blank = "|" + " |" * ncols
123
+ out = []
124
+ by_sec = {}
125
+ for r in rows:
126
+ by_sec.setdefault(section_of(r), []).append(r)
127
+ for sec in section_order:
128
+ if sec not in by_sec:
129
+ continue
130
+ if out:
131
+ out.append(blank)
132
+ out.append(f"| **{sec}**" + " |" * ncols)
133
+ tiers = {}
134
+ for r in by_sec[sec]:
135
+ tiers.setdefault(tier_label(r, n_full_steps), []).append(r)
136
+ for lab in TIER_ORDER:
137
+ if lab not in tiers:
138
+ continue
139
+ if lab != "FFFF":
140
+ out.append(blank)
141
+ out.append(f"| *{lab}*" + " |" * ncols)
142
+ for r in sorted(tiers[lab], key=row_key):
143
+ out.append(("row", r))
144
+ return out
145
+
146
+
147
+ def section_sf_cf(r):
148
+ return "首 chunk FFFF(`_c0FFFF`)" if r["strategy"].endswith("_c0FFFF") else "原始调度(chunk 0 与其它 chunk 相同)"
149
+
150
+
151
+ SECTIONS_SF_CF = ["原始调度(chunk 0 与其它 chunk 相同)", "首 chunk FFFF(`_c0FFFF`)"]
152
+
153
+
154
+ def section_cfa(r):
155
+ m = re.search(r"_(\d+)c(?:_|$)", r["strategy"])
156
+ n = int(m.group(1)) if m else 7
157
+ return f"{n} chunk({n * 12 - 3} 帧)"
158
+
159
+
160
+ def n_full_steps_cfa(r):
161
+ m = re.search(r"_(\d+)c(?:_|$)", r["strategy"])
162
+ return 4 * (int(m.group(1)) if m else 7)
163
+
164
+
165
+ def section_hy(r):
166
+ if (r["strategy"].endswith("_c0FFFF") or r.get("first_chunk_schedule") == "FFFF"
167
+ or r["method"].startswith("predictor_")):
168
+ return "首 chunk FFFF(`_c0FFFF`;Predictor 行 chunk 0 固定全算)"
169
+ return "原始调度(chunk 0 与其它 chunk 相同)"
170
+
171
+
172
+ SECTIONS_HY = ["原始调度(chunk 0 与其它 chunk 相同)", "首 chunk FFFF(`_c0FFFF`;Predictor 行 chunk 0 固定全算)"]
173
+
174
+
175
+ def hy_chunks(r):
176
+ """Chunk count of an HY row: 8 (125 frames) unless the id carries _<n>c."""
177
+ m = re.search(r"_(\d+)c(?:_|$)", r["strategy"])
178
+ return int(m.group(1)) if m else 8
179
+
180
+
181
+ def section_hy_long(r):
182
+ n = hy_chunks(r)
183
+ return f"{n} chunk({(4 * n - 1) * 4 + 1} 帧,chunk 0 FFFF)"
184
+
185
+
186
+ import re as _re
187
+
188
+
189
+ def _natural(text):
190
+ """Sort key that orders embedded integers numerically (s500 < s1000 < s2000)."""
191
+ return [int(t) if t.isdigit() else t for t in _re.split(r"(\d+)", text)]
192
+
193
+
194
+ def method_key(r):
195
+ return (r.get("is_baseline", False),
196
+ METHOD_ORDER.index(r["method"]) if r["method"] in METHOD_ORDER else 99,
197
+ r["schedule"] != "FxxF", float(r.get("target_speedup") or 0), _natural(r["strategy"]))
198
+
199
+
200
+ def fmt_eval_table(rows):
201
+ ffff = next(r for r in rows if r["method"] == "none")
202
+ ffff_ms = float(ffff["policy_latency_ms"])
203
+ is_cfa = any(r["strategy"].startswith("cfa_") for r in rows)
204
+ if is_cfa:
205
+ secs = sorted({section_cfa(r) for r in rows}, key=lambda t: int(t.split(" ")[0]))
206
+ # n_full_steps differs per chunk count: tier inside each section
207
+ plan = []
208
+ for sec in secs:
209
+ sub = [r for r in rows if section_cfa(r) == sec]
210
+ part = grouped(sub, section_cfa, [sec], n_full_steps_cfa(sub[0]), method_key, 9)
211
+ plan += (["|" + " |" * 9] if plan else []) + part
212
+ else:
213
+ plan = grouped(rows, section_sf_cf, SECTIONS_SF_CF, 28, method_key, 9)
214
+ lines = [HEADER]
215
+ for item in plan:
216
+ if isinstance(item, str):
217
+ lines.append(item)
218
+ continue
219
+ r = item[1]
220
+ full, pred = forward_counts(r["strategy"])
221
+ ms = float(r["policy_latency_ms"])
222
+ if r["strategy"].endswith("_ffff"):
223
+ psnr, ssim, lpips = 120.0, 1.0, 0.0
224
+ else:
225
+ psnr, ssim, lpips = (float(r[k] or "nan") for k in ("psnr", "ssim", "lpips"))
226
+ # "P" counts forwards served from cache. A naive-N-step row runs a
227
+ # *shorter* schedule -- those forwards are never issued, not reused -- so
228
+ # the column would be misleading there.
229
+ naive_steps = (r["method"] == "none" and not r["strategy"].endswith("_ffff"))
230
+ p_cell = "—" if naive_steps else f"{pred:.3f}"
231
+ # A strategy added after the first generation run whose latency has not
232
+ # yet been paired with FFFF in the same process is only provisional.
233
+ # (only the sf_/cf_ strategies added after their FFFF run can be provisional;
234
+ # the predictor strategies were generated together with their own FFFF)
235
+ provisional = (r["strategy"].startswith(("sf_", "cf_"))
236
+ and r["schedule"] not in ("FxxF", "FFFF")
237
+ and not r.get("latency_source", "").startswith(("paired", "strategy retime")))
238
+ # Any strategy whose latency mean covers fewer prompts than its quality
239
+ # metrics (records flagged latency_excluded) is provisional as well.
240
+ lat_n = r.get("latency_num_videos")
241
+ if "latency_excluded" in r.get("latency_source", "") and lat_n:
242
+ provisional = True
243
+ PARTIAL_LATENCY.append((r["id"], int(float(lat_n)), int(float(r["num_videos"]))))
244
+ # Timed on the one prompt shard that had its GPU to itself (aggregate.py
245
+ # --latency-subsets); quality still covers every prompt.
246
+ shard_timed = (r.get("latency_source", "").startswith("generation run, shard")
247
+ or "re-timed" in r.get("latency_source", ""))
248
+ mark = " ‡" if shard_timed else (" †" if provisional else "")
249
+ mp4 = int(float(r.get("mp4_reference_records") or 0))
250
+ pmark = " §" if mp4 > 0 else ""
251
+ vb = r.get("selected_vbench_percent") or ""
252
+ vb = f"{float(vb):.4f}" if vb else "待打分"
253
+ lines.append(
254
+ f"| `{r['id']}` "
255
+ f"| {vb} "
256
+ f"| {p_cell} "
257
+ f"| {full:.3f} "
258
+ f"| {ms:.2f}{mark} "
259
+ f"| {1.0 / float(r['latency_ratio_vs_ffff']):.3f}×{mark} "
260
+ f"| {psnr:.3f}{pmark} | {ssim:.4f}{pmark} | {lpips:.4f}{pmark} |")
261
+ return "\n".join(lines)
262
+
263
+
264
+ PARAM_LABEL = {"thresh": "`thresh`", "interval": "`interval`"}
265
+
266
+
267
+ def hy_config_table():
268
+ """Parameter table for the HY-WorldPlay strategies (from hy_strategies.load_strategies)."""
269
+ try:
270
+ sys.path.insert(0, ROOT)
271
+ from hy_strategies import load_strategies
272
+ strategies = load_strategies()
273
+ except Exception as e: # noqa: BLE001
274
+ return ""
275
+ label = {"teacache": "TeaCache", "taylorseer": "TaylorSeer", "motioncache": "MotionCache",
276
+ "flowcache": "FlowCache", "none": "无缓存", "reuse": "reuse"}
277
+ lines = ["| 策略 | 方法 | 调度 | 参数 | 取值 | 目标加速比 | 来源 |", "|---|---|---|---|---:|---:|---|"]
278
+ for st in strategies:
279
+ sched = st["schedule"]
280
+ if st.get("first_chunk_schedule"):
281
+ sched += "(首 chunk FFFF)"
282
+ param = f"`{st['param']}`" if st.get("param") else "—"
283
+ val = f"{st['value']:g}" if st.get("value") is not None else "—"
284
+ tgt = f"{st['target']:g}×" if st.get("target") else "—"
285
+ src = st.get("source", "—")
286
+ if st["method"] == "teacache" and st.get("coefficients"):
287
+ src += ";rescale 系数 hy_coeff.json"
288
+ lines.append(f"| `{st['name'].split('_', 1)[1]}` | {label.get(st['method'], st['method'])} | {sched} "
289
+ f"| {param} | {val} | {tgt} | {src} |")
290
+ lines.append("| `atc_s1_fppf` / `atc_s1_fppp` | ATC Stage-1 predictor | FPPF / FPPP | — | — | — | "
291
+ "HY-WorldPlay-DEV-Predictor validation25(¶) |")
292
+ lines.append("| `atc_s2_s{500,800,1000,1500,2000}_fppf` / `_fppp` | ATC Stage-1 + on-policy detached chunk+timestep FPPP rollout(step 500/800/1000/1500/2000) | FPPF / FPPP | — | — | — | "
293
+ "HY-WorldPlay-DEV-Predictor validation25(¶) |")
294
+ lines.append("| `disca_s1_fppf` / `disca_s1_fppp` | DisCa Stage-1 predictor(双 block,step 2000) | FPPF / FPPP | — | — | — | "
295
+ "HY-WorldPlay-DEV-Predictor validation25(¶) |")
296
+ lines.append("| `disca_s1000_fppf` / `disca_s1000_fppp` | DisCa Stage-1 predictor(step 1000) | FPPF / FPPP | — | — | — | "
297
+ "HY-WorldPlay-DEV-Predictor validation25(¶) |")
298
+ lines.append("| `disca_s500_fppf` | DisCa Stage-1 predictor(step 500) | FPPF | — | — | — | "
299
+ "HY-WorldPlay-DEV-Predictor validation25(¶) |")
300
+ lines.append("| `<n>c_ffff` / `naive2step_<n>c_c0FFFF`(n = 16 / 32) | 长视频 FFFF 参考 / naive 2 步(首 chunk FFFF),253 / 509 帧 | FFFF / FF | — | — | — | "
301
+ "hycache,同进程配对 FFFF |")
302
+ lines.append("| `atc_s2_s{500,1000,2000}_<n>c_fppf_c0FFFF`、`disca_s{500,1000,2000}_<n>c_fppf`(n = 16 / 32) | ATC rollout / DisCa Stage-1 predictor 各 step 的长视频行(64 / 128 latent,相机动作等比拉长,pose-retrieved memory 上限 20 latent) | FPPF | — | — | — | "
303
+ "HY-WorldPlay-DEV-Predictor 生成器(`hy_dev_gen_long.py`,¶),像素指标对照 `<n>c_ffff` 的 MP4 |")
304
+ return "\n".join(lines)
305
+
306
+
307
+ def lb_config_table():
308
+ """Parameter table for the LingBot-World-V2 strategies (from lb_strategies.load_strategies)."""
309
+ try:
310
+ sys.path.insert(0, ROOT)
311
+ from lb_strategies import load_strategies
312
+ strategies = load_strategies()
313
+ except Exception: # noqa: BLE001
314
+ return ""
315
+ label = {"teacache": "TeaCache", "taylorseer": "TaylorSeer", "motioncache": "MotionCache",
316
+ "none": "无缓存", "reuse": "reuse(velocity)"}
317
+ lines = ["| 策略 | 方法 | 调度 | 参数 | 取值 | 目标加速比 | 来源 |", "|---|---|---|---|---:|---:|---|"]
318
+ for st in strategies:
319
+ sched = st["schedule"]
320
+ if st.get("first_chunk_schedule"):
321
+ sched += "(首 chunk FFFF)"
322
+ param = f"`{st['param']}`" if st.get("param") else "—"
323
+ val = f"{st['value']:g}" if st.get("value") is not None else "—"
324
+ tgt = f"{st['target']:g}×" if st.get("target") else "—"
325
+ src = st.get("source", "—")
326
+ if st["method"] == "teacache" and st.get("coefficients"):
327
+ src += ";rescale 系数 lb_coeff.json"
328
+ lines.append(f"| `{st['name'].split('_', 1)[1]}` | {label.get(st['method'], st['method'])} | {sched} "
329
+ f"| {param} | {val} | {tgt} | {src} |")
330
+ # Layer-17 Predictor rows (lingbot-world-v2-a, Stage-1 only): names follow
331
+ # lb_generate_predictor_eval.py, one row per model with the evaluated patterns.
332
+ try:
333
+ import csv as _csv
334
+ rows = list(_csv.DictReader(open(LB_SUMMARY))) if os.path.exists(LB_SUMMARY) else []
335
+ except Exception: # noqa: BLE001
336
+ rows = []
337
+ by_model = {}
338
+ for r in rows:
339
+ if r["method"].startswith("predictor_"):
340
+ by_model.setdefault(r["method"][len("predictor_"):], []).append(r["strategy"].split("_")[-1].upper())
341
+ desc = {"atc_chunk": "ATC Stage-1 predictor(block 17,previous_scope=chunk)",
342
+ "disca": "DisCa Stage-1 predictor(block 17,无 previous-chunk 通道)"}
343
+ for m, pats in sorted(by_model.items()):
344
+ names = " / ".join(f"`{m}_{p.lower()}`" for p in sorted(set(pats)))
345
+ lines.append(f"| {names} | {desc.get(m, m)} | {' / '.join(sorted(set(pats)))}(首 chunk FFFF) | — | — | — | "
346
+ "lingbot-world-v2-a Stage-1,100 组图 × 4 动作离线集,2000 步 |")
347
+ return "\n".join(lines)
348
+
349
+
350
+ def config_tables():
351
+ """One row per strategy: the knob and its settled value, with provenance."""
352
+ sys.path.insert(0, ROOT)
353
+ from eval.strategies import load_strategies
354
+ out = {}
355
+ for base in ["self_forcing", "causal_forcing"]:
356
+ finals = {}
357
+ for fp in glob.glob(os.path.join(ROOT, f"results/final_{base}*.json")):
358
+ for r in json.load(open(fp))["rows"]:
359
+ key = r.get("name") or (r["method"], r.get("schedule", "FxxF"),
360
+ r["target_speedup"])
361
+ finals[key] = (r, os.path.basename(fp))
362
+ coeff_path = os.path.join(ROOT, f"results/coeff_{base}.json")
363
+ coeff = json.load(open(coeff_path))["coefficients"] if os.path.exists(coeff_path) else None
364
+ lines = ["| 策略 | 方法 | 调度 | 参数 | 取值 | 目标加速比 | 搜索时 Full | 来源 |",
365
+ "|---|---|---|---|---:|---:|---:|---|"]
366
+ for st in load_strategies(base):
367
+ if st["is_reference"]:
368
+ lines.append("| `ffff` | 无缓存 | FFFF | — | — | 1.0× | 28.000 | — |")
369
+ continue
370
+ key = st["name"] if st["name"] in finals else (st["method"], st["schedule"], st["target"])
371
+ r, src = finals[key]
372
+ note = src
373
+ if "heldout_flops_drift" in r:
374
+ note += f",held-out 漂移 {r['heldout_flops_drift']:+.3f}"
375
+ elif "band_note" in r:
376
+ note += f",按实测加速比定点(扫描 {r['scan_measured_speedup']:.3f}×"
377
+ if r.get("scan_active_step_ratio"):
378
+ note += f",活跃步 {100*r['scan_active_step_ratio']:.0f}%"
379
+ note += f",选中 {100*r['scan_mean_selected_fraction']:.0f}%"
380
+ note += ")" + (f";{r['band_note']}" if r["band_note"] else "")
381
+ elif "note" in r:
382
+ note += ",3-prompt 搜索点,未经 finalize"
383
+ if st.get("target") in (None, 0.0):
384
+ lines.append(f"| `{st['name'].split('_', 1)[1]}` | {METHOD_LABEL.get(st['method'], st['method'])} "
385
+ f"| {st['schedule']} | — | — | — | — | 基线(无搜索参数) |")
386
+ continue
387
+ lines.append(
388
+ f"| {strategy_label(st['method'], st['schedule'], st['target'])} "
389
+ f"| {METHOD_LABEL[st['method']]} "
390
+ f"| {st['schedule']}{'(首 chunk ' + st['first_chunk_schedule'] + ')' if st.get('first_chunk_schedule') else ''} "
391
+ f"| {PARAM_LABEL.get(st['param'], st['param'])} | {st['value']:.6g} "
392
+ f"| {st['target']:g}× "
393
+ f"| {r.get('compute_equivalent_forwards', r.get('scan_compute_equivalent', float('nan'))):.3f} "
394
+ f"| {note} |")
395
+ out[base] = ("\n".join(lines), coeff)
396
+ return out
397
+
398
+
399
+ HY_SUMMARY = os.path.join(ROOT, "eval_out_hy/summaries/final_summary.csv")
400
+ LB_SUMMARY = os.path.join(ROOT, "eval_out_lb/summaries/final_summary.csv")
401
+ HY_HEADER = ("| 策略 | VBench-I2V-100 原始 (%) | VBench-I2V-100 归一 (%) | 平均 P | Full "
402
+ "| 模型路径耗时 (ms) | 加速比 | PSNR | SSIM | LPIPS |"
403
+ "\n|---|---:|---:|---:|---:|---:|---:|---:|---:|---:|")
404
+ HY_ACT_HEADER = ("| 策略 | 参数 | 调度 | 活跃步 % | 空步 % | 平均选中 token % |"
405
+ "\n|---|---|---|---:|---:|---:|")
406
+
407
+
408
+ def fmt_hy_table(summary=HY_SUMMARY):
409
+ """The I2V-100 table (HY-WorldPlay by default; the LingBot table has the same shape)."""
410
+ if not os.path.exists(summary):
411
+ return None
412
+ rows = list(csv.DictReader(open(summary)))
413
+ if not rows:
414
+ return None
415
+ for r in rows:
416
+ r["is_baseline"] = ("naive" in r["strategy"]) or ("_reuse_" in r["strategy"])
417
+ lines = [HY_HEADER]
418
+ # 8-chunk rows in the two first-chunk sections, then one section per longer video
419
+ plan = grouped([r for r in rows if hy_chunks(r) == 8], section_hy, SECTIONS_HY, 32, method_key, 10)
420
+ for n in sorted({hy_chunks(r) for r in rows if hy_chunks(r) != 8}):
421
+ sub = [r for r in rows if hy_chunks(r) == n]
422
+ plan += ["|" + " |" * 10] + grouped(sub, section_hy_long, [section_hy_long(sub[0])], 4 * n, method_key, 10)
423
+ for item in plan:
424
+ if isinstance(item, str):
425
+ lines.append(item)
426
+ continue
427
+ r = item[1]
428
+ fw = float(r["denoise_forwards"])
429
+ ce = float(r["mean_compute_equivalent_forwards"])
430
+ ms = float(r["policy_latency_ms"])
431
+ if r["strategy"].endswith("_ffff"):
432
+ psnr, ssim, lpips = 120.0, 1.0, 0.0
433
+ else:
434
+ psnr, ssim, lpips = (float(r[k] or "nan") for k in ("psnr", "ssim", "lpips"))
435
+ # "P" counts forwards served from cache. A naive-N-step row runs a
436
+ # *shorter* schedule -- those forwards are never issued, not reused -- so
437
+ # the column would be misleading there.
438
+ naive_steps = (r["method"] == "none" and not r["strategy"].endswith("_ffff"))
439
+ p_cell = "—" if naive_steps else f"{fw - ce:.3f}"
440
+ # Predictor rows: same convention as the Causal-Forcing-a table -- P counts
441
+ # Predictor steps, Full counts full DiT forwards (the 1/54 Predictor cost is
442
+ # only used for the compute-equivalent speedup target).
443
+ if r["method"].startswith("predictor_") and r.get("mean_predictor_forwards"):
444
+ p_cell = f"{float(r['mean_predictor_forwards']):.3f}"
445
+ ce = float(r["mean_full_forwards"])
446
+ raw = r.get("core5_percent") or ""
447
+ nrm = r.get("score_5d_percent") or ""
448
+ raw = f"{float(raw):.4f}" if raw else "待打分"
449
+ nrm = f"{float(nrm):.4f}" if nrm else "待打分"
450
+ pmark = " §" if int(float(r.get("mp4_reference_records") or 0)) > 0 else ""
451
+ # DEV-project imports carry host-side stage timing, not CUDA-event timing
452
+ tmark = " ¶" if r.get("latency_source", "").startswith("DEV generator") else ""
453
+ lines.append(
454
+ f"| `{r['strategy'].split('_', 1)[1]}` | {raw} | {nrm} | {p_cell} | {ce:.3f} | {ms:.2f}{tmark} "
455
+ f"| {1.0 / float(r['latency_ratio_vs_ffff']):.3f}×{tmark} | {psnr:.3f}{pmark} | {ssim:.4f}{pmark} | {lpips:.4f}{pmark} |")
456
+ return "\n".join(lines)
457
+
458
+
459
+ def pending_points():
460
+ """Operating points from non-default-schedule sweeps that have no eval row yet."""
461
+ evaluated = {r["strategy"] for rows in eval_rows().values() for r in rows}
462
+ out = {}
463
+ for p in sorted(glob.glob(os.path.join(ROOT, "results/sweep_*_F*.json"))):
464
+ d = json.load(open(p))
465
+ sched = d.get("schedule", "FxxF")
466
+ short = {"self_forcing": "sf", "causal_forcing": "cf"}[d["base"]]
467
+ for pt in d["operating_points"]:
468
+ name = f"{short}_{d['method']}_{sched}_x{pt['target_speedup']:g}"
469
+ if name in evaluated:
470
+ continue
471
+ out.setdefault(d["base"], []).append(dict(pt, method=d["method"], schedule=sched,
472
+ param=d["param"], name=name))
473
+ return out
474
+
475
+
476
+ def fmt_pending_table(pts):
477
+ lines = ["| 策略 | 参数 | 平均 P | Full | compute 加速比 | 配对实测加速比 (3 prompt) | VBench / PSNR / SSIM / LPIPS |",
478
+ "|---|---|---:|---:|---:|---:|---|"]
479
+ pts = sorted(pts, key=lambda p: (METHOD_ORDER.index(p["method"]), p["schedule"],
480
+ p["target_speedup"]))
481
+ for p in pts:
482
+ ce = p["mean_compute_equivalent_forwards"]
483
+ lines.append(
484
+ f"| {strategy_label(p['method'], p['schedule'], p['target_speedup'])} "
485
+ f"| `{p['param']}={p[p['param']]:.4g}` "
486
+ f"| {FORWARDS - ce:.3f} | {ce:.3f} "
487
+ f"| {p['flops_speedup']:.3f}× "
488
+ f"| {p['measured_speedup']:.2f}× (±{p['measured_speedup_stdev']:.2f}) "
489
+ f"| 待评测 |")
490
+ return "\n".join(lines)
491
+
492
+
493
+ def main():
494
+ by_base = eval_rows()
495
+ pending = pending_points()
496
+ doc = []
497
+ doc.append("# Experiment: training-free caching on 4-step block-causal video DiTs\n")
498
+ doc.append("四个 training-free 缓存方法(TeaCache / FlowCache / TaylorSeer / MotionCache)"
499
+ "移植到两个 4-step 自回归视频 DiT(Self-Forcing、Causal-Forcing,均为 Wan2.1-1.3B "
500
+ "block-causal)上,在匹配的 compute 预算下比较速度与质量。\n")
501
+ doc.append("## 列定义\n")
502
+ doc.append("- **策略**:方法 + 调度 + 目标加速比��调度字符串按 chunk 内 4 个去噪步写,"
503
+ "`F` = 必算完整 DiT,`x` = 允许方法从缓存服务。`FxxF` 是原始设定"
504
+ "(等价于上游 `ret_steps=1` / `cutoff_steps=num_steps-1`),"
505
+ "`FFxx` 让 TaylorSeer 在第一次预测前有两个已算点,`Fxxx` 去掉最后一步必算的限制,"
506
+ "算术上限从 2.0× 提到 4.0×。")
507
+ doc.append("- **VBench-251 (%)**:Extended-251 协议的 VBench-8 selected 分(4×quality + semantic)/5,"
508
+ "251 条 prompt(subject_consistency 72 / overall_consistency 93 / scene 86)。")
509
+ doc.append("- **Full**:一条视频(7 chunk × 4 步 = 28 次去噪 DiT forward)中实际执行的完整 DiT forward "
510
+ "等效数,251 条 prompt 的平均;MotionCache / FlowCache 这类部分重算的步按 compute-equivalent "
511
+ "折算。所有方法按这一列匹配 compute。")
512
+ doc.append("- **平均 P**:一条视频中被**缓存复用**的 forward 数 = 28 − Full。"
513
+ "`naiveNstep` 基线走的是更短的去噪调度,缺的 forward 是**根本没有发起**而不是被复用,"
514
+ "所以这一列对它们记为 —(它们的 Full 仍按 28 步的标尺给出,便于等算力对照)。"
515
+ "Predictor 策略(`cfa_*`,Causal-Forcing-a)按记录里的 `full_forwards` / `predictor_forwards` 计:"
516
+ "Full 为完整 DiT 次数,P 为 predictor 调用次数(每次约 0.03 个 forward,不计入 Full)。")
517
+ doc.append("- **模型路径耗时 (ms)**:251 条 prompt 上 denoise policy 路径的 GPU 平均耗时,"
518
+ "含缓存方法自己的控制开销;不含 context/KV-cache 刷新 DiT(另计,~790 ms/视频)、"
519
+ "文本编码、VAE 解码。")
520
+ doc.append("- **加速比**:matched FFFF 平均耗时 / 该策略平均耗时(同 prompt、同 seed、同一次运行内配对)。"
521
+ "原始 26 个策略与 FFFF 同批生成;后加的策略由 `eval/retime_eval.py` 与 FFFF 在同一进程内"
522
+ "逐 prompt 配对重新计时(只跑 denoise 路径),其\"模型路径耗时\"来自这次配对计时,"
523
+ "绝对 ms 与首批不在同一争用条件下,只有加速比可跨行比较。"
524
+ "首 chunk FFFF 变体(`_c0FFFF`,`teacache_x2_c0FFFF` 除外)的耗时来自 Sep 7 在空闲 GPU 上"
525
+ "只重跑策略 denoise 路径的单次重计时(FFFF 不重跑,以各基模 FFFF 首批记录为分母;逐条核对算量一致,"
526
+ "视频与质量指标不变)。")
527
+ doc.append("- **PSNR / SSIM / LPIPS**:相对同 prompt、同 seed 的 FFFF,在解码后的 81 帧 RGB 上计算,"
528
+ "编码 MP4 之前。FFFF 对自身固定为 120 dB / 1.0 / 0.0。"
529
+ "Sep 7 起新增的策略不再重新生成 FFFF,参考帧读自 FFFF 那次运行写出的 MP4(H.264),表中以 § 标出;"
530
+ "在同一批视频上实测该替换使 PSNR +0.10 dB、SSIM −0.024、LPIPS +0.012(MP4 抹掉了参考的高频细节),"
531
+ "与其它行比较时按此修正。")
532
+ doc.append("- 策略 id 与 `eval_out/` 目录一致(去掉 `sf_`/`cf_`/`cfa_` 前缀):不带调度后缀的是原始 `FxxF` 研究,"
533
+ "`_FFxx_`/`_Fxxx_` 为放宽调度后的操作点,`_x<N>` 是搜索时的目标加速比,实际 compute 看 Full 列;"
534
+ "`cfa_*` 为 Causal-Forcing-a 上的 Predictor 策略(DisCa / ATC-chunk / ATC-last-frame,均为 Stage-1 监督蒸馏;"
535
+ "`atc_chunk_s2_*` 为 ATC-chunk 再经 Stage-2 随机出口 DMD(Wan-14B real score、LoRA rank-128 fake score,2000 步)后的 EMA 权重),"
536
+ "后缀 `fppf`/`fppp` 是 chunk 内的调度模式(P = predictor 步)。\n")
537
+ doc.append("视频规格:81 帧、480×832、16 FPS、seed 0、bf16、每 prompt 一个样本。\n")
538
+
539
+ doc.append("## 1. Extended-251 评测结果(已完成)\n")
540
+ for base in BASES:
541
+ if base not in by_base:
542
+ continue
543
+ doc.append(f"### {BASE_LABEL[base]}\n")
544
+ doc.append(fmt_eval_table(by_base[base]) + "\n")
545
+
546
+ hy = fmt_hy_table()
547
+ if hy:
548
+ doc.append("### HY-WorldPlay(I2V,VBench-I2V-100)\n")
549
+ doc.append("第三个基模:HY-WorldPlay 的 4-step 蒸馏自回归 I2V 模型(HunyuanVideo-1.5 架构,54 个 "
550
+ "double-stream block,480×832,125 帧 = 8 chunk × 4 步 = **32 次去噪 forward**)。"
551
+ "评测集为 DEV 项目的 validation25:25 张 VBench-I2V 图 × 4 组双向相机动作 = 100 个视频,"
552
+ "seed 0。两列 VBench 都基于 `custom_input` 模式下的同一组 **Core5** 五个画质维度"
553
+ "(subject_consistency、background_consistency、motion_smoothness、aesthetic_quality、"
554
+ "imaging_quality,后者先除以 100):**原始**列是五项原始分的简单平均,口径与 "
555
+ "HY-WorldPlay-DEV-Predictor 项目 experiment.md 第 8 节的 VBench Core5 一致,便于直接对照;"
556
+ "**归一**列先按 VBench 官方 min-max 归一再平均,"
557
+ "即 `((sc−0.1462)/0.8538 + (bc−0.2615)/0.7385 + (ms−0.7060)/0.2915 + aq + iq) / 5`,"
558
+ "与 251 表的质量组口径一致。平均 P = 32 − Full。"
559
+ "耗时列为去噪路径(32 次 forward)的 GPU 时间,不含每 chunk 一次的 context KV pass "
560
+ "和文本 KV pass;加速比与同进程内同一 job 的 FFFF 配对。\n")
561
+ doc.append(hy + "\n")
562
+
563
+ lb = fmt_hy_table(LB_SUMMARY)
564
+ if lb:
565
+ doc.append("### LingBot-World-V2-1.3B-Causal-Fast(I2V,VBench-I2V-100)\n")
566
+ doc.append("第四个基模:LingBot-World-V2 的 1.3B causal-fast 蒸馏自回归 I2V 世界模型(Wan2.1-1.3B block-causal "
567
+ "架构,30 个 block,相机 Plucker 条件,480×832,16 fps,125 帧 = 8 chunk × 4 latent × 4 步 = "
568
+ "**32 次去噪 forward**,KV 窗口 18 latent、sink 6)。评测协议与 HY-WorldPlay 完全相同:"
569
+ "validation25 的 25 张图 × 4 组双向相机动作 = 100 个视频,seed 0,Core5 五维、原始/归一两列同上;"
570
+ "相机动作把 HY 的逐 latent 位姿(前进 0.08 单位/latent、旋转 3°/latent,前半程正向、后半程反向)"
571
+ "换算成 LingBot 需要的逐帧 OpenCV c2w 位姿(4 帧/latent),内参取模型 480×832 示例数据的 "
572
+ "fx = fy ≈ 415.6。**这里的 `reuse_*` 复用的是 velocity 而不是 block 残差**:R 步完全不调用 DiT,"
573
+ "直接把上一次算出的 flow 预测当作本步预测(`x0 = x_t − σ_t·v_prev`),再照常 renoise;"
574
+ "因此 R 步耗时≈0,FRFF/FRRF/FRRR 的 Full 精确为 24/16/8。三个缓存方法(TeaCache / TaylorSeer / MotionCache)按 `cachelib` 的同一套移植接在 30 个 block 的循环上(block 级重实现与官方 forward 逐位一致,`lb_test_exact.py`),操作点沿用 HY 的流程:TeaCache 的 rescale 多项式用 3 个 case × 125 帧标定(`lb_coeff.json`,一次多项式,R² 0.63);`x1.3` 由 compute fraction 二分得到(`lb_sweep_*.json`,61 帧);`x1.75` / `Fxxx_x2.85` 及其 `_c0FFFF` 变体在 61 帧、配对 FFFF 的实测加速比网格上定点(`lb_point_v2.json` / `lb_point_c0.json`,选点规则与 HY 相同)。naive 减步按 Self-Forcing 的规则取 4 步网格的均匀子集(4 步网格 t = 999/937/833/624;3 步 = 999/833/624、2 步 = 999/624、1 步 = 999)。`atc_chunk_*` / `disca_*` 为 Layer-17 Predictor(`lingbot-world-v2-a`,Causal-Forcing-a 的同款移植:复制教师 block 17 + 融合模块,预测 head 输入的 final hidden;离线集 = 100 组 HY 训练图 × 4 动作 × 7 chunk × 3 相邻转移 = 8400 个样本,Stage-1 监督蒸馏 2000 步、全局 batch 64、fusion lr 1e-4 / block lr 1e-5,未做 Stage-2);chunk 0 固定 FFFF,FPPF / FPPP 中 P 步锚定同 chunk 上一步的 hidden,FPF 只走 t = 999 / 937 / 624 三步(P 锚定 t = 999);P 列为 Predictor 调用次数,Full 为完整 DiT 次数,Predictor 按 1/30 次 forward 计入算量。耗时列为去噪路径的 GPU 时间,不含每 chunk "
575
+ "一次的 context KV pass(t=0 的 KV 重写);加速比与同进程内同一 job 的 FFFF 配对。\n")
576
+ doc.append(lb + "\n")
577
+
578
+ doc.append("† 耗时来自该策略自己的生成运行(独占 GPU、单进程),与各基模 FFFF 首批记录相比得到加速比,"
579
+ "未做同进程配对计时;按约定不再做 FFFF 重计时。"
580
+ + (("其中 " + "、".join(f"`{i}`({n}/{t} 条)" for i, n, t in PARTIAL_LATENCY)
581
+ + " 的耗时只来自生成时计时未被破坏的那部分 prompt:其余记录的原始计时被一次中断且遭遇 GPU 争用的"
582
+ "配对重计时覆盖,已在记录中标记 `latency_excluded` 并从耗时均值剔除,VBench 与像素指标仍用全部 251 条。")
583
+ if PARTIAL_LATENCY else "")
584
+ + "\n")
585
+ doc.append("‡ 该行有部分记录在生成时 GPU 被其他进程短暂共用(Sep 7 的 `disca_s1000_*`:GPU 4/7 上的 gpu_burn 占位,"
586
+ "06:22–06:40,每策略约 84 条),这些记录事后在空闲 GPU 上只重跑策略路径重新计时(FFFF 不重跑,逐条核对算量一致,"
587
+ "旧值保留在记录的 `generation_run_latency`);其余记录为独占 GPU 的生成运行值。所有记录均为单进程计时。\n")
588
+ doc.append("§ 像素指标以 FFFF 运行写出的 MP4 解码帧为参考(其余行以 MP4 编码前的原始帧为参考);同一批视频上实测差异:"
589
+ "PSNR +0.10 dB、SSIM −0.024、LPIPS +0.012。`cf_teacache_x2_c0FFFF` 为混合(75/251 条用 MP4 参考)。\n")
590
+ doc.append("¶ `hy_atc_s1_*` / `hy_disca_s1_*` 来自 HY-WorldPlay-DEV-Predictor 的 validation25 评测(ATC Stage-1,"
591
+ "`predictor_v4_atc-full_transport-global-chunk_…_4gpu_bs8x2_steps2000`,step 2000,FPPF/FPPP,chunk 0 四步全算——DEV 的 rollout 固定如此,Predictor 需要前一 chunk;FPPF = 18 full + 14 Predictor,FPPP = 11 + 21),"
592
+ "耗时为该项目生成器的 host 端分段计时(`ar_step_transformer + ar_step_predictor`,即去噪路径,不含 context/history KV),"
593
+ "与本表其它行的 CUDA event 计时口径接近但不完全相同;像素指标对照 DEV 项目 validation 的 FFFF 视频(与 `hy_ffff` 同源)。"
594
+ "DisCa 为双 block Predictor(blocks [0,53],Sep 8 用 `--force_first_chunk_full` 重跑)。"
595
+ "`hy_atc_s2_s<N>_*` 为同一 ATC Stage-1 再经 on-policy detached chunk+timestep FPPP rollout 微调(4 卡、每卡 1 条轨迹 × 累积 2、flr 5e-5 / blr 5e-6、2000 steps)后第 N 步的权重,"
596
+ "Sep 10 评测(DEV experiment.md 第 12 节),生成设置与 `hy_atc_s1_*` 相同。"
597
+ "Predictor 步按 1/54(DisCa 2/54)次 forward 计入 Full。\n")
598
+ doc.append("### 读数备注\n")
599
+ doc.append("- 2.0× 是 `FxxF` 的算术上限(14/28),到了这一档 TeaCache / FlowCache / MotionCache "
600
+ "全部退化成\"中间两步整体跳过、残差拷贝\",走的是同一条代码路径,所以三者数字一致;"
601
+ "TaylorSeer 在 2.0× 上不同(逐模块拷贝 + 当前步调制),且略差。")
602
+ doc.append("- `FxxF` 下 TaylorSeer 的一阶预测从未被触发:跳步前 chunk 内只算过 step 0,"
603
+ "差分导数不存在,实际走的是 order-0(拷贝)。`FFxx` 调度就是为了让预测真正生效。")
604
+ doc.append("- 像素指标(PSNR 12–15 dB)与 VBench(掉 0–1.4 分)严重脱钩;在这个设定里 PSNR/SSIM "
605
+ "只能当\"偏离 FFFF 的程度\"读,不是质量代理。")
606
+ doc.append("- **第一个 chunk 不该被缓存。** `teacache_x2_c0FFFF` 与 `teacache_x2` 用同一个阈值,"
607
+ "唯一区别是 chunk 0 走满 FFFF 四步(算力 16/28 vs 14/28)。Self-Forcing 上 VBench "
608
+ "从 78.7743 升到 79.7515(**+0.98**,把相对 FFFF 的 1.76 分差距砍掉 55%),"
609
+ "像素保真度改善更大:PSNR 13.02→16.61(**+3.59 dB**)、SSIM 0.4222→0.6511、"
610
+ "LPIPS 0.4854→0.1883(几乎减半)。逐维增益集中在外观类"
611
+ "(imaging_quality +0.021、aesthetic_quality +0.021、subject_consistency +0.014、"
612
+ "scene +0.011),dynamic_degree −0.014(画面更稳)。机理很直接:第一个 chunk 没有"
613
+ "前序 chunk 可复用,且整段视频的外观都继承自它,缓存它等于把误差灌进后面所有 chunk。"
614
+ "值得注意的是它同时**又快又好于** `teacache_x1.3`(1.788× vs 1.240×,79.75 vs 79.59,"
615
+ "PSNR 16.61 vs 15.16)——「首 chunk 全算 + 后续激进缓存」比「全程温和缓存」是更优的算力分配。")
616
+ doc.append("- **首 chunk FFFF 对三种方法、三个档位都成立(SF,`_c0FFFF` 行,Sep 6)。** 同参数下 VBench "
617
+ "一律上升:TeaCache 1.3× 79.59→80.39、1.6× 78.99→80.06(+1.07,1.353×)、`Fxxx` 3× 58.68→61.31;TaylorSeer 1.3× 79.83→80.44、"
618
+ "1.75× 78.63→79.44、`Fxxx` 2.85× 60.30→65.54(**+5.2**);MotionCache 1.3× 79.23→79.97、"
619
+ "1.75× 79.03→80.34(**+1.31**,已到 FFFF 的 80.54 只差 0.2)、`Fxxx` 2.85× 58.60→62.04。"
620
+ "像素保真度更是整体抬升一个台阶:`FxxF` 各档 PSNR 从 13.0–15.2 dB 升到 16.7–20.4 dB、LPIPS 从 "
621
+ "0.32–0.52 降到 0.09–0.21;`Fxxx` 档 PSNR 也从 11.7–11.9 升到 14.0–14.3。代价是首 chunk 多算 "
622
+ "1–3 次 forward,实测加速比回落 0.08–0.6×(1.3× 档几乎不亏:1.24→1.16、1.30→1.26、1.14→1.13;"
623
+ "3× 档亏最多:3.47→2.89、2.95→2.37、2.54→1.90)。两点值得写进论文:(i) `motioncache_x1.75_c0FFFF` "
624
+ "在 1.445× 上达到 80.34 / PSNR 16.75,是 SF 上所有非 FFFF 配置里最接近 FFFF 的一档;(ii) 即便首 chunk "
625
+ "全算,`Fxxx` 仍停在 61–66 分——最后一步的损失是逐 chunk 局部的,不是从首 chunk 传下来的,"
626
+ "所以两条规则相互独立:首 chunk 全算、最后一步全算。")
627
+ doc.append("- **首 chunk FFFF 在 Causal-Forcing 上同样成立,但 1.3× 档没有余量。** CF 的 FFFF 是 81.17,"
628
+ "而三种方法的 1.3× 原版已经在 81.2–81.6(与 FFFF 持平或更高,属评测噪声),所以 `_c0FFFF` 在这一档 "
629
+ "VBench 变化在 ±0.3 内(TeaCache 81.22→81.04、TaylorSeer 81.62→81.31、MotionCache 81.25→81.39);"
630
+ "但只要原版有损失,首 chunk 全算就把损失补回来:TeaCache 2× 79.97→**81.18**(+1.21,1.789× 下回到 FFFF 的 81.17;"
631
+ "PSNR 11.90→14.43),1.75× TaylorSeer 79.95→80.74、MotionCache 80.67→81.11(回到 FFFF 水平),`Fxxx` 档 TaylorSeer 60.96→65.46、MotionCache 59.58→64.08(各 **+4.5**)、"
632
+ "TeaCache 65.02→65.66。像素保真度则和 SF 一样全面抬升:`FxxF` 各档 PSNR 12.0–13.2→14.4–16.5、"
633
+ "LPIPS 0.34–0.52→0.14–0.27。SF/CF 两个基模合起来,16 组同参数对照中 VBench 14 升 2 平"
634
+ "(2 平的都是原本已到 FFFF 的 CF 1.3× 档),PSNR 16/16 上升。")
635
+ doc.append("- **naive 减步是很强的对照。** 在 Causal-Forcing 上按等算力配对(Full 完全相同):"
636
+ "21/28 档 `naive3step` 81.40 vs `reuse_FRFF` 81.31,14/28 档 80.57 vs 80.04,"
637
+ "7/28 档 **75.52 vs 58.86**——直接少走几步全面不输于、低算力时远好于固定位置的残差复用,"
638
+ "因为 `FRRR` 只算首步、其余三步复用同一个残差,误差累积到崩溃。"
639
+ "更关键的是 `naive2step`(14/28、80.57)优于所有缓存方法在同一算力下的成绩"
640
+ "(`teacache_x2` / `motioncache_x2` 均为 79.97–79.99),"
641
+ "即在这个基模上「直接少走两步」比「走满四步再缓存两步」更划算。")
642
+ doc.append("- **HY-WorldPlay 上 naive 减步几乎免费,直接复用不是(Sep 6,Core5 原始分)。** `naive3step` 84.29、"
643
+ "`naive2step` 84.26 与 FFFF 84.26 持平,`naive1step` 83.11(−1.1)却拿到 **3.90×**;像素上 "
644
+ "naive3/2/1 的 PSNR 19.4 / 18.0 / 16.1。等算力对照:24/32 档 `naive3step` 84.29 ≈ `reuse_FRFF` 84.29 "
645
+ "≈ `teacache_x1.3` 84.37;16/32 档 `naive2step` 84.26 ≈ `reuse_FRRF` 84.23;8/32 档 `naive1step` 83.11 "
646
+ "vs `reuse_FRRR` 81.27(**+1.8**,PSNR 16.1 vs 15.0)。也就是说 HY 这类蒸馏 AR 模型对步数极不敏感"
647
+ "(4 步→2 步无损、→1 步只掉 1 分),三种缓存方法在 `FxxF` 下做到的 1.5–1.7× 都被 `naive2step` 的 1.98× "
648
+ "无损覆盖;缓存方法唯一还能争的是 2.5–2.9× 那一档,而那一档它们(81.3–82.9)也输给 `naive1step`(83.1,3.9×)。"
649
+ "把 Self-Forcing/Causal-Forcing 上「naive 减步强于缓存」的结论推广到 HY 是成立的,而且更极端。")
650
+ doc.append("- **首 chunk FFFF + naive 减步是 CF 上目前最强的算力分配(Sep 7)。** 后 6 个 chunk 减步、chunk 0 仍走 4 步:"
651
+ "`naive3step_c0FFFF` 81.39(22/28,1.284×)、`naive2step_c0FFFF` **81.71**(16/28,1.807×,高于 FFFF 的 81.17)、"
652
+ "`naive1step_c0FFFF` **79.15**(10/28,3.048×)。对比同算力的其它配置:16/28 档 `teacache_x2_c0FFFF` = "
653
+ "`reuse_FRRF_c0FFFF` 81.18、`taylorseer_x1.75_c0FFFF`(17) 80.74;10/28 档所有 `Fxxx` 缓存方法 61–66、"
654
+ "`reuse_FRRR_c0FFFF` 59.5,而 `naive1step_c0FFFF` 79.15 领先 13 分以上——原因同前:减步让最后一次预测仍在 "
655
+ "t=1000 这一训练过的时间步上做(对 1 步就是唯一一步),而 `Fxxx` 是把最后一步换成过期残差。首 chunk FFFF 对 naive "
656
+ "的增益随减步幅度放大:3 步 −0.01、2 步 +1.14、1 步 **+3.63**(75.52→79.15),像素指标也从 11.5–11.9 dB 抬到 14.1–14.4 dB。"
657
+ "直接复用(reuse)在同算力下始终不如减步:22/28 档 81.34 vs 81.39,16/28 档 81.18 vs 81.71,10/28 档 59.5 vs 79.2。")
658
+ doc.append("- **HY 上首 chunk FFFF 对基线的作用小得多(Sep 7)。** naive/reuse 六个 `_c0FFFF` 变体里,VBench 只有本来有损的两个动了:"
659
+ "`naive1step` 83.11→83.63(+0.51,3.90×→3.33×)、`reuse_FRRR` 81.27→81.53(+0.26,3.77×→3.27×);"
660
+ "已在 FFFF 水平的 3 步 / 2 步 / FRFF / FRRF 保持不变(±0.05)。像素指标仍全面上升(PSNR +1.6–2.4 dB,如 "
661
+ "`naive2step` 18.0→19.7、`naive3step` 19.4→21.7)。这与 HY 是 I2V 一致:chunk 0 有输入图像做强条件,"
662
+ "外观不像 T2V 那样完全由首 chunk 决定,所以 SF/CF 上 +1~+3.6 的 VBench 增益在 HY 上只剩零点几分。"
663
+ "ATC Stage-1 predictor(`atc_s1_fppf`,DEV 项目 validation25)在 1.67× 下 84.18 / PSNR 20.1,"
664
+ "像素保真度高于同速的 `teacache_x1.75`(PSNR 17.6)、与 `naive2step_c0FFFF`(1.87×,PSNR 19.7)相当。")
665
+ doc.append("- **HY 缓存方法在 c0FFFF 下重新搜参后达到了目标档位(Sep 8,`*_x1.75_c0FFFF` / `*_Fxxx_x2.85_c0FFFF`)。** "
666
+ "实测加速比 TeaCache 1.857× / 2.535×、TaylorSeer 1.704× / 2.870×、MotionCache 1.634× / 2.517×"
667
+ "(之前为 1.54 / 2.51、1.68 / 2.52、1.53 / 2.49)。`FxxF` 档三者 VBench 全部保持 FFFF 水平(84.26–84.28 vs 84.26),"
668
+ "像素指标比原版高 1–2 dB(PSNR 18.6 vs 16.9–17.6);但这一档 TeaCache 与 TaylorSeer 落到的都是「后 7 chunk 中间两步全跳」"
669
+ "的量化上限点(Full = 18/32),与 `reuse_FRRF_c0FFFF` 算力等价、结果也几乎一样(84.28 / PSNR 18.6),"
670
+ "只有 MotionCache 仍保留 27% 的 token 级活跃步。`Fxxx` 档 VBench 82.6 / 81.7 / 81.4,与原版持平或略低"
671
+ "(TaylorSeer 82.43→81.69 是换了更激进的 interval 3.9 以换取 2.52×→2.87×),像素指标同样 +1.2–1.6 dB。"
672
+ "同算力对照仍然是 naive 减步占优:16–18/32 档 `naive2step_c0FFFF` 84.26 / 1.87× / PSNR 19.7 不输任何缓存方法,"
673
+ "11/32 档 `naive1step_c0FFFF` 83.63 / 3.33× 高出所有 `Fxxx` 缓存点 1–2 分。ATC Stage-1 predictor "
674
+ "`atc_s1_fppp` 在 2.59× 下 81.98 / PSNR 19.3——VBench 与 `Fxxx` 缓存点相当,像素保真度高 2–3 dB。"
675
+ "DisCa Stage-1(双 block,blocks [0,53],同样 chunk 0 全算)`disca_s1_fppf` 84.17 / PSNR 19.7 / LPIPS 0.135,1.80×:"
676
+ "VBench 与 ATC 持平,像素保真度介于 ATC(20.1 / 0.126)与 naive2step_c0FFFF(19.7 / 0.148)之间,高于残差复用类"
677
+ "(18.6 / 0.167)。FPPP 档 `disca_s1_fppp` 81.98 / PSNR 19.0(3.00×)与 `atc_s1_fppp` 81.98 / 19.3(2.59×)持平,"
678
+ "仍低于 `naive1step_c0FFFF` 83.63。DisCa 的 step-1000 与 step-2000 checkpoint 几乎无差别"
679
+ "(FPPF 84.15 vs 84.17,FPPP 82.02 vs 81.98,像素指标差 <0.1 dB)——HY 上 DisCa 在 1000 步已收敛,"
680
+ "与 CF 上 DisCa 1000→2000 步 FPPP +3.7 的情况不同。")
681
+ doc.append("- **长视频(Sep 8,`*_14c_*` / `*_28c_*`:14 / 28 chunk = 165 / 333 帧,超过 21 帧训练上下文后 KV 走 21 帧滚动窗口)。** "
682
+ "14 chunk 时 FFFF 自身从 81.17 降到 81.01(`14c_ffff`;subject_consistency 95.7→92.7、background 95.8→94.1,"
683
+ "scene 反而 56.0→61.3),说明滚动窗口下长程一致性本身在退化。ATC-chunk FPPF 在 14 chunk 上 1.766×:"
684
+ "Stage-1 80.57(相对 `14c_ffff` −0.43,7 chunk 时是 +0.38)、Stage-2 **80.97**(−0.03);像素指标从 7 chunk 的 "
685
+ "PSNR 14.6 / LPIPS 0.22 降到 12.8 / 0.34——Predictor 的误差随 chunk 累积(前 7 chunk 之后没有 FFFF 的「重锚定」),"
686
+ "Stage-2(随机出口 DMD)在长视频上比 Stage-1 稳得多(VBench +0.40,主要是 subject/background consistency)。"
687
+ "28 chunk(333 帧)时趋势放大:FFFF 自身掉到 **77.99**(subject 95.7→88.3、background 95.8→89.6、aesthetic 66.6→62.2——"
688
+ "滚动窗口下的长程漂移是基模本身的问题),ATC Stage-1 FPPF 77.48(−0.51)、**Stage-2 78.65(+0.67,高于同长度 FFFF;"
689
+ "subject 89.1 vs 88.3、background 91.3 vs 89.6)**,加速比 1.793×;像素指标继续下滑到 PSNR 11.0 / LPIPS 0.47–0.48。"
690
+ "三种长度合起来:Stage-1 相对同长度 FFFF 为 +0.38 / −0.43 / −0.51,Stage-2 为 +0.08 / −0.03 / +0.67——"
691
+ "随机出口 DMD 训练出来的 Predictor 不会随视频变长而退化,反而在 FFFF 自己漂移最严重的 28 chunk 上略优于 FFFF。")
692
+ doc.append("- **长视频上的 checkpoint 扫描(Sep 11–12,CF 14 / 28 chunk,FPPF,chunk 0 FFFF;HY 16 / 32 chunk 进行中)。** "
693
+ "对比 DisCa Stage-1 的 step 500 / 1000 / 2000、ATC Stage-2(随机出口 DMD,EMA)的 step 500 / 1000 / 2000 与 naive 2 步"
694
+ "(`naive2step_<n>c`:chunk 0 四步全算,之后每 chunk 只走 t=1000 / 250,与 `cf_naive2step_c0FFFF` 同一子集),"
695
+ "三者 Full 完全相同(14 chunk 30/56、28 chunk 58/112),参考帧读同长度 FFFF 的 MP4(§)。"
696
+ "14 chunk:ATC Stage-2 s500 / s1000 / s2000 = 81.08 / **81.11** / 80.97(FFFF 81.01,1.77–1.78×),"
697
+ "DisCa s500 / s1000 / s2000 = 80.12 / 80.51 / 80.60(1.82×),`naive2step_14c` 80.79(1.91×);"
698
+ "28 chunk:ATC Stage-2 78.55 / **78.84** / 78.65(FFFF 77.99,1.80×),DisCa 75.46 / 77.40 / 77.87(1.84×),"
699
+ "`naive2step_28c` 78.74(1.95×)。三点读数:(i) ATC Stage-2 三个 step 相差不到 0.15(14c)/ 0.3(28c),"
700
+ "s500 就已经到达平台并且不低于同长度 FFFF——Stage-2 对长视频的增益来得很早,2000 步不是必要条件;"
701
+ "(ii) DisCa 随步数单调上升,但 2000 步仍低于 FFFF 与 naive,且视频越长早期权重掉得越多(28c 的 s500 比 FFFF 低 2.5)——"
702
+ "没有前一 chunk 通道的 Predictor 在长视频上误差累积更快;(iii) 等 Full 的 naive 2 步与最好的 ATC Stage-2 在 14c 只差 0.3、"
703
+ "28c 持平(78.74 vs 78.84),像素指标也几乎相同(PSNR 12.6 vs 12.7–12.8、11.0 vs 11.1),而 naive 的实测加速比更高"
704
+ "(Predictor 调用的真实开销高于按 1/30 forward 记的算量)——在 CF 的长视频上,ATC Stage-2 相对 naive 减步的优势只剩零点几分,"
705
+ "主要收益是不低于 FFFF 的一致性指标(subject / background consistency)。HY 的 16 / 32 chunk 行(64 / 128 latent,"
706
+ "相机动作等比拉长)生成中,完成后补入 HY 表。")
707
+ doc.append("- **`FPF`(Sep 8):chunk 内只走 3 个时间步——t=1000 全算、t=750 一步 Predictor(锚定 t=1000,与训练一致)、跳过 t=500、"
708
+ "t=250 全算。** ATC-chunk Stage-1 的 `atc_chunk_fpf` 在 **1.773×** 下 81.30(FFFF 81.17,同算力 16 full 的 `atc_chunk_fppf` "
709
+ "81.55 / 1.697×,`naive3step` 81.40 / 1.327×),像素指标 PSNR 14.5 / LPIPS 0.24 与 FPPF 相当。也就是说少调用一次 "
710
+ "Predictor、直接跳过一个时间步,质量几乎不变而更快——和 naive 减步同一逻辑:中间步的价值主要在于让最后一步有一个好的 "
711
+ "起点,而不在于步数本身。")
712
+ doc.append("- MotionCache 在 1.3×/1.6× 的实测加速比明显低于 compute 折算(差 9–11 个百分点):"
713
+ "逐 token 选择与 selective forward 的簿记开销是真实存在的;`Fxxx` 下更甚,compute 3.0× 只换来 "
714
+ "实测 1.85–1.95×。")
715
+ doc.append("- **最后一步不能缓存。** 凡是让 step 3 走缓存的配置——`Fxxx` 全部、`FFxx` 在 ≥1.6× 时——"
716
+ "VBench 掉 15–25 分:imaging/aesthetic 从 ~0.66 掉到 0.41–0.50,scene 从 ~0.57 掉到 0.03–0.37,"
717
+ "而 dynamic_degree 从 0.69–0.82 **升**到 0.89–0.96,即残留噪声没有被去掉、画面在抖。"
718
+ "`FFxx ×1.3` 实际是 FFxF(最后一步仍算),质量与 `FxxF ×1.3` 相当。")
719
+ doc.append("- TaylorSeer 的一阶预测在 `FFxx` 下确实被触发了,但 ≥1.6× 时把预测用在了最后一步,"
720
+ "\"预测 vs 拷贝\"与\"跳不跳最后一步\"在这组数据里是混在一起的;"
721
+ "要单独检验预测本身,需要最后一步必算、中间步用一阶预测的调度(如 FFxF,上限 1.33×)。")
722
+ doc.append("- `Fxxx` 下 TeaCache/FlowCache 的阈值在 3 条 prompt 上搜到 ~3.0× compute,251 条上实际为 "
723
+ "3.4–3.6×(Self-Forcing)/ 2.8–2.9×(Causal-Forcing):indicator 跨 chunk 几乎不变,"
724
+ "可达点是 {1, 2, 4}× 的台阶,中间值靠少数 chunk 落在台阶另一侧凑出,随 prompt 集漂移。"
725
+ "MotionCache(逐 token)和 TaylorSeer(确定性调度)不漂。\n")
726
+
727
+ doc.append("## 2. 各策略的配置参数\n")
728
+ doc.append("阈值类方法(TeaCache / FlowCache / MotionCache)的 `thresh` 作用在**重标定后**的累计相对 L1 距离上"
729
+ "(`calibrate.py` 按 TeaCache 的拟合流程得到的 1 次多项式,见下方系数),indicator 为"
730
+ "时间步调制后的噪声输入(TeaCache 原始定义,非 Wan 移植的 `e0`)。"
731
+ "TaylorSeer 的 `interval` 为平均刷新间隔,小数部分用 Bresenham 交替在相邻整数间隔间实现,"
732
+ "`max_order=1`。固定超参:FlowCache `group_size=1`(3 帧组/chunk);"
733
+ "MotionCache `weight_norm=mean`、`min_update_ratio=0`、无 temporal consistency。"
734
+ "\"搜索时 Full\"是定参数时在搜索/配对 prompt 上的 compute,251 条上的实际值见第 1 节。\n")
735
+ for base, (table, coeff) in config_tables().items():
736
+ doc.append(f"### {BASE_LABEL[base]}\n")
737
+ if coeff:
738
+ doc.append(f"重标定多项式系数(最高次在前):`{', '.join(f'{c:.6g}' for c in coeff)}`\n")
739
+ doc.append(table + "\n")
740
+ hy_cfg = hy_config_table()
741
+ if hy_cfg:
742
+ doc.append("### HY-WorldPlay\n")
743
+ doc.append(hy_cfg + "\n")
744
+ lb_cfg = lb_config_table()
745
+ if lb_cfg and os.path.exists(LB_SUMMARY):
746
+ doc.append("### LingBot-World-V2-1.3B-Causal-Fast\n")
747
+ doc.append(lb_cfg + "\n")
748
+
749
+ if pending:
750
+ doc.append("## 3. 新调度下的操作点(已搜索,待 251 评测)\n")
751
+ doc.append("参数由 `sweep.py --schedule ...` 在 3 条 prompt 上按 compute fraction 搜索得到;"
752
+ "\"配对实测加速比\"来自 3 对 A/B 计时,仅供参考,不与上表的 251-prompt 耗时直接比较。"
753
+ "质量列在跑完 Extended-251 评测后由 `experiment_md.py` 自动填入上表。\n")
754
+ for base in ["self_forcing", "causal_forcing"]:
755
+ if base in pending:
756
+ doc.append(f"### {BASE_LABEL[base]}\n")
757
+ doc.append(fmt_pending_table(pending[base]) + "\n")
758
+
759
+ with open(OUT, "w") as f:
760
+ # Footnotes for markers no row uses any more are dropped.
761
+ body = "\n".join(doc)
762
+ for mark in ("†", "‡", "§", "¶"):
763
+ if not any(f" {mark} |" in line for line in body.splitlines()):
764
+ doc = [d for d in doc if not d.startswith(mark + " ")]
765
+ f.write("\n".join(doc))
766
+ print(f"wrote {OUT}")
767
+
768
+
769
+ if __name__ == "__main__":
770
+ main()
finalize.py ADDED
@@ -0,0 +1,255 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """Authoritative pass: re-target and cleanly re-measure every operating point.
3
+
4
+ Two things the parallel sweeps could not do well:
5
+
6
+ 1. **Targeting.** The sweeps aimed at ``target / measured_overhead``, but that
7
+ overhead is itself a timing measurement on a contended node -- one probe came
8
+ back at 1.110, which is impossible, and it dragged that method's operating
9
+ points well below their targets. Here the search aims at the **compute budget**
10
+ directly, which is deterministic, and also puts all four methods on identical
11
+ compute so a later quality comparison is like-for-like.
12
+
13
+ 2. **Timing.** The sweeps ran four at a time across the node, so their wall-clock
14
+ column includes contention from each other. Here every point is measured
15
+ serially in one session, paired against the baseline on the same prompt.
16
+
17
+ Each point is also re-checked on a held-out prompt slice: a threshold that only
18
+ reached its target by sitting inside a narrow band of the indicator distribution
19
+ shows up here as compute-fraction drift.
20
+
21
+ python finalize.py --base self_forcing --out results/final_self_forcing.json
22
+ """
23
+
24
+ import argparse
25
+ import json
26
+ import os
27
+ import sys
28
+
29
+ ROOT = os.path.dirname(os.path.abspath(__file__))
30
+ sys.path.insert(0, ROOT)
31
+
32
+ from harness import (BASES, enter_base, evaluate, load_pipeline, # noqa: E402
33
+ load_prompts, paired_evaluate)
34
+
35
+ METHOD_ORDER = ["teacache", "flowcache", "taylorseer", "motioncache"]
36
+
37
+
38
+ def main():
39
+ ap = argparse.ArgumentParser()
40
+ ap.add_argument("--base", choices=sorted(BASES), required=True)
41
+ ap.add_argument("--pair-prompts", type=int, default=10)
42
+ ap.add_argument("--search-prompts", type=int, default=4)
43
+ ap.add_argument("--tolerance", type=float, default=0.02,
44
+ help="Re-bisect when |flops - target| exceeds this fraction")
45
+ ap.add_argument("--bisect-iters", type=int, default=18)
46
+ ap.add_argument("--correction-iters", type=int, default=9,
47
+ help="Bisection steps for the correction pass on the timed prompts")
48
+ ap.add_argument("--heldout-offset", type=int, default=64)
49
+ ap.add_argument("--heldout-prompts", type=int, default=8)
50
+ ap.add_argument("--num-output-frames", type=int, default=21)
51
+ ap.add_argument("--seed", type=int, default=0)
52
+ ap.add_argument("--save-video-dir", default=None)
53
+ ap.add_argument("--methods", default=None,
54
+ help="Comma-separated subset of methods to (re)measure")
55
+ ap.add_argument("--suffix", default="",
56
+ help="Look for results/sweep_<base>_<method><suffix>.json")
57
+ ap.add_argument("--targets", default=None,
58
+ help="Comma-separated subset of target speedups to (re)measure")
59
+ ap.add_argument("--resume", action="store_true",
60
+ help="Keep rows already in --out and skip those (method, target) pairs")
61
+ ap.add_argument("--out", required=True)
62
+ args = ap.parse_args()
63
+
64
+ out_path = args.out if os.path.isabs(args.out) else os.path.join(ROOT, args.out)
65
+
66
+ done = {}
67
+ rows = []
68
+ if args.resume and os.path.exists(out_path):
69
+ with open(out_path) as f:
70
+ rows = json.load(f).get("rows", [])
71
+ done = {(r["method"], r["target_speedup"]) for r in rows}
72
+ print(f"resuming: {len(rows)} rows already done", flush=True)
73
+ else:
74
+ done = set()
75
+
76
+ wanted = set(args.methods.split(",")) if args.methods else None
77
+ sweeps = []
78
+ for m in METHOD_ORDER:
79
+ if wanted and m not in wanted:
80
+ continue
81
+ sp = os.path.join(ROOT, f"results/sweep_{args.base}_{m}{args.suffix}.json")
82
+ if os.path.exists(sp):
83
+ with open(sp) as f:
84
+ sweeps.append(json.load(f))
85
+ if not sweeps:
86
+ print(f"no sweep files for {args.base}")
87
+ return
88
+ print(f"methods: {[s['method'] for s in sweeps]}", flush=True)
89
+
90
+ base = enter_base(args.base)
91
+
92
+ import torch
93
+ from cachelib import CacheController, build_method, install, parse_schedule
94
+
95
+ torch.set_grad_enabled(False)
96
+ pipeline = load_pipeline(base)
97
+ num_steps = len(pipeline.denoising_step_list)
98
+
99
+ tune_prompts = load_prompts(args.pair_prompts + 1)
100
+ held_prompts = load_prompts(args.heldout_prompts, offset=args.heldout_offset)
101
+
102
+ def make_ctrl(sweep, method_name, value):
103
+ kw = dict(indicator=sweep.get("indicator", "modulated_input"),
104
+ coefficients=sweep.get("coefficients"))
105
+ if method_name != "none":
106
+ kw[sweep["param"]] = value
107
+ ctrl = CacheController(
108
+ build_method(method_name, **kw), num_steps=num_steps,
109
+ forced_steps=parse_schedule(sweep.get("schedule", "FxxF"), num_steps))
110
+ install(pipeline.generator.model, ctrl)
111
+ return ctrl
112
+
113
+ def flops_at(sweep, value, prompts=None):
114
+ r = evaluate(pipeline, make_ctrl(sweep, sweep["method"], value),
115
+ prompts if prompts is not None else tune_prompts[:args.search_prompts],
116
+ num_output_frames=args.num_output_frames, seed=args.seed,
117
+ warmup=0)
118
+ return r["flops_speedup_estimate"], r["mean_compute_equivalent_forwards"]
119
+
120
+ def retarget(sweep, target, prompts=None, iters=None):
121
+ """Bisect the stored curve's bracket for the requested compute budget."""
122
+ curve = sweep["curve"]
123
+ max_flops = max(c["flops_speedup"] for c in curve)
124
+ goal = min(target, max_flops)
125
+ lo = min(c["value"] for c in curve)
126
+ hi = max(c["value"] for c in curve)
127
+ a, b = lo, hi
128
+ for c in curve:
129
+ if c["flops_speedup"] < goal:
130
+ a = max(a, c["value"])
131
+ for c in reversed(curve):
132
+ if c["flops_speedup"] >= goal:
133
+ b = min(b, c["value"])
134
+ best = None
135
+ for _ in range(iters or args.bisect_iters):
136
+ mid = 0.5 * (a + b)
137
+ f, ce = flops_at(sweep, mid, prompts)
138
+ if best is None or abs(f - goal) < abs(best[1] - goal):
139
+ best = (mid, f, ce)
140
+ if f < goal:
141
+ a = mid
142
+ else:
143
+ b = mid
144
+ # Bisection only probes interior points; when the curve steps up exactly at
145
+ # the upper bracket it converges from below and never samples the value that
146
+ # actually reaches the target. Score the closing ends too.
147
+ for endpoint in (a, b):
148
+ f, ce = flops_at(sweep, endpoint, prompts)
149
+ if abs(f - goal) < abs(best[1] - goal):
150
+ best = (endpoint, f, ce)
151
+ return best
152
+
153
+ print("=== warm-up ===", flush=True)
154
+ evaluate(pipeline, make_ctrl(sweeps[0], "none", None), tune_prompts[:3],
155
+ num_output_frames=args.num_output_frames, seed=args.seed, warmup=0)
156
+
157
+ for sweep in sweeps:
158
+ pname = sweep["param"]
159
+ for p in sweep["operating_points"]:
160
+ target = p["target_speedup"]
161
+ if (sweep["method"], target) in done:
162
+ continue
163
+ if args.targets and target not in [float(t) for t in args.targets.split(",")]:
164
+ continue
165
+ value = p[pname]
166
+ f, ce = flops_at(sweep, value)
167
+ retargeted = False
168
+ if abs(f - target) > args.tolerance * target:
169
+ new = retarget(sweep, target)
170
+ if abs(new[1] - target) < abs(f - target):
171
+ value, f, ce = new
172
+ retargeted = True
173
+ print(f" retargeted {sweep['method']} {target}x -> "
174
+ f"{pname}={value:.6g} flops={f:.3f}", flush=True)
175
+
176
+ vid_dir = None
177
+ if args.save_video_dir:
178
+ sched = sweep.get("schedule", "FxxF")
179
+ tag = "" if sched.upper() == "FXXF" else f"_{sched}"
180
+ vid_dir = os.path.join(ROOT, args.save_video_dir,
181
+ f"{args.base}_{sweep['method']}{tag}_x{target:g}")
182
+
183
+ def measure(v, save=None):
184
+ return paired_evaluate(
185
+ pipeline,
186
+ lambda s=sweep: make_ctrl(s, "none", None),
187
+ lambda s=sweep, vv=v: make_ctrl(s, s["method"], vv),
188
+ tune_prompts, num_output_frames=args.num_output_frames,
189
+ seed=args.seed, warmup=1, save_video_dir=save)
190
+
191
+ paired = measure(value, save=vid_dir)
192
+ # The compute fraction of the timed runs is the one that counts. Near a
193
+ # decision boundary it can differ from the search subset's, so if it
194
+ # misses, re-tune on the timed prompts themselves and measure again.
195
+ if abs(paired["paired_flops_speedup"] - target) > args.tolerance * target:
196
+ new_pt = retarget(sweep, target, prompts=tune_prompts[1:],
197
+ iters=args.correction_iters)
198
+ if abs(new_pt[1] - target) < abs(paired["paired_flops_speedup"] - target):
199
+ value, _, _ = new_pt
200
+ retargeted = True
201
+ print(f" corrected {sweep['method']} {target}x on timed prompts "
202
+ f"-> {pname}={value:.6g} flops={new_pt[1]:.3f}", flush=True)
203
+ paired = measure(value, save=vid_dir)
204
+ f = paired["paired_flops_speedup"]
205
+ ce = paired["paired_compute_equivalent"]
206
+ held = evaluate(pipeline, make_ctrl(sweep, sweep["method"], value),
207
+ held_prompts, num_output_frames=args.num_output_frames,
208
+ seed=args.seed, warmup=0)
209
+ row = {
210
+ "base": args.base,
211
+ "method": sweep["method"],
212
+ "param": pname,
213
+ "value": value,
214
+ "schedule": sweep.get("schedule", "FxxF"),
215
+ "retargeted": retargeted,
216
+ "target_speedup": target,
217
+ "flops_speedup": f,
218
+ "compute_equivalent_forwards": ce,
219
+ "denoise_forwards": 28.0,
220
+ "measured_speedup": paired["speedup_from_minima"],
221
+ "measured_speedup_paired_median": paired["paired_speedup_median"],
222
+ "measured_speedup_paired_mean": paired["paired_speedup_mean"],
223
+ "measured_speedup_paired_stdev": paired["paired_speedup_stdev"],
224
+ "measured_speedup_paired_range": [paired["paired_speedup_min"],
225
+ paired["paired_speedup_max"]],
226
+ "min_baseline_ms": paired["min_baseline_ms"],
227
+ "min_method_ms": paired["min_method_ms"],
228
+ "median_baseline_ms": paired["median_baseline_ms"],
229
+ "median_method_ms": paired["median_method_ms"],
230
+ "baseline_ms": paired["baseline_ms"],
231
+ "method_ms": paired["method_ms"],
232
+ "num_pairs": paired["num_pairs"],
233
+ "heldout_flops_speedup": held["flops_speedup_estimate"],
234
+ "heldout_compute_equivalent": held["mean_compute_equivalent_forwards"],
235
+ "heldout_flops_drift": held["flops_speedup_estimate"] - f,
236
+ "video_dir": vid_dir,
237
+ }
238
+ rows.append(row)
239
+ print(f"{sweep['method']:12s} target {target:g}x "
240
+ f"{pname}={value:<10.6g} measured={row['measured_speedup']:.3f}x "
241
+ f"(paired {row['measured_speedup_paired_median']:.3f}"
242
+ f"±{row['measured_speedup_paired_stdev']:.3f}) flops={f:.3f}x "
243
+ f"heldout_flops={row['heldout_flops_speedup']:.3f}x "
244
+ f"({row['heldout_flops_drift']:+.3f})", flush=True)
245
+
246
+ with open(out_path, "w") as fh:
247
+ json.dump({"base": args.base, "pair_prompts": args.pair_prompts,
248
+ "heldout_offset": args.heldout_offset, "rows": rows},
249
+ fh, indent=2)
250
+
251
+ print(f"wrote {out_path}", flush=True)
252
+
253
+
254
+ if __name__ == "__main__":
255
+ main()
harness.py ADDED
@@ -0,0 +1,253 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared model loading / evaluation so a sweep can reuse one loaded pipeline.
2
+
3
+ Import this only *after* chdir-ing into the chosen base repo (``enter_base``
4
+ does that), because both base repos load ``wan_models/...`` by relative path.
5
+ """
6
+
7
+ import os
8
+ import statistics
9
+ import sys
10
+
11
+ ROOT = os.path.dirname(os.path.abspath(__file__))
12
+
13
+ BASES = {
14
+ "self_forcing": {
15
+ "repo": os.path.join(ROOT, "repos/Self-Forcing"),
16
+ "config": "configs/self_forcing_dmd.yaml",
17
+ "checkpoint": "checkpoints/self_forcing_dmd.pt",
18
+ },
19
+ "causal_forcing": {
20
+ "repo": os.path.join(ROOT, "repos/Causal-Forcing"),
21
+ "config": "configs/causal_forcing_dmd_chunkwise.yaml",
22
+ "checkpoint": "checkpoints/chunkwise/causal_forcing.pt",
23
+ },
24
+ }
25
+
26
+
27
+ def enter_base(name):
28
+ base = BASES[name]
29
+ os.chdir(base["repo"])
30
+ sys.path.insert(0, base["repo"])
31
+ sys.path.insert(0, ROOT)
32
+ return base
33
+
34
+
35
+ def load_pipeline(base, device=None):
36
+ import torch
37
+ from omegaconf import OmegaConf
38
+ from pipeline import CausalInferencePipeline
39
+
40
+ device = device or torch.device("cuda")
41
+ config = OmegaConf.merge(OmegaConf.load("configs/default_config.yaml"),
42
+ OmegaConf.load(base["config"]))
43
+ pipeline = CausalInferencePipeline(config, device=device)
44
+
45
+ sd = torch.load(base["checkpoint"], map_location="cpu")
46
+ # self_forcing_dmd.pt ships only EMA weights, causal_forcing.pt only raw ones.
47
+ gen_sd = sd["generator"] if "generator" in sd else sd["generator_ema"]
48
+ try:
49
+ pipeline.generator.load_state_dict(gen_sd)
50
+ except RuntimeError:
51
+ pipeline.generator.load_state_dict(
52
+ {k.replace("model._fsdp_wrapped_module.", "model.", 1): v
53
+ for k, v in gen_sd.items()}, strict=False)
54
+
55
+ pipeline = pipeline.to(dtype=torch.bfloat16)
56
+ pipeline.text_encoder.to(device)
57
+ pipeline.generator.to(device)
58
+ pipeline.vae.to(device)
59
+ return pipeline
60
+
61
+
62
+ def load_prompts(n, offset=0):
63
+ from utils.dataset import TextDataset
64
+ path = ("prompts/MovieGenVideoBench.txt"
65
+ if os.path.exists("prompts/MovieGenVideoBench.txt")
66
+ else "prompts/demos.txt")
67
+ ds = TextDataset(prompt_path=path)
68
+ idx = range(offset, min(offset + n, len(ds)))
69
+ return [ds[i]["prompts"] for i in idx]
70
+
71
+
72
+ def free_gpus(min_free_mb=70000, max_util=5):
73
+ """Indices of GPUs with no meaningful other tenant, most-free first.
74
+
75
+ This node is shared, and a neighbour saturating the SMs inflates timings by
76
+ 30%+ and drifts them within a single sweep, so runs must be placed carefully
77
+ and speedups measured pairwise.
78
+ """
79
+ import subprocess
80
+ try:
81
+ out = subprocess.check_output(
82
+ ["nvidia-smi", "--query-gpu=index,utilization.gpu,memory.used,memory.total",
83
+ "--format=csv,noheader,nounits"], text=True)
84
+ except Exception:
85
+ return []
86
+ rows = []
87
+ for line in out.strip().splitlines():
88
+ idx, util, used, total = [int(v.strip()) for v in line.split(",")]
89
+ if util <= max_util and (total - used) >= min_free_mb:
90
+ rows.append((total - used, idx))
91
+ return [i for _, i in sorted(rows, reverse=True)]
92
+
93
+
94
+ def paired_evaluate(pipeline, make_baseline_ctrl, make_method_ctrl, prompts,
95
+ num_output_frames=21, seed=0, warmup=1, save_video_dir=None):
96
+ """Interleave baseline and method on the same prompt, one pair at a time.
97
+
98
+ Returns per-prompt ratios. Absolute timings drift with GPU contention, but
99
+ the two halves of a pair are seconds apart, so their ratio is stable in a way
100
+ a start-of-sweep baseline is not.
101
+ """
102
+ import statistics
103
+
104
+ import torch
105
+ from utils.misc import set_seed
106
+ from cachelib import cached_inference
107
+
108
+ ratios, base_ms, meth_ms, meth_ce, meth_fw = [], [], [], [], []
109
+ for i, prompt in enumerate(prompts):
110
+ row = {}
111
+ for tag, make in (("base", make_baseline_ctrl), ("method", make_method_ctrl)):
112
+ ctrl = make()
113
+ set_seed(seed)
114
+ noise = torch.randn([1, num_output_frames, 16, 60, 104],
115
+ device=torch.device("cuda"), dtype=torch.bfloat16)
116
+ video, latents, timing = cached_inference(
117
+ pipeline, ctrl, noise, [prompt],
118
+ decode=bool(save_video_dir) and tag == "method")
119
+ row[tag] = timing["denoise_dit_ms"]
120
+ row[tag + "_summary"] = ctrl.summary()
121
+ if tag == "method" and save_video_dir and i >= warmup:
122
+ from einops import rearrange
123
+ from torchvision.io import write_video
124
+ os.makedirs(save_video_dir, exist_ok=True)
125
+ frames = 255.0 * rearrange(video, "b t c h w -> b t h w c").cpu()
126
+ write_video(os.path.join(save_video_dir, f"{i:04d}.mp4"),
127
+ frames[0], fps=16)
128
+ pipeline.vae.model.clear_cache()
129
+ if i < warmup:
130
+ continue
131
+ ratios.append(row["base"] / row["method"])
132
+ base_ms.append(row["base"])
133
+ meth_ms.append(row["method"])
134
+ # Compute fraction of the very runs that were timed. Tuning a threshold on
135
+ # one prompt subset and timing it on another silently disagrees whenever the
136
+ # threshold sits near a decision boundary, so the two must come from the
137
+ # same runs to be comparable.
138
+ summ = row["method_summary"]
139
+ meth_ce.append(summ["compute_equivalent_forwards"])
140
+ meth_fw.append(summ["denoise_forwards"])
141
+
142
+ # Contention is one-sided: a neighbouring job can only ever make a run slower.
143
+ # The fastest observed run is therefore the best estimate of the uncontended
144
+ # time, and min(baseline)/min(method) is the headline speedup. The paired
145
+ # median is kept alongside, but it is biased *upward* here because the
146
+ # baseline run is longer and so more exposed to being hit by a spike -- which
147
+ # is why it sometimes exceeds the method's arithmetic ceiling.
148
+ ce = statistics.fmean(meth_ce)
149
+ fw = statistics.fmean(meth_fw)
150
+ return {
151
+ "speedup_from_minima": min(base_ms) / min(meth_ms),
152
+ "paired_flops_speedup": fw / ce if ce else None,
153
+ "paired_compute_equivalent": ce,
154
+ "paired_denoise_forwards": fw,
155
+ "paired_speedup_median": statistics.median(ratios),
156
+ "paired_speedup_mean": statistics.fmean(ratios),
157
+ "paired_speedup_stdev": statistics.stdev(ratios) if len(ratios) > 1 else 0.0,
158
+ "paired_speedup_min": min(ratios),
159
+ "paired_speedup_max": max(ratios),
160
+ "min_baseline_ms": min(base_ms),
161
+ "min_method_ms": min(meth_ms),
162
+ "median_baseline_ms": statistics.median(base_ms),
163
+ "median_method_ms": statistics.median(meth_ms),
164
+ "num_pairs": len(ratios),
165
+ "ratios": ratios,
166
+ "baseline_ms": base_ms,
167
+ "method_ms": meth_ms,
168
+ }
169
+
170
+
171
+ def evaluate(pipeline, controller, prompts, num_output_frames=21, seed=0,
172
+ warmup=1, save_video_dir=None, save_latents_dir=None):
173
+ """Run ``prompts`` and return timing / compute-fraction statistics."""
174
+ import torch
175
+ from utils.misc import set_seed
176
+ from cachelib import cached_inference
177
+
178
+ records = []
179
+ for i, prompt in enumerate(prompts):
180
+ set_seed(seed)
181
+ noise = torch.randn([1, num_output_frames, 16, 60, 104],
182
+ device=torch.device("cuda"), dtype=torch.bfloat16)
183
+ video, latents, timing = cached_inference(
184
+ pipeline, controller, noise, [prompt],
185
+ decode=bool(save_video_dir))
186
+ rec = dict(timing)
187
+ rec.update(controller.summary())
188
+ rec["prompt_index"] = i
189
+ rec["warmup"] = i < warmup
190
+ records.append(rec)
191
+
192
+ if i >= warmup and save_latents_dir:
193
+ os.makedirs(save_latents_dir, exist_ok=True)
194
+ torch.save(latents.float().cpu(),
195
+ os.path.join(save_latents_dir, f"{i:04d}.pt"))
196
+ if i >= warmup and save_video_dir:
197
+ from einops import rearrange
198
+ from torchvision.io import write_video
199
+ os.makedirs(save_video_dir, exist_ok=True)
200
+ frames = 255.0 * rearrange(video, "b t c h w -> b t h w c").cpu()
201
+ write_video(os.path.join(save_video_dir, f"{i:04d}.mp4"), frames[0], fps=16)
202
+ pipeline.vae.model.clear_cache()
203
+
204
+ timed = [r for r in records if not r["warmup"]] or records
205
+ ms = sorted(r["denoise_dit_ms"] for r in timed)
206
+ compute = statistics.fmean(r["compute_equivalent_forwards"] for r in timed)
207
+ forwards = statistics.fmean(r["denoise_forwards"] for r in timed)
208
+ return {
209
+ "median_denoise_dit_ms": statistics.median(ms),
210
+ "mean_denoise_dit_ms": statistics.fmean(ms),
211
+ "stdev_denoise_dit_ms": statistics.stdev(ms) if len(ms) > 1 else 0.0,
212
+ "min_denoise_dit_ms": ms[0],
213
+ "max_denoise_dit_ms": ms[-1],
214
+ "mean_compute_equivalent_forwards": compute,
215
+ "mean_denoise_forwards": forwards,
216
+ "flops_speedup_estimate": forwards / compute if compute else None,
217
+ "mean_first_chunk_denoise_ms": statistics.fmean(
218
+ r["first_chunk_denoise_ms"] for r in timed),
219
+ "num_timed": len(timed),
220
+ "records": records,
221
+ }
222
+
223
+
224
+ def denoising_steps_for(original, num_steps):
225
+ """The ``num_steps`` subset of ``original`` that use_denoising_steps would install."""
226
+ import torch
227
+ if num_steps is None or num_steps == len(original):
228
+ return original
229
+ n_full = len(original)
230
+ idx = sorted({int(round(i * (n_full - 1) / max(num_steps - 1, 1)))
231
+ for i in range(num_steps)}) if num_steps > 1 else [0]
232
+ return original[torch.tensor(idx)]
233
+
234
+
235
+ def use_denoising_steps(pipeline, num_steps):
236
+ """Temporarily reduce the model's denoising schedule to ``num_steps``.
237
+
238
+ These are step-distilled models: the generator was only ever trained at the
239
+ timesteps in ``denoising_step_list`` (1000/750/500/250 warped), so a shorter
240
+ schedule has to be a *subset* of them rather than a freshly spaced grid. The
241
+ subset is uniform and keeps both ends, so the last prediction is still made
242
+ at the finest trained timestep (n=3 -> 1000/500/250, n=2 -> 1000/250,
243
+ n=1 -> 1000). Returns the original list; the caller restores it.
244
+ """
245
+ import torch
246
+ original = pipeline.denoising_step_list
247
+ if num_steps is None or num_steps == len(original):
248
+ return original
249
+ n_full = len(original)
250
+ idx = sorted({int(round(i * (n_full - 1) / max(num_steps - 1, 1)))
251
+ for i in range(num_steps)}) if num_steps > 1 else [0]
252
+ pipeline.denoising_step_list = original[torch.tensor(idx)]
253
+ return original
hy_aggregate.py ADDED
@@ -0,0 +1,130 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """Summarise the HY-WorldPlay evaluation into eval_out_hy/summaries/final_summary.{json,csv}.
3
+
4
+ Latency: ratio of means against the FFFF latency measured in the same process for
5
+ the same job (matched FFFF). Pixel metrics: PSNR from the mean per-video MSE, SSIM
6
+ and LPIPS averaged. VBench: the eight validation25 dimensions, normalised with
7
+ VBench's official ranges; the headline "VBench-I2V-100" is the 251-protocol
8
+ formula with temporal_flickering in the quality group and overall_consistency as
9
+ the semantic group (there is no scene dimension for I2V):
10
+ quality = (sc + bc + tf + ms + 0.5*dd + aq + iq) / 6.5
11
+ semantic = oc
12
+ selected = (4*quality + semantic) / 5
13
+ "core5" (mean of raw sc, bc, ms, aq, iq) is kept for comparison with the DEV
14
+ project's tables.
15
+ """
16
+ import csv, glob, json, math, os, sys
17
+ ROOT = os.path.dirname(os.path.abspath(__file__))
18
+ OUT = os.path.join(ROOT, "eval_out_hy")
19
+ # Two headline numbers over the same five dimensions, both reported:
20
+ #
21
+ # core5 the plain mean of the raw scores -- the HY-WorldPlay DEV protocol's
22
+ # "VBench Core5" for validation25, so the tables line up with it;
23
+ # score_5d the mean after VBench's *official* min-max normalisation, which is
24
+ # what the 251-prompt tables use for their quality group.
25
+ #
26
+ # VBench reports imaging_quality *per video* on 0..100 but already divides its
27
+ # own aggregate by 100, and the aggregate is what is collected here -- so no
28
+ # further scaling is applied (dividing again would cost ~14 points of Core5).
29
+ # aesthetic_quality and imaging_quality live on [0, 1], so their official
30
+ # normalisation is the identity.
31
+ DIMS = ["subject_consistency", "background_consistency", "motion_smoothness",
32
+ "aesthetic_quality", "imaging_quality"]
33
+ NORM_RANGE = {"subject_consistency": (0.1462, 1.0),
34
+ "background_consistency": (0.2615, 1.0),
35
+ "motion_smoothness": (0.7060, 0.9975),
36
+ "aesthetic_quality": (0.0, 1.0),
37
+ "imaging_quality": (0.0, 1.0)}
38
+
39
+
40
+ def normalize_score(dim, value):
41
+ return value
42
+
43
+
44
+ def official_normalize(dim, value):
45
+ lo, hi = NORM_RANGE[dim]
46
+ return (value - lo) / (hi - lo)
47
+ only = sys.argv[1] if len(sys.argv) > 1 else None
48
+
49
+ rows, problems = [], []
50
+ for d in sorted(glob.glob(os.path.join(OUT, "per_prompt", "hy_*"))):
51
+ s = os.path.basename(d)
52
+ recs = [json.load(open(p)) for p in sorted(glob.glob(os.path.join(d, "*.json")))]
53
+ recs = [r for r in recs if r.get("status") == "complete"]
54
+ if len(recs) != 100:
55
+ problems.append(f"{s}: {len(recs)} records"); continue
56
+ sc = os.path.join(OUT, "vbench", "scores", s + ".json")
57
+ vb = json.load(open(sc)) if os.path.exists(sc) else None
58
+ if vb is None:
59
+ problems.append(f"{s}: no VBench scores")
60
+ lat = sum(r["policy_latency_ms"] for r in recs) / 100
61
+ matched = [r.get("matched_ffff_policy_latency_ms") for r in recs]
62
+ if all(m is not None for m in matched):
63
+ ref = sum(matched) / 100
64
+ latency_source = "paired with FFFF in the same process"
65
+ else:
66
+ # FFFF was not regenerated for these jobs: compare against the reference
67
+ # strategy's own records (hy_ffff, or hy_<n>c_ffff for the long videos).
68
+ ref_name = recs[0].get("reference_strategy") or "hy_ffff"
69
+ ff = [json.load(open(p)) for p in sorted(glob.glob(os.path.join(OUT, "per_prompt", ref_name, "*.json")))]
70
+ ref = sum(r["policy_latency_ms"] for r in ff if r.get("status") == "complete") / 100
71
+ latency_source = "generation run (FFFF from its own records)"
72
+ if all(str(r.get("latency_source", "")).startswith("DEV generator") for r in recs):
73
+ latency_source = recs[0]["latency_source"]
74
+ ce = sum(r["cache_diagnostics"]["compute_equivalent_forwards"] for r in recs) / 100
75
+ fw = recs[0]["cache_diagnostics"]["denoise_forwards"]
76
+ mse = sum(r["pixel_metrics_vs_ffff"]["mean_mse"] for r in recs) / 100
77
+ row = {"strategy": s, "base_model": "hy_worldplay", "method": recs[0]["method"],
78
+ "schedule": recs[0]["schedule"], "target_speedup": recs[0]["target_speedup"],
79
+ "param": recs[0]["param"], "param_value": recs[0]["param_value"], "num_videos": 100,
80
+ "policy_latency_ms": lat, "matched_ffff_policy_latency_ms": ref,
81
+ "latency_ratio_vs_ffff": lat / ref, "speedup_percent_vs_ffff": 100 * (1 - lat / ref),
82
+ "latency_source": latency_source,
83
+ "first_chunk_schedule": recs[0].get("first_chunk_schedule"),
84
+ "mp4_reference_records": sum(1 for r in recs if r.get("reference_source") == "ffff_mp4"),
85
+ "excluded_context_kv_latency_ms": sum(r["excluded_context_kv_latency_ms"] for r in recs) / 100,
86
+ "denoise_forwards": fw, "mean_compute_equivalent_forwards": ce,
87
+ "mean_full_forwards": (sum(r["cache_diagnostics"]["full_forwards"] for r in recs) / 100
88
+ if all("full_forwards" in r["cache_diagnostics"] for r in recs) else None),
89
+ "mean_predictor_forwards": (sum(r["cache_diagnostics"]["predictor_forwards"] for r in recs) / 100
90
+ if all("predictor_forwards" in r["cache_diagnostics"] for r in recs) else None),
91
+ "psnr": -10 * math.log10(max(mse, 1e-12)),
92
+ "ssim": sum(r["pixel_metrics_vs_ffff"]["ssim"] for r in recs) / 100,
93
+ "lpips": sum(r["pixel_metrics_vs_ffff"]["lpips"] for r in recs) / 100,
94
+ "peak_mem_gib": max(r.get("peak_mem_gib", 0) for r in recs)}
95
+ if vb:
96
+ scores, normed = {}, {}
97
+ for k in DIMS:
98
+ row["raw_" + k] = vb["raw"][k]
99
+ scores[k] = normalize_score(k, vb["raw"][k])
100
+ normed[k] = official_normalize(k, scores[k])
101
+ row["score_" + k] = scores[k]
102
+ row["normalized_" + k] = normed[k]
103
+ core5 = sum(scores.values()) / len(DIMS)
104
+ score_5d = sum(normed.values()) / len(DIMS)
105
+ row.update(core5=core5, core5_percent=100 * core5,
106
+ score_5d=score_5d, score_5d_percent=100 * score_5d,
107
+ selected_vbench_score=score_5d, selected_vbench_percent=100 * score_5d)
108
+ rows.append(row)
109
+ rows.sort(key=lambda r: (["none", "teacache", "flowcache", "taylorseer", "motioncache"].index(r["method"])
110
+ if r["method"] in ("none", "teacache", "flowcache", "taylorseer", "motioncache") else 9,
111
+ r["schedule"] != "FxxF", r["target_speedup"]))
112
+ os.makedirs(os.path.join(OUT, "summaries"), exist_ok=True)
113
+ json.dump({"protocol": "HY-WorldPlay VBench-I2V-100 (validation25 x 4 actions, Core5)",
114
+ "num_strategies": len(rows), "rows": rows, "problems": problems, "dimensions": DIMS,
115
+ "aggregation": {
116
+ "core5": "mean of raw(sc, bc, ms, aq, iq/100)",
117
+ "score_5d": "mean of ((sc-0.1462)/0.8538, (bc-0.2615)/0.7385, "
118
+ "(ms-0.7060)/0.2915, aq, iq/100)"},
119
+ "normalize_range": NORM_RANGE},
120
+ open(os.path.join(OUT, "summaries", "final_summary.json"), "w"), indent=2)
121
+ keys = sorted({k for r in rows for k in r}, key=lambda k: (k not in ("strategy", "method"), k))
122
+ with open(os.path.join(OUT, "summaries", "final_summary.csv"), "w", newline="") as f:
123
+ w = csv.DictWriter(f, fieldnames=keys); w.writeheader(); [w.writerow(r) for r in rows]
124
+ print(f"{'strategy':26s} {'lat_ms':>8} {'ffff_ms':>8} {'x':>6} {'Full':>6} {'PSNR':>6} {'LPIPS':>6} {'raw%':>7} {'norm%':>7}")
125
+ for r in rows:
126
+ print(f"{r['strategy']:26s} {r['policy_latency_ms']:8.0f} {r['matched_ffff_policy_latency_ms']:8.0f} "
127
+ f"{1/r['latency_ratio_vs_ffff']:6.3f} {r['mean_compute_equivalent_forwards']:6.2f} {r['psnr']:6.2f} "
128
+ f"{r['lpips']:6.3f} {r.get('core5_percent', float('nan')):7.2f} "
129
+ f"{r.get('score_5d_percent', float('nan')):7.2f}")
130
+ if problems: print("problems:", problems)
hy_calibrate.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """Fit the TeaCache rescale polynomial on the HY-WorldPlay base (see calibrate.py).
3
+
4
+ CUDA_VISIBLE_DEVICES=5 python hy_calibrate.py --out results/hy_coeff.json
5
+ """
6
+ import argparse, json, os, sys
7
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
8
+ from hycache import harness as H
9
+ H.enter_repo()
10
+ import numpy as np
11
+ import torch
12
+ from hycache.measure import make_ctrl
13
+
14
+ ap = argparse.ArgumentParser()
15
+ ap.add_argument("--num-cases", type=int, default=3)
16
+ ap.add_argument("--frames", type=int, default=125)
17
+ ap.add_argument("--degree", type=int, default=1)
18
+ ap.add_argument("--out", default="results/hy_coeff.json")
19
+ args = ap.parse_args()
20
+
21
+ pipe = H.load_pipeline()
22
+ ctrl = make_ctrl(pipe, "calibrate")
23
+ cases = H.load_cases()
24
+ for i in range(args.num_cases):
25
+ # vary the camera action with the case so the samples span motion types
26
+ H.generate(pipe, cases[i], H.ACTIONS[i % 4], controller=ctrl, num_frames=args.frames, decode=False)
27
+ print(f"[{i}] samples={len(ctrl.method.samples)}", flush=True)
28
+ s = ctrl.method.samples
29
+ xs = np.array([r["x"] for r in s]); ys = np.array([r["y"] for r in s])
30
+ coeffs = np.polyfit(xs, ys, args.degree); pred = np.poly1d(coeffs)(xs)
31
+ res = {"base": "hy_worldplay", "indicator": "modulated_input", "degree": args.degree,
32
+ "num_samples": int(xs.size), "coefficients": [float(c) for c in coeffs],
33
+ "x_range": [float(xs.min()), float(xs.max())], "y_range": [float(ys.min()), float(ys.max())],
34
+ "fit_r2": float(1 - ((ys - pred) ** 2).sum() / ((ys - ys.mean()) ** 2).sum()),
35
+ "per_step_mean_x": {str(k): float(xs[[r["step"] == k for r in s]].mean()) for k in sorted({r["step"] for r in s})},
36
+ "per_step_std_x": {str(k): float(xs[[r["step"] == k for r in s]].std()) for k in sorted({r["step"] for r in s})},
37
+ "per_step_mean_y": {str(k): float(ys[[r["step"] == k for r in s]].mean()) for k in sorted({r["step"] for r in s})},
38
+ "samples": s}
39
+ print(json.dumps({k: v for k, v in res.items() if k != "samples"}, indent=1))
40
+ out = args.out if os.path.isabs(args.out) else os.path.join(os.path.dirname(os.path.abspath(__file__)), args.out)
41
+ json.dump(res, open(out, "w"), indent=2); print("wrote", out)
hy_dev_gen_disca.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """Run HY-WorldPlay-DEV-Predictor's generate_predictor_v4_train_case_eval.py with the
3
+ DisCa predictor: the current DEV rollout passes ``anchor_distance`` (an ATC input) to
4
+ every predictor, which HYWorldPlayPredictorDisCa.forward does not accept. Wrap its
5
+ forward to drop every keyword it does not declare; everything else is the stock DEV script."""
6
+ import os, runpy, sys
7
+ DEV = "/local/zoubin/cz/projects/HY-WorldPlay-DEV-Predictor"
8
+ sys.path.insert(0, DEV); os.chdir(DEV)
9
+ import models # noqa: E402
10
+ _orig = models.HYWorldPlayPredictorDisCa.forward
11
+
12
+
13
+ import inspect # noqa: E402
14
+ _accepted = set(inspect.signature(_orig).parameters)
15
+
16
+
17
+ def forward(self, *args, **kw):
18
+ # drop inputs the ATC-era rollout passes that DisCa never took
19
+ # (anchor_distance, previous_step_chunk_hidden, ...)
20
+ return _orig(self, *args, **{k: v for k, v in kw.items() if k in _accepted})
21
+
22
+
23
+ models.HYWorldPlayPredictorDisCa.forward = forward
24
+ sys.argv[0] = os.path.join(DEV, "tools/generate_predictor_v4_train_case_eval.py")
25
+ runpy.run_path(sys.argv[0], run_name="__main__")
hy_dev_gen_long.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """Run HY-WorldPlay-DEV-Predictor's generate_predictor_v4_train_case_eval.py at a
3
+ video length other than the 125-frame protocol (long-video rows of the comparison).
4
+
5
+ HY_NUM_LATENTS (64 = 16 chunks = 253 frames, 128 = 32 chunks = 509 frames) replaces the
6
+ generator's hard-coded 32 latents / 125 frames:
7
+ * the four bidirectional camera actions are rescaled the way hycache does it
8
+ ("w-15,s-16" -> "w-31,s-32" for 64 latents: forward for floor((n-1)/2) latents,
9
+ back for the rest, so the video still turns around half-way);
10
+ * pose_to_input gets the new latent count and the pipeline call the matching
11
+ video_length.
12
+ The pipeline's own long-video mechanism (pose-retrieved memory frames, at most 20
13
+ history latents per chunk) is left as is. DisCa's forward drops the ATC-only keywords
14
+ the rollout passes (same as hy_dev_gen_disca.py)."""
15
+ import inspect, os, sys
16
+ DEV = "/local/zoubin/cz/projects/HY-WorldPlay-DEV-Predictor"
17
+ sys.path.insert(0, DEV); os.chdir(DEV)
18
+ N = int(os.environ["HY_NUM_LATENTS"])
19
+ assert N % 4 == 0 and N > 0, N
20
+ FRAMES = (N - 1) * 4 + 1
21
+
22
+ import hyvideo.generate as G # noqa: E402
23
+ import predictor_data.prefeature_schema as S # noqa: E402
24
+ from hyvideo.pipelines.worldplay_video_pipeline import HunyuanVideo_1_5_Pipeline # noqa: E402
25
+ import models # noqa: E402
26
+
27
+
28
+ def rescale(pose):
29
+ (fwd, _), (back, _) = [p.strip().split("-") for p in pose.split(",")]
30
+ n = N - 1
31
+ return f"{fwd}-{n // 2},{back}-{n - n // 2}"
32
+
33
+
34
+ S.DEFAULT_ACTIONS = tuple((name, rescale(pose)) for name, pose in S.DEFAULT_ACTIONS)
35
+ print(f"[hy_dev_gen_long] {N} latents = {FRAMES} frames; actions {S.DEFAULT_ACTIONS}", flush=True)
36
+
37
+ _pose_to_input = G.pose_to_input
38
+
39
+
40
+ def pose_to_input(pose_data, latent_num, tps=False):
41
+ return _pose_to_input(pose_data, N if latent_num == 32 else latent_num, tps)
42
+
43
+
44
+ G.pose_to_input = pose_to_input
45
+
46
+ _call = HunyuanVideo_1_5_Pipeline.__call__
47
+
48
+
49
+ def __call__(self, *args, **kw):
50
+ if kw.get("video_length") == 125:
51
+ kw["video_length"] = FRAMES
52
+ return _call(self, *args, **kw)
53
+
54
+
55
+ HunyuanVideo_1_5_Pipeline.__call__ = __call__
56
+
57
+ _orig = models.HYWorldPlayPredictorDisCa.forward
58
+ _accepted = set(inspect.signature(_orig).parameters)
59
+
60
+
61
+ def forward(self, *args, **kw):
62
+ return _orig(self, *args, **{k: v for k, v in kw.items() if k in _accepted})
63
+
64
+
65
+ models.HYWorldPlayPredictorDisCa.forward = forward
66
+
67
+ # The generator's completion check (resume + post-encode validation) hard-codes 125
68
+ # decoded frames; load it as a module so the check can be re-pointed at FRAMES.
69
+ import av # noqa: E402
70
+ import tools.generate_predictor_v4_train_case_eval as gen # noqa: E402
71
+
72
+
73
+ def video_is_complete(path):
74
+ if not path.is_file() or path.stat().st_size == 0:
75
+ return False
76
+ try:
77
+ with av.open(str(path)) as container:
78
+ stream = container.streams.video[0]
79
+ if stream.width != 832 or stream.height != 480:
80
+ return False
81
+ return sum(1 for _ in container.decode(stream)) == FRAMES
82
+ except Exception:
83
+ return False
84
+
85
+
86
+ gen.video_is_complete = video_is_complete
87
+ sys.argv[0] = gen.__file__
88
+ gen.main()
hy_generate_eval.py ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """Generate the VBench-I2V-100 evaluation videos on the HY-WorldPlay base.
3
+
4
+ 100 jobs = 25 validation cases x 4 camera actions, 125 frames, 480x832, seed 0.
5
+ For every job the FFFF reference is generated first and every cache strategy is
6
+ timed back to back with it in the same process (the protocol's matched-FFFF
7
+ latency), scored against its decoded frames (PSNR/SSIM/LPIPS, all 125 frames),
8
+ and written as mp4 (fps 24, like the DEV project's validation videos).
9
+
10
+ CUDA_VISIBLE_DEVICES=5 python hy_generate_eval.py --shard 0 --num-shards 2
11
+ """
12
+ import argparse, gc, json, os, sys, time
13
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
14
+ from hycache import harness as H
15
+ H.enter_repo()
16
+ import torch
17
+ from hycache.measure import make_ctrl
18
+ from hy_strategies import load_strategies
19
+ from eval.pixel_metrics import PixelMetrics
20
+
21
+ ROOT = os.path.dirname(os.path.abspath(__file__))
22
+ ap = argparse.ArgumentParser()
23
+ ap.add_argument("--shard", type=int, default=0)
24
+ ap.add_argument("--num-shards", type=int, default=1)
25
+ ap.add_argument("--out-root", default="eval_out_hy")
26
+ ap.add_argument("--frames", type=int, default=125)
27
+ ap.add_argument("--seed", type=int, default=0)
28
+ ap.add_argument("--limit", type=int, default=None)
29
+ ap.add_argument("--only-strategy", default=None)
30
+ ap.add_argument("--strategies", default=None, help="Comma-separated subset (FFFF always kept)")
31
+ ap.add_argument("--overwrite", action="store_true")
32
+ ap.add_argument("--regenerate-ffff", action="store_true",
33
+ help="Regenerate the FFFF reference instead of reading hy_ffff's MP4")
34
+ ap.add_argument("--tag", default="",
35
+ help="Video-length tag for long videos, e.g. _16c with --frames 253: the reference "
36
+ "becomes hy_16c_ffff and every strategy gets the tag inserted before its "
37
+ "_c0FFFF suffix (hy_naive2step_16c_c0FFFF), so nothing collides with the "
38
+ "125-frame rows")
39
+ args = ap.parse_args()
40
+ out_root = args.out_root if os.path.isabs(args.out_root) else os.path.join(ROOT, args.out_root)
41
+
42
+ cases = H.load_cases()
43
+ jobs = [(c, ai) for c in cases for ai in range(len(H.ACTIONS))]
44
+ if args.limit:
45
+ jobs = jobs[:args.limit]
46
+ shard_jobs = jobs[args.shard::args.num_shards]
47
+ strategies = load_strategies()
48
+ if args.only_strategy:
49
+ strategies = [s for s in strategies if s["is_reference"] or s["name"] == args.only_strategy]
50
+ if args.strategies:
51
+ keep = set(args.strategies.split(","))
52
+ strategies = [s for s in strategies if s["is_reference"] or s["name"] in keep]
53
+ if args.tag:
54
+ for s in strategies:
55
+ if s["is_reference"]:
56
+ s["name"] = f"hy{args.tag}_ffff"
57
+ elif s["name"].endswith("_c0FFFF"):
58
+ s["name"] = s["name"][:-len("_c0FFFF")] + args.tag + "_c0FFFF"
59
+ else:
60
+ s["name"] += args.tag
61
+ ref_name = strategies[0]["name"]
62
+ print(f"shard {args.shard}/{args.num_shards}: {len(shard_jobs)} jobs x {len(strategies)} strategies", flush=True)
63
+
64
+ pipe = H.load_pipeline()
65
+ metrics = PixelMetrics(torch.device("cuda"))
66
+ from hyvideo.generate import save_video
67
+
68
+
69
+ def paths(strategy, case, ai):
70
+ stem = f"case_{case['split_case_id']:04d}_action_{ai:02d}"
71
+ d = os.path.join(out_root, "per_prompt", strategy); os.makedirs(d, exist_ok=True)
72
+ v = os.path.join(out_root, "generated_videos", strategy); os.makedirs(v, exist_ok=True)
73
+ return os.path.join(d, stem + ".json"), os.path.join(v, stem + ".mp4")
74
+
75
+
76
+ def is_done(strategy, case, ai):
77
+ rp, vp = paths(strategy, case, ai)
78
+ if args.overwrite or not os.path.exists(rp):
79
+ return False
80
+ try:
81
+ rec = json.load(open(rp))
82
+ return rec.get("status") == "complete" and os.path.exists(rec.get("video", ""))
83
+ except Exception:
84
+ return False
85
+
86
+
87
+ def write_json(path, payload):
88
+ tmp = path + ".tmp"
89
+ json.dump(payload, open(tmp, "w"), indent=2)
90
+ os.replace(tmp, path)
91
+
92
+
93
+ def run_one(strategy, case, ai):
94
+ kw = {strategy["param"]: strategy["value"]} if strategy.get("param") else {}
95
+ n_steps = strategy.get("num_inference_steps") or H.NUM_STEPS
96
+ first = strategy.get("first_chunk_schedule")
97
+ ctrl = make_ctrl(pipe, strategy["method"], schedule=strategy["schedule"],
98
+ coefficients=strategy["coefficients"], num_steps=n_steps,
99
+ first_chunk_schedule=first, **kw)
100
+ gc.collect(); torch.cuda.empty_cache(); torch.cuda.reset_peak_memory_stats()
101
+ video, _, timing = H.generate(pipe, case, H.ACTIONS[ai], controller=ctrl,
102
+ num_frames=args.frames, seed=args.seed, decode=True,
103
+ num_steps=n_steps,
104
+ first_chunk_steps=(len(first) if first and len(first) != n_steps else None))
105
+ return video, timing, ctrl.summary()
106
+
107
+
108
+ # warm-up (TaylorSeer's compiled forecast, allocator) -- not recorded
109
+ if shard_jobs:
110
+ for s in strategies:
111
+ run_one(s, *shard_jobs[0])
112
+ torch.cuda.empty_cache()
113
+
114
+ t_start = time.time()
115
+ for n, (case, ai) in enumerate(shard_jobs):
116
+ todo = [s for s in strategies if not is_done(s["name"], case, ai)]
117
+ if not todo:
118
+ continue
119
+ ref_from_mp4 = False
120
+ ref_rp, ref_vp = paths(ref_name, case, ai)
121
+ if (not args.regenerate_ffff and os.path.exists(ref_vp)
122
+ and not any(s["is_reference"] for s in todo)):
123
+ # Reference from the hy_ffff run's MP4: FFFF is not regenerated, so there is
124
+ # no same-process FFFF timing (hy_aggregate falls back to hy_ffff's records).
125
+ from torchvision.io import read_video
126
+ vid, _, _ = read_video(ref_vp, pts_unit="sec", output_format="TCHW")
127
+ ref_frames = (vid.to(torch.device("cuda"), torch.float16) / 255.0)
128
+ ref_video, ref_timing, ref_summary, ref_from_mp4 = None, None, None, True
129
+ else:
130
+ ref_video, ref_timing, ref_summary = run_one(strategies[0], case, ai)
131
+ ref_frames = ref_video[0].permute(1, 0, 2, 3).contiguous() # [T, C, H, W] in [0,1]
132
+ for s in strategies:
133
+ if s not in todo:
134
+ continue
135
+ if s["is_reference"]:
136
+ video, timing, summary = ref_video, ref_timing, ref_summary
137
+ pix = PixelMetrics.identity(ref_frames.shape[0])
138
+ else:
139
+ video, timing, summary = run_one(s, case, ai)
140
+ frames = video[0].permute(1, 0, 2, 3).contiguous()
141
+ pix = metrics.compute(frames, ref_frames.to(torch.float16))
142
+ rp, vp = paths(s["name"], case, ai)
143
+ save_video(video, vp)
144
+ write_json(rp, {
145
+ "status": "complete", "protocol": "HY-WorldPlay VBench-I2V-100 (validation25 x 4 actions)",
146
+ "strategy": s["name"], "base_model": "hy_worldplay", "method": s["method"],
147
+ "param": s["param"], "param_value": s["value"], "target_speedup": s["target"],
148
+ "schedule": s["schedule"], "num_inference_steps": s.get("num_inference_steps") or 4,
149
+ "first_chunk_schedule": s.get("first_chunk_schedule"),
150
+ "case_id": case["case_id"], "split_case_id": case["split_case_id"],
151
+ "action_id": ai, "action_name": H.ACTIONS[ai][0],
152
+ "prompt": case["caption"], "image_path": case["image_path"], "seed": args.seed,
153
+ "video": vp, "num_frames": int(video.shape[2]), "height": int(video.shape[3]),
154
+ "width": int(video.shape[4]), "fps": 24,
155
+ "policy_latency_ms": timing["denoise_dit_ms"],
156
+ "excluded_context_kv_latency_ms": timing["context_kv_dit_ms"],
157
+ "excluded_text_cache_ms": timing["text_cache_ms"],
158
+ "matched_ffff_policy_latency_ms": ref_timing["denoise_dit_ms"] if ref_timing else None,
159
+ "latency_source": ("generation run (FFFF from its own records)" if ref_from_mp4
160
+ else "generation run, paired with FFFF in the same process"),
161
+ "reference_source": "ffff_mp4" if ref_from_mp4 else "ffff_frames",
162
+ "wall_generation_s": timing["wall_s"], "peak_mem_gib": timing["peak_mem_gib"],
163
+ "reference_strategy": ref_name, "pixel_metrics_vs_ffff": pix,
164
+ "cache_diagnostics": dict(summary),
165
+ })
166
+ del video
167
+ del ref_video, ref_frames
168
+ done = n + 1
169
+ rate = (time.time() - t_start) / done
170
+ print(f"[hy shard {args.shard}] {done}/{len(shard_jobs)} jobs ({case['split_case_id']:04d}/{ai}) "
171
+ f"{rate:.0f}s/job eta {(len(shard_jobs) - done) * rate / 60:.0f} min", flush=True)
172
+ print(f"shard {args.shard} done in {(time.time() - t_start) / 60:.1f} min", flush=True)
hy_mc_scan.py ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """MotionCache threshold scan on the HY-WorldPlay base -- same diagnostic as
3
+ mc_scan.py: what the compute fraction hides, i.e. whether the cacheable steps are
4
+ making *partial* token decisions or degenerating into whole-step skips.
5
+
6
+ CUDA_VISIBLE_DEVICES=4 python hy_mc_scan.py --schedule FxxF \
7
+ --thresholds 0.05,0.1,0.2,0.4,0.7,1.0 --out results/hy_mc_scan_FxxF.json
8
+ """
9
+ import argparse, json, os, statistics as st, sys
10
+ ROOT = os.path.dirname(os.path.abspath(__file__))
11
+ sys.path.insert(0, ROOT)
12
+ from hycache import harness as H
13
+ H.enter_repo()
14
+ import torch
15
+ from hycache.measure import make_ctrl
16
+
17
+ ap = argparse.ArgumentParser()
18
+ ap.add_argument("--schedule", default="FxxF")
19
+ ap.add_argument("--thresholds", required=True)
20
+ ap.add_argument("--frames", type=int, default=61)
21
+ ap.add_argument("--num-cases", type=int, default=2)
22
+ ap.add_argument("--out", default=None)
23
+ args = ap.parse_args()
24
+
25
+ pipe = H.load_pipeline()
26
+ cases = H.load_cases()
27
+ jobs = [(cases[i], H.ACTIONS[0]) for i in range(args.num_cases + 1)] # first = warm-up
28
+ forced = set(range(H.NUM_STEPS)) if False else None
29
+
30
+
31
+ def run(method, **kw):
32
+ ctrl = make_ctrl(pipe, method, schedule=args.schedule, **kw)
33
+ ms, recs = [], []
34
+ for i, (case, action) in enumerate(jobs):
35
+ _, _, t = H.generate(pipe, case, action, controller=ctrl, num_frames=args.frames, decode=False)
36
+ if i == 0:
37
+ continue
38
+ ms.append(t["denoise_dit_ms"])
39
+ recs += [r for r in ctrl.records if r["step"] not in ctrl.forced]
40
+ return min(ms), recs, ctrl.summary()
41
+
42
+
43
+ base_ms, _, _ = run("none")
44
+ print(f"baseline FFFF min denoise {base_ms:.0f} ms ({args.frames} frames, schedule {args.schedule})", flush=True)
45
+ print(f"{'thresh':>8}{'Full':>8}{'compute_x':>10}{'measured_x':>11}{'active%':>9}{'empty%':>8}{'full%':>7}{'sel_mean%':>10}{'sel_p90%':>9}")
46
+ rows = []
47
+ for t in [float(v) for v in args.thresholds.split(",")]:
48
+ ms, recs, summ = run("motioncache", thresh=t)
49
+ fr = [r["compute_fraction"] for r in recs]
50
+ act = [f for f in fr if 1e-9 < f < 1 - 1e-9]
51
+ q = lambda v, p: sorted(v)[min(int(p * (len(v) - 1)), len(v) - 1)] if v else float("nan")
52
+ row = {"thresh": t, "compute_equivalent": summ["compute_equivalent_forwards"],
53
+ "compute_speedup": summ["flops_speedup_estimate"], "measured_speedup": base_ms / ms,
54
+ "active_ratio": len(act) / len(fr), "empty_ratio": sum(f <= 1e-9 for f in fr) / len(fr),
55
+ "full_ratio": sum(f >= 1 - 1e-9 for f in fr) / len(fr),
56
+ "sel_mean": st.fmean(act) if act else 0.0, "sel_p90": q(act, .9), "min_denoise_ms": ms}
57
+ rows.append(row)
58
+ print(f"{t:>8.4g}{row['compute_equivalent']:>8.2f}{row['compute_speedup']:>10.3f}{row['measured_speedup']:>11.3f}"
59
+ f"{100*row['active_ratio']:>9.1f}{100*row['empty_ratio']:>8.1f}{100*row['full_ratio']:>7.1f}"
60
+ f"{100*row['sel_mean']:>10.1f}{100*row['sel_p90']:>9.1f}", flush=True)
61
+ if args.out:
62
+ out = args.out if os.path.isabs(args.out) else os.path.join(ROOT, args.out)
63
+ os.makedirs(os.path.dirname(out), exist_ok=True)
64
+ json.dump({"base": "hy_worldplay", "schedule": args.schedule, "frames": args.frames,
65
+ "baseline_ms": base_ms, "rows": rows}, open(out, "w"), indent=2)
66
+ print("wrote", out)
hy_mc_scan_run.sh ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -u
3
+ C=/local/zoubin/cz/projects/comparison; PY=/local/zoubin/cz/envs/hy_worldplay_july20260720/bin/python
4
+ LOG="$1"
5
+ export SSL_CERT_FILE=/etc/pki/tls/certs/ca-bundle.crt HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1
6
+ export HF_HOME=/local/zoubin/cz/checkpoints/hy_worldplay/huggingface HF_HUB_CACHE=/local/zoubin/cz/checkpoints/hy_worldplay/huggingface/hub
7
+ export TRANSFORMERS_CACHE=/local/zoubin/cz/checkpoints/hy_worldplay/huggingface/hub TORCH_HOME=/local/zoubin/cz/.cache/torch XDG_CACHE_HOME=/local/zoubin/cz/.cache
8
+ cd "$C"
9
+ CUDA_VISIBLE_DEVICES=4 $PY hy_mc_scan.py --schedule FxxF --thresholds 0.02,0.05,0.09,0.15,0.25,0.4 --out results/hy_mc_scan_FxxF_a.json > "$LOG/hy_mc_scan_FxxF_a.log" 2>&1 &
10
+ CUDA_VISIBLE_DEVICES=5 $PY hy_mc_scan.py --schedule FxxF --thresholds 0.6,0.8,1.0,1.3,1.8,2.5 --out results/hy_mc_scan_FxxF_b.json > "$LOG/hy_mc_scan_FxxF_b.log" 2>&1 &
11
+ CUDA_VISIBLE_DEVICES=6 $PY hy_mc_scan.py --schedule Fxxx --thresholds 0.05,0.1,0.2,0.35,0.55,0.8 --out results/hy_mc_scan_Fxxx_a.json > "$LOG/hy_mc_scan_Fxxx_a.log" 2>&1 &
12
+ CUDA_VISIBLE_DEVICES=7 $PY hy_mc_scan.py --schedule Fxxx --thresholds 1.1,1.5,2.0,2.6,3.3,4.2 --out results/hy_mc_scan_Fxxx_b.json > "$LOG/hy_mc_scan_Fxxx_b.log" 2>&1 &
13
+ wait
14
+ echo "ALL HY MC SCANS DONE $(date +%H:%M:%S)"
hy_memtest.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os, sys, time, json
2
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
3
+ from hycache import harness as H
4
+ H.enter_repo()
5
+ import torch
6
+ from hycache.measure import make_ctrl
7
+ pipe = H.load_pipeline(); case = H.load_cases()[0]
8
+ for name, kw in [("none", {}), ("motioncache", {"thresh": 0.05}), ("taylorseer", {"interval": 3.0}), ("flowcache", {"thresh": 0.05})]:
9
+ ctrl = make_ctrl(pipe, name, **kw)
10
+ torch.cuda.empty_cache(); torch.cuda.reset_peak_memory_stats()
11
+ _, _, t = H.generate(pipe, case, H.ACTIONS[0], controller=ctrl, num_frames=125, decode=False)
12
+ print(f"{name:12s} {kw} denoise={t['denoise_dit_ms']:.0f}ms context={t['context_kv_dit_ms']:.0f}ms peak={t['peak_mem_gib']:.1f}GiB "
13
+ f"reserved={torch.cuda.max_memory_reserved()/1024**3:.1f}GiB compute={ctrl.summary()['compute_equivalent_forwards']:.2f}/32 wall={t['wall_s']:.0f}s", flush=True)
hy_run_eval.sh ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # HY-WorldPlay evaluation: generation (2 shards) -> VBench -> aggregate -> Experiment.md
3
+ # GPUS="5 6" hy_run_eval.sh <logdir>
4
+ set -u
5
+ C=/local/zoubin/cz/projects/comparison
6
+ PY=/local/zoubin/cz/envs/hy_worldplay_july20260720/bin/python
7
+ LOG="$1"; GPUS=(${GPUS:-5 6})
8
+ export SSL_CERT_FILE=/etc/pki/tls/certs/ca-bundle.crt HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1
9
+ export HF_HOME=/local/zoubin/cz/checkpoints/hy_worldplay/huggingface HF_HUB_CACHE=/local/zoubin/cz/checkpoints/hy_worldplay/huggingface/hub
10
+ export TRANSFORMERS_CACHE=/local/zoubin/cz/checkpoints/hy_worldplay/huggingface/hub TORCH_HOME=/local/zoubin/cz/.cache/torch XDG_CACHE_HOME=/local/zoubin/cz/.cache
11
+ cd "$C"; mkdir -p "$LOG"
12
+ echo "=== generation on GPUs ${GPUS[*]} ($(date +%H:%M:%S)) ==="
13
+ pids=()
14
+ for i in "${!GPUS[@]}"; do
15
+ # A shard may already have been started by hand on an idle GPU; never run the
16
+ # same shard twice -- both copies would generate the same videos.
17
+ if pgrep -f "hy_generate_eval.py --shard $i " > /dev/null 2>&1; then
18
+ echo "shard $i already running elsewhere, not starting a second copy"
19
+ continue
20
+ fi
21
+ CUDA_VISIBLE_DEVICES=${GPUS[$i]} $PY hy_generate_eval.py --shard $i --num-shards ${#GPUS[@]} --out-root eval_out_hy > "$LOG/hy_gen_$i.log" 2>&1 &
22
+ pids+=($!)
23
+ done
24
+ for p in "${pids[@]:-}"; do wait "$p" 2>/dev/null; done
25
+ # Also wait for any shard that was started outside this driver.
26
+ while pgrep -f "[h]y_generate_eval.py" > /dev/null 2>&1; do sleep 60; done
27
+ echo "=== generation done ($(date +%H:%M:%S)) ==="
28
+ GPUS="${GPUS[*]}" bash hy_vbench.sh "$LOG" 2>&1 | tee "$LOG/hy_vbench_driver.log"
29
+ echo "=== aggregating ($(date +%H:%M:%S)) ==="
30
+ python3 hy_aggregate.py 2>&1 | tee "$LOG/hy_aggregate.log"
31
+ python3 experiment_md.py
32
+ echo "ALL HY EVAL DONE $(date +%H:%M:%S)"
hy_run_sweeps.sh ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Calibration + the four FxxF sweeps on the HY-WorldPlay base, on two GPUs.
3
+ # GPU A: calibrate -> teacache -> motioncache GPU B: taylorseer -> (wait coeff) -> flowcache
4
+ set -u
5
+ C=/local/zoubin/cz/projects/comparison
6
+ PY=/local/zoubin/cz/envs/hy_worldplay_july20260720/bin/python
7
+ LOG="$1"; A=${GPU_A:-5}; B=${GPU_B:-6}
8
+ export SSL_CERT_FILE=/etc/pki/tls/certs/ca-bundle.crt HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1
9
+ export HF_HOME=/local/zoubin/cz/checkpoints/hy_worldplay/huggingface HF_HUB_CACHE=/local/zoubin/cz/checkpoints/hy_worldplay/huggingface/hub
10
+ export TRANSFORMERS_CACHE=/local/zoubin/cz/checkpoints/hy_worldplay/huggingface/hub TORCH_HOME=/local/zoubin/cz/.cache/torch XDG_CACHE_HOME=/local/zoubin/cz/.cache
11
+ cd "$C"; mkdir -p "$LOG" results
12
+ COEFF=results/hy_coeff.json
13
+ (
14
+ [ -f $COEFF ] || CUDA_VISIBLE_DEVICES=$A $PY hy_calibrate.py --out $COEFF > "$LOG/hy_calibrate.log" 2>&1
15
+ echo "calibrate done $(date +%H:%M:%S)"
16
+ for m in teacache motioncache; do
17
+ [ -f results/hy_sweep_$m.json ] && { echo "skip $m"; continue; }
18
+ CUDA_VISIBLE_DEVICES=$A $PY hy_sweep.py --method $m --coefficients $COEFF --out results/hy_sweep_$m.json > "$LOG/hy_sweep_$m.log" 2>&1
19
+ echo "$m sweep done $(date +%H:%M:%S) exit=$?"
20
+ done
21
+ ) &
22
+ (
23
+ [ -f results/hy_sweep_taylorseer.json ] || CUDA_VISIBLE_DEVICES=$B $PY hy_sweep.py --method taylorseer --out results/hy_sweep_taylorseer.json > "$LOG/hy_sweep_taylorseer.log" 2>&1
24
+ echo "taylorseer sweep done $(date +%H:%M:%S)"
25
+ until [ -f $COEFF ]; do sleep 30; done
26
+ [ -f results/hy_sweep_flowcache.json ] || CUDA_VISIBLE_DEVICES=$B $PY hy_sweep.py --method flowcache --coefficients $COEFF --out results/hy_sweep_flowcache.json > "$LOG/hy_sweep_flowcache.log" 2>&1
27
+ echo "flowcache sweep done $(date +%H:%M:%S)"
28
+ ) &
29
+ wait
30
+ echo "ALL HY SWEEPS DONE $(date +%H:%M:%S)"
hy_run_sweeps_a.sh ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -u
3
+ C=/local/zoubin/cz/projects/comparison; PY=/local/zoubin/cz/envs/hy_worldplay_july20260720/bin/python
4
+ LOG="$1"; A=${GPU_A:-5}
5
+ export SSL_CERT_FILE=/etc/pki/tls/certs/ca-bundle.crt HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1
6
+ export HF_HOME=/local/zoubin/cz/checkpoints/hy_worldplay/huggingface HF_HUB_CACHE=/local/zoubin/cz/checkpoints/hy_worldplay/huggingface/hub
7
+ export TRANSFORMERS_CACHE=/local/zoubin/cz/checkpoints/hy_worldplay/huggingface/hub TORCH_HOME=/local/zoubin/cz/.cache/torch XDG_CACHE_HOME=/local/zoubin/cz/.cache
8
+ cd "$C"; COEFF=results/hy_coeff.json
9
+ [ -f $COEFF ] || CUDA_VISIBLE_DEVICES=$A $PY hy_calibrate.py --out $COEFF > "$LOG/hy_calibrate.log" 2>&1
10
+ echo "calibrate done $(date +%H:%M:%S) exit=$? coeff=$([ -f $COEFF ] && echo yes || echo NO)"
11
+ [ -f $COEFF ] || exit 1
12
+ for m in teacache motioncache; do
13
+ [ -f results/hy_sweep_$m.json ] && { echo "skip $m"; continue; }
14
+ CUDA_VISIBLE_DEVICES=$A $PY hy_sweep.py --method $m --coefficients $COEFF --out results/hy_sweep_$m.json > "$LOG/hy_sweep_$m.log" 2>&1
15
+ echo "$m sweep done $(date +%H:%M:%S) exit=$?"
16
+ done
17
+ echo "GPU-A SWEEPS DONE $(date +%H:%M:%S)"
hy_run_sweeps_a2.sh ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -u
3
+ C=/local/zoubin/cz/projects/comparison; PY=/local/zoubin/cz/envs/hy_worldplay_july20260720/bin/python
4
+ LOG="$1"; A=${GPU_A:-5}
5
+ export SSL_CERT_FILE=/etc/pki/tls/certs/ca-bundle.crt HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1
6
+ export HF_HOME=/local/zoubin/cz/checkpoints/hy_worldplay/huggingface HF_HUB_CACHE=/local/zoubin/cz/checkpoints/hy_worldplay/huggingface/hub
7
+ export TRANSFORMERS_CACHE=/local/zoubin/cz/checkpoints/hy_worldplay/huggingface/hub TORCH_HOME=/local/zoubin/cz/.cache/torch XDG_CACHE_HOME=/local/zoubin/cz/.cache
8
+ cd "$C"
9
+ until [ -f results/hy_sweep_teacache.json ]; do sleep 30; done
10
+ echo "teacache json present $(date +%H:%M:%S)"
11
+ # MotionCache without the rescale polynomial: the HY fit has a negative slope
12
+ # (R^2 0.14); applied per token it would suppress exactly the high-motion tokens.
13
+ [ -f results/hy_sweep_motioncache.json ] || CUDA_VISIBLE_DEVICES=$A $PY hy_sweep.py --method motioncache --targets 1.3,1.6 --coarse-points 5 --bisect-iters 5 --pair-prompts 2 --hi 6 --out results/hy_sweep_motioncache.json > "$LOG/hy_sweep_motioncache.log" 2>&1
14
+ echo "motioncache sweep done $(date +%H:%M:%S) exit=$?"
15
+ echo "GPU-A SWEEPS DONE $(date +%H:%M:%S)"
hy_run_sweeps_b2.sh ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -u
3
+ C=/local/zoubin/cz/projects/comparison; PY=/local/zoubin/cz/envs/hy_worldplay_july20260720/bin/python
4
+ LOG="$1"; A=${GPU_A:-6}
5
+ export SSL_CERT_FILE=/etc/pki/tls/certs/ca-bundle.crt HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1
6
+ export HF_HOME=/local/zoubin/cz/checkpoints/hy_worldplay/huggingface HF_HUB_CACHE=/local/zoubin/cz/checkpoints/hy_worldplay/huggingface/hub
7
+ export TRANSFORMERS_CACHE=/local/zoubin/cz/checkpoints/hy_worldplay/huggingface/hub TORCH_HOME=/local/zoubin/cz/.cache/torch XDG_CACHE_HOME=/local/zoubin/cz/.cache
8
+ cd "$C"
9
+ until [ -f results/hy_sweep_flowcache.json ]; do sleep 30; done
10
+ echo "teacache json present $(date +%H:%M:%S)"
11
+ # MotionCache without the rescale polynomial: the HY fit has a negative slope
12
+ # (R^2 0.14); applied per token it would suppress exactly the high-motion tokens.
13
+ [ -f results/hy_sweep_motioncache_x2.json ] || CUDA_VISIBLE_DEVICES=$A $PY hy_sweep.py --method motioncache --targets 2.0 --coarse-points 4 --bisect-iters 4 --pair-prompts 2 --hi 6 --out results/hy_sweep_motioncache_x2.json > "$LOG/hy_sweep_motioncache_x2.log" 2>&1
14
+ echo "motioncache sweep done $(date +%H:%M:%S) exit=$?"
15
+ echo "GPU-B2 SWEEPS DONE $(date +%H:%M:%S)"
hy_scan_points.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """MotionCache threshold scan on the HY-WorldPlay base -- same diagnostic as
3
+ mc_scan.py: what the compute fraction hides, i.e. whether the cacheable steps are
4
+ making *partial* token decisions or degenerating into whole-step skips.
5
+
6
+ CUDA_VISIBLE_DEVICES=4 python hy_mc_scan.py --schedule FxxF \
7
+ --thresholds 0.05,0.1,0.2,0.4,0.7,1.0 --out results/hy_mc_scan_FxxF.json
8
+ """
9
+ import argparse, json, os, statistics as st, sys
10
+ ROOT = os.path.dirname(os.path.abspath(__file__))
11
+ sys.path.insert(0, ROOT)
12
+ from hycache import harness as H
13
+ H.enter_repo()
14
+ import torch
15
+ from hycache.measure import make_ctrl
16
+
17
+ ap = argparse.ArgumentParser()
18
+ ap.add_argument("--schedule", default="FxxF")
19
+ ap.add_argument("--method", default="motioncache",
20
+ choices=["teacache", "flowcache", "taylorseer", "motioncache"])
21
+ ap.add_argument("--values", required=True)
22
+ ap.add_argument("--coefficients", default="results/hy_coeff.json")
23
+ ap.add_argument("--frames", type=int, default=61)
24
+ ap.add_argument("--num-cases", type=int, default=2)
25
+ ap.add_argument("--out", default=None)
26
+ ap.add_argument("--first-chunk", default=None, help="schedule for chunk 0, e.g. FFFF")
27
+ args = ap.parse_args()
28
+
29
+ COEFF = None
30
+ if args.coefficients and args.method in ("teacache", "flowcache"):
31
+ p = args.coefficients if os.path.isabs(args.coefficients) else os.path.join(ROOT, args.coefficients)
32
+ COEFF = json.load(open(p))["coefficients"]
33
+
34
+ pipe = H.load_pipeline()
35
+ cases = H.load_cases()
36
+ jobs = [(cases[i], H.ACTIONS[0]) for i in range(args.num_cases + 1)] # first = warm-up
37
+ forced = set(range(H.NUM_STEPS)) if False else None
38
+
39
+
40
+ def run(method, **kw):
41
+ ctrl = make_ctrl(pipe, method, schedule=args.schedule, coefficients=COEFF,
42
+ first_chunk_schedule=args.first_chunk, **kw)
43
+ ms, recs, chunk_ms = [], [], []
44
+ for i, (case, action) in enumerate(jobs):
45
+ _, _, t = H.generate(pipe, case, action, controller=ctrl, num_frames=args.frames, decode=False)
46
+ if i == 0:
47
+ continue
48
+ ms.append(t["denoise_dit_ms"])
49
+ per = t["per_step_denoise_ms"]
50
+ n = H.NUM_STEPS
51
+ chunk_ms.append([sum(per[b * n:(b + 1) * n]) for b in range(len(per) // n)])
52
+ # activity stats over the cacheable steps only (chunk 0 excluded when it is forced full)
53
+ recs += [r for r in ctrl.records if r["step"] not in ctrl.forced
54
+ and not (args.first_chunk and r["block"] == 0)]
55
+ # per-chunk denoise ms of the fastest (least contended) run, for extrapolation
56
+ best = chunk_ms[ms.index(min(ms))]
57
+ return min(ms), recs, ctrl.summary(), best
58
+
59
+
60
+ def extrapolate(chunks, n_target=8):
61
+ """Denoise ms for n_target chunks from a shorter run: chunks beyond the measured
62
+ ones cost what the last measured chunk cost (per-chunk cost is flat once the
63
+ context window is full)."""
64
+ return sum(chunks) + (n_target - len(chunks)) * chunks[-1]
65
+
66
+
67
+ PARAM = {"teacache": "thresh", "flowcache": "thresh", "motioncache": "thresh",
68
+ "taylorseer": "interval"}
69
+ pname = PARAM[args.method]
70
+
71
+ base_ms, _, _, base_chunks = run("none") # warm-up + reference point
72
+ print(f"baseline FFFF min denoise {base_ms:.0f} ms ({args.frames} frames, schedule {args.schedule})", flush=True)
73
+ print(f"{pname[:8]:>8}{'Full':>8}{'compute_x':>10}{'measured_x':>11}{'ext8_Full':>10}{'ext8_x':>8}{'active%':>9}{'empty%':>8}{'full%':>7}{'sel_mean%':>10}{'sel_p90%':>9}")
74
+ rows = []
75
+ for t in [float(v) for v in args.values.split(",")]:
76
+ b_ms, _, _, b_chunks = run("none")
77
+ ms, recs, summ, s_chunks = run(args.method, **{pname: t})
78
+ n_chunks = len(b_chunks)
79
+ # extrapolated 8-chunk (125-frame) figures: chunk 0 (forced full) is measured, the
80
+ # cacheable chunks' per-chunk cost is taken from the last measured chunk
81
+ ext_ms = extrapolate(s_chunks); ext_b = extrapolate(b_chunks)
82
+ fr = [r["compute_fraction"] for r in recs]
83
+ act = [f for f in fr if 1e-9 < f < 1 - 1e-9]
84
+ q = lambda v, p: sorted(v)[min(int(p * (len(v) - 1)), len(v) - 1)] if v else float("nan")
85
+ row = {"value": t, "param": pname, "method": args.method, "compute_equivalent": summ["compute_equivalent_forwards"],
86
+ "compute_speedup": summ["flops_speedup_estimate"], "measured_speedup": b_ms / ms, "paired_baseline_ms": b_ms,
87
+ "active_ratio": len(act) / len(fr), "empty_ratio": sum(f <= 1e-9 for f in fr) / len(fr),
88
+ "full_ratio": sum(f >= 1 - 1e-9 for f in fr) / len(fr),
89
+ "sel_mean": st.fmean(act) if act else 0.0, "sel_p90": q(act, .9), "min_denoise_ms": ms,
90
+ "measured_chunks": n_chunks, "ext8_measured_speedup": ext_b / ext_ms,
91
+ "ext8_compute_equivalent": summ["compute_equivalent_forwards"]
92
+ + (8 - n_chunks) * (summ["compute_equivalent_forwards"] - 4.0) / max(n_chunks - 1, 1)}
93
+ rows.append(row)
94
+ print(f"{t:>8.4g}{row['compute_equivalent']:>8.2f}{row['compute_speedup']:>10.3f}{row['measured_speedup']:>11.3f}"
95
+ f"{row['ext8_compute_equivalent']:>10.2f}{row['ext8_measured_speedup']:>8.3f}"
96
+ f"{100*row['active_ratio']:>9.1f}{100*row['empty_ratio']:>8.1f}{100*row['full_ratio']:>7.1f}"
97
+ f"{100*row['sel_mean']:>10.1f}{100*row['sel_p90']:>9.1f}", flush=True)
98
+ if args.out:
99
+ out = args.out if os.path.isabs(args.out) else os.path.join(ROOT, args.out)
100
+ os.makedirs(os.path.dirname(out), exist_ok=True)
101
+ json.dump({"base": "hy_worldplay", "method": args.method, "param": pname,
102
+ "schedule": args.schedule, "first_chunk_schedule": args.first_chunk, "frames": args.frames,
103
+ "baseline_ms": base_ms, "rows": rows}, open(out, "w"), indent=2)
104
+ print("wrote", out)
hy_smoke.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """FFFF smoke run on the HY-WorldPlay base: per-forward timing, peak memory, and a
3
+ bitwise/PSNR comparison against the DEV project's reference FFFF video for the
4
+ same case/action/seed (proves weights + environment reproduce their pipeline).
5
+
6
+ CUDA_VISIBLE_DEVICES=5 python hy_smoke.py --frames 61
7
+ CUDA_VISIBLE_DEVICES=5 python hy_smoke.py --frames 125 --compare
8
+ """
9
+ import argparse, json, os, sys, time
10
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
11
+ from hycache import harness as H
12
+
13
+ ap = argparse.ArgumentParser()
14
+ ap.add_argument("--frames", type=int, default=61)
15
+ ap.add_argument("--case", type=int, default=0)
16
+ ap.add_argument("--action", type=int, default=0)
17
+ ap.add_argument("--compare", action="store_true", help="save mp4 and compare with DEV FFFF video")
18
+ ap.add_argument("--out", default="/tmp/hy_smoke.mp4")
19
+ args = ap.parse_args()
20
+
21
+ H.enter_repo()
22
+ import torch
23
+ t0 = time.time()
24
+ pipe = H.load_pipeline()
25
+ print(f"pipeline loaded in {time.time()-t0:.0f}s; transformer blocks: "
26
+ f"{len(pipe.transformer.double_blocks)} double / {len(pipe.transformer.single_blocks)} single, "
27
+ f"attn_param keys: {sorted(pipe.transformer.attn_param)}", flush=True)
28
+ case = H.load_cases()[args.case]
29
+ action = H.ACTIONS[args.action]
30
+ video, latents, timing = H.generate(pipe, case, action, num_frames=args.frames,
31
+ decode=args.compare)
32
+ steps = timing["per_step_denoise_ms"]
33
+ print(json.dumps({k: (round(v, 1) if isinstance(v, float) else v)
34
+ for k, v in timing.items() if k != "per_step_denoise_ms"}, indent=1))
35
+ print(f"per-forward ms: n={len(steps)} min={min(steps):.0f} median={sorted(steps)[len(steps)//2]:.0f} max={max(steps):.0f}")
36
+ if args.compare:
37
+ from hyvideo.generate import save_video
38
+ save_video(video, args.out)
39
+ ref = os.path.join(H.DATASET, "validation/full",
40
+ f"case_{case['split_case_id']:04d}_action_{args.action:02d}.mp4")
41
+ import av, numpy as np
42
+ def frames(p):
43
+ with av.open(p) as c:
44
+ return np.stack([f.to_ndarray(format="rgb24") for f in c.decode(video=0)])
45
+ a, b = frames(args.out), frames(ref)
46
+ print("ours", a.shape, "ref", b.shape)
47
+ if a.shape == b.shape:
48
+ mse = ((a.astype(np.float64) - b) ** 2).mean()
49
+ print(f"PSNR vs DEV FFFF video: {10*np.log10(255**2/max(mse,1e-12)):.2f} dB (identical frames: {(a==b).all(axis=(1,2,3)).sum()}/{len(a)})")
hy_strategies.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Strategy list for the HY-WorldPlay evaluation.
2
+
3
+ FFFF plus three methods (FlowCache was dropped on Sep 4) at three points:
4
+ `FxxF` ~1.3x from the original compute-targeted sweep, and two slots targeted on
5
+ *measured* wall-clock speedup -- `FxxF` 1.70-1.80x and `Fxxx` 2.70-3.00x -- built
6
+ by ``build_points.py`` into ``results/hy_point_v2.json``.
7
+ """
8
+ import glob, json, os
9
+
10
+ ROOT = os.path.dirname(os.path.abspath(__file__))
11
+ METHOD_ORDER = ["teacache", "taylorseer", "motioncache", "none", "reuse"]
12
+ KEEP_FROM_SWEEP = {1.3} # 1.6x and 2.0x were dropped from the study
13
+
14
+
15
+ def load_strategies():
16
+ out = [{"name": "hy_ffff", "method": "none", "param": None, "value": None,
17
+ "target": 1.0, "schedule": "FxxF", "coefficients": None, "is_reference": True}]
18
+ coeff_path = os.path.join(ROOT, "results/hy_coeff.json")
19
+ coeff = json.load(open(coeff_path))["coefficients"] if os.path.exists(coeff_path) else None
20
+
21
+ rows = []
22
+ for p in sorted(glob.glob(os.path.join(ROOT, "results/hy_sweep_*.json"))):
23
+ d = json.load(open(p))
24
+ if d["method"] not in METHOD_ORDER:
25
+ continue
26
+ for pt in d["operating_points"]:
27
+ if pt["target_speedup"] not in KEEP_FROM_SWEEP:
28
+ continue
29
+ rows.append({"method": d["method"], "param": d["param"], "value": pt[d["param"]],
30
+ "target": pt["target_speedup"], "schedule": d.get("schedule", "FxxF"),
31
+ "source": os.path.basename(p)})
32
+ p2 = os.path.join(ROOT, "results/hy_point_v2.json")
33
+ if os.path.exists(p2):
34
+ for r in json.load(open(p2))["rows"]:
35
+ if r["method"] not in METHOD_ORDER:
36
+ continue
37
+ rows.append({"method": r["method"], "param": r["param"], "value": r["value"],
38
+ "target": r["target_speedup"], "schedule": r["schedule"],
39
+ "source": "hy_point_v2.json"})
40
+ # Naive baselines: fewer denoising steps (HY's scheduler re-derives the grid
41
+ # from num_inference_steps), and fixed-schedule direct reuse on the 4-step
42
+ # grid -- FRFF / FRRF / FRRR are 3 / 2 / 1 full DiT evaluations per chunk.
43
+ naive = []
44
+ for n in (3, 2, 1):
45
+ naive.append({"method": "none", "param": None, "value": None, "target": 0.0,
46
+ "schedule": "F" * n, "num_inference_steps": n,
47
+ "name": f"hy_naive{n}step", "source": "naive baseline"})
48
+ for sched, n_full in (("FRFF", 3), ("FRRF", 2), ("FRRR", 1)):
49
+ naive.append({"method": "reuse", "param": None, "value": None, "target": 0.0,
50
+ "schedule": sched, "num_inference_steps": 4,
51
+ "name": f"hy_reuse_{sched}", "source": "naive cache baseline"})
52
+ # Operating points re-searched under the first-chunk-FFFF configuration (Sep 7):
53
+ # results/hy_point_c0.json rows carry first_chunk_schedule and an explicit name.
54
+ p3 = os.path.join(ROOT, "results/hy_point_c0.json")
55
+ if os.path.exists(p3):
56
+ for r in json.load(open(p3))["rows"]:
57
+ rows.append({"method": r["method"], "param": r["param"], "value": r["value"],
58
+ "target": r["target_speedup"], "schedule": r["schedule"],
59
+ "first_chunk_schedule": r.get("first_chunk_schedule", "FFFF"),
60
+ "name": r["name"], "source": "hy_point_c0.json"})
61
+ # First-chunk-FFFF variants of the baselines: chunk 0 runs the full 4-step grid,
62
+ # chunks 1..7 the reduced grid (naive) or the reuse schedule.
63
+ for r in list(naive):
64
+ naive.append(dict(r, first_chunk_schedule="FFFF", name=r["name"] + "_c0FFFF",
65
+ source=r["source"] + " (chunk 0 FFFF)"))
66
+ rows.sort(key=lambda r: (METHOD_ORDER.index(r["method"]), r["schedule"] != "FxxF", r["target"]))
67
+ rows += naive
68
+ for r in rows:
69
+ tag = "" if r["schedule"].upper() == "FXXF" else f"_{r['schedule']}"
70
+ # TeaCache uses the refitted rescale polynomial; MotionCache does not (its
71
+ # per-token use would extrapolate a negative-slope fit, see README).
72
+ out.append(dict(r, name=r.get("name") or f"hy_{r['method']}{tag}_x{r['target']:g}", is_reference=False,
73
+ coefficients=coeff if r["method"] == "teacache" else None))
74
+ return out
75
+
76
+
77
+ if __name__ == "__main__":
78
+ for s in load_strategies():
79
+ v = "-" if s["value"] is None else f"{s['param']}={s['value']:.6g}"
80
+ print(f"{s['name']:28s} {s['schedule']:5s} {v}")
hy_sweep.py ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """Find the parameter that hits each target compute speedup on the HY-WorldPlay
3
+ base (the analogue of sweep.py; same protocol: search on the deterministic
4
+ compute fraction, then a paired A/B timing at the settled value).
5
+
6
+ Search videos are 61 frames (4 chunks x 4 steps = 16 forwards) on the first
7
+ ``--search-cases`` validation cases with the w/s action; the evaluation later uses
8
+ the full 125-frame protocol.
9
+
10
+ CUDA_VISIBLE_DEVICES=5 python hy_sweep.py --method teacache \
11
+ --coefficients results/hy_coeff.json --out results/hy_sweep_teacache.json
12
+ """
13
+ import argparse, json, os, sys, time
14
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
15
+ from hycache import harness as H
16
+ H.enter_repo()
17
+ import torch
18
+ from hycache.measure import evaluate, make_ctrl, paired_evaluate, taylorseer_compute
19
+
20
+ ROOT = os.path.dirname(os.path.abspath(__file__))
21
+ PARAM = {"teacache": ("thresh", 0.0, 4.0), "flowcache": ("thresh", 0.0, 4.0),
22
+ "motioncache": ("thresh", 0.0, 12.0), "taylorseer": ("interval", 1.0, 3.0)}
23
+
24
+ ap = argparse.ArgumentParser()
25
+ ap.add_argument("--method", choices=sorted(PARAM), required=True)
26
+ ap.add_argument("--schedule", default="FxxF")
27
+ ap.add_argument("--targets", default="1.3,1.6,2.0")
28
+ ap.add_argument("--coefficients", default=None)
29
+ ap.add_argument("--search-cases", type=int, default=3)
30
+ ap.add_argument("--frames", type=int, default=61)
31
+ ap.add_argument("--eval-frames", type=int, default=125,
32
+ help="TaylorSeer's compute fraction is analytic; aim it at the evaluation's chunk count")
33
+ ap.add_argument("--coarse-points", type=int, default=7)
34
+ ap.add_argument("--bisect-iters", type=int, default=6)
35
+ ap.add_argument("--pair-prompts", type=int, default=3)
36
+ ap.add_argument("--lo", type=float, default=None)
37
+ ap.add_argument("--hi", type=float, default=None)
38
+ ap.add_argument("--out", required=True)
39
+ args = ap.parse_args()
40
+ out_path = args.out if os.path.isabs(args.out) else os.path.join(ROOT, args.out)
41
+
42
+ coefficients = None
43
+ if args.coefficients:
44
+ p = args.coefficients if os.path.isabs(args.coefficients) else os.path.join(ROOT, args.coefficients)
45
+ coefficients = json.load(open(p))["coefficients"]
46
+
47
+ pipe = H.load_pipeline()
48
+ cases = H.load_cases()
49
+ search_jobs = [(cases[i], H.ACTIONS[0]) for i in range(args.search_cases)]
50
+ pair_jobs = [(cases[i], H.ACTIONS[0]) for i in range(args.pair_prompts + 1)]
51
+ pname, lo, hi = PARAM[args.method]
52
+ lo = args.lo if args.lo is not None else lo
53
+ hi = args.hi if args.hi is not None else hi
54
+ num_chunks = ((args.frames - 1) // 4 + 1) // H.CHUNK_LATENTS
55
+ eval_chunks = ((args.eval_frames - 1) // 4 + 1) // H.CHUNK_LATENTS
56
+ analytic = args.method == "taylorseer"
57
+
58
+
59
+ def ctrl_for(method, value):
60
+ kw = {pname: value} if method != "none" else {}
61
+ return make_ctrl(pipe, method, schedule=args.schedule, coefficients=coefficients, **kw)
62
+
63
+
64
+ def compute_fraction(value):
65
+ if analytic:
66
+ return taylorseer_compute(value, eval_chunks, H.NUM_STEPS, args.schedule)
67
+ r = evaluate(pipe, ctrl_for(args.method, value), search_jobs, num_frames=args.frames)
68
+ return r["flops_speedup_estimate"], r["mean_compute_equivalent_forwards"]
69
+
70
+
71
+ t0 = time.time()
72
+ print("=== warm-up ===", flush=True)
73
+ evaluate(pipe, ctrl_for("none", None), search_jobs[:1], num_frames=args.frames)
74
+
75
+ print(f"=== coarse scan on {pname} in [{lo}, {hi}] (compute fraction, {num_chunks} chunks) ===", flush=True)
76
+ curve = []
77
+ for i in range(args.coarse_points):
78
+ v = lo + (hi - lo) * i / (args.coarse_points - 1)
79
+ f, ce = compute_fraction(v)
80
+ curve.append({"value": v, "flops_speedup": f, "compute_equivalent": ce})
81
+ print(f" {pname}={v:.4f} flops_x={f:.4f} compute_eq={ce:.3f}", flush=True)
82
+
83
+ targets = [float(t) for t in args.targets.split(",")]
84
+ max_flops = max(c["flops_speedup"] for c in curve)
85
+ points = []
86
+ for target in targets:
87
+ goal = min(target, max_flops)
88
+ a, b = lo, hi
89
+ for c in curve:
90
+ if c["flops_speedup"] < goal:
91
+ a = max(a, c["value"])
92
+ for c in reversed(curve):
93
+ if c["flops_speedup"] >= goal:
94
+ b = min(b, c["value"])
95
+ best = None
96
+ for _ in range(args.bisect_iters):
97
+ mid = 0.5 * (a + b)
98
+ f, ce = compute_fraction(mid)
99
+ if best is None or abs(f - goal) < abs(best[1] - goal):
100
+ best = (mid, f, ce)
101
+ if f < goal:
102
+ a = mid
103
+ else:
104
+ b = mid
105
+ for end in (a, b):
106
+ f, ce = compute_fraction(end)
107
+ if abs(f - goal) < abs(best[1] - goal):
108
+ best = (end, f, ce)
109
+ value, f_at, ce_at = best
110
+ paired = paired_evaluate(pipe, lambda: ctrl_for("none", None),
111
+ lambda v=value: ctrl_for(args.method, v),
112
+ pair_jobs, num_frames=args.frames, warmup=1)
113
+ pt = {"target_speedup": target, pname: value, "flops_speedup": f_at,
114
+ "mean_compute_equivalent_forwards": ce_at,
115
+ "measured_speedup": paired["paired_speedup_median"],
116
+ "measured_speedup_from_minima": paired["speedup_from_minima"],
117
+ "measured_speedup_stdev": paired["paired_speedup_stdev"],
118
+ "paired_compute_equivalent": paired["paired_compute_equivalent"],
119
+ "median_baseline_ms": paired["median_baseline_ms"],
120
+ "median_method_ms": paired["median_method_ms"], "num_pairs": paired["num_pairs"]}
121
+ points.append(pt)
122
+ print(f"TARGET {target}x -> {pname}={value:.6g} measured={pt['measured_speedup']:.3f}x "
123
+ f"(+-{pt['measured_speedup_stdev']:.3f}) flops={f_at:.3f}x compute_eq={ce_at:.2f}", flush=True)
124
+
125
+ result = {"base": "hy_worldplay", "method": args.method, "param": pname, "schedule": args.schedule,
126
+ "coefficients": coefficients, "frames": args.frames, "num_chunks": num_chunks,
127
+ "search_cases": args.search_cases, "eval_frames": args.eval_frames,
128
+ "analytic_compute": analytic, "max_flops_speedup": max_flops, "curve": curve,
129
+ "operating_points": points, "sweep_seconds": time.time() - t0}
130
+ os.makedirs(os.path.dirname(out_path), exist_ok=True)
131
+ json.dump(result, open(out_path, "w"), indent=2)
132
+ print(f"wrote {out_path}", flush=True)
hy_sweep_queue.sh ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Queue of HY sweeps, one per free GPU among $GPUS (memory < 8 GB, not ours).
3
+ set -u
4
+ C=/local/zoubin/cz/projects/comparison; PY=/local/zoubin/cz/envs/hy_worldplay_july20260720/bin/python
5
+ LOG="$1"; GPUS=(${GPUS:-4 5 6 7})
6
+ export SSL_CERT_FILE=/etc/pki/tls/certs/ca-bundle.crt HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1
7
+ export HF_HOME=/local/zoubin/cz/checkpoints/hy_worldplay/huggingface HF_HUB_CACHE=/local/zoubin/cz/checkpoints/hy_worldplay/huggingface/hub
8
+ export TRANSFORMERS_CACHE=/local/zoubin/cz/checkpoints/hy_worldplay/huggingface/hub TORCH_HOME=/local/zoubin/cz/.cache/torch XDG_CACHE_HOME=/local/zoubin/cz/.cache
9
+ cd "$C"; COEFF=results/hy_coeff.json
10
+ # name | output json | args
11
+ JOBS=(
12
+ "teacache|results/hy_sweep_teacache.json|--method teacache --coefficients $COEFF --hi 1.0 --coarse-points 5 --bisect-iters 6 --pair-prompts 3"
13
+ "flowcache|results/hy_sweep_flowcache.json|--method flowcache --coefficients $COEFF --hi 1.0 --coarse-points 5 --bisect-iters 6 --pair-prompts 3"
14
+ "motioncache_a|results/hy_sweep_motioncache.json|--method motioncache --targets 1.3,1.6 --hi 6 --coarse-points 5 --bisect-iters 5 --pair-prompts 3"
15
+ "motioncache_x2|results/hy_sweep_motioncache_x2.json|--method motioncache --targets 2.0 --hi 6 --coarse-points 4 --bisect-iters 4 --pair-prompts 3"
16
+ )
17
+ declare -A BUSY; pids=()
18
+ free_gpu() {
19
+ for g in "${GPUS[@]}"; do
20
+ [ -n "${BUSY[$g]:-}" ] && kill -0 "${BUSY[$g]}" 2>/dev/null && continue
21
+ used=$(nvidia-smi --query-gpu=memory.used --format=csv,noheader,nounits -i "$g" 2>/dev/null | tr -d ' ')
22
+ [ -n "$used" ] && [ "$used" -lt 8000 ] && { echo "$g"; return; }
23
+ done
24
+ }
25
+ for job in "${JOBS[@]}"; do
26
+ IFS='|' read -r name out args <<<"$job"
27
+ [ -f "$out" ] && { echo "skip $name (done)"; continue; }
28
+ while true; do g=$(free_gpu); [ -n "$g" ] && break; sleep 60; done
29
+ echo "[$(date +%H:%M:%S)] $name -> GPU $g"
30
+ CUDA_VISIBLE_DEVICES=$g $PY hy_sweep.py $args --out "$out" > "$LOG/hy_sweep_$name.log" 2>&1 &
31
+ BUSY[$g]=$!; pids+=($!); sleep 90 # let it claim memory before the next scan
32
+ done
33
+ for p in "${pids[@]}"; do wait "$p"; done
34
+ echo "ALL HY SWEEPS DONE $(date +%H:%M:%S)"; ls results/hy_sweep_*.json
hy_test_exact.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """Bit-exactness of the re-implemented block loop and the selective path against
3
+ the stock forward, on one 61-frame video (4 chunks x 4 steps).
4
+
5
+ CUDA_VISIBLE_DEVICES=5 python hy_test_exact.py
6
+ """
7
+ import json, os, sys, time
8
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
9
+ from hycache import harness as H
10
+ H.enter_repo()
11
+ import torch
12
+ from hycache.methods import build_method
13
+ from hycache.patch import CacheController, install, parse_schedule
14
+
15
+ pipe = H.load_pipeline()
16
+ case = H.load_cases()[0]
17
+ action = H.ACTIONS[0]
18
+
19
+ def run(method_name, **kw):
20
+ ctrl = CacheController(build_method(method_name, **kw), num_steps=4,
21
+ forced_steps=parse_schedule("FxxF", 4))
22
+ install(pipe.transformer, ctrl)
23
+ t0 = time.time()
24
+ _, lat, timing = H.generate(pipe, case, action, controller=ctrl, num_frames=61, decode=False)
25
+ print(f"{method_name:12s} {kw} lat {tuple(lat.shape)} denoise {timing['denoise_dit_ms']:.0f} ms "
26
+ f"compute {ctrl.summary().get('compute_equivalent_forwards')}/{ctrl.summary().get('denoise_forwards')} "
27
+ f"peak {timing['peak_mem_gib']:.1f} GiB wall {time.time()-t0:.0f}s", flush=True)
28
+ return lat.float()
29
+
30
+ ref = run("none")
31
+ full = "--full" in sys.argv
32
+ if full:
33
+ ref2 = run("none")
34
+ print(" stock vs stock (determinism): max|d| =", (ref - ref2).abs().max().item())
35
+ checks = [("exactcheck", {"mode": "selective"}), ("taylorseer", {"interval": 1.0})]
36
+ if full:
37
+ checks.insert(0, ("exactcheck", {"mode": "reimpl"}))
38
+ for name, kw in checks:
39
+ lat = run(name, **kw)
40
+ print(f" stock vs {name} {kw}: max|d| = {(ref - lat).abs().max().item():.3e} "
41
+ f"mean|d| = {(ref - lat).abs().mean().item():.3e}", flush=True)
42
+ # a real cached run of each method, just to see it complete and what it computes
43
+ for name, kw in [("teacache", {"thresh": 0.1}), ("flowcache", {"thresh": 0.1}),
44
+ ("motioncache", {"thresh": 0.1}), ("taylorseer", {"interval": 3.0})]:
45
+ lat = run(name, **kw)
46
+ print(f" vs FFFF: mean|d| = {(ref - lat).abs().mean().item():.3e}", flush=True)
hy_vbench.sh ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # VBench-I2V-100 scoring for the HY-WorldPlay strategies: the eight dimensions the
3
+ # DEV project's validation25 protocol uses, in custom_input mode (prompt = the
4
+ # case caption), one strategy at a time, sharded over the GPUs in $GPUS.
5
+ # GPUS="5 6" hy_vbench.sh <logdir>
6
+ set -u
7
+ C=/local/zoubin/cz/projects/comparison
8
+ V=/local/zoubin/cz/projects/VBench
9
+ PY=/local/zoubin/cz/envs/vbench_eval/bin/python
10
+ LOG="$1"; shift
11
+ OUT=$C/eval_out_hy
12
+ GPUS=(${GPUS:-5 6})
13
+ # Core5: the five video-quality dimensions the HY-WorldPlay DEV protocol reports
14
+ # for validation25 (section 8.1), so these numbers line up with that project's tables.
15
+ DIMS=(subject_consistency background_consistency motion_smoothness aesthetic_quality imaging_quality)
16
+
17
+ export PYTHONPATH="$V:$C"
18
+ export VBENCH_CACHE_DIR=/local/zoubin/cz/.cache/vbench
19
+ export HF_HOME=/local/zoubin/cz/.cache/huggingface HF_HUB_CACHE=/local/zoubin/cz/.cache/huggingface/hub
20
+ export TRANSFORMERS_CACHE=/local/zoubin/cz/.cache/huggingface/hub TORCH_HOME=/local/zoubin/cz/.cache/torch
21
+ export XDG_CACHE_HOME=/local/zoubin/cz/.cache SSL_CERT_FILE=/etc/pki/tls/certs/ca-bundle.crt
22
+ mkdir -p "$LOG" "$OUT/vbench/raw" "$OUT/vbench/scores"
23
+
24
+ mapfile -t STRATS < <(ls "$OUT/generated_videos")
25
+ echo "scoring ${#STRATS[@]} strategies on GPUs ${GPUS[*]}"
26
+ cd "$V"
27
+ pids=()
28
+ for gi in "${!GPUS[@]}"; do
29
+ (
30
+ for i in $(seq $gi ${#GPUS[@]} $(( ${#STRATS[@]} - 1 ))); do
31
+ s="${STRATS[$i]}"
32
+ n=$(ls "$OUT/generated_videos/$s"/*.mp4 2>/dev/null | wc -l)
33
+ if [ "$n" -ne 100 ]; then echo "skip $s: $n videos (need 100)"; continue; fi
34
+ if [ -f "$OUT/vbench/scores/$s.json" ]; then echo "skip $s (already scored)"; continue; fi
35
+ $PY "$C/hy_vbench_prompts.py" --strategy "$s" --out-root "$OUT" || { echo "FAILED prompt map $s"; continue; }
36
+ ok=1
37
+ for d in "${DIMS[@]}"; do
38
+ od="$OUT/vbench/raw/$s/$d"; mkdir -p "$od"
39
+ if ls "$od"/*_eval_results.json >/dev/null 2>&1; then continue; fi
40
+ echo "[gpu ${GPUS[$gi]}] $s / $d $(date +%H:%M:%S)"
41
+ # VBench's evaluate.py always calls dist_init(), which binds MASTER_PORT
42
+ # (default 29500); concurrent workers on one host collide on it.
43
+ MASTER_ADDR=127.0.0.1 MASTER_PORT=$((29500 + gi)) RANK=0 LOCAL_RANK=0 WORLD_SIZE=1 \
44
+ CUDA_VISIBLE_DEVICES=${GPUS[$gi]} $PY "$V/evaluate.py" --videos_path "$OUT/generated_videos/$s" \
45
+ --dimension "$d" --mode custom_input --prompt_file "$OUT/vbench/prompts/$s.json" \
46
+ --load_ckpt_from_local True --imaging_quality_preprocessing_mode longer \
47
+ --output_path "$od" > "$LOG/vbench_${s}_$d.log" 2>&1 || { echo "[gpu ${GPUS[$gi]}] FAILED $s / $d"; ok=0; }
48
+ done
49
+ [ "$ok" -eq 1 ] && $PY "$C/hy_vbench_prompts.py" --strategy "$s" --out-root "$OUT" --collect
50
+ done
51
+ ) &
52
+ pids+=($!)
53
+ done
54
+ for p in "${pids[@]}"; do wait "$p"; done
55
+ echo "ALL HY VBENCH DONE"
hy_vbench_prompts.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """Prompt map (video filename -> caption) for VBench custom_input, and collection of
3
+ the eight raw result files into one score file per strategy."""
4
+ import argparse, glob, json, os
5
+ ap = argparse.ArgumentParser()
6
+ ap.add_argument("--strategy", required=True)
7
+ ap.add_argument("--out-root", required=True)
8
+ ap.add_argument("--collect", action="store_true")
9
+ a = ap.parse_args()
10
+ DIMS = ["subject_consistency", "background_consistency", "motion_smoothness",
11
+ "aesthetic_quality", "imaging_quality"]
12
+ recs = {os.path.basename(p)[:-5]: json.load(open(p))
13
+ for p in glob.glob(os.path.join(a.out_root, "per_prompt", a.strategy, "*.json"))}
14
+ if not a.collect:
15
+ pm = {stem + ".mp4": r["prompt"] for stem, r in recs.items()}
16
+ assert len(pm) == 100, len(pm)
17
+ os.makedirs(os.path.join(a.out_root, "vbench", "prompts"), exist_ok=True)
18
+ json.dump(pm, open(os.path.join(a.out_root, "vbench", "prompts", a.strategy + ".json"), "w"), indent=1, sort_keys=True)
19
+ print(f"{a.strategy}: {len(pm)} prompts")
20
+ else:
21
+ out = {"strategy": a.strategy, "num_videos": len(recs), "raw": {}, "per_video": {}}
22
+ for d in DIMS:
23
+ fs = glob.glob(os.path.join(a.out_root, "vbench", "raw", a.strategy, d, "*_eval_results.json"))
24
+ assert len(fs) == 1, (d, fs)
25
+ overall, videos = json.load(open(fs[0]))[d]
26
+ assert len(videos) == 100, (d, len(videos))
27
+ out["raw"][d] = overall
28
+ out["per_video"][d] = {os.path.basename(v["video_path"]): v["video_results"] for v in videos}
29
+ json.dump(out, open(os.path.join(a.out_root, "vbench", "scores", a.strategy + ".json"), "w"), indent=1)
30
+ print(f"{a.strategy}: collected", {d: round(v, 4) for d, v in out["raw"].items()})
logs_cfa_driver.log ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ === cfa generation (11:41:20) gpus=0 1 2 3 ===
2
+ === cfa generation done (12:26:31) status=0 ===
3
+ eval/run_predictor_eval.sh: line 35: /local/zoubin/cz/projects/comparison/eval/run_vbench_all.sh: Permission denied
4
+ === aggregating (12:26:31) ===
5
+ strategy videos lat_ms speedup% psnr ssim lpips sel_vbench%
6
+ ----------------------------------------------------------------------------------------
7
+ cf_flowcache_x1.3 251 2683.3 14.98 13.26 0.5272 0.3415 81.822
8
+ cf_flowcache_x1.6 251 2086.4 33.89 11.74 0.4424 0.4744 80.421
9
+ cf_flowcache_x2 251 1612.3 48.92 11.90 0.4402 0.4835 79.968
10
+ cf_flowcache_Fxxx_x3 251 1630.3 48.35 11.34 0.3387 0.6278 65.173
11
+ cf_motioncache_x1.3 251 2716.4 13.93 12.07 0.4614 0.4450 81.248
12
+ cf_motioncache_x1.6 251 2243.4 28.92 11.91 0.4404 0.4737 80.827
13
+ cf_motioncache_x2 251 1618.6 48.72 11.90 0.4402 0.4835 79.991
14
+ cf_motioncache_Fxxx_x3 251 2272.7 27.99 10.94 0.2716 0.6802 60.986
15
+ cf_ffff 251 3156.1 0.00 120.00 1.0000 0.0000 81.166
16
+ cf_taylorseer_FFxx_x1.3 251 3512.5 -11.29 11.39 0.4381 0.4580 80.257
17
+ cf_taylorseer_x1.3 251 2437.8 22.76 11.99 0.4488 0.4509 81.625
18
+ cf_taylorseer_FFxx_x1.6 251 2927.3 7.25 9.92 0.3015 0.6262 65.895
19
+ cf_taylorseer_x1.6 251 2008.2 36.37 12.17 0.4082 0.5063 80.421
20
+ cf_taylorseer_FFxx_x2 251 2309.7 26.82 8.79 0.1646 0.8242 57.312
21
+ cf_taylorseer_x2 251 1666.3 47.20 12.16 0.3995 0.5260 79.741
22
+ cf_teacache_x1.3 251 2488.5 21.15 13.23 0.5272 0.3419 81.224
23
+ cf_teacache_x1.6 251 2058.4 34.78 11.93 0.4590 0.4511 81.209
24
+ cf_teacache_x2 251 1607.0 49.08 11.90 0.4402 0.4835 79.968
25
+ cf_teacache_Fxxx_x3 251 1542.4 51.13 11.35 0.3356 0.6346 65.019
26
+ cfa_ffff 251 3225.3 0.00 120.00 1.0000 0.0000 -
27
+ cfa_atc_chunk_fppf 251 1900.5 41.08 14.64 0.6532 0.2215 -
28
+ cfa_atc_chunk_fppp 251 1238.6 61.60 14.33 0.6088 0.3012 -
29
+ cfa_atc_last_frame_fppf 251 1897.4 41.17 14.62 0.6531 0.2217 -
30
+ cfa_atc_last_frame_fppp 251 1234.6 61.72 14.30 0.6096 0.3005 -
31
+ cfa_disca_fppf 251 1857.5 42.41 14.55 0.6516 0.2213 -
32
+ cfa_disca_fppp 251 1157.3 64.12 14.07 0.5782 0.3242 -
33
+ sf_flowcache_x1.3 251 2547.8 19.32 15.15 0.5325 0.3202 79.621
34
+ sf_flowcache_x1.6 251 2215.6 29.84 12.99 0.4339 0.4659 78.500
35
+ sf_flowcache_x2 251 1613.5 48.91 13.02 0.4222 0.4854 78.774
36
+ sf_flowcache_Fxxx_x3 251 1158.3 69.16 12.01 0.2866 0.6946 55.800
37
+ sf_motioncache_x1.3 251 2762.3 12.53 13.26 0.4499 0.4431 79.229
38
+ sf_motioncache_x1.6 251 2127.0 32.65 13.13 0.4332 0.4722 79.491
39
+ sf_motioncache_x2 251 1621.1 48.67 13.02 0.4222 0.4854 78.781
40
+ sf_motioncache_Fxxx_x3 251 1830.5 51.58 12.24 0.2860 0.6889 59.279
41
+ sf_ffff 251 3158.0 0.00 120.00 1.0000 0.0000 80.537
42
+ sf_taylorseer_FFxx_x1.3 251 3012.0 19.82 13.13 0.4449 0.4290 79.220
43
+ sf_taylorseer_x1.3 251 2439.2 22.76 13.31 0.4421 0.4469 79.831
44
+ sf_taylorseer_FFxx_x1.6 251 2454.9 34.65 11.32 0.3028 0.6140 66.382
45
+ sf_taylorseer_x1.6 251 2008.9 36.39 13.40 0.4082 0.5029 79.082
46
+ sf_taylorseer_FFxx_x2 251 1970.8 47.87 9.63 0.1555 0.8272 57.177
47
+ sf_taylorseer_x2 251 1667.0 47.21 13.49 0.3974 0.5240 78.275
48
+ sf_teacache_x1.3 251 2547.5 19.33 15.16 0.5325 0.3198 79.588
49
+ sf_teacache_x1.6 251 2187.4 30.73 13.12 0.4428 0.4520 78.995
50
+ sf_teacache_x2 251 1608.2 49.07 13.02 0.4222 0.4854 78.774
51
+ sf_teacache_Fxxx_x3 251 1066.3 71.45 11.95 0.2851 0.7049 58.678
52
+
53
+ notes:
54
+ - cfa_atc_chunk_fppf: no VBench scores yet
55
+ - cfa_atc_chunk_fppp: no VBench scores yet
56
+ - cfa_atc_last_frame_fppf: no VBench scores yet
57
+ - cfa_atc_last_frame_fppp: no VBench scores yet
58
+ - cfa_disca_fppf: no VBench scores yet
59
+ - cfa_disca_fppp: no VBench scores yet
60
+ - cfa_ffff: no VBench scores yet
61
+
62
+ wrote /local/zoubin/cz/projects/comparison/eval_out/summaries/final_summary.json
63
+ wrote /local/zoubin/cz/projects/comparison/eval_out/summaries/final_summary.csv
64
+ ALL CFA PHASES DONE 12:26:32
logs_cfa_vbench_driver.log ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ scoring 45 strategies across 4 GPUs
2
+ skip cf_ffff (already scored)
3
+ skip cf_flowcache_x2 (already scored)
4
+ skip cf_motioncache_x2 (already scored)
5
+ skip cf_taylorseer_x1.3 (already scored)
6
+ skip cf_teacache_x1.3 (already scored)
7
+ skip cf_flowcache_Fxxx_x3 (already scored)
8
+ skip cf_motioncache_Fxxx_x3 (already scored)
9
+ skip cf_taylorseer_FFxx_x1.3 (already scored)
10
+ skip cf_taylorseer_x1.6 (already scored)
11
+ skip cf_teacache_x1.6 (already scored)
12
+ skip cf_flowcache_x1.3 (already scored)
13
+ skip cf_motioncache_x1.3 (already scored)
14
+ skip cf_taylorseer_FFxx_x1.6 (already scored)
15
+ skip cf_taylorseer_x2 (already scored)
16
+ skip cf_teacache_x2 (already scored)
17
+ skip cf_flowcache_x1.6 (already scored)
18
+ skip cf_motioncache_x1.6 (already scored)
19
+ skip cf_taylorseer_FFxx_x2 (already scored)
20
+ skip cf_teacache_Fxxx_x3 (already scored)
21
+ [gpu 0] cfa_atc_chunk_fppp 12:27:28
22
+ [gpu 1] cfa_atc_last_frame_fppf 12:27:28
23
+ [gpu 2] cfa_atc_last_frame_fppp 12:27:28
24
+ [gpu 3] cfa_atc_chunk_fppf 12:27:28
25
+ [gpu 0] cfa_disca_fppp 12:59:00
26
+ [gpu 3] cfa_disca_fppf 12:59:31
27
+ [gpu 1] cfa_ffff 12:59:43
28
+ skip sf_ffff (already scored)
29
+ skip sf_flowcache_x2 (already scored)
30
+ skip sf_motioncache_x2 (already scored)
31
+ skip sf_taylorseer_x1.3 (already scored)
32
+ skip sf_teacache_x1.3 (already scored)
33
+ skip sf_flowcache_Fxxx_x3 (already scored)
34
+ skip sf_motioncache_Fxxx_x3 (already scored)
35
+ skip sf_taylorseer_FFxx_x1.3 (already scored)
36
+ skip sf_taylorseer_x1.6 (already scored)
37
+ skip sf_teacache_x1.6 (already scored)
38
+ skip sf_flowcache_x1.6 (already scored)
39
+ skip sf_motioncache_x1.6 (already scored)
40
+ skip sf_taylorseer_FFxx_x2 (already scored)
41
+ skip sf_teacache_Fxxx_x3 (already scored)
42
+ skip sf_flowcache_x1.3 (already scored)
43
+ skip sf_motioncache_x1.3 (already scored)
44
+ skip sf_taylorseer_FFxx_x1.6 (already scored)
45
+ skip sf_taylorseer_x2 (already scored)
46
+ skip sf_teacache_x2 (already scored)
47
+ ALL VBENCH DONE
48
+ === aggregating (13:16:42) ===
49
+ strategy videos lat_ms speedup% psnr ssim lpips sel_vbench%
50
+ ----------------------------------------------------------------------------------------
51
+ cf_flowcache_x1.3 251 2683.3 14.98 13.26 0.5272 0.3415 81.822
52
+ cf_flowcache_x1.6 251 2086.4 33.89 11.74 0.4424 0.4744 80.421
53
+ cf_flowcache_x2 251 1612.3 48.92 11.90 0.4402 0.4835 79.968
54
+ cf_flowcache_Fxxx_x3 251 1569.6 63.30 11.34 0.3387 0.6278 65.173
55
+ cf_motioncache_x1.3 251 2716.4 13.93 12.07 0.4614 0.4450 81.248
56
+ cf_motioncache_x1.6 251 2243.4 28.92 11.91 0.4404 0.4737 80.827
57
+ cf_motioncache_x2 251 1618.6 48.72 11.90 0.4402 0.4835 79.991
58
+ cf_motioncache_Fxxx_x3 251 2200.1 48.68 10.94 0.2716 0.6802 60.986
59
+ cf_ffff 251 3156.1 0.00 120.00 1.0000 0.0000 81.166
60
+ cf_taylorseer_FFxx_x1.3 251 3465.2 18.98 11.39 0.4381 0.4580 80.257
61
+ cf_taylorseer_x1.3 251 2437.8 22.76 11.99 0.4488 0.4509 81.625
62
+ cf_taylorseer_FFxx_x1.6 251 2821.5 34.19 9.92 0.3015 0.6262 65.895
63
+ cf_taylorseer_x1.6 251 2008.2 36.37 12.17 0.4082 0.5063 80.421
64
+ cf_taylorseer_FFxx_x2 251 2241.9 47.70 8.79 0.1646 0.8242 57.312
65
+ cf_taylorseer_x2 251 1666.3 47.20 12.16 0.3995 0.5260 79.741
66
+ cf_teacache_x1.3 251 2488.5 21.15 13.23 0.5272 0.3419 81.224
67
+ cf_teacache_x1.6 251 2058.4 34.78 11.93 0.4590 0.4511 81.209
68
+ cf_teacache_x2 251 1607.0 49.08 11.90 0.4402 0.4835 79.968
69
+ cf_teacache_Fxxx_x3 251 1477.1 65.46 11.35 0.3356 0.6346 65.019
70
+ cfa_ffff 251 3225.3 0.00 120.00 1.0000 0.0000 81.166
71
+ cfa_atc_chunk_fppf 251 1900.5 41.08 14.64 0.6532 0.2215 81.550
72
+ cfa_atc_chunk_fppp 251 1238.6 61.60 14.33 0.6088 0.3012 77.340
73
+ cfa_atc_last_frame_fppf 251 1897.4 41.17 14.62 0.6531 0.2217 81.273
74
+ cfa_atc_last_frame_fppp 251 1234.6 61.72 14.30 0.6096 0.3005 77.384
75
+ cfa_disca_fppf 251 1857.5 42.41 14.55 0.6516 0.2213 81.437
76
+ cfa_disca_fppp 251 1157.3 64.12 14.07 0.5782 0.3242 75.958
77
+ sf_flowcache_x1.3 251 2547.8 19.32 15.15 0.5325 0.3202 79.621
78
+ sf_flowcache_x1.6 251 2215.6 29.84 12.99 0.4339 0.4659 78.500
79
+ sf_flowcache_x2 251 1613.5 48.91 13.02 0.4222 0.4854 78.774
80
+ sf_flowcache_Fxxx_x3 251 991.9 68.95 12.01 0.2866 0.6946 55.800
81
+ sf_motioncache_x1.3 251 2762.3 12.53 13.26 0.4499 0.4431 79.229
82
+ sf_motioncache_x1.6 251 2127.0 32.65 13.13 0.4332 0.4722 79.491
83
+ sf_motioncache_x2 251 1621.1 48.67 13.02 0.4222 0.4854 78.781
84
+ sf_motioncache_Fxxx_x3 251 1637.5 48.76 12.24 0.2860 0.6889 59.279
85
+ sf_ffff 251 3158.0 0.00 120.00 1.0000 0.0000 80.537
86
+ sf_taylorseer_FFxx_x1.3 251 2603.7 18.49 13.13 0.4449 0.4290 79.220
87
+ sf_taylorseer_x1.3 251 2439.2 22.76 13.31 0.4421 0.4469 79.831
88
+ sf_taylorseer_FFxx_x1.6 251 2114.2 33.81 11.32 0.3028 0.6140 66.382
89
+ sf_taylorseer_x1.6 251 2008.9 36.39 13.40 0.4082 0.5029 79.082
90
+ sf_taylorseer_FFxx_x2 251 1697.1 46.90 9.63 0.1555 0.8272 57.177
91
+ sf_taylorseer_x2 251 1667.0 47.21 13.49 0.3974 0.5240 78.275
92
+ sf_teacache_x1.3 251 2547.5 19.33 15.16 0.5325 0.3198 79.588
93
+ sf_teacache_x1.6 251 2187.4 30.73 13.12 0.4428 0.4520 78.995
94
+ sf_teacache_x2 251 1608.2 49.07 13.02 0.4222 0.4854 78.774
95
+ sf_teacache_Fxxx_x3 251 918.0 71.25 11.95 0.2851 0.7049 58.678
96
+
97
+ wrote /local/zoubin/cz/projects/comparison/eval_out/summaries/final_summary.json
98
+ wrote /local/zoubin/cz/projects/comparison/eval_out/summaries/final_summary.csv
99
+ ALL CFA PHASES DONE 13:16:43
logs_lb_pred_driver.log ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ === generation on GPUs 0 1 2 3 (08:21:52) models=atc_chunk,disca patterns=FPPF,FPF,FPPP ===
2
+ === generation done rc=0 (09:08:46) ===
3
+ scoring 34 strategies on GPUs 0 1 2 3
4
+ lb_disca_fpf: 100 prompts
5
+ lb_atc_chunk_fpf: 100 prompts
6
+ lb_atc_chunk_fppf: 100 prompts
7
+ lb_atc_chunk_fppp: 100 prompts
8
+ [gpu 3] lb_disca_fpf / subject_consistency 09:08:46
9
+ [gpu 1] lb_atc_chunk_fppf / subject_consistency 09:08:46
10
+ [gpu 0] lb_atc_chunk_fpf / subject_consistency 09:08:46
11
+ [gpu 2] lb_atc_chunk_fppp / subject_consistency 09:08:46
12
+ [gpu 0] lb_atc_chunk_fpf / background_consistency 09:12:22
13
+ [gpu 3] lb_disca_fpf / background_consistency 09:12:23
14
+ [gpu 1] lb_atc_chunk_fppf / background_consistency 09:12:23
15
+ [gpu 2] lb_atc_chunk_fppp / background_consistency 09:12:35
16
+ [gpu 0] lb_atc_chunk_fpf / motion_smoothness 09:14:36
17
+ [gpu 3] lb_disca_fpf / motion_smoothness 09:14:37
18
+ [gpu 1] lb_atc_chunk_fppf / motion_smoothness 09:14:37
19
+ [gpu 2] lb_atc_chunk_fppp / motion_smoothness 09:15:04
20
+ [gpu 0] lb_atc_chunk_fpf / aesthetic_quality 09:36:12
21
+ [gpu 2] lb_atc_chunk_fppp / aesthetic_quality 09:37:08
22
+ [gpu 3] lb_disca_fpf / aesthetic_quality 09:38:17
23
+ [gpu 1] lb_atc_chunk_fppf / aesthetic_quality 09:38:17
24
+ [gpu 0] lb_atc_chunk_fpf / imaging_quality 09:38:54
25
+ [gpu 2] lb_atc_chunk_fppp / imaging_quality 09:39:49
26
+ [gpu 3] lb_disca_fpf / imaging_quality 09:40:38
27
+ [gpu 1] lb_atc_chunk_fppf / imaging_quality 09:40:40
28
+ lb_atc_chunk_fpf: collected {'subject_consistency': 0.8521, 'background_consistency': 0.8996, 'motion_smoothness': 0.9768, 'aesthetic_quality': 0.5931, 'imaging_quality': 0.69}
29
+ lb_disca_fppf: 100 prompts
30
+ [gpu 0] lb_disca_fppf / subject_consistency 09:46:48
31
+ lb_atc_chunk_fppp: collected {'subject_consistency': 0.761, 'background_consistency': 0.8444, 'motion_smoothness': 0.9745, 'aesthetic_quality': 0.4925, 'imaging_quality': 0.6104}
32
+ skip lb_ffff (already scored)
33
+ skip lb_motioncache_x1.75 (already scored)
34
+ skip lb_naive2step (already scored)
35
+ skip lb_reuse_FRFF (already scored)
36
+ skip lb_reuse_FRRR (already scored)
37
+ skip lb_taylorseer_x1.3 (already scored)
38
+ skip lb_teacache_Fxxx_x2.85_c0FFFF (already scored)
39
+ lb_disca_fpf: collected {'subject_consistency': 0.8532, 'background_consistency': 0.8999, 'motion_smoothness': 0.977, 'aesthetic_quality': 0.5946, 'imaging_quality': 0.6905}
40
+ skip lb_motioncache_Fxxx_x2.85 (already scored)
41
+ skip lb_motioncache_x1.75_c0FFFF (already scored)
42
+ skip lb_naive2step_c0FFFF (already scored)
43
+ skip lb_reuse_FRFF_c0FFFF (already scored)
44
+ skip lb_reuse_FRRR_c0FFFF (already scored)
45
+ skip lb_taylorseer_x1.75 (already scored)
46
+ skip lb_teacache_x1.3 (already scored)
47
+ lb_atc_chunk_fppf: collected {'subject_consistency': 0.8491, 'background_consistency': 0.8969, 'motion_smoothness': 0.9769, 'aesthetic_quality': 0.5896, 'imaging_quality': 0.6875}
48
+ lb_disca_fppp: 100 prompts
49
+ [gpu 1] lb_disca_fppp / subject_consistency 09:48:44
50
+ [gpu 0] lb_disca_fppf / background_consistency 09:50:27
51
+ [gpu 1] lb_disca_fppp / background_consistency 09:52:26
52
+ [gpu 0] lb_disca_fppf / motion_smoothness 09:52:38
53
+ [gpu 1] lb_disca_fppp / motion_smoothness 09:54:51
54
+ [gpu 0] lb_disca_fppf / aesthetic_quality 09:56:47
55
+ [gpu 1] lb_disca_fppp / aesthetic_quality 09:58:37
56
+ [gpu 0] lb_disca_fppf / imaging_quality 09:59:08
57
+ [gpu 1] lb_disca_fppp / imaging_quality 10:01:06
58
+ lb_disca_fppf: collected {'subject_consistency': 0.8498, 'background_consistency': 0.8978, 'motion_smoothness': 0.9771, 'aesthetic_quality': 0.5886, 'imaging_quality': 0.6882}
59
+ skip lb_motioncache_Fxxx_x2.85_c0FFFF (already scored)
60
+ skip lb_naive1step (already scored)
61
+ skip lb_naive3step (already scored)
62
+ skip lb_reuse_FRRF (already scored)
63
+ skip lb_taylorseer_Fxxx_x2.85 (already scored)
64
+ skip lb_taylorseer_x1.75_c0FFFF (already scored)
65
+ skip lb_teacache_x1.75 (already scored)
66
+ lb_disca_fppp: collected {'subject_consistency': 0.7487, 'background_consistency': 0.8351, 'motion_smoothness': 0.9723, 'aesthetic_quality': 0.486, 'imaging_quality': 0.6399}
67
+ skip lb_motioncache_x1.3 (already scored)
68
+ skip lb_naive1step_c0FFFF (already scored)
69
+ skip lb_naive3step_c0FFFF (already scored)
70
+ skip lb_reuse_FRRF_c0FFFF (already scored)
71
+ skip lb_taylorseer_Fxxx_x2.85_c0FFFF (already scored)
72
+ skip lb_teacache_Fxxx_x2.85 (already scored)
73
+ skip lb_teacache_x1.75_c0FFFF (already scored)
74
+ ALL LB VBENCH DONE
75
+ === aggregating (10:06:35) ===
76
+ strategy lat_ms ffff_ms x Full PSNR LPIPS raw% norm%
77
+ lb_ffff 6094 6094 1.000 32.00 120.00 0.000 82.35 80.26
78
+ lb_naive1step 1542 6099 3.955 8.00 14.20 0.437 75.17 72.25
79
+ lb_naive1step_c0FFFF 1960 6099 3.111 11.00 15.43 0.357 76.66 73.95
80
+ lb_naive2step 3062 6099 1.992 16.00 14.95 0.370 80.52 78.32
81
+ lb_naive2step_c0FFFF 3342 6099 1.825 18.00 16.16 0.301 80.87 78.72
82
+ lb_naive3step 4582 6099 1.331 24.00 15.37 0.336 82.13 80.08
83
+ lb_naive3step_c0FFFF 4720 6099 1.292 25.00 16.47 0.276 82.16 80.11
84
+ lb_teacache_x1.3 4645 6099 1.313 24.00 15.93 0.309 82.15 80.13
85
+ lb_teacache_x1.75 4331 6099 1.408 22.07 15.66 0.339 80.98 78.81
86
+ lb_teacache_x1.75_c0FFFF 3440 6099 1.773 18.00 16.66 0.327 78.91 76.32
87
+ lb_teacache_Fxxx_x2.85 2895 6099 2.106 14.41 13.44 0.550 75.14 71.62
88
+ lb_teacache_Fxxx_x2.85_c0FFFF 3324 6099 1.835 17.35 15.71 0.387 76.70 73.52
89
+ lb_taylorseer_x1.3 5024 6099 1.214 25.00 16.04 0.313 81.83 79.81
90
+ lb_taylorseer_x1.75 3405 6099 1.791 16.00 15.13 0.459 76.62 73.85
91
+ lb_taylorseer_x1.75_c0FFFF 3860 6099 1.580 19.00 16.25 0.397 77.47 74.76
92
+ lb_taylorseer_Fxxx_x2.85 2535 6099 2.406 11.00 11.43 0.765 70.86 65.44
93
+ lb_taylorseer_Fxxx_x2.85_c0FFFF 2372 6099 2.572 11.00 12.11 0.708 62.06 53.70
94
+ lb_motioncache_x1.3 5071 6099 1.203 24.71 16.00 0.311 81.24 79.14
95
+ lb_motioncache_x1.75 3836 6099 1.590 18.06 15.50 0.373 79.49 77.08
96
+ lb_motioncache_x1.75_c0FFFF 3733 6099 1.634 18.01 16.66 0.327 78.91 76.32
97
+ lb_motioncache_Fxxx_x2.85 2357 6099 2.587 8.38 11.08 0.792 71.02 64.62
98
+ lb_motioncache_Fxxx_x2.85_c0FFFF 2266 6099 2.691 11.00 12.19 0.698 62.03 53.91
99
+ lb_reuse_FRFF 4574 6094 1.332 24.00 15.86 0.308 82.07 80.03
100
+ lb_reuse_FRFF_c0FFFF 4721 6099 1.292 25.00 17.29 0.238 82.19 80.16
101
+ lb_reuse_FRRF 3059 6094 1.992 16.00 14.87 0.429 76.77 73.57
102
+ lb_reuse_FRRF_c0FFFF 3341 6099 1.825 18.00 16.00 0.379 76.94 73.74
103
+ lb_reuse_FRRR 1542 6094 3.952 8.00 10.16 0.844 71.54 65.45
104
+ lb_reuse_FRRR_c0FFFF 1962 6099 3.109 11.00 11.30 0.740 62.12 53.96
105
+ lb_atc_chunk_fppf 3536 6111 1.728 18.47 17.30 0.278 80.00 77.81
106
+ lb_disca_fppf 3482 6111 1.755 18.47 17.28 0.277 80.03 77.85
107
+ lb_atc_chunk_fpf 3446 6111 1.774 18.23 16.77 0.294 80.23 78.06
108
+ lb_disca_fpf 3414 6111 1.790 18.23 16.73 0.293 80.30 78.15
109
+ lb_atc_chunk_fppp 2257 6111 2.707 11.70 16.58 0.390 73.65 70.66
110
+ lb_disca_fppp 2167 6111 2.820 11.70 16.52 0.386 73.64 70.43
111
+ wrote /local/zoubin/cz/projects/comparison/Experiment.md
112
+ ALL LB PREDICTOR EVAL DONE 10:06:37
mc_profile.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """How does a selective (partial-token) step actually cost, as a function of the
3
+ selected fraction? Times the block stack directly: full forward vs selective
4
+ forward at several ratios, plus the components of a selective step.
5
+ """
6
+ import os, sys, time
7
+ ROOT = os.path.dirname(os.path.abspath(__file__)); sys.path.insert(0, ROOT)
8
+ from harness import BASES, enter_base, load_pipeline, load_prompts
9
+ base = enter_base("self_forcing")
10
+ import torch
11
+ from utils.misc import set_seed
12
+ from cachelib import CacheController, build_method, cached_inference, install
13
+ from cachelib.methods import run_blocks_full
14
+ from cachelib.selective import run_blocks_selective
15
+
16
+ torch.set_grad_enabled(False)
17
+ pipe = load_pipeline(base)
18
+ captured = {}
19
+
20
+ class Capture(build_method("none").__class__):
21
+ name = "capture"
22
+ def forward(self, ctx):
23
+ if ctx.block_idx == 3 and ctx.step_idx == 1 and not captured:
24
+ captured["ctx"] = ctx
25
+ return run_blocks_full(ctx.model, ctx.x, ctx.kwargs, ctx.kv_cache,
26
+ ctx.crossattn_cache, ctx.current_start, ctx.cache_start), 1.0
27
+
28
+ ctrl = CacheController(Capture(), num_steps=4, forced_steps=(0, 3))
29
+ install(pipe.generator.model, ctrl)
30
+ set_seed(0)
31
+ noise = torch.randn([1, 21, 16, 60, 104], device="cuda", dtype=torch.bfloat16)
32
+ cached_inference(pipe, ctrl, noise, [load_prompts(1)[0]], decode=False)
33
+ ctx = captured["ctx"]
34
+ L = ctx.x.shape[1]
35
+ print(f"chunk tokens L = {L}, blocks = {len(ctx.model.blocks)}", flush=True)
36
+
37
+ def timeit(fn, n=5):
38
+ for _ in range(2): fn()
39
+ torch.cuda.synchronize(); t0 = time.perf_counter()
40
+ for _ in range(n): fn()
41
+ torch.cuda.synchronize(); return (time.perf_counter() - t0) / n * 1000
42
+
43
+ full_ms = timeit(lambda: run_blocks_full(ctx.model, ctx.x, ctx.kwargs, ctx.kv_cache,
44
+ ctx.crossattn_cache, ctx.current_start, ctx.cache_start))
45
+ print(f"full block stack: {full_ms:.1f} ms", flush=True)
46
+ print(f"{'ratio':>7}{'n_sel':>8}{'ms':>9}{'% of full':>11}")
47
+ import argparse
48
+ if os.environ.get("MC_PROFILE_OPS"):
49
+ from torch.profiler import profile, ProfilerActivity
50
+ sel = torch.arange(46, device=ctx.x.device)
51
+ fn = lambda: run_blocks_selective(ctx.model, ctx.x, sel, ctx.e0, ctx.kwargs,
52
+ ctx.kv_cache, ctx.crossattn_cache,
53
+ ctx.current_start, ctx.cache_start, ctx.grid_sizes)
54
+ for _ in range(3): fn()
55
+ torch.cuda.synchronize()
56
+ with profile(activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA]) as prof:
57
+ for _ in range(3): fn()
58
+ torch.cuda.synchronize()
59
+ print("\n=== selective step, n_sel=46 (1%): top CUDA ops ===")
60
+ print(prof.key_averages().table(sort_by="cuda_time_total", row_limit=14))
61
+ ffn = lambda: run_blocks_full(ctx.model, ctx.x, ctx.kwargs, ctx.kv_cache,
62
+ ctx.crossattn_cache, ctx.current_start, ctx.cache_start)
63
+ for _ in range(2): ffn()
64
+ torch.cuda.synchronize()
65
+ with profile(activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA]) as prof2:
66
+ for _ in range(3): ffn()
67
+ torch.cuda.synchronize()
68
+ print("\n=== full step: top CUDA ops ===")
69
+ print(prof2.key_averages().table(sort_by="cuda_time_total", row_limit=10))
70
+ sys.exit(0)
71
+
72
+ for r in (0.005, 0.01, 0.02, 0.05, 0.1, 0.25, 0.5, 1.0):
73
+ n = max(1, int(r * L))
74
+ sel = torch.arange(n, device=ctx.x.device)
75
+ ms = timeit(lambda: run_blocks_selective(ctx.model, ctx.x, sel, ctx.e0, ctx.kwargs,
76
+ ctx.kv_cache, ctx.crossattn_cache,
77
+ ctx.current_start, ctx.cache_start, ctx.grid_sizes))
78
+ print(f"{r:>7.3f}{n:>8}{ms:>9.1f}{100*ms/full_ms:>11.1f}", flush=True)
mc_scan.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """Threshold scan for MotionCache, reporting what the compute fraction hides:
3
+ how the recomputed-token budget is spread over the cacheable steps.
4
+
5
+ For a token-wise method the interesting quantity is not "how many tokens in
6
+ total" but "is every cacheable step making a *partial* decision". A point where
7
+ most cacheable steps are empty (or nearly full) is behaviourally TeaCache with
8
+ extra bookkeeping, whatever its compute fraction says.
9
+
10
+ Reports per threshold:
11
+ compute compute-equivalent forwards / total, and the implied FLOPs speedup
12
+ measured paired wall-clock speedup against FFFF on the same prompts
13
+ active fraction of cacheable steps with 0 < selected < 100% of tokens
14
+ sel mean / p10 / p90 selected-token fraction over the active steps
15
+
16
+ CUDA_VISIBLE_DEVICES=0 python mc_scan.py --base self_forcing \
17
+ --schedule FxxF --thresholds 0.5,0.75,1.0,1.25,1.5,2.0,2.5
18
+ """
19
+ import argparse, json, os, statistics as st, sys
20
+
21
+ ROOT = os.path.dirname(os.path.abspath(__file__))
22
+ sys.path.insert(0, ROOT)
23
+ from harness import BASES, enter_base, load_pipeline, load_prompts # noqa: E402
24
+
25
+ ap = argparse.ArgumentParser()
26
+ ap.add_argument("--base", choices=sorted(BASES), required=True)
27
+ ap.add_argument("--schedule", default="FxxF")
28
+ ap.add_argument("--thresholds", required=True)
29
+ ap.add_argument("--coefficients", default=None)
30
+ ap.add_argument("--weight-norm", default=None)
31
+ ap.add_argument("--num-prompts", type=int, default=3)
32
+ ap.add_argument("--num-output-frames", type=int, default=21)
33
+ ap.add_argument("--seed", type=int, default=0)
34
+ ap.add_argument("--out", default=None)
35
+ args = ap.parse_args()
36
+
37
+ coefficients = None
38
+ if args.coefficients:
39
+ p = args.coefficients if os.path.isabs(args.coefficients) else os.path.join(ROOT, args.coefficients)
40
+ coefficients = json.load(open(p))["coefficients"]
41
+
42
+ base = enter_base(args.base)
43
+ import torch
44
+ from utils.misc import set_seed
45
+ from cachelib import CacheController, build_method, cached_inference, install, parse_schedule
46
+
47
+ torch.set_grad_enabled(False)
48
+ pipe = load_pipeline(base)
49
+ num_steps = len(pipe.denoising_step_list)
50
+ forced = set(parse_schedule(args.schedule, num_steps))
51
+ prompts = load_prompts(args.num_prompts + 1)
52
+
53
+
54
+ def run(method, **kw):
55
+ ctrl = CacheController(build_method(method, coefficients=coefficients, **kw),
56
+ num_steps=num_steps, forced_steps=tuple(sorted(forced)))
57
+ install(pipe.generator.model, ctrl)
58
+ ms, recs = [], []
59
+ for i, prompt in enumerate(prompts):
60
+ set_seed(args.seed)
61
+ noise = torch.randn([1, args.num_output_frames, 16, 60, 104],
62
+ device=torch.device("cuda"), dtype=torch.bfloat16)
63
+ _, _, timing = cached_inference(pipe, ctrl, noise, [prompt], decode=False)
64
+ if i == 0:
65
+ continue # warm-up prompt
66
+ ms.append(timing["denoise_dit_ms"])
67
+ recs += [r for r in ctrl.records if r["step"] not in forced]
68
+ return min(ms), recs, ctrl.summary()
69
+
70
+
71
+ base_ms, _, _ = run("none")
72
+ print(f"baseline (FFFF) min denoise: {base_ms:.0f} ms over {args.num_prompts} prompts, "
73
+ f"schedule {args.schedule}, {num_steps} steps", flush=True)
74
+ print(f"{'thresh':>8}{'Full/28':>9}{'compute_x':>10}{'measured_x':>11}"
75
+ f"{'active%':>9}{'empty%':>8}{'full%':>7}{'sel_mean%':>10}{'sel_p10%':>9}{'sel_p90%':>9}")
76
+ rows = []
77
+ for t in [float(v) for v in args.thresholds.split(",")]:
78
+ kw = dict(thresh=t)
79
+ if args.weight_norm:
80
+ kw["weight_norm"] = args.weight_norm
81
+ ms, recs, summary = run("motioncache", **kw)
82
+ fr = [r["compute_fraction"] for r in recs]
83
+ act = [f for f in fr if 1e-9 < f < 1 - 1e-9]
84
+ q = lambda v, p: sorted(v)[min(int(p * (len(v) - 1)), len(v) - 1)] if v else float("nan")
85
+ row = {"thresh": t, "compute_equivalent": summary["compute_equivalent_forwards"],
86
+ "compute_speedup": summary["flops_speedup_estimate"], "measured_speedup": base_ms / ms,
87
+ "active_ratio": len(act) / len(fr), "empty_ratio": sum(f <= 1e-9 for f in fr) / len(fr),
88
+ "full_ratio": sum(f >= 1 - 1e-9 for f in fr) / len(fr),
89
+ "sel_mean": st.fmean(act) if act else 0.0, "sel_p10": q(act, .1), "sel_p90": q(act, .9),
90
+ "min_denoise_ms": ms}
91
+ rows.append(row)
92
+ print(f"{t:>8.4g}{row['compute_equivalent']:>9.2f}{row['compute_speedup']:>10.3f}"
93
+ f"{row['measured_speedup']:>11.3f}{100*row['active_ratio']:>9.1f}{100*row['empty_ratio']:>8.1f}"
94
+ f"{100*row['full_ratio']:>7.1f}{100*row['sel_mean']:>10.1f}{100*row['sel_p10']:>9.1f}"
95
+ f"{100*row['sel_p90']:>9.1f}", flush=True)
96
+
97
+ if args.out:
98
+ out = args.out if os.path.isabs(args.out) else os.path.join(ROOT, args.out)
99
+ os.makedirs(os.path.dirname(out), exist_ok=True)
100
+ json.dump({"base": args.base, "schedule": args.schedule, "baseline_ms": base_ms,
101
+ "weight_norm": args.weight_norm, "coefficients": coefficients, "rows": rows},
102
+ open(out, "w"), indent=2)
103
+ print("wrote", out)
mc_scan_queue.sh ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Run the MotionCache activity scans as soon as a quiet GPU appears.
3
+ # GPUS="0 1 2 3 4 5 6 7" mc_scan_queue.sh <logdir>
4
+ set -u
5
+ C=/local/zoubin/cz/projects/comparison; PY=/local/zoubin/cz/envs/self_forcing/bin/python
6
+ LOG="$1"; GPUS=(${GPUS:-0 1 2 3 4 5 6 7}); WAIT=${WAIT:-120}
7
+ export SSL_CERT_FILE=/etc/pki/tls/certs/ca-bundle.crt
8
+ export HF_HOME=/local/zoubin/cz/.cache/huggingface HF_HUB_CACHE=/local/zoubin/cz/.cache/huggingface/hub
9
+ export TRANSFORMERS_CACHE=/local/zoubin/cz/.cache/huggingface/hub TORCH_HOME=/local/zoubin/cz/.cache/torch
10
+ export XDG_CACHE_HOME=/local/zoubin/cz/.cache
11
+ cd "$C"; mkdir -p "$LOG" results
12
+ # The HY scans measure wall clock on the same GPUs and need 74 GB; never overlap.
13
+ while pgrep -f "[h]y_mc_scan.py|[h]y_generate_eval.py" > /dev/null 2>&1; do sleep 60; done
14
+ quiet_gpu() {
15
+ for g in "${GPUS[@]}"; do
16
+ used=$(nvidia-smi --query-gpu=memory.used --format=csv,noheader,nounits -i "$g" 2>/dev/null | tr -d ' ')
17
+ [ -z "$used" ] || [ "$used" -ge 25000 ] && continue
18
+ peak=0
19
+ for _ in 1 2 3; do
20
+ u=$(nvidia-smi --query-gpu=utilization.gpu --format=csv,noheader,nounits -i "$g" 2>/dev/null | tr -d ' ')
21
+ [ -n "$u" ] && [ "$u" -gt "$peak" ] && peak=$u
22
+ sleep 1
23
+ done
24
+ [ "$peak" -lt 15 ] && { echo "$g"; return; }
25
+ done
26
+ }
27
+ # base | schedule | thresholds | coefficients | out
28
+ JOBS=(
29
+ "self_forcing|FxxF|0.6,0.9,1.1,1.2,1.25,1.28,1.29,1.3,1.5,2.0,2.5|results/coeff_self_forcing.json|results/mc_scan_sf_FxxF.json"
30
+ "causal_forcing|FxxF|0.6,0.9,1.15,1.25,1.28,1.29,1.3,1.5,2.0,2.9|results/coeff_causal_forcing.json|results/mc_scan_cf_FxxF.json"
31
+ "self_forcing|Fxxx|0.9,1.3,1.6,1.79,1.9,2.1,2.4,2.8,3.5|results/coeff_self_forcing.json|results/mc_scan_sf_Fxxx.json"
32
+ "causal_forcing|Fxxx|0.9,1.3,1.6,1.77,1.9,2.1,2.4,2.8,3.5|results/coeff_causal_forcing.json|results/mc_scan_cf_Fxxx.json"
33
+ )
34
+ for job in "${JOBS[@]}"; do
35
+ IFS='|' read -r b sched th coeff out <<<"$job"
36
+ [ -f "$out" ] && { echo "skip $out"; continue; }
37
+ while true; do g=$(quiet_gpu); [ -n "$g" ] && break; sleep "$WAIT"; done
38
+ name=$(basename "$out" .json)
39
+ echo "[$(date +%H:%M:%S)] $name -> GPU $g"
40
+ CUDA_VISIBLE_DEVICES=$g $PY mc_scan.py --base "$b" --schedule "$sched" --thresholds "$th" \
41
+ --coefficients "$coeff" --num-prompts 3 --out "$out" > "$LOG/$name.log" 2>&1 \
42
+ && echo "[$(date +%H:%M:%S)] $name done" || echo "[$(date +%H:%M:%S)] $name FAILED"
43
+ done
44
+ echo "ALL MC SCANS DONE $(date +%H:%M:%S)"
overhead_bench.py ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """Measure what a cached step actually costs, per method, contention-robustly.
3
+
4
+ Whole-video wall-clock timings are unusable on a busy shared node: a single
5
+ neighbouring job distorts a 4-second measurement, and with only ~10 videos per
6
+ configuration even the minimum is sometimes never clean.
7
+
8
+ But wall-clock only adds *one* thing on top of the (exact, deterministic) compute
9
+ fraction: how much a skipped or partially-recomputed step still costs relative to
10
+ a full one. That is a per-step quantity, and one run yields 28 samples, so a
11
+ handful of runs gives hundreds. Minima over hundreds of samples are robust in a
12
+ way minima over ten are not.
13
+
14
+ For each method this fits
15
+
16
+ step_cost(fraction) = t_skip + fraction * (t_full - t_skip)
17
+
18
+ from per-step minima bucketed by compute fraction, then reports the derived
19
+ denoise-DiT speedup at any operating point:
20
+
21
+ speedup = 28 * t_full / sum_over_steps(step_cost(fraction_of_that_step))
22
+
23
+ python overhead_bench.py --base self_forcing --out results/overhead_self_forcing.json
24
+ """
25
+
26
+ import argparse
27
+ import json
28
+ import os
29
+ import statistics
30
+ import sys
31
+
32
+ ROOT = os.path.dirname(os.path.abspath(__file__))
33
+ sys.path.insert(0, ROOT)
34
+
35
+ from harness import BASES, enter_base, load_pipeline, load_prompts # noqa: E402
36
+
37
+ # Settings chosen to produce plenty of fully-cached steps and, for the two
38
+ # partial-recompute methods, a spread of intermediate fractions.
39
+ PROBES = {
40
+ "teacache": [("thresh", 1e9)],
41
+ "flowcache": [("thresh", 1e9), ("thresh", 1.27), ("thresh", 1.25)],
42
+ "taylorseer": [("interval", 3.0)],
43
+ "motioncache": [("thresh", 1e9), ("thresh", 1.25), ("thresh", 1.1),
44
+ ("thresh", 0.9), ("thresh", 0.75)],
45
+ }
46
+
47
+ BIN = 0.1 # width of the compute-fraction bins used for per-bin minima
48
+
49
+
50
+ def main():
51
+ ap = argparse.ArgumentParser()
52
+ ap.add_argument("--base", choices=sorted(BASES), required=True)
53
+ ap.add_argument("--num-prompts", type=int, default=6)
54
+ ap.add_argument("--num-output-frames", type=int, default=21)
55
+ ap.add_argument("--seed", type=int, default=0)
56
+ ap.add_argument("--out", required=True)
57
+ args = ap.parse_args()
58
+
59
+ out_path = args.out if os.path.isabs(args.out) else os.path.join(ROOT, args.out)
60
+ base = enter_base(args.base)
61
+
62
+ import torch
63
+ from utils.misc import set_seed
64
+ from cachelib import CacheController, build_method, cached_inference, install
65
+
66
+ torch.set_grad_enabled(False)
67
+ pipeline = load_pipeline(base)
68
+ num_steps = len(pipeline.denoising_step_list)
69
+ prompts = load_prompts(args.num_prompts)
70
+
71
+ coeff_path = os.path.join(ROOT, f"results/coeff_{args.base}.json")
72
+ coefficients = None
73
+ if os.path.exists(coeff_path):
74
+ with open(coeff_path) as f:
75
+ coefficients = json.load(f)["coefficients"]
76
+
77
+ def run(method_name, pname=None, value=None, n=None):
78
+ """Return [(compute_fraction, step_ms), ...] over all denoising steps."""
79
+ kw = dict(indicator="modulated_input", coefficients=coefficients)
80
+ if method_name != "none":
81
+ kw[pname] = value
82
+ samples = []
83
+ for i, prompt in enumerate(prompts[:n or len(prompts)]):
84
+ ctrl = CacheController(build_method(method_name, **kw),
85
+ num_steps=num_steps,
86
+ forced_steps=(0, num_steps - 1))
87
+ install(pipeline.generator.model, ctrl)
88
+ set_seed(args.seed)
89
+ noise = torch.randn([1, args.num_output_frames, 16, 60, 104],
90
+ device=torch.device("cuda"), dtype=torch.bfloat16)
91
+ _, _, timing = cached_inference(pipeline, ctrl, noise, [prompt],
92
+ decode=False)
93
+ if i == 0:
94
+ continue # warm-up run
95
+ for rec, ms in zip(ctrl.records, timing["per_step_denoise_ms"]):
96
+ samples.append((rec["compute_fraction"], ms))
97
+ return samples
98
+
99
+ print("=== baseline (all steps full) ===", flush=True)
100
+ base_samples = run("none")
101
+ t_full = min(ms for _, ms in base_samples)
102
+ print(f"t_full = {t_full:.2f} ms (min over {len(base_samples)} full steps, "
103
+ f"median {statistics.median([ms for _, ms in base_samples]):.2f})", flush=True)
104
+
105
+ results = {}
106
+ all_full = [ms for _, ms in base_samples]
107
+ for method, probes in PROBES.items():
108
+ samples = []
109
+ for pname, value in probes:
110
+ samples += run(method, pname, value)
111
+ # Bin coarsely: a partial-recompute method produces a different fraction on
112
+ # almost every step, and a bucket holding one sample has a "minimum" that is
113
+ # really just whatever contention it happened to meet.
114
+ buckets = {}
115
+ for frac, ms in samples:
116
+ if frac <= 1e-6:
117
+ key = 0.0
118
+ elif frac >= 1 - 1e-6:
119
+ key = 1.0
120
+ else:
121
+ key = min(0.95, max(0.05, round(frac / BIN) * BIN))
122
+ buckets.setdefault(round(key, 3), []).append(ms)
123
+ points = sorted((f, min(v), len(v)) for f, v in buckets.items())
124
+
125
+ skip = [p for p in points if p[0] <= 1e-6]
126
+ full = [p for p in points if p[0] >= 1 - 1e-6]
127
+ t_skip = skip[0][1] if skip else None
128
+ t_full_m = full[0][1] if full else t_full
129
+
130
+ all_full.extend(ms for f, ms in samples if f >= 1 - 1e-6)
131
+
132
+ results[method] = {
133
+ "t_full_ms": t_full_m,
134
+ "t_skip_ms": t_skip,
135
+ "skip_cost_ratio": (t_skip / t_full_m) if t_skip else None,
136
+ "buckets": [{"fraction": f, "min_ms": m, "n": n} for f, m, n in points],
137
+ "n_samples": len(samples),
138
+ }
139
+ r = results[method]["skip_cost_ratio"]
140
+ print(f"{method:12s} t_full={t_full_m:7.2f}ms "
141
+ f"t_skip={t_skip if t_skip is None else round(t_skip, 2)}ms "
142
+ f"skip costs {'-' if r is None else format(r, '.3f')} of a full step "
143
+ f"({len(points)} bins, {len(samples)} steps)", flush=True)
144
+
145
+ # The node is saturated, so no single configuration is guaranteed a clean
146
+ # sample. Contention only ever slows a step down, so the smallest full-step
147
+ # time seen anywhere is the best estimate of the uncontended cost, and every
148
+ # method's skip ratio is quoted against it.
149
+ t_full_global = min(all_full)
150
+ print(f"\nglobal t_full = {t_full_global:.2f} ms over {len(all_full)} full steps",
151
+ flush=True)
152
+ for method, r in results.items():
153
+ r["skip_cost_ratio_global"] = (r["t_skip_ms"] / t_full_global
154
+ if r["t_skip_ms"] else None)
155
+ print(f" {method:12s} skip = {r['skip_cost_ratio_global']:.4f} of a full step "
156
+ f"-> ceiling {28 / (14 + 14 * r['skip_cost_ratio_global']):.3f}x at 14/28",
157
+ flush=True)
158
+
159
+ payload = {
160
+ "base": args.base,
161
+ "num_prompts": args.num_prompts,
162
+ "bin_width": BIN,
163
+ "t_full_global_ms": t_full_global,
164
+ "n_full_step_samples": len(all_full),
165
+ "baseline_t_full_ms": t_full,
166
+ "baseline_median_step_ms": statistics.median([ms for _, ms in base_samples]),
167
+ "methods": results,
168
+ }
169
+ os.makedirs(os.path.dirname(out_path), exist_ok=True)
170
+ with open(out_path, "w") as f:
171
+ json.dump(payload, f, indent=2)
172
+ print(f"wrote {out_path}", flush=True)
173
+
174
+
175
+ if __name__ == "__main__":
176
+ main()
pick_points.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """Choose operating points from the scans.
3
+
4
+ Targets are on *measured* wall-clock speedup: FxxF at 1.70-1.80x, Fxxx at
5
+ 2.70-3.00x. For the token-wise method the fastest setting inside the band is
6
+ often one whose per-token decision has collapsed (it selects ~0 tokens and is
7
+ then bit-identical to TeaCache), so a point also has to keep the decision alive:
8
+ >=25% of cacheable steps partial and >=5% of tokens selected on those steps.
9
+ Where no setting satisfies both, the fastest *active* setting is reported and
10
+ flagged -- that gap is the result, not a search failure.
11
+ """
12
+ import glob, json, os, sys
13
+
14
+ ROOT = os.path.dirname(os.path.abspath(__file__))
15
+ BANDS = {"FxxF": (1.70, 1.80), "Fxxx": (2.70, 3.00)}
16
+ ACT_MIN, SEL_MIN = 0.25, 0.05
17
+ NEEDS_ACTIVITY = {"motioncache", "flowcache"}
18
+
19
+ rows = {}
20
+ for p in glob.glob(os.path.join(ROOT, "results/scan_*.json")):
21
+ d = json.load(open(p))
22
+ base = {"self_forcing": "sf", "causal_forcing": "cf", "hy_worldplay": "hy"}[d["base"]]
23
+ rows.setdefault((base, d["method"], d["schedule"]), []).extend(d["rows"])
24
+
25
+ print(f"{'base':>4} {'method':12s}{'sched':>6}{'param':>10}{'measured':>10}{'compute':>9}"
26
+ f"{'active%':>9}{'sel%':>7} note")
27
+ picks = {}
28
+ for key in sorted(rows):
29
+ base, method, sched = key
30
+ lo, hi = BANDS[sched]
31
+ cand = sorted(rows[key], key=lambda r: r["value"])
32
+ active_ok = (lambda r: r["active_ratio"] >= ACT_MIN and r["sel_mean"] >= SEL_MIN) \
33
+ if method in NEEDS_ACTIVITY else (lambda r: True)
34
+ in_band = [r for r in cand if lo <= r["measured_speedup"] <= hi and active_ok(r)]
35
+ note = ""
36
+ if in_band:
37
+ best = max(in_band, key=lambda r: r["measured_speedup"])
38
+ else:
39
+ alive = [r for r in cand if active_ok(r) and r["measured_speedup"] <= hi]
40
+ if alive:
41
+ best = max(alive, key=lambda r: r["measured_speedup"])
42
+ note = (f"活跃度受限,达不到 {lo:.2f}x" if best["measured_speedup"] < lo
43
+ else "")
44
+ else:
45
+ best = min(cand, key=lambda r: abs(r["measured_speedup"] - (lo + hi) / 2))
46
+ note = "无活跃点"
47
+ if not note and not (lo <= best["measured_speedup"] <= hi):
48
+ note = "带外"
49
+ picks[key] = best
50
+ print(f"{base:>4} {method:12s}{sched:>6}{best['value']:>10.5g}"
51
+ f"{best['measured_speedup']:>10.3f}{best['compute_speedup']:>9.3f}"
52
+ f"{100*best['active_ratio']:>9.1f}{100*best['sel_mean']:>7.1f} {note}")
53
+
54
+ out = os.path.join(ROOT, "results/picked_points.json")
55
+ json.dump({f"{b}|{m}|{s}": dict(v, base=b, method=m, schedule=s)
56
+ for (b, m, s), v in picks.items()}, open(out, "w"), indent=2)
57
+ print("\nwrote", out)
refine2_queue.sh ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Scan (base, method, schedule) grids for the new operating points, one job per
3
+ # quiet GPU among $GPUS. Targets are *measured* wall-clock speedup: 1.7-1.8x
4
+ # under FxxF and 2.7-3.0x under Fxxx, so the search must see time, not compute.
5
+ set -u
6
+ C=/local/zoubin/cz/projects/comparison
7
+ SFPY=/local/zoubin/cz/envs/self_forcing/bin/python
8
+ HYPY=/local/zoubin/cz/envs/hy_worldplay_july20260720/bin/python
9
+ LOG="$1"; GPUS=(${GPUS:-4 5 6 7}); WAIT=${WAIT:-60}
10
+ export SSL_CERT_FILE=/etc/pki/tls/certs/ca-bundle.crt
11
+ export TORCH_HOME=/local/zoubin/cz/.cache/torch XDG_CACHE_HOME=/local/zoubin/cz/.cache
12
+ cd "$C"; mkdir -p "$LOG" results
13
+ # The coarse queue owns the GPUs until it is done.
14
+
15
+ declare -A BUSY; pids=()
16
+ quiet_gpu() {
17
+ for g in "${GPUS[@]}"; do
18
+ [ -n "${BUSY[$g]:-}" ] && kill -0 "${BUSY[$g]}" 2>/dev/null && continue
19
+ used=$(nvidia-smi --query-gpu=memory.used --format=csv,noheader,nounits -i "$g" 2>/dev/null | tr -d ' ')
20
+ [ -z "$used" ] || [ "$used" -ge 8000 ] && continue
21
+ echo "$g"; return
22
+ done
23
+ }
24
+ # tag | kind | base | method | schedule | values
25
+ JOBS=( # transition bands at fine granularity, on quiet GPUs
26
+ "sf_teacache_FxxF_fine|sf|self_forcing|teacache|FxxF|1.2460,1.2478,1.2496,1.2514,1.2532,1.2548"
27
+ "cf_teacache_FxxF_fine|cf|causal_forcing|teacache|FxxF|1.2700,1.2718,1.2736,1.2754,1.2772,1.2790"
28
+ "sf_teacache_Fxxx_fine|sf|self_forcing|teacache|Fxxx|1.7205,1.7212,1.7218,1.7224,1.7231,1.7238"
29
+ "hy_teacache_FxxF_fine|hy|-|teacache|FxxF|0.4745,0.4756,0.4767,0.4778,0.4789,0.4796"
30
+ "hy_teacache_Fxxx_fine|hy|-|teacache|Fxxx|0.655,0.660,0.665,0.670,0.674,0.678"
31
+ )
32
+ for job in "${JOBS[@]}"; do
33
+ IFS='|' read -r tag kind b m sched vals <<<"$job"
34
+ out="results/scan_${tag}.json"
35
+ [ -f "$out" ] && { echo "skip $tag"; continue; }
36
+ while true; do g=$(quiet_gpu); [ -n "$g" ] && break; sleep "$WAIT"; done
37
+ echo "[$(date +%H:%M:%S)] $tag -> GPU $g"
38
+ if [ "$kind" = hy ]; then
39
+ HF_HOME=/local/zoubin/cz/checkpoints/hy_worldplay/huggingface \
40
+ HF_HUB_CACHE=/local/zoubin/cz/checkpoints/hy_worldplay/huggingface/hub \
41
+ TRANSFORMERS_CACHE=/local/zoubin/cz/checkpoints/hy_worldplay/huggingface/hub \
42
+ HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1 \
43
+ CUDA_VISIBLE_DEVICES=$g $HYPY hy_scan_points.py --method "$m" --schedule "$sched" \
44
+ --values "$vals" --out "$out" > "$LOG/scan_$tag.log" 2>&1 &
45
+ else
46
+ HF_HOME=/local/zoubin/cz/.cache/huggingface HF_HUB_CACHE=/local/zoubin/cz/.cache/huggingface/hub \
47
+ TRANSFORMERS_CACHE=/local/zoubin/cz/.cache/huggingface/hub \
48
+ CUDA_VISIBLE_DEVICES=$g $SFPY scan_points.py --base "$b" --method "$m" --schedule "$sched" \
49
+ --values "$vals" --coefficients "results/coeff_${b}.json" --num-prompts 3 \
50
+ --out "$out" > "$LOG/scan_$tag.log" 2>&1 &
51
+ fi
52
+ BUSY[$g]=$!; pids+=($!); sleep 45
53
+ done
54
+ for p in "${pids[@]}"; do wait "$p"; done
55
+ echo "ALL REFINE SCANS DONE $(date +%H:%M:%S)"; ls results/scan_*.json 2>/dev/null | wc -l
refine_queue.sh ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Scan (base, method, schedule) grids for the new operating points, one job per
3
+ # quiet GPU among $GPUS. Targets are *measured* wall-clock speedup: 1.7-1.8x
4
+ # under FxxF and 2.7-3.0x under Fxxx, so the search must see time, not compute.
5
+ set -u
6
+ C=/local/zoubin/cz/projects/comparison
7
+ SFPY=/local/zoubin/cz/envs/self_forcing/bin/python
8
+ HYPY=/local/zoubin/cz/envs/hy_worldplay_july20260720/bin/python
9
+ LOG="$1"; GPUS=(${GPUS:-4 5 6 7}); WAIT=${WAIT:-60}
10
+ export SSL_CERT_FILE=/etc/pki/tls/certs/ca-bundle.crt
11
+ export TORCH_HOME=/local/zoubin/cz/.cache/torch XDG_CACHE_HOME=/local/zoubin/cz/.cache
12
+ cd "$C"; mkdir -p "$LOG" results
13
+ # The coarse queue owns the GPUs until it is done.
14
+ while pgrep -f "[s]can_queue.sh" > /dev/null 2>&1; do sleep 60; done
15
+ declare -A BUSY; pids=()
16
+ quiet_gpu() {
17
+ for g in "${GPUS[@]}"; do
18
+ [ -n "${BUSY[$g]:-}" ] && kill -0 "${BUSY[$g]}" 2>/dev/null && continue
19
+ used=$(nvidia-smi --query-gpu=memory.used --format=csv,noheader,nounits -i "$g" 2>/dev/null | tr -d ' ')
20
+ [ -z "$used" ] || [ "$used" -ge 8000 ] && continue
21
+ echo "$g"; return
22
+ done
23
+ }
24
+ # tag | kind | base | method | schedule | values
25
+ JOBS=( # refinement: the transition bands the coarse grid stepped over
26
+ "sf_teacache_FxxF_fine|sf|self_forcing|teacache|FxxF|1.205,1.215,1.225,1.235,1.245,1.255"
27
+ "cf_teacache_FxxF_fine|cf|causal_forcing|teacache|FxxF|1.262,1.268,1.274,1.280,1.286,1.291"
28
+ "sf_motioncache_FxxF_fine|sf|self_forcing|motioncache|FxxF|1.60,1.75,1.90,2.05,2.20,2.40"
29
+ "cf_motioncache_FxxF_fine|cf|causal_forcing|motioncache|FxxF|1.35,1.55,1.75,1.95,2.20,2.60"
30
+ "sf_teacache_Fxxx_fine|sf|self_forcing|teacache|Fxxx|1.702,1.708,1.714,1.720,1.724,1.727"
31
+ "sf_motioncache_Fxxx_fine|sf|self_forcing|motioncache|Fxxx|1.95,2.00,2.06,2.12,2.18,2.30"
32
+ "cf_motioncache_Fxxx_fine|cf|causal_forcing|motioncache|Fxxx|1.95,2.00,2.06,2.12,2.18,2.30"
33
+ "hy_teacache_FxxF_fine|hy|-|teacache|FxxF|0.462,0.468,0.474,0.480,0.485,0.489"
34
+ "hy_teacache_Fxxx_fine|hy|-|teacache|Fxxx|0.62,0.65,0.68,0.70,0.72,0.74"
35
+ )
36
+ for job in "${JOBS[@]}"; do
37
+ IFS='|' read -r tag kind b m sched vals <<<"$job"
38
+ out="results/scan_${tag}.json"
39
+ [ -f "$out" ] && { echo "skip $tag"; continue; }
40
+ while true; do g=$(quiet_gpu); [ -n "$g" ] && break; sleep "$WAIT"; done
41
+ echo "[$(date +%H:%M:%S)] $tag -> GPU $g"
42
+ if [ "$kind" = hy ]; then
43
+ HF_HOME=/local/zoubin/cz/checkpoints/hy_worldplay/huggingface \
44
+ HF_HUB_CACHE=/local/zoubin/cz/checkpoints/hy_worldplay/huggingface/hub \
45
+ TRANSFORMERS_CACHE=/local/zoubin/cz/checkpoints/hy_worldplay/huggingface/hub \
46
+ HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1 \
47
+ CUDA_VISIBLE_DEVICES=$g $HYPY hy_scan_points.py --method "$m" --schedule "$sched" \
48
+ --values "$vals" --out "$out" > "$LOG/scan_$tag.log" 2>&1 &
49
+ else
50
+ HF_HOME=/local/zoubin/cz/.cache/huggingface HF_HUB_CACHE=/local/zoubin/cz/.cache/huggingface/hub \
51
+ TRANSFORMERS_CACHE=/local/zoubin/cz/.cache/huggingface/hub \
52
+ CUDA_VISIBLE_DEVICES=$g $SFPY scan_points.py --base "$b" --method "$m" --schedule "$sched" \
53
+ --values "$vals" --coefficients "results/coeff_${b}.json" --num-prompts 3 \
54
+ --out "$out" > "$LOG/scan_$tag.log" 2>&1 &
55
+ fi
56
+ BUSY[$g]=$!; pids+=($!); sleep 45
57
+ done
58
+ for p in "${pids[@]}"; do wait "$p"; done
59
+ echo "ALL REFINE SCANS DONE $(date +%H:%M:%S)"; ls results/scan_*.json 2>/dev/null | wc -l
retime.py ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """Re-time the settled operating points with a plain stopwatch, on a quiet GPU.
3
+
4
+ The sweeps and the finalize pass ran while the node was saturated, so their
5
+ wall-clock columns are unusable and the headline speedups had to be derived from
6
+ per-step cost minima instead. When the node is idle, whole-video denoise timing
7
+ is reliable again (baseline spread ~0.2%), and this script simply re-measures
8
+ each already-settled operating point: no searching, no retargeting.
9
+
10
+ python retime.py --base self_forcing --out results/retime_self_forcing.json
11
+
12
+ Check the GPU is actually idle first -- `harness.free_gpus()` is printed on start.
13
+ """
14
+
15
+ import argparse
16
+ import glob
17
+ import json
18
+ import os
19
+ import sys
20
+
21
+ ROOT = os.path.dirname(os.path.abspath(__file__))
22
+ sys.path.insert(0, ROOT)
23
+
24
+ from harness import (BASES, enter_base, evaluate, free_gpus, # noqa: E402
25
+ load_pipeline, load_prompts, paired_evaluate)
26
+
27
+ METHOD_ORDER = ["teacache", "flowcache", "taylorseer", "motioncache"]
28
+
29
+
30
+ def main():
31
+ ap = argparse.ArgumentParser()
32
+ ap.add_argument("--base", choices=sorted(BASES), required=True)
33
+ ap.add_argument("--pair-prompts", type=int, default=8)
34
+ ap.add_argument("--num-output-frames", type=int, default=21)
35
+ ap.add_argument("--seed", type=int, default=0)
36
+ ap.add_argument("--out", required=True)
37
+ args = ap.parse_args()
38
+
39
+ out_path = args.out if os.path.isabs(args.out) else os.path.join(ROOT, args.out)
40
+ print(f"[gpu] CUDA_VISIBLE_DEVICES={os.environ.get('CUDA_VISIBLE_DEVICES')} "
41
+ f"free={free_gpus()}", flush=True)
42
+
43
+ points = []
44
+ for p in sorted(glob.glob(os.path.join(ROOT, f"results/final_{args.base}*.json"))):
45
+ with open(p) as f:
46
+ for r in json.load(f)["rows"]:
47
+ points.append(r)
48
+ if not points:
49
+ print(f"no final_{args.base}*.json rows")
50
+ return
51
+ points.sort(key=lambda r: (METHOD_ORDER.index(r["method"])
52
+ if r["method"] in METHOD_ORDER else 9,
53
+ r["target_speedup"]))
54
+ print(f"{len(points)} operating points", flush=True)
55
+
56
+ base = enter_base(args.base)
57
+
58
+ import torch
59
+ from cachelib import CacheController, build_method, install
60
+
61
+ torch.set_grad_enabled(False)
62
+ pipeline = load_pipeline(base)
63
+ num_steps = len(pipeline.denoising_step_list)
64
+
65
+ coeff_path = os.path.join(ROOT, f"results/coeff_{args.base}.json")
66
+ coefficients = None
67
+ if os.path.exists(coeff_path):
68
+ with open(coeff_path) as f:
69
+ coefficients = json.load(f)["coefficients"]
70
+
71
+ prompts = load_prompts(args.pair_prompts + 1)
72
+
73
+ def make_ctrl(method_name, pname=None, value=None):
74
+ kw = dict(indicator="modulated_input", coefficients=coefficients)
75
+ if method_name != "none":
76
+ kw[pname] = value
77
+ ctrl = CacheController(build_method(method_name, **kw), num_steps=num_steps,
78
+ forced_steps=(0, num_steps - 1))
79
+ install(pipeline.generator.model, ctrl)
80
+ return ctrl
81
+
82
+ print("=== warm-up ===", flush=True)
83
+ evaluate(pipeline, make_ctrl("none"), prompts[:3],
84
+ num_output_frames=args.num_output_frames, seed=args.seed, warmup=0)
85
+
86
+ rows = []
87
+ for r in points:
88
+ paired = paired_evaluate(
89
+ pipeline,
90
+ lambda: make_ctrl("none"),
91
+ lambda p=r["param"], v=r["value"]: make_ctrl(r["method"], p, v),
92
+ prompts, num_output_frames=args.num_output_frames, seed=args.seed,
93
+ warmup=1)
94
+ row = dict(r)
95
+ row.update({
96
+ "retimed_speedup_median": paired["paired_speedup_median"],
97
+ "retimed_speedup_stdev": paired["paired_speedup_stdev"],
98
+ "retimed_speedup_min_based": paired["speedup_from_minima"],
99
+ "retimed_baseline_ms_median": paired["median_baseline_ms"],
100
+ "retimed_method_ms_median": paired["median_method_ms"],
101
+ "retimed_flops_speedup": paired["paired_flops_speedup"],
102
+ "retimed_compute_equivalent": paired["paired_compute_equivalent"],
103
+ "retimed_baseline_ms": paired["baseline_ms"],
104
+ "retimed_method_ms": paired["method_ms"],
105
+ })
106
+ rows.append(row)
107
+ print(f"{r['method']:12s} target {r['target_speedup']:g}x "
108
+ f"{r['param']}={r['value']:<10.6g} "
109
+ f"speedup={row['retimed_speedup_median']:.3f}x "
110
+ f"(±{row['retimed_speedup_stdev']:.3f}) "
111
+ f"compute={row['retimed_flops_speedup']:.3f}x "
112
+ f"{row['retimed_baseline_ms_median']:.0f} -> "
113
+ f"{row['retimed_method_ms_median']:.0f} ms", flush=True)
114
+ with open(out_path, "w") as f:
115
+ json.dump({"base": args.base, "rows": rows}, f, indent=2)
116
+
117
+ print(f"wrote {out_path}", flush=True)
118
+
119
+
120
+ if __name__ == "__main__":
121
+ main()
run_cf_fpf.sh ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # cfa_atc_chunk_fpf: ATC-chunk Stage-1 on the 7-chunk protocol with a reduced 3-position
3
+ # schedule (F at t=1000, one Predictor step at t=750, F at t=250; step 2 skipped).
4
+ # One process on GPU 5 (burn guard on), reference from cfa_ffff's MP4s, VBench on GPU 5.
5
+ set -u
6
+ C=/local/zoubin/cz/projects/comparison; SFPY=/local/zoubin/cz/envs/self_forcing/bin/python
7
+ LOG="$1"; cd "$C"
8
+ export SSL_CERT_FILE=/etc/pki/tls/certs/ca-bundle.crt
9
+ export HF_HOME=/local/zoubin/cz/.cache/huggingface HF_HUB_CACHE=/local/zoubin/cz/.cache/huggingface/hub
10
+ export TRANSFORMERS_CACHE=/local/zoubin/cz/.cache/huggingface/hub TORCH_HOME=/local/zoubin/cz/.cache/torch
11
+ export XDG_CACHE_HOME=/local/zoubin/cz/.cache
12
+ bash burn_guard.sh "5" > "$LOG/burn_guard.log" 2>&1 &
13
+ guard=$!
14
+ sleep 3
15
+ echo "=== generation $(date +%H:%M:%S) ==="
16
+ CUDA_VISIBLE_DEVICES=5 $SFPY eval/generate_predictor_eval.py --models atc_chunk --patterns FPF --shard 0 --num-shards 1 --out-root eval_out > "$LOG/gen.log" 2>&1
17
+ kill $guard 2>/dev/null
18
+ echo "=== vbench on GPU 5 $(date +%H:%M:%S) ==="
19
+ bash run_vbench_gpu5.sh "$LOG" 5 cfa_atc_chunk_fpf 7 8 1 > "$LOG/vb.log" 2>&1
20
+ echo "ALL CF_FPF DONE $(date +%H:%M:%S)"
run_cf_long.sh ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Causal-Forcing-a Predictor rows at longer video lengths (14 and 28 chunks = 165 / 333
3
+ # frames; the 21-frame KV window rolls beyond chunk 7): FFFF reference + ATC-chunk
4
+ # Stage-1 + Stage-2 at FPPF, generated paired in the same process, two prompt shards on
5
+ # GPUs 4/7 with the burn guard; VBench-251 afterwards on GPUs 5/6.
6
+ set -u
7
+ C=/local/zoubin/cz/projects/comparison; SFPY=/local/zoubin/cz/envs/self_forcing/bin/python
8
+ LOG="$1"; cd "$C"
9
+ export SSL_CERT_FILE=/etc/pki/tls/certs/ca-bundle.crt
10
+ export HF_HOME=/local/zoubin/cz/.cache/huggingface HF_HUB_CACHE=/local/zoubin/cz/.cache/huggingface/hub
11
+ export TRANSFORMERS_CACHE=/local/zoubin/cz/.cache/huggingface/hub TORCH_HOME=/local/zoubin/cz/.cache/torch
12
+ export XDG_CACHE_HOME=/local/zoubin/cz/.cache
13
+ bash burn_guard.sh "4 7" > "$LOG/burn_guard.log" 2>&1 &
14
+ guard=$!
15
+ sleep 3
16
+ for n in 14 28; do
17
+ echo "=== ${n}-chunk generation $(date +%H:%M:%S) ==="
18
+ CUDA_VISIBLE_DEVICES=4 $SFPY eval/generate_predictor_eval.py --models atc_chunk,atc_chunk_s2 --patterns FPPF \
19
+ --num-chunks $n --tag _${n}c --ref-tag _${n}c --shard 0 --num-shards 2 --out-root eval_out > "$LOG/gen_${n}c_0.log" 2>&1 &
20
+ p0=$!
21
+ CUDA_VISIBLE_DEVICES=7 $SFPY eval/generate_predictor_eval.py --models atc_chunk,atc_chunk_s2 --patterns FPPF \
22
+ --num-chunks $n --tag _${n}c --ref-tag _${n}c --shard 1 --num-shards 2 --out-root eval_out > "$LOG/gen_${n}c_1.log" 2>&1 &
23
+ p1=$!
24
+ wait $p0; wait $p1
25
+ done
26
+ kill $guard 2>/dev/null
27
+ echo "=== vbench on GPUs 5/6 $(date +%H:%M:%S) ==="
28
+ bash run_vbench_gpu5.sh "$LOG" 5 cfa_14c_ffff,cfa_atc_chunk_14c_fppf,cfa_atc_chunk_s2_14c_fppf 6 8 2 > "$LOG/vb5.log" 2>&1 &
29
+ bash run_vbench_gpu5.sh "$LOG" 6 cfa_28c_ffff,cfa_atc_chunk_28c_fppf,cfa_atc_chunk_s2_28c_fppf 6 8 2 > "$LOG/vb6.log" 2>&1 &
30
+ wait
31
+ $SFPY eval/aggregate.py --out-root eval_out --allow-incomplete 2>&1 | tail -1
32
+ python3 experiment_md.py
33
+ echo "ALL CF_LONG DONE $(date +%H:%M:%S)"
run_compare.py ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """Run one (base model, cache method, parameter) configuration and report the
3
+ denoise-DiT speedup.
4
+
5
+ python run_compare.py --base self_forcing --method teacache --thresh 0.05 \
6
+ --num-prompts 8 --out results/sf_teacache_0.05.json
7
+
8
+ Both base models expect to be run from inside their own repo (they load
9
+ ``wan_models/...`` by relative path), so this script chdirs there and puts the
10
+ repo first on ``sys.path``.
11
+ """
12
+
13
+ import argparse
14
+ import json
15
+ import os
16
+ import sys
17
+ import time
18
+
19
+ ROOT = os.path.dirname(os.path.abspath(__file__))
20
+ sys.path.insert(0, ROOT)
21
+
22
+ from harness import BASES, enter_base, load_pipeline # noqa: E402
23
+
24
+
25
+ def parse_args():
26
+ p = argparse.ArgumentParser()
27
+ p.add_argument("--base", choices=sorted(BASES), required=True)
28
+ p.add_argument("--method", default="none")
29
+ p.add_argument("--thresh", type=float, default=None)
30
+ p.add_argument("--interval", type=float, default=None)
31
+ p.add_argument("--max-order", type=int, default=None)
32
+ p.add_argument("--group-size", type=int, default=None)
33
+ p.add_argument("--weight-norm", default=None)
34
+ p.add_argument("--min-update-ratio", type=float, default=None)
35
+ p.add_argument("--temporal-consistency", action="store_true")
36
+ p.add_argument("--schedule", default="FxxF",
37
+ help="Per-chunk step schedule, F = always full, x = cacheable")
38
+ p.add_argument("--indicator", default="modulated_input",
39
+ choices=["modulated_input", "e0"])
40
+ p.add_argument("--coefficients", default=None,
41
+ help="JSON file or comma list of rescale polynomial coefficients")
42
+ p.add_argument("--prompt-file", default=None)
43
+ p.add_argument("--num-prompts", type=int, default=8)
44
+ p.add_argument("--num-output-frames", type=int, default=21)
45
+ p.add_argument("--seed", type=int, default=0)
46
+ p.add_argument("--warmup", type=int, default=1,
47
+ help="Prompts run before timing starts (excluded from the mean)")
48
+ p.add_argument("--save-video-dir", default=None)
49
+ p.add_argument("--save-latents-dir", default=None)
50
+ p.add_argument("--out", default=None)
51
+ p.add_argument("--baseline-ms", type=float, default=None,
52
+ help="Reference denoise-DiT ms/video for the speedup column")
53
+ return p.parse_args()
54
+
55
+
56
+ def load_coefficients(spec):
57
+ if spec is None:
58
+ return None
59
+ # main() chdirs into the base repo, so resolve a relative file against ROOT.
60
+ if not os.path.isabs(spec) and os.path.exists(os.path.join(ROOT, spec)):
61
+ spec = os.path.join(ROOT, spec)
62
+ if os.path.exists(spec):
63
+ with open(spec) as f:
64
+ data = json.load(f)
65
+ return data["coefficients"] if isinstance(data, dict) else data
66
+ return [float(v) for v in spec.split(",")]
67
+
68
+
69
+ def main():
70
+ args = parse_args()
71
+ base = enter_base(args.base)
72
+
73
+ import torch
74
+
75
+ from utils.dataset import TextDataset
76
+ from utils.misc import set_seed
77
+
78
+ from cachelib import (CacheController, build_method, cached_inference, install,
79
+ parse_schedule)
80
+
81
+ set_seed(args.seed)
82
+ torch.set_grad_enabled(False)
83
+ device = torch.device("cuda")
84
+ pipeline = load_pipeline(base)
85
+
86
+ method = build_method(
87
+ args.method,
88
+ thresh=args.thresh,
89
+ interval=args.interval,
90
+ max_order=args.max_order,
91
+ group_size=args.group_size,
92
+ weight_norm=args.weight_norm,
93
+ min_update_ratio=args.min_update_ratio,
94
+ temporal_consistency=args.temporal_consistency or None,
95
+ indicator=args.indicator,
96
+ coefficients=load_coefficients(args.coefficients),
97
+ )
98
+ num_steps = len(pipeline.denoising_step_list)
99
+ controller = CacheController(method, num_steps=num_steps,
100
+ forced_steps=parse_schedule(args.schedule, num_steps))
101
+ install(pipeline.generator.model, controller)
102
+
103
+ prompt_file = args.prompt_file or ("prompts/MovieGenVideoBench.txt"
104
+ if os.path.exists("prompts/MovieGenVideoBench.txt")
105
+ else "prompts/demos.txt")
106
+ dataset = TextDataset(prompt_path=prompt_file)
107
+ n = min(args.num_prompts + args.warmup, len(dataset))
108
+
109
+ # main() has chdir'd into the base repo, so a relative output dir would land
110
+ # inside the clone; resolve it against the project root instead.
111
+ def _resolve(d):
112
+ return d if d is None or os.path.isabs(d) else os.path.join(ROOT, d)
113
+
114
+ args.save_video_dir = _resolve(args.save_video_dir)
115
+ args.save_latents_dir = _resolve(args.save_latents_dir)
116
+ for d in (args.save_video_dir, args.save_latents_dir):
117
+ if d:
118
+ os.makedirs(d, exist_ok=True)
119
+
120
+ records = []
121
+ for i in range(n):
122
+ prompt = dataset[i]["prompts"]
123
+ set_seed(args.seed)
124
+ noise = torch.randn([1, args.num_output_frames, 16, 60, 104],
125
+ device=device, dtype=torch.bfloat16)
126
+
127
+ wall0 = time.time()
128
+ video, latents, timing = cached_inference(
129
+ pipeline, controller, noise, [prompt],
130
+ decode=bool(args.save_video_dir))
131
+ wall = time.time() - wall0
132
+
133
+ rec = dict(timing)
134
+ rec.update(controller.summary())
135
+ rec["prompt_index"] = i
136
+ rec["warmup"] = i < args.warmup
137
+ rec["wall_s"] = wall
138
+ records.append(rec)
139
+
140
+ if args.save_latents_dir and i >= args.warmup:
141
+ torch.save(latents.float().cpu(),
142
+ os.path.join(args.save_latents_dir, f"{i:04d}.pt"))
143
+ if args.save_video_dir and i >= args.warmup:
144
+ from einops import rearrange
145
+ from torchvision.io import write_video
146
+ frames = 255.0 * rearrange(video, "b t c h w -> b t h w c").cpu()
147
+ write_video(os.path.join(args.save_video_dir, f"{i:04d}.mp4"),
148
+ frames[0], fps=16)
149
+ pipeline.vae.model.clear_cache()
150
+
151
+ print(f"[{i}] denoise_dit={timing['denoise_dit_ms']:.1f}ms "
152
+ f"compute_eq={rec.get('compute_equivalent_forwards', 0):.2f}"
153
+ f"/{rec.get('denoise_forwards', 0)} wall={wall:.1f}s", flush=True)
154
+
155
+ import statistics
156
+
157
+ timed = [r for r in records if not r["warmup"]]
158
+ ms = sorted(r["denoise_dit_ms"] for r in timed)
159
+ mean_ms = statistics.fmean(ms)
160
+ # The node is shared, so a few prompts land on a contended GPU and show up as
161
+ # high outliers. The median is the stable statistic; the mean is kept for
162
+ # reference and the spread is reported so an unusable run is visible.
163
+ median_ms = statistics.median(ms)
164
+ mean_compute = statistics.fmean(r["compute_equivalent_forwards"] for r in timed)
165
+ mean_forwards = statistics.fmean(r["denoise_forwards"] for r in timed)
166
+
167
+ summary = {
168
+ "base": args.base,
169
+ "method": args.method,
170
+ "method_config": method.config(),
171
+ "schedule": controller.schedule,
172
+ "num_prompts": len(timed),
173
+ "num_output_frames": args.num_output_frames,
174
+ "median_denoise_dit_ms": median_ms,
175
+ "mean_denoise_dit_ms": mean_ms,
176
+ "stdev_denoise_dit_ms": statistics.stdev(ms) if len(ms) > 1 else 0.0,
177
+ "min_denoise_dit_ms": ms[0],
178
+ "max_denoise_dit_ms": ms[-1],
179
+ "mean_compute_equivalent_forwards": mean_compute,
180
+ "mean_denoise_forwards": mean_forwards,
181
+ "flops_speedup_estimate": mean_forwards / mean_compute if mean_compute else None,
182
+ "mean_first_chunk_denoise_ms": statistics.fmean(
183
+ r["first_chunk_denoise_ms"] for r in timed),
184
+ "records": records,
185
+ }
186
+ if args.baseline_ms:
187
+ summary["measured_speedup"] = args.baseline_ms / median_ms
188
+
189
+ print(json.dumps({k: v for k, v in summary.items() if k != "records"}, indent=2))
190
+
191
+ if args.out:
192
+ out = args.out if os.path.isabs(args.out) else os.path.join(ROOT, args.out)
193
+ os.makedirs(os.path.dirname(out), exist_ok=True)
194
+ with open(out, "w") as f:
195
+ json.dump(summary, f, indent=2)
196
+ print(f"wrote {out}")
197
+
198
+
199
+ if __name__ == "__main__":
200
+ main()
run_hy_disca_c0.sh ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # HY DisCa Stage-1 (DEV project, blocks [0,53], step 2000) on validation25, FPPF with chunk 0
3
+ # forced full: DEV generator with --force_first_chunk_full (2 workers on GPUs 4/7), DEV
4
+ # metrics, imported as hy_disca_s1_fppf, Core5 scoring on GPUs 5/6, hy_aggregate, md.
5
+ set -u
6
+ C=/local/zoubin/cz/projects/comparison; PY=/local/zoubin/cz/envs/hy_worldplay_july20260720/bin/python
7
+ DEV=/local/zoubin/cz/projects/HY-WorldPlay-DEV-Predictor
8
+ DS=$DEV/datasets/hyworldplay_predictor_vbench_val25_test50
9
+ WEIGHTS=$DEV/checkpoints/predictor_disca_blocks0-53_bf16_8gpu_flr1e-4_blr1e-5_schedsteps2000_swarmup100_bwarmup100_swanlab/predictor_step_02000.safetensors
10
+ BASE=/local/zoubin/cz/checkpoints/hy_worldplay/huggingface/hub/models--tencent--HunyuanVideo-1.5/snapshots/9b49404b3f5df2a8f0b31df27a0c7ab872e7b038
11
+ ACT=/local/zoubin/cz/checkpoints/hy_worldplay/huggingface/hub/models--tencent--HY-WorldPlay/snapshots/f4c29235647707b571479a69b569e4166f9f5bf8/ar_distilled_action_model/diffusion_pytorch_model.safetensors
12
+ LOG="$1"; cd "$C"
13
+ export SSL_CERT_FILE=/etc/pki/tls/certs/ca-bundle.crt HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1
14
+ export HF_HOME=/local/zoubin/cz/checkpoints/hy_worldplay/huggingface HF_HUB_CACHE=/local/zoubin/cz/checkpoints/hy_worldplay/huggingface/hub
15
+ export TRANSFORMERS_CACHE=/local/zoubin/cz/checkpoints/hy_worldplay/huggingface/hub TORCH_HOME=/local/zoubin/cz/.cache XDG_CACHE_HOME=/local/zoubin/cz/.cache
16
+ bash burn_guard.sh "4 7" > "$LOG/burn_guard.log" 2>&1 &
17
+ guard=$!
18
+ sleep 3
19
+ sched=fppf; rs="1,2"
20
+ name="eval_validation25_disca_blocks0-53_bf16_ckptstep2000_schedule-${sched}_c0FFFF"
21
+ root="$DS/evaluations/$name"; mkdir -p "$root/logs"
22
+ n=$(find "$root/predictor" -name '*.mp4' 2>/dev/null | wc -l)
23
+ if [ "$n" -ne 100 ]; then
24
+ echo "=== DisCa S1 $sched c0FFFF generation $(date +%H:%M:%S) ==="
25
+ pids=()
26
+ for w in 0 1; do
27
+ gpu=$([ $w -eq 0 ] && echo 4 || echo 7)
28
+ ( cd "$DEV" && PYTHONPATH=$DEV HY_PROFILE_TIMING=1 CUDA_VISIBLE_DEVICES=$gpu $PY -u /local/zoubin/cz/projects/comparison/hy_dev_gen_disca.py \
29
+ --dataset_root "$DS/validation" --output_root "$root" --weights "$WEIGHTS" --base_model "$BASE" --action_ckpt "$ACT" \
30
+ --source_blocks 0,53 --predictor_variant disca --replace_steps "$rs" --modes predictor --force_first_chunk_full \
31
+ --worker_id $w --num_workers 2 >>> "$root/logs/generate_worker_$w.log" 2>&1 ) &
32
+ pids+=($!)
33
+ done
34
+ for p in "${pids[@]}"; do wait "$p"; done
35
+ n=$(find "$root/predictor" -name '*.mp4' | wc -l); echo "DisCa S1 $sched: $n videos"
36
+ fi
37
+ if [ ! -f "$root/metrics.completed" ]; then
38
+ echo "=== DisCa S1 $sched metrics $(date +%H:%M:%S) ==="
39
+ pids=()
40
+ for w in 0 1; do
41
+ gpu=$([ $w -eq 0 ] && echo 4 || echo 7)
42
+ ( cd "$DEV" && PYTHONPATH=$DEV CUDA_VISIBLE_DEVICES=$gpu $PY -u tools/compute_predictor_v4_train_case_metrics.py \
43
+ --dataset_root "$DS/validation" --output_root "$root" --num_cases 25 --reference_subdir full --modes predictor \
44
+ --metric_batch_size 4 --worker_id $w --num_workers 2 > "$root/logs/metrics_worker_$w.log" 2>&1 ) &
45
+ pids+=($!)
46
+ done
47
+ for p in "${pids[@]}"; do wait "$p"; done
48
+ ( cd "$DEV" && PYTHONPATH=$DEV $PY tools/merge_predictor_v4_train_case_metrics.py --output_root "$root" --num_workers 2 \
49
+ --num_cases 25 --modes predictor --replace_steps "$rs" --reference_label "Full-DiT validation videos" > "$root/logs/metrics_merge.log" 2>&1 ) \
50
+ && date -u +%FT%TZ > "$root/metrics.completed" || echo "metrics merge FAILED"
51
+ fi
52
+ kill $guard 2>/dev/null
53
+ /local/zoubin/cz/envs/self_forcing/bin/python hy_import_dev_eval.py --eval-root "$root" --strategy hy_disca_s1_fppf \
54
+ --schedule FPPF --model disca_stage1 --predictor-blocks 2 || echo "IMPORT FAILED"
55
+ while pgrep -f "run_vbench.py --strategy" >/dev/null; do sleep 30; done
56
+ echo "=== scoring on GPUs 5/6 $(date +%H:%M:%S) ==="
57
+ OMP_NUM_THREADS=16 MKL_NUM_THREADS=16 GPUS="5 6 5 6" bash hy_vbench.sh "$LOG" 2>&1 | tee "$LOG/hy_vbench_driver.log" | grep -v "^\[gpu"
58
+ python3 hy_aggregate.py 2>&1 | tail -2
59
+ python3 experiment_md.py
60
+ echo "ALL HY_DISCA_C0 DONE $(date +%H:%M:%S)"
run_hy_disca_finish47.sh ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Finish the DisCa batch on GPUs 4-7: resume step-2000 FPPP generation (DEV generator
3
+ # skips finished videos), DEV metrics, import, then Core5 scoring of the three unscored
4
+ # DisCa sets, hy_aggregate, Experiment.md.
5
+ set -u
6
+ C=/local/zoubin/cz/projects/comparison; PY=/local/zoubin/cz/envs/hy_worldplay_july20260720/bin/python
7
+ DEV=/local/zoubin/cz/projects/HY-WorldPlay-DEV-Predictor
8
+ DS=$DEV/datasets/hyworldplay_predictor_vbench_val25_test50
9
+ CK=$DEV/checkpoints/predictor_disca_blocks0-53_bf16_8gpu_flr1e-4_blr1e-5_schedsteps2000_swarmup100_bwarmup100_swanlab
10
+ BASE=/local/zoubin/cz/checkpoints/hy_worldplay/huggingface/hub/models--tencent--HunyuanVideo-1.5/snapshots/9b49404b3f5df2a8f0b31df27a0c7ab872e7b038
11
+ ACT=/local/zoubin/cz/checkpoints/hy_worldplay/huggingface/hub/models--tencent--HY-WorldPlay/snapshots/f4c29235647707b571479a69b569e4166f9f5bf8/ar_distilled_action_model/diffusion_pytorch_model.safetensors
12
+ LOG="$1"; cd "$C"
13
+ export SSL_CERT_FILE=/etc/pki/tls/certs/ca-bundle.crt HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1
14
+ export HF_HOME=/local/zoubin/cz/checkpoints/hy_worldplay/huggingface HF_HUB_CACHE=/local/zoubin/cz/checkpoints/hy_worldplay/huggingface/hub
15
+ export TRANSFORMERS_CACHE=/local/zoubin/cz/checkpoints/hy_worldplay/huggingface/hub TORCH_HOME=/local/zoubin/cz/.cache XDG_CACHE_HOME=/local/zoubin/cz/.cache
16
+ GPUS=(4 5 6 7)
17
+ bash burn_guard.sh "4 5 6 7" > "$LOG/burn_guard.log" 2>&1 &
18
+ guard=$!
19
+ sleep 3
20
+ root=$DS/evaluations/eval_validation25_disca_blocks0-53_bf16_ckptstep2000_schedule-fppp_c0FFFF
21
+ if [ "$(find "$root/predictor" -name '*.mp4' | wc -l)" -ne 100 ]; then
22
+ echo "=== hy_disca_s1_fppp resume generation $(date +%H:%M:%S) ==="
23
+ pids=()
24
+ for w in 0 1 2 3; do
25
+ ( cd "$DEV" && PYTHONPATH=$DEV HY_PROFILE_TIMING=1 CUDA_VISIBLE_DEVICES=${GPUS[$w]} $PY -u $C/hy_dev_gen_disca.py \
26
+ --dataset_root "$DS/validation" --output_root "$root" --weights $CK/predictor_step_02000.safetensors --base_model "$BASE" --action_ckpt "$ACT" \
27
+ --source_blocks 0,53 --predictor_variant disca --replace_steps 1,2,3 --modes predictor --force_first_chunk_full \
28
+ --worker_id $w --num_workers 4 > "$root/logs/generate_resume47_worker_$w.log" 2>&1 ) &
29
+ pids+=($!)
30
+ done
31
+ for p in "${pids[@]}"; do wait "$p"; done
32
+ echo "hy_disca_s1_fppp: $(find $root/predictor -name '*.mp4' | wc -l) videos"
33
+ fi
34
+ if [ ! -f "$root/metrics.completed" ]; then
35
+ echo "=== hy_disca_s1_fppp metrics $(date +%H:%M:%S) ==="
36
+ rm -rf "$root/metrics"; pids=()
37
+ for w in 0 1 2 3; do
38
+ ( cd "$DEV" && PYTHONPATH=$DEV CUDA_VISIBLE_DEVICES=${GPUS[$w]} $PY -u tools/compute_predictor_v4_train_case_metrics.py \
39
+ --dataset_root "$DS/validation" --output_root "$root" --num_cases 25 --reference_subdir full --modes predictor \
40
+ --metric_batch_size 4 --worker_id $w --num_workers 4 > "$root/logs/metrics_worker_$w.log" 2>&1 ) &
41
+ pids+=($!)
42
+ done
43
+ for p in "${pids[@]}"; do wait "$p"; done
44
+ ( cd "$DEV" && PYTHONPATH=$DEV $PY tools/merge_predictor_v4_train_case_metrics.py --output_root "$root" --num_workers 4 \
45
+ --num_cases 25 --modes predictor --replace_steps 1,2,3 --reference_label "Full-DiT validation videos" > "$root/logs/metrics_merge.log" 2>&1 ) \
46
+ && date -u +%FT%TZ > "$root/metrics.completed" || echo "metrics merge FAILED"
47
+ fi
48
+ /local/zoubin/cz/envs/self_forcing/bin/python hy_import_dev_eval.py --eval-root "$root" --strategy hy_disca_s1_fppp --schedule FPPP --model disca_stage1 --predictor-blocks 2 || echo "IMPORT FAILED"
49
+ kill $guard 2>/dev/null
50
+ export HF_HOME=/local/zoubin/cz/.cache/huggingface HF_HUB_CACHE=/local/zoubin/cz/.cache/huggingface/hub
51
+ echo "=== scoring on GPUs 4-7 $(date +%H:%M:%S) ==="
52
+ OMP_NUM_THREADS=16 MKL_NUM_THREADS=16 GPUS="4 5 6 7" bash hy_vbench.sh "$LOG" 2>&1 | tee "$LOG/hy_vbench_driver.log" | grep -v "^\[gpu"
53
+ python3 hy_aggregate.py 2>&1 | tail -1
54
+ python3 experiment_md.py
55
+ echo "ALL HY_DISCA_FINISH DONE $(date +%H:%M:%S)"
run_hy_disca_more.sh ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # HY DisCa Stage-1 on validation25, chunk 0 forced full: step-1000 FPPF/FPPP and
3
+ # step-2000 FPPP. DEV generator via the DisCa compatibility wrapper, 4 workers on
4
+ # GPUs 4-7 (burn guard on), DEV metrics, import, Core5 scoring on GPUs 5/6.
5
+ set -u
6
+ C=/local/zoubin/cz/projects/comparison; PY=/local/zoubin/cz/envs/hy_worldplay_july20260720/bin/python
7
+ DEV=/local/zoubin/cz/projects/HY-WorldPlay-DEV-Predictor
8
+ DS=$DEV/datasets/hyworldplay_predictor_vbench_val25_test50
9
+ CK=$DEV/checkpoints/predictor_disca_blocks0-53_bf16_8gpu_flr1e-4_blr1e-5_schedsteps2000_swarmup100_bwarmup100_swanlab
10
+ BASE=/local/zoubin/cz/checkpoints/hy_worldplay/huggingface/hub/models--tencent--HunyuanVideo-1.5/snapshots/9b49404b3f5df2a8f0b31df27a0c7ab872e7b038
11
+ ACT=/local/zoubin/cz/checkpoints/hy_worldplay/huggingface/hub/models--tencent--HY-WorldPlay/snapshots/f4c29235647707b571479a69b569e4166f9f5bf8/ar_distilled_action_model/diffusion_pytorch_model.safetensors
12
+ LOG="$1"; cd "$C"
13
+ export SSL_CERT_FILE=/etc/pki/tls/certs/ca-bundle.crt HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1
14
+ export HF_HOME=/local/zoubin/cz/checkpoints/hy_worldplay/huggingface HF_HUB_CACHE=/local/zoubin/cz/checkpoints/hy_worldplay/huggingface/hub
15
+ export TRANSFORMERS_CACHE=/local/zoubin/cz/checkpoints/hy_worldplay/huggingface/hub TORCH_HOME=/local/zoubin/cz/.cache XDG_CACHE_HOME=/local/zoubin/cz/.cache
16
+ GPUS=(4 5 6 7)
17
+ bash burn_guard.sh "4 5 6 7" > "$LOG/burn_guard.log" 2>&1 &
18
+ guard=$!
19
+ sleep 3
20
+ # step:schedule:strategy
21
+ for spec in "1000:fppf:hy_disca_s1000_fppf" "1000:fppp:hy_disca_s1000_fppp" "2000:fppp:hy_disca_s1_fppp"; do
22
+ IFS=: read -r step sched strat <<<"$spec"
23
+ rs="1,2"; [ "$sched" = fppp ] && rs="1,2,3"
24
+ W=$CK/predictor_step_$(printf "%05d" "$step").safetensors
25
+ name="eval_validation25_disca_blocks0-53_bf16_ckptstep${step}_schedule-${sched}_c0FFFF"
26
+ root="$DS/evaluations/$name"; mkdir -p "$root/logs"
27
+ n=$(find "$root/predictor" -name '*.mp4' 2>/dev/null | wc -l)
28
+ if [ "$n" -ne 100 ]; then
29
+ echo "=== $strat generation $(date +%H:%M:%S) ==="
30
+ pids=()
31
+ for w in 0 1 2 3; do
32
+ ( cd "$DEV" && PYTHONPATH=$DEV HY_PROFILE_TIMING=1 CUDA_VISIBLE_DEVICES=${GPUS[$w]} $PY -u $C/hy_dev_gen_disca.py \
33
+ --dataset_root "$DS/validation" --output_root "$root" --weights "$W" --base_model "$BASE" --action_ckpt "$ACT" \
34
+ --source_blocks 0,53 --predictor_variant disca --replace_steps "$rs" --modes predictor --force_first_chunk_full \
35
+ --worker_id $w --num_workers 4 >> "$root/logs/generate_worker_$w.log" 2>&1 ) &
36
+ pids+=($!)
37
+ done
38
+ for p in "${pids[@]}"; do wait "$p"; done
39
+ n=$(find "$root/predictor" -name '*.mp4' | wc -l); echo "$strat: $n videos"
40
+ fi
41
+ if [ ! -f "$root/metrics.completed" ]; then
42
+ echo "=== $strat metrics $(date +%H:%M:%S) ==="
43
+ pids=()
44
+ for w in 0 1 2 3; do
45
+ ( cd "$DEV" && PYTHONPATH=$DEV CUDA_VISIBLE_DEVICES=${GPUS[$w]} $PY -u tools/compute_predictor_v4_train_case_metrics.py \
46
+ --dataset_root "$DS/validation" --output_root "$root" --num_cases 25 --reference_subdir full --modes predictor \
47
+ --metric_batch_size 4 --worker_id $w --num_workers 4 > "$root/logs/metrics_worker_$w.log" 2>&1 ) &
48
+ pids+=($!)
49
+ done
50
+ for p in "${pids[@]}"; do wait "$p"; done
51
+ ( cd "$DEV" && PYTHONPATH=$DEV $PY tools/merge_predictor_v4_train_case_metrics.py --output_root "$root" --num_workers 4 \
52
+ --num_cases 25 --modes predictor --replace_steps "$rs" --reference_label "Full-DiT validation videos" > "$root/logs/metrics_merge.log" 2>&1 ) \
53
+ && date -u +%FT%TZ > "$root/metrics.completed" || echo "$strat metrics merge FAILED"
54
+ fi
55
+ U=$(echo "$sched" | tr a-z A-Z)
56
+ /local/zoubin/cz/envs/self_forcing/bin/python hy_import_dev_eval.py --eval-root "$root" --strategy "$strat" \
57
+ --schedule "$U" --model disca_stage1 --predictor-blocks 2 || echo "IMPORT FAILED $strat"
58
+ done
59
+ kill $guard 2>/dev/null
60
+ echo "=== scoring on GPUs 5/6 $(date +%H:%M:%S) ==="
61
+ OMP_NUM_THREADS=16 MKL_NUM_THREADS=16 GPUS="5 6 5 6" bash hy_vbench.sh "$LOG" 2>&1 | tee "$LOG/hy_vbench_driver.log" | grep -v "^\[gpu"
62
+ python3 hy_aggregate.py 2>&1 | tail -2
63
+ python3 experiment_md.py
64
+ echo "ALL HY_DISCA_MORE DONE $(date +%H:%M:%S)"
scan_points.py ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """Parameter scan for one (base, method, schedule), reporting what the compute
3
+ fraction hides:
4
+ how the recomputed-token budget is spread over the cacheable steps.
5
+
6
+ For a token-wise method the interesting quantity is not "how many tokens in
7
+ total" but "is every cacheable step making a *partial* decision". A point where
8
+ most cacheable steps are empty (or nearly full) is behaviourally TeaCache with
9
+ extra bookkeeping, whatever its compute fraction says.
10
+
11
+ Reports per threshold:
12
+ compute compute-equivalent forwards / total, and the implied FLOPs speedup
13
+ measured paired wall-clock speedup against FFFF on the same prompts
14
+ active fraction of cacheable steps with 0 < selected < 100% of tokens
15
+ sel mean / p10 / p90 selected-token fraction over the active steps
16
+
17
+ CUDA_VISIBLE_DEVICES=0 python mc_scan.py --base self_forcing \
18
+ --schedule FxxF --thresholds 0.5,0.75,1.0,1.25,1.5,2.0,2.5
19
+ """
20
+ import argparse, json, os, statistics as st, sys
21
+
22
+ ROOT = os.path.dirname(os.path.abspath(__file__))
23
+ sys.path.insert(0, ROOT)
24
+ from harness import BASES, enter_base, load_pipeline, load_prompts # noqa: E402
25
+
26
+ ap = argparse.ArgumentParser()
27
+ ap.add_argument("--base", choices=sorted(BASES), required=True)
28
+ ap.add_argument("--schedule", default="FxxF")
29
+ ap.add_argument("--method", default="motioncache",
30
+ choices=["teacache", "flowcache", "taylorseer", "motioncache"])
31
+ ap.add_argument("--values", required=True, help="Comma-separated parameter values")
32
+ ap.add_argument("--coefficients", default=None)
33
+ ap.add_argument("--weight-norm", default=None)
34
+ ap.add_argument("--max-order", type=int, default=None)
35
+ ap.add_argument("--num-prompts", type=int, default=3)
36
+ ap.add_argument("--num-output-frames", type=int, default=21)
37
+ ap.add_argument("--seed", type=int, default=0)
38
+ ap.add_argument("--out", default=None)
39
+ args = ap.parse_args()
40
+
41
+ coefficients = None
42
+ if args.coefficients:
43
+ p = args.coefficients if os.path.isabs(args.coefficients) else os.path.join(ROOT, args.coefficients)
44
+ coefficients = json.load(open(p))["coefficients"]
45
+
46
+ base = enter_base(args.base)
47
+ import torch
48
+ from utils.misc import set_seed
49
+ from cachelib import CacheController, build_method, cached_inference, install, parse_schedule
50
+
51
+ torch.set_grad_enabled(False)
52
+ pipe = load_pipeline(base)
53
+ num_steps = len(pipe.denoising_step_list)
54
+ forced = set(parse_schedule(args.schedule, num_steps))
55
+ prompts = load_prompts(args.num_prompts + 1)
56
+
57
+
58
+ def run(method, **kw):
59
+ ctrl = CacheController(build_method(method, coefficients=coefficients, **kw),
60
+ num_steps=num_steps, forced_steps=tuple(sorted(forced)))
61
+ install(pipe.generator.model, ctrl)
62
+ ms, recs = [], []
63
+ for i, prompt in enumerate(prompts):
64
+ set_seed(args.seed)
65
+ noise = torch.randn([1, args.num_output_frames, 16, 60, 104],
66
+ device=torch.device("cuda"), dtype=torch.bfloat16)
67
+ _, _, timing = cached_inference(pipe, ctrl, noise, [prompt], decode=False)
68
+ if i == 0:
69
+ continue # warm-up prompt
70
+ ms.append(timing["denoise_dit_ms"])
71
+ recs += [r for r in ctrl.records if r["step"] not in forced]
72
+ return min(ms), recs, ctrl.summary()
73
+
74
+
75
+ PARAM = {"teacache": "thresh", "flowcache": "thresh", "motioncache": "thresh",
76
+ "taylorseer": "interval"}
77
+ pname = PARAM[args.method]
78
+
79
+ base_ms, _, _ = run("none") # warm-up + reference point
80
+ print(f"baseline (FFFF) min denoise: {base_ms:.0f} ms over {args.num_prompts} prompts, "
81
+ f"schedule {args.schedule}, {num_steps} steps", flush=True)
82
+ print(f"{pname[:8]:>8}{'Full/28':>9}{'compute_x':>10}{'measured_x':>11}"
83
+ f"{'active%':>9}{'empty%':>8}{'full%':>7}{'sel_mean%':>10}{'sel_p10%':>9}{'sel_p90%':>9}")
84
+ rows = []
85
+ for t in [float(v) for v in args.values.split(",")]:
86
+ kw = {pname: t}
87
+ if args.weight_norm and args.method == "motioncache":
88
+ kw["weight_norm"] = args.weight_norm
89
+ if args.max_order is not None and args.method == "taylorseer":
90
+ kw["max_order"] = args.max_order
91
+ # Pair every point with its own baseline: a start-of-scan reference drifts
92
+ # whenever a neighbour lands on the GPU, and this search targets *time*.
93
+ b_ms, _, _ = run("none")
94
+ ms, recs, summary = run(args.method, **kw)
95
+ fr = [r["compute_fraction"] for r in recs]
96
+ act = [f for f in fr if 1e-9 < f < 1 - 1e-9]
97
+ q = lambda v, p: sorted(v)[min(int(p * (len(v) - 1)), len(v) - 1)] if v else float("nan")
98
+ row = {"value": t, "param": pname, "method": args.method, "compute_equivalent": summary["compute_equivalent_forwards"],
99
+ "compute_speedup": summary["flops_speedup_estimate"], "measured_speedup": b_ms / ms, "paired_baseline_ms": b_ms,
100
+ "active_ratio": len(act) / len(fr), "empty_ratio": sum(f <= 1e-9 for f in fr) / len(fr),
101
+ "full_ratio": sum(f >= 1 - 1e-9 for f in fr) / len(fr),
102
+ "sel_mean": st.fmean(act) if act else 0.0, "sel_p10": q(act, .1), "sel_p90": q(act, .9),
103
+ "min_denoise_ms": ms}
104
+ rows.append(row)
105
+ print(f"{t:>8.4g}{row['compute_equivalent']:>9.2f}{row['compute_speedup']:>10.3f}"
106
+ f"{row['measured_speedup']:>11.3f}{100*row['active_ratio']:>9.1f}{100*row['empty_ratio']:>8.1f}"
107
+ f"{100*row['full_ratio']:>7.1f}{100*row['sel_mean']:>10.1f}{100*row['sel_p10']:>9.1f}"
108
+ f"{100*row['sel_p90']:>9.1f}", flush=True)
109
+
110
+ if args.out:
111
+ out = args.out if os.path.isabs(args.out) else os.path.join(ROOT, args.out)
112
+ os.makedirs(os.path.dirname(out), exist_ok=True)
113
+ json.dump({"base": args.base, "method": args.method, "param": pname,
114
+ "schedule": args.schedule, "baseline_ms": base_ms,
115
+ "weight_norm": args.weight_norm, "coefficients": coefficients, "rows": rows},
116
+ open(out, "w"), indent=2)
117
+ print("wrote", out)
scan_queue.sh ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Scan (base, method, schedule) grids for the new operating points, one job per
3
+ # quiet GPU among $GPUS. Targets are *measured* wall-clock speedup: 1.7-1.8x
4
+ # under FxxF and 2.7-3.0x under Fxxx, so the search must see time, not compute.
5
+ set -u
6
+ C=/local/zoubin/cz/projects/comparison
7
+ SFPY=/local/zoubin/cz/envs/self_forcing/bin/python
8
+ HYPY=/local/zoubin/cz/envs/hy_worldplay_july20260720/bin/python
9
+ LOG="$1"; GPUS=(${GPUS:-4 5 6 7}); WAIT=${WAIT:-60}
10
+ export SSL_CERT_FILE=/etc/pki/tls/certs/ca-bundle.crt
11
+ export TORCH_HOME=/local/zoubin/cz/.cache/torch XDG_CACHE_HOME=/local/zoubin/cz/.cache
12
+ cd "$C"; mkdir -p "$LOG" results
13
+ declare -A BUSY; pids=()
14
+ quiet_gpu() {
15
+ for g in "${GPUS[@]}"; do
16
+ [ -n "${BUSY[$g]:-}" ] && kill -0 "${BUSY[$g]}" 2>/dev/null && continue
17
+ used=$(nvidia-smi --query-gpu=memory.used --format=csv,noheader,nounits -i "$g" 2>/dev/null | tr -d ' ')
18
+ [ -z "$used" ] || [ "$used" -ge 8000 ] && continue
19
+ echo "$g"; return
20
+ done
21
+ }
22
+ # tag | kind | base | method | schedule | values
23
+ JOBS=(
24
+ "sf_teacache_FxxF|sf|self_forcing|teacache|FxxF|0.30,0.45,0.60,0.75,0.90,1.05,1.20,1.26"
25
+ "sf_taylorseer_FxxF|sf|self_forcing|taylorseer|FxxF|2.30,2.50,2.65,2.75,2.83,2.90"
26
+ "sf_motioncache_FxxF|sf|self_forcing|motioncache|FxxF|0.9,1.1,1.2,1.25,1.28,1.30,1.35,1.5"
27
+ "cf_teacache_FxxF|cf|causal_forcing|teacache|FxxF|0.30,0.45,0.60,0.75,0.90,1.05,1.20,1.26"
28
+ "cf_taylorseer_FxxF|cf|causal_forcing|taylorseer|FxxF|2.30,2.50,2.65,2.75,2.83,2.90"
29
+ "cf_motioncache_FxxF|cf|causal_forcing|motioncache|FxxF|0.9,1.1,1.2,1.25,1.28,1.30,1.35,1.5"
30
+ "sf_teacache_Fxxx|sf|self_forcing|teacache|Fxxx|0.9,1.1,1.25,1.4,1.55,1.7"
31
+ "sf_taylorseer_Fxxx|sf|self_forcing|taylorseer|Fxxx|3.0,3.3,3.5,3.65,3.8,3.9"
32
+ "sf_motioncache_Fxxx|sf|self_forcing|motioncache|Fxxx|1.9,2.2,2.5,2.9,3.4,4.0,5.0"
33
+ "cf_taylorseer_Fxxx|cf|causal_forcing|taylorseer|Fxxx|3.0,3.3,3.5,3.65,3.8,3.9"
34
+ "cf_motioncache_Fxxx|cf|causal_forcing|motioncache|Fxxx|1.9,2.2,2.5,2.9,3.4,4.0,5.0"
35
+ "hy_teacache_FxxF|hy|-|teacache|FxxF|0.15,0.25,0.33,0.40,0.46,0.49"
36
+ "hy_taylorseer_FxxF|hy|-|taylorseer|FxxF|2.3,2.5,2.65,2.75,2.85,2.92"
37
+ "hy_teacache_Fxxx|hy|-|teacache|Fxxx|0.30,0.45,0.60,0.75,0.90,1.05"
38
+ "hy_taylorseer_Fxxx|hy|-|taylorseer|Fxxx|3.0,3.3,3.5,3.65,3.8,3.9"
39
+ "hy_motioncache_FxxF|hy|-|motioncache|FxxF|0.17,0.20,0.23,0.27,0.31,0.36"
40
+ "hy_motioncache_Fxxx|hy|-|motioncache|Fxxx|0.45,0.60,0.65,0.70,0.75,0.90"
41
+ )
42
+ for job in "${JOBS[@]}"; do
43
+ IFS='|' read -r tag kind b m sched vals <<<"$job"
44
+ out="results/scan_${tag}.json"
45
+ [ -f "$out" ] && { echo "skip $tag"; continue; }
46
+ while true; do g=$(quiet_gpu); [ -n "$g" ] && break; sleep "$WAIT"; done
47
+ echo "[$(date +%H:%M:%S)] $tag -> GPU $g"
48
+ if [ "$kind" = hy ]; then
49
+ HF_HOME=/local/zoubin/cz/checkpoints/hy_worldplay/huggingface \
50
+ HF_HUB_CACHE=/local/zoubin/cz/checkpoints/hy_worldplay/huggingface/hub \
51
+ TRANSFORMERS_CACHE=/local/zoubin/cz/checkpoints/hy_worldplay/huggingface/hub \
52
+ HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1 \
53
+ CUDA_VISIBLE_DEVICES=$g $HYPY hy_scan_points.py --method "$m" --schedule "$sched" \
54
+ --values "$vals" --out "$out" > "$LOG/scan_$tag.log" 2>&1 &
55
+ else
56
+ HF_HOME=/local/zoubin/cz/.cache/huggingface HF_HUB_CACHE=/local/zoubin/cz/.cache/huggingface/hub \
57
+ TRANSFORMERS_CACHE=/local/zoubin/cz/.cache/huggingface/hub \
58
+ CUDA_VISIBLE_DEVICES=$g $SFPY scan_points.py --base "$b" --method "$m" --schedule "$sched" \
59
+ --values "$vals" --coefficients "results/coeff_${b}.json" --num-prompts 3 \
60
+ --out "$out" > "$LOG/scan_$tag.log" 2>&1 &
61
+ fi
62
+ BUSY[$g]=$!; pids+=($!); sleep 45
63
+ done
64
+ for p in "${pids[@]}"; do wait "$p"; done
65
+ echo "ALL SCANS DONE $(date +%H:%M:%S)"; ls results/scan_*.json 2>/dev/null | wc -l
summarize.py ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """Collect the results into one comparison table.
3
+
4
+ Prefers ``results/final_<base>.json`` (the serial re-measurement pass, which is
5
+ authoritative) and falls back to ``results/sweep_<base>_<method>.json``.
6
+
7
+ python summarize.py # markdown to stdout
8
+ python summarize.py --format csv
9
+ """
10
+
11
+ import argparse
12
+ import glob
13
+ import json
14
+ import os
15
+
16
+ ROOT = os.path.dirname(os.path.abspath(__file__))
17
+
18
+ METHOD_ORDER = ["teacache", "flowcache", "taylorseer", "motioncache"]
19
+ BASE_ORDER = ["self_forcing", "causal_forcing"]
20
+
21
+
22
+ def load_cost_models():
23
+ """Per-method (t_full, t_skip) in ms from the per-step overhead benchmark.
24
+
25
+ The two base models are the same architecture at the same shapes, so a full
26
+ step costs the same on both; the uncontended cost is therefore estimated by the
27
+ single fastest full step seen across every run of both. Using the smaller
28
+ number makes each skip ratio larger, so the derived speedups are the
29
+ conservative reading.
30
+ """
31
+ per_base, t_fulls = {}, []
32
+ for base in BASE_ORDER:
33
+ p = os.path.join(ROOT, f"results/overhead_{base}.json")
34
+ if not os.path.exists(p):
35
+ continue
36
+ with open(p) as f:
37
+ d = json.load(f)
38
+ t_fulls.append(d["t_full_global_ms"])
39
+ per_base[base] = d["methods"]
40
+ if not t_fulls:
41
+ return {}
42
+ t_full = min(t_fulls)
43
+ models = {}
44
+ for base, methods in per_base.items():
45
+ for m, r in methods.items():
46
+ if r.get("t_skip_ms"):
47
+ models[(base, m)] = (t_full, r["t_skip_ms"])
48
+ return models
49
+
50
+
51
+ def derived_speedup(models, base, method, compute_eq, forwards=28.0):
52
+ """Wall-clock speedup implied by the compute fraction and the step cost model.
53
+
54
+ A step costs t_skip when fully cached and t_full when fully recomputed, and is
55
+ affine in between, so the total is 28*t_skip + CE*(t_full - t_skip) where CE is
56
+ the compute-equivalent forward count. This is far more trustworthy than a
57
+ whole-video stopwatch on a saturated node: t_full and t_skip come from minima
58
+ over hundreds of per-step samples, while a video timing has ten.
59
+ """
60
+ if (base, method) not in models:
61
+ return None
62
+ t_full, t_skip = models[(base, method)]
63
+ total = forwards * t_skip + compute_eq * (t_full - t_skip)
64
+ return forwards * t_full / total if total else None
65
+
66
+
67
+ def rows_from_final(path):
68
+ with open(path) as f:
69
+ d = json.load(f)
70
+ out = []
71
+ for r in d["rows"]:
72
+ out.append({
73
+ "base": r["base"], "method": r["method"], "param": r["param"],
74
+ "value": r["value"], "target": r["target_speedup"],
75
+ "measured": r["measured_speedup"],
76
+ "paired_median": r.get("measured_speedup_paired_median"),
77
+ "paired_sd": r.get("measured_speedup_paired_stdev"),
78
+ "flops": r["flops_speedup"],
79
+ "compute_eq": r["compute_equivalent_forwards"],
80
+ "heldout_flops": r.get("heldout_flops_speedup"),
81
+ "heldout_drift": r.get("heldout_flops_drift"),
82
+ "base_ms": r.get("min_baseline_ms"),
83
+ "method_ms": r.get("min_method_ms"),
84
+ "retargeted": r.get("retargeted", False),
85
+ "source": "final",
86
+ })
87
+ return out
88
+
89
+
90
+ def rows_from_sweep(path):
91
+ with open(path) as f:
92
+ d = json.load(f)
93
+ out = []
94
+ for p in d.get("operating_points", []):
95
+ out.append({
96
+ "base": d["base"], "method": d["method"], "param": d["param"],
97
+ "value": p[d["param"]], "target": p["target_speedup"],
98
+ "measured": p["measured_speedup"],
99
+ "paired_median": p["measured_speedup"],
100
+ "paired_sd": p.get("measured_speedup_stdev"),
101
+ "flops": p["flops_speedup"],
102
+ "compute_eq": p["mean_compute_equivalent_forwards"],
103
+ "heldout_flops": None, "heldout_drift": None,
104
+ "base_ms": p.get("median_baseline_ms"),
105
+ "method_ms": p.get("median_method_ms"),
106
+ "retargeted": False,
107
+ "source": "sweep",
108
+ })
109
+ return out
110
+
111
+
112
+ def load_retimes():
113
+ """Stopwatch re-measurement of the settled points, keyed by (base, method, target)."""
114
+ out = {}
115
+ for base in BASE_ORDER:
116
+ p = os.path.join(ROOT, f"results/retime_{base}.json")
117
+ if not os.path.exists(p):
118
+ continue
119
+ with open(p) as f:
120
+ for r in json.load(f)["rows"]:
121
+ out[(base, r["method"], r["target_speedup"])] = r
122
+ return out
123
+
124
+
125
+ def load_all():
126
+ models = load_cost_models()
127
+ retimes = load_retimes()
128
+ rows = []
129
+ covered = set()
130
+ for base in BASE_ORDER:
131
+ # The final pass is split across processes (one per GPU), so a base can have
132
+ # several shards: final_<base>.json plus final_<base>_<suffix>.json.
133
+ for p in sorted(glob.glob(os.path.join(ROOT, f"results/final_{base}*.json"))):
134
+ got = rows_from_final(p)
135
+ rows += got
136
+ covered |= {(r["base"], r["method"]) for r in got}
137
+ for p in sorted(glob.glob(os.path.join(ROOT, "results/sweep_*.json"))):
138
+ with open(p) as f:
139
+ d = json.load(f)
140
+ if (d["base"], d["method"]) in covered:
141
+ continue
142
+ rows += rows_from_sweep(p)
143
+ for r in rows:
144
+ r["derived"] = derived_speedup(models, r["base"], r["method"], r["compute_eq"])
145
+ rt = retimes.get((r["base"], r["method"], r["target"]))
146
+ if rt:
147
+ r["stopwatch"] = rt["retimed_speedup_median"]
148
+ r["stopwatch_sd"] = rt["retimed_speedup_stdev"]
149
+ r["compute_eq"] = rt["retimed_compute_equivalent"]
150
+ r["flops"] = rt["retimed_flops_speedup"]
151
+ r["derived"] = derived_speedup(models, r["base"], r["method"],
152
+ r["compute_eq"])
153
+ rows.sort(key=lambda r: (
154
+ BASE_ORDER.index(r["base"]) if r["base"] in BASE_ORDER else 9,
155
+ METHOD_ORDER.index(r["method"]) if r["method"] in METHOD_ORDER else 9,
156
+ r["target"]))
157
+ return rows
158
+
159
+
160
+ def fmt_markdown(rows):
161
+ out = []
162
+ for base in BASE_ORDER:
163
+ sub = [r for r in rows if r["base"] == base]
164
+ if not sub:
165
+ continue
166
+ out.append(f"\n### {base}\n")
167
+ out.append("| method | target | param | value | denoise-DiT speedup | compute "
168
+ "speedup | forwards computed / 28 | held-out compute | stopwatch |")
169
+ out.append("|---|---|---|---|---|---|---|---|---|")
170
+ for r in sub:
171
+ ho = (f"{r['heldout_flops']:.3f}x ({r['heldout_drift']:+.3f})"
172
+ if r["heldout_flops"] is not None else "-")
173
+ dv = f"**{r['derived']:.3f}x**" if r.get("derived") else "-"
174
+ sw = (f"{r['stopwatch']:.2f}x ±{r['stopwatch_sd']:.2f}"
175
+ if r.get("stopwatch") else "-")
176
+ out.append(
177
+ f"| {r['method']} | {r['target']:g}x | {r['param']} | {r['value']:.5g} "
178
+ f"| {dv} | {r['flops']:.3f}x | {r['compute_eq']:.2f} | {ho} | {sw} |")
179
+ return "\n".join(out)
180
+
181
+
182
+ def fmt_csv(rows):
183
+ import csv
184
+ import io
185
+ buf = io.StringIO()
186
+ if not rows:
187
+ return ""
188
+ w = csv.DictWriter(buf, fieldnames=list(rows[0].keys()))
189
+ w.writeheader()
190
+ w.writerows(rows)
191
+ return buf.getvalue()
192
+
193
+
194
+ def main():
195
+ ap = argparse.ArgumentParser()
196
+ ap.add_argument("--format", choices=["markdown", "csv"], default="markdown")
197
+ ap.add_argument("--out", default=None)
198
+ args = ap.parse_args()
199
+
200
+ rows = load_all()
201
+ if not rows:
202
+ print("no results yet")
203
+ return
204
+ text = fmt_markdown(rows) if args.format == "markdown" else fmt_csv(rows)
205
+ print(text)
206
+ if args.out:
207
+ with open(args.out, "w") as f:
208
+ f.write(text)
209
+ print(f"\nwrote {args.out}")
210
+
211
+
212
+ if __name__ == "__main__":
213
+ main()
sweep.py ADDED
@@ -0,0 +1,264 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """Find, for one (base model, cache method) pair, the parameter values that hit
3
+ target denoise-DiT speedups.
4
+
5
+ The pipeline is loaded once and every parameter value is evaluated in the same
6
+ process, so a full sweep costs one model load.
7
+
8
+ Measurement protocol
9
+ --------------------
10
+ This node is shared. A neighbouring job inflates absolute timings by 30%+ and
11
+ drifts them *within* a sweep, so a baseline measured once at the start makes
12
+ later configurations look artificially fast. Two things follow:
13
+
14
+ * the parameter search runs on the **compute fraction**, which is exactly
15
+ deterministic given the prompt set and immune to contention;
16
+ * every reported speedup comes from a **paired A/B**: baseline and method are
17
+ run back to back on the same prompt and the per-prompt ratio is taken, so
18
+ drift cancels. The median over prompts is the headline number.
19
+
20
+ python sweep.py --base self_forcing --method teacache \
21
+ --coefficients results/coeff_self_forcing.json \
22
+ --out results/sweep_self_forcing_teacache.json
23
+ """
24
+
25
+ import argparse
26
+ import json
27
+ import os
28
+ import sys
29
+ import time
30
+
31
+ ROOT = os.path.dirname(os.path.abspath(__file__))
32
+ sys.path.insert(0, ROOT)
33
+
34
+ from harness import (BASES, enter_base, evaluate, free_gpus, # noqa: E402
35
+ load_pipeline, load_prompts, paired_evaluate)
36
+
37
+ # Parameter name and default search bracket for each method. Thresholds are on
38
+ # the rescaled accumulated distance; TaylorSeer's knob is its refresh interval.
39
+ PARAM = {
40
+ "teacache": ("thresh", 0.0, 4.0),
41
+ "flowcache": ("thresh", 0.0, 4.0),
42
+ "motioncache": ("thresh", 0.0, 12.0),
43
+ "taylorseer": ("interval", 1.0, 3.0),
44
+ }
45
+
46
+
47
+ def parse_args():
48
+ p = argparse.ArgumentParser()
49
+ p.add_argument("--base", choices=sorted(BASES), required=True)
50
+ p.add_argument("--method", choices=sorted(PARAM), required=True)
51
+ p.add_argument("--targets", default="1.3,1.6,2.0")
52
+ p.add_argument("--schedule", default="FxxF",
53
+ help="Per-chunk step schedule, F = always full, x = cacheable "
54
+ "(FxxF default; FFxx, Fxxx)")
55
+ p.add_argument("--indicator", default="modulated_input",
56
+ choices=["modulated_input", "e0"])
57
+ p.add_argument("--coefficients", default=None)
58
+ p.add_argument("--group-size", type=int, default=None)
59
+ p.add_argument("--weight-norm", default=None)
60
+ p.add_argument("--max-order", type=int, default=None)
61
+ p.add_argument("--min-update-ratio", type=float, default=None)
62
+ p.add_argument("--lo", type=float, default=None)
63
+ p.add_argument("--hi", type=float, default=None)
64
+ p.add_argument("--coarse-points", type=int, default=17)
65
+ p.add_argument("--search-prompts", type=int, default=3)
66
+ p.add_argument("--bisect-iters", type=int, default=12)
67
+ p.add_argument("--pair-prompts", type=int, default=7,
68
+ help="Prompts per paired A/B measurement (plus 1 warm-up pair)")
69
+ p.add_argument("--num-output-frames", type=int, default=21)
70
+ p.add_argument("--seed", type=int, default=0)
71
+ p.add_argument("--save-video-dir", default=None)
72
+ p.add_argument("--overhead-correction", action="store_true",
73
+ help="Aim the search at target/measured-overhead instead of at the "
74
+ "target compute budget directly (noisy on a shared node)")
75
+ p.add_argument("--skip-gpu-check", action="store_true")
76
+ p.add_argument("--out", required=True)
77
+ return p.parse_args()
78
+
79
+
80
+ def main():
81
+ args = parse_args()
82
+ out_path = args.out if os.path.isabs(args.out) else os.path.join(ROOT, args.out)
83
+
84
+ if not args.skip_gpu_check:
85
+ vis = os.environ.get("CUDA_VISIBLE_DEVICES")
86
+ free = free_gpus()
87
+ print(f"[gpu] CUDA_VISIBLE_DEVICES={vis} free_gpus={free}", flush=True)
88
+
89
+ base = enter_base(args.base)
90
+
91
+ import torch
92
+ from cachelib import CacheController, build_method, install, parse_schedule
93
+
94
+ torch.set_grad_enabled(False)
95
+ pipeline = load_pipeline(base)
96
+ num_steps = len(pipeline.denoising_step_list)
97
+ forced_steps = parse_schedule(args.schedule, num_steps)
98
+ print(f"[schedule] {args.schedule} -> forced steps {forced_steps}", flush=True)
99
+
100
+ coefficients = None
101
+ if args.coefficients:
102
+ path = (args.coefficients if os.path.isabs(args.coefficients)
103
+ else os.path.join(ROOT, args.coefficients))
104
+ with open(path) as f:
105
+ coefficients = json.load(f)["coefficients"]
106
+
107
+ prompts = load_prompts(args.pair_prompts + 4)
108
+ pname, lo, hi = PARAM[args.method]
109
+ lo = args.lo if args.lo is not None else lo
110
+ hi = args.hi if args.hi is not None else hi
111
+
112
+ def make_ctrl(method_name, value):
113
+ kw = dict(indicator=args.indicator, coefficients=coefficients)
114
+ if method_name != "none":
115
+ kw[pname] = value
116
+ for key, val in (("group_size", args.group_size),
117
+ ("weight_norm", args.weight_norm),
118
+ ("max_order", args.max_order),
119
+ ("min_update_ratio", args.min_update_ratio)):
120
+ if val is not None:
121
+ kw[key] = val
122
+ method = build_method(method_name, **kw)
123
+ ctrl = CacheController(method, num_steps=num_steps, forced_steps=forced_steps)
124
+ install(pipeline.generator.model, ctrl)
125
+ return ctrl
126
+
127
+ def compute_fraction(value, n=None):
128
+ """Deterministic FLOPs-equivalent speedup for one parameter value."""
129
+ ctrl = make_ctrl(args.method, value)
130
+ r = evaluate(pipeline, ctrl, prompts[:n or args.search_prompts],
131
+ num_output_frames=args.num_output_frames, seed=args.seed,
132
+ warmup=0)
133
+ return r["flops_speedup_estimate"], r["mean_compute_equivalent_forwards"]
134
+
135
+ t0 = time.time()
136
+
137
+ print("=== warm-up ===", flush=True)
138
+ evaluate(pipeline, make_ctrl("none", None), prompts[:2],
139
+ num_output_frames=args.num_output_frames, seed=args.seed, warmup=0)
140
+
141
+ print(f"=== coarse scan on {pname} in [{lo}, {hi}] (compute fraction) ===",
142
+ flush=True)
143
+ curve = []
144
+ for i in range(args.coarse_points):
145
+ v = lo + (hi - lo) * i / (args.coarse_points - 1)
146
+ f, ce = compute_fraction(v)
147
+ curve.append({"value": v, "flops_speedup": f, "compute_equivalent": ce})
148
+ print(f" {pname}={v:.4f} flops_x={f:.4f} compute_eq={ce:.3f}", flush=True)
149
+
150
+ # One paired probe at the most aggressive setting gives the method's overhead
151
+ # ratio (how much of the FLOPs saving survives into wall clock).
152
+ aggressive = max(curve, key=lambda c: c["flops_speedup"])
153
+ probe = paired_evaluate(pipeline,
154
+ lambda: make_ctrl("none", None),
155
+ lambda: make_ctrl(args.method, aggressive["value"]),
156
+ prompts[:min(4, len(prompts))],
157
+ num_output_frames=args.num_output_frames,
158
+ seed=args.seed, warmup=1)
159
+ overhead = probe["paired_speedup_median"] / aggressive["flops_speedup"]
160
+ print(f"overhead probe: {pname}={aggressive['value']:.4f} "
161
+ f"flops_x={aggressive['flops_speedup']:.3f} "
162
+ f"paired_x={probe['paired_speedup_median']:.3f} "
163
+ f"-> measured/flops = {overhead:.3f}", flush=True)
164
+
165
+ targets = [float(t) for t in args.targets.split(",")]
166
+ max_flops = aggressive["flops_speedup"]
167
+ operating_points = []
168
+
169
+ for target in targets:
170
+ # Target the compute budget directly by default. Correcting the target by
171
+ # the measured/FLOPs ratio sounds right but that ratio is itself a timing
172
+ # measurement on a contended node -- one probe came back at 1.11, which is
173
+ # impossible, and it dragged every operating point below its target.
174
+ # Targeting FLOPs also puts all four methods on identical compute budgets,
175
+ # which is the basis a quality comparison needs.
176
+ divisor = min(overhead, 1.0) if args.overhead_correction else 1.0
177
+ flops_target = min(target / divisor, max_flops)
178
+ a, b = lo, hi
179
+ for c in curve:
180
+ if c["flops_speedup"] < flops_target:
181
+ a = max(a, c["value"])
182
+ for c in reversed(curve):
183
+ if c["flops_speedup"] >= flops_target:
184
+ b = min(b, c["value"])
185
+ best = None
186
+ for _ in range(args.bisect_iters):
187
+ mid = 0.5 * (a + b)
188
+ f, ce = compute_fraction(mid)
189
+ if best is None or abs(f - flops_target) < abs(best[1] - flops_target):
190
+ best = (mid, f, ce)
191
+ if f < flops_target:
192
+ a = mid
193
+ else:
194
+ b = mid
195
+ # Bisection only ever probes strict interior points, so when the curve
196
+ # steps up exactly at the upper bracket it converges from below and never
197
+ # samples the value that actually reaches the target. Score the closing
198
+ # bracket ends too and keep whichever lands nearest.
199
+ for endpoint in (a, b):
200
+ f, ce = compute_fraction(endpoint)
201
+ if abs(f - flops_target) < abs(best[1] - flops_target):
202
+ best = (endpoint, f, ce)
203
+ value, flops_at, ce_at = best
204
+
205
+ vid_dir = None
206
+ if args.save_video_dir:
207
+ tag = "" if args.schedule.upper() == "FXXF" else f"_{args.schedule}"
208
+ vid_dir = os.path.join(
209
+ args.save_video_dir, f"{args.base}_{args.method}{tag}_x{target:g}")
210
+ if not os.path.isabs(vid_dir):
211
+ vid_dir = os.path.join(ROOT, vid_dir)
212
+
213
+ paired = paired_evaluate(pipeline,
214
+ lambda: make_ctrl("none", None),
215
+ lambda v=value: make_ctrl(args.method, v),
216
+ prompts[:args.pair_prompts + 1],
217
+ num_output_frames=args.num_output_frames,
218
+ seed=args.seed, warmup=1,
219
+ save_video_dir=vid_dir)
220
+ point = {
221
+ "target_speedup": target,
222
+ pname: value,
223
+ "flops_speedup": flops_at,
224
+ "mean_compute_equivalent_forwards": ce_at,
225
+ "measured_speedup": paired["paired_speedup_median"],
226
+ "measured_speedup_mean": paired["paired_speedup_mean"],
227
+ "measured_speedup_stdev": paired["paired_speedup_stdev"],
228
+ "measured_speedup_range": [paired["paired_speedup_min"],
229
+ paired["paired_speedup_max"]],
230
+ "median_baseline_ms": paired["median_baseline_ms"],
231
+ "median_method_ms": paired["median_method_ms"],
232
+ "num_pairs": paired["num_pairs"],
233
+ "video_dir": vid_dir,
234
+ }
235
+ operating_points.append(point)
236
+ print(f"TARGET {target}x -> {pname}={value:.6g} "
237
+ f"measured={point['measured_speedup']:.3f}x "
238
+ f"(+-{point['measured_speedup_stdev']:.3f}) "
239
+ f"flops={flops_at:.3f}x compute_eq={ce_at:.2f}", flush=True)
240
+
241
+ result = {
242
+ "base": args.base,
243
+ "method": args.method,
244
+ "param": pname,
245
+ "schedule": args.schedule,
246
+ "forced_steps": list(forced_steps),
247
+ "indicator": args.indicator,
248
+ "coefficients": coefficients,
249
+ "num_output_frames": args.num_output_frames,
250
+ "max_flops_speedup": max_flops,
251
+ "measured_over_flops_ratio": overhead,
252
+ "overhead_probe": {k: v for k, v in probe.items() if k != "ratios"},
253
+ "curve": curve,
254
+ "operating_points": operating_points,
255
+ "sweep_seconds": time.time() - t0,
256
+ }
257
+ os.makedirs(os.path.dirname(out_path), exist_ok=True)
258
+ with open(out_path, "w") as f:
259
+ json.dump(result, f, indent=2)
260
+ print(f"wrote {out_path}", flush=True)
261
+
262
+
263
+ if __name__ == "__main__":
264
+ main()
verify.py ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """Re-measure a sweep's operating points on held-out prompts.
3
+
4
+ The sweep tunes each parameter on prompts 0..N. A threshold that only reaches its
5
+ target because it sits inside a razor-thin band of the indicator distribution will
6
+ not reproduce on prompts it was not tuned on, so every operating point is re-run
7
+ here on a disjoint prompt slice. The gap between the tuned and held-out speedup
8
+ is the honest measure of how transferable the setting is.
9
+
10
+ python verify.py --sweep results/sweep_self_forcing_teacache.json \
11
+ --prompt-offset 64 --num-prompts 8 \
12
+ --out results/verify_self_forcing_teacache.json
13
+ """
14
+
15
+ import argparse
16
+ import json
17
+ import os
18
+ import sys
19
+
20
+ ROOT = os.path.dirname(os.path.abspath(__file__))
21
+ sys.path.insert(0, ROOT)
22
+
23
+ from harness import (BASES, enter_base, evaluate, load_pipeline, # noqa: E402
24
+ load_prompts, paired_evaluate)
25
+
26
+
27
+ def main():
28
+ ap = argparse.ArgumentParser()
29
+ ap.add_argument("--sweep", required=True, help="sweep_*.json to verify")
30
+ ap.add_argument("--prompt-offset", type=int, default=64)
31
+ ap.add_argument("--num-prompts", type=int, default=8)
32
+ ap.add_argument("--num-output-frames", type=int, default=21)
33
+ ap.add_argument("--seed", type=int, default=0)
34
+ ap.add_argument("--save-video-dir", default=None)
35
+ ap.add_argument("--out", required=True)
36
+ args = ap.parse_args()
37
+
38
+ sweep_path = (args.sweep if os.path.isabs(args.sweep)
39
+ else os.path.join(ROOT, args.sweep))
40
+ out_path = args.out if os.path.isabs(args.out) else os.path.join(ROOT, args.out)
41
+ with open(sweep_path) as f:
42
+ sweep = json.load(f)
43
+
44
+ base = enter_base(sweep["base"])
45
+
46
+ import torch
47
+ from cachelib import CacheController, build_method, install
48
+
49
+ torch.set_grad_enabled(False)
50
+ pipeline = load_pipeline(base)
51
+ num_steps = len(pipeline.denoising_step_list)
52
+ pname = sweep["param"]
53
+ coefficients = sweep.get("coefficients")
54
+
55
+ prompts = load_prompts(args.num_prompts + 1, offset=args.prompt_offset)
56
+ print(f"held-out prompts {args.prompt_offset}..{args.prompt_offset + len(prompts)}",
57
+ flush=True)
58
+
59
+ def make_ctrl(method_name, value):
60
+ kw = dict(indicator=sweep.get("indicator", "modulated_input"),
61
+ coefficients=coefficients)
62
+ if method_name != "none":
63
+ kw[pname] = value
64
+ ctrl = CacheController(build_method(method_name, **kw), num_steps=num_steps,
65
+ forced_steps=(0, num_steps - 1))
66
+ install(pipeline.generator.model, ctrl)
67
+ return ctrl
68
+
69
+ evaluate(pipeline, make_ctrl("none", None), prompts[:2],
70
+ num_output_frames=args.num_output_frames, seed=args.seed, warmup=0)
71
+
72
+ verified = []
73
+ for p in sweep["operating_points"]:
74
+ value = p[pname]
75
+ vid_dir = None
76
+ if args.save_video_dir:
77
+ vid_dir = os.path.join(ROOT, args.save_video_dir,
78
+ f"heldout_{sweep['base']}_{sweep['method']}"
79
+ f"_x{p['target_speedup']:g}")
80
+ paired = paired_evaluate(pipeline,
81
+ lambda: make_ctrl("none", None),
82
+ lambda v=value: make_ctrl(sweep["method"], v),
83
+ prompts, num_output_frames=args.num_output_frames,
84
+ seed=args.seed, warmup=1, save_video_dir=vid_dir)
85
+ det = evaluate(pipeline, make_ctrl(sweep["method"], value), prompts,
86
+ num_output_frames=args.num_output_frames, seed=args.seed,
87
+ warmup=0)
88
+ row = {
89
+ "target_speedup": p["target_speedup"],
90
+ pname: value,
91
+ "tuned_measured_speedup": p["measured_speedup"],
92
+ "tuned_flops_speedup": p["flops_speedup"],
93
+ "heldout_measured_speedup": paired["paired_speedup_median"],
94
+ "heldout_measured_stdev": paired["paired_speedup_stdev"],
95
+ "heldout_flops_speedup": det["flops_speedup_estimate"],
96
+ "heldout_compute_equivalent": det["mean_compute_equivalent_forwards"],
97
+ "flops_speedup_drift": det["flops_speedup_estimate"] - p["flops_speedup"],
98
+ }
99
+ verified.append(row)
100
+ print(f"target {row['target_speedup']:g}x {pname}={value:.6g} "
101
+ f"tuned_flops={row['tuned_flops_speedup']:.3f} "
102
+ f"heldout_flops={row['heldout_flops_speedup']:.3f} "
103
+ f"heldout_measured={row['heldout_measured_speedup']:.3f}x", flush=True)
104
+
105
+ result = {
106
+ "base": sweep["base"],
107
+ "method": sweep["method"],
108
+ "param": pname,
109
+ "sweep_file": os.path.basename(sweep_path),
110
+ "prompt_offset": args.prompt_offset,
111
+ "num_prompts": len(prompts),
112
+ "points": verified,
113
+ }
114
+ os.makedirs(os.path.dirname(out_path), exist_ok=True)
115
+ with open(out_path, "w") as f:
116
+ json.dump(result, f, indent=2)
117
+ print(f"wrote {out_path}", flush=True)
118
+
119
+
120
+ if __name__ == "__main__":
121
+ main()