softcache 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Shimon Malnick, Nadav Orenstein, Ohad Fried, Shai Avidan
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,192 @@
1
+ Metadata-Version: 2.5
2
+ Name: softcache
3
+ Version: 0.1.0
4
+ Summary: SoftCache: training-free caching with adaptive jumps for FLUX.1-dev, HunyuanVideo and Wan2.1.
5
+ Project-URL: Homepage, https://www.malnick.net/softcache/
6
+ Project-URL: Repository, https://github.com/ShimonMalnick/softcache
7
+ Project-URL: Paper, https://arxiv.org/abs/2610.22369
8
+ Project-URL: Demo, https://huggingface.co/spaces/ShimonM/softcache
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: acceleration,caching,diffusers,diffusion,flux,hunyuanvideo,wan
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
14
+ Requires-Python: >=3.10
15
+ Requires-Dist: accelerate
16
+ Requires-Dist: diffusers>=0.39
17
+ Requires-Dist: ftfy
18
+ Requires-Dist: imageio
19
+ Requires-Dist: imageio-ffmpeg
20
+ Requires-Dist: numpy
21
+ Requires-Dist: pillow
22
+ Requires-Dist: protobuf
23
+ Requires-Dist: sentencepiece
24
+ Requires-Dist: torch>=2.5
25
+ Requires-Dist: transformers>=5.13
26
+ Description-Content-Type: text/markdown
27
+
28
+ <h1 align="center">SoftCache</h1>
29
+ <h3 align="center">Adaptive Step Size Caching for Diffusion Transformers</h3>
30
+
31
+ <p align="center">
32
+ Shimon Malnick<sup>1</sup> ·
33
+ Nadav Orenstein<sup>1</sup> ·
34
+ Ohad Fried<sup>2</sup> ·
35
+ Shai Avidan<sup>1</sup>
36
+ <br>
37
+ <sup>1</sup>Tel Aviv University &nbsp;&nbsp; <sup>2</sup>Reichman University
38
+ </p>
39
+
40
+ <p align="center">
41
+ <a href="https://arxiv.org/abs/2610.22369"><img src="https://img.shields.io/badge/arXiv-2610.22369-b31b1b" alt="arXiv"></a>
42
+ <a href="https://www.malnick.net/softcache/"><img src="https://img.shields.io/badge/Project-Page-1B6898" alt="Project page"></a>
43
+ <a href="https://huggingface.co/spaces/ShimonM/softcache"><img src="https://img.shields.io/badge/%F0%9F%A4%97%20Demo-Hugging%20Face%20Space-ffd21e" alt="Hugging Face demo"></a>
44
+ <!-- add when the link exists: ComfyUI -->
45
+ </p>
46
+
47
+ <p align="center">
48
+ <picture>
49
+ <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/ShimonMalnick/softcache/main/assets/teaser_dark.png">
50
+ <img src="https://raw.githubusercontent.com/ShimonMalnick/softcache/main/assets/teaser.png" width="75%" alt="SoftCache sets how far each cached step goes: a reused step skips several scheduled nodes and lands between them">
51
+ </picture>
52
+ </p>
53
+
54
+ **Official implementation of [SoftCache](https://arxiv.org/abs/2610.22369).** Training-free, 3.5×–6.9× faster sampling for FLUX.1-dev, HunyuanVideo and Wan2.1.
55
+ Hard caching only decides whether to refresh or reuse. SoftCache also uses the cache's *headroom*
56
+ to set how far each cached step jumps, even between scheduled nodes, and it is ahead of every
57
+ baseline on all four fidelity metrics.
58
+
59
+ <p align="center">
60
+ <img src="https://raw.githubusercontent.com/ShimonMalnick/softcache/main/assets/qualitative.jpg" width="100%" alt="FLUX.1-dev on DrawBench at about 5.2x: reference, TeaCache, TaylorSeer, SeaCache, DPCache and SoftCache, with zoomed insets">
61
+ <br><sub>FLUX.1-dev on DrawBench at ≈5.2× (Fig. 4 of the paper). Red ellipses mark structural errors, and each inset enlarges one region.</sub>
62
+ </p>
63
+
64
+ ## Quick start
65
+
66
+ From a clone (the exact tested stack, pinned in `uv.lock`):
67
+
68
+ ```bash
69
+ git clone --recursive https://github.com/ShimonMalnick/softcache && cd softcache # SeaCache is a submodule
70
+ uv sync
71
+ uv run softcache --prompts prompts.json --out outputs # --model-family flux | hunyuan | wan
72
+ ```
73
+
74
+ Or with pip (newest compatible `torch`, `diffusers` and `transformers`):
75
+
76
+ ```bash
77
+ pip install softcache # or: pip install git+https://github.com/ShimonMalnick/softcache
78
+ softcache --prompts prompts.json --out outputs
79
+ ```
80
+
81
+ With pip, SeaCache's code is downloaded once from its repository into `~/.cache/softcache` on first use.
82
+
83
+ `prompts.json`: `[{"prompt": "A zebra to the right of a fire hydrant.", "seed": 0}]`
84
+
85
+ To use it from your own code, set the config once, then call `generate` for your model:
86
+
87
+ ```python
88
+ import torch
89
+ from softcache import Config
90
+ cfg = Config(tau=0.8, beta=0.5) # the paper's 5.2x FLUX band; lower tau = slower, closer to the reference
91
+ ```
92
+
93
+ FLUX.1-dev:
94
+ ```python
95
+ from diffusers import FluxPipeline
96
+ from softcache import flux
97
+
98
+ pipe = FluxPipeline.from_pretrained("black-forest-labs/FLUX.1-dev", torch_dtype=torch.bfloat16).to("cuda")
99
+ # stats: the step actions and node counts
100
+ image, stats = flux.generate(pipe, "A zebra to the right of a fire hydrant.", seed=0, cfg=cfg)
101
+ image.save("zebra.png")
102
+ ```
103
+
104
+ <p align="center">
105
+ <img src="https://raw.githubusercontent.com/ShimonMalnick/softcache/main/assets/demo.jpg" width="70%" alt="Reference and SoftCache on FLUX.1-dev for the prompt: A zebra to the right of a fire hydrant">
106
+ <br><sub>This prompt with <code>tau=0.8, beta=0.5</code>, the paper's 5.2× FLUX band (5.44× band mean).</sub>
107
+ </p>
108
+
109
+ HunyuanVideo:
110
+ ```python
111
+ from diffusers import HunyuanVideoPipeline
112
+ from diffusers.utils import export_to_video
113
+ from softcache import hunyuan
114
+
115
+ pipe = HunyuanVideoPipeline.from_pretrained("hunyuanvideo-community/HunyuanVideo", torch_dtype=torch.bfloat16).to("cuda")
116
+ pipe.vae.enable_tiling()
117
+ frames, stats = hunyuan.generate(pipe, "A cat walks on grass.", seed=0, cfg=cfg)
118
+ export_to_video(frames, "cat.mp4", fps=8)
119
+ ```
120
+
121
+ Wan2.1:
122
+ ```python
123
+ from diffusers import WanPipeline
124
+ from diffusers.utils import export_to_video
125
+ from softcache import wan
126
+
127
+ pipe = WanPipeline.from_pretrained("Wan-AI/Wan2.1-T2V-1.3B-Diffusers", torch_dtype=torch.bfloat16).to("cuda")
128
+ pipe.vae.enable_tiling()
129
+ frames, stats = wan.generate(pipe, "A cat walks on grass.", seed=0, cfg=cfg)
130
+ export_to_video(frames, "cat.mp4", fps=16)
131
+ ```
132
+
133
+ ## Options
134
+
135
+ | flag | default | |
136
+ |---|---|---|
137
+ | `--tau` | 0.30 | higher = faster; `0` = no caching (the baseline to time against) |
138
+ | `--beta` | 1.0 | 1.0 below ~4x speedup, 0.5 above |
139
+ | `--jf-max` | 8.0 | max jump length |
140
+ | `--device` | `cuda:0` | GPU to run on |
141
+ | `--low-memory` | off | encode all prompts first, then move the text encoders to the CPU |
142
+ | `--model`, `--steps`, `--height`, `--width`, `--num-frames`, `--guidance` | per model | |
143
+
144
+ FLUX.1-dev is gated on Hugging Face: accept its license and run `huggingface-cli login`.
145
+ Wan uses first-order Euler instead of its default UniPC scheduler.
146
+ ## Gradio demo
147
+
148
+ FLUX only. Fits a 32 GB GPU (the text encoders and the transformer take turns on it).
149
+
150
+ ```bash
151
+ uv run --with gradio python app.py # add --share for a temporary public link
152
+ ```
153
+
154
+ It opens with the zebra prompt at the ~5.4× preset. Pick a speed (3.8×, 5.4×, 6.9×), tick *Also run
155
+ uncached FLUX* to see the measured speedup on your GPU. Renders are cached in `demo_cache/`.
156
+
157
+ ## Docker
158
+
159
+ ```bash
160
+ docker build -t softcache . # clone with --recursive first (SeaCache submodule)
161
+ docker run --rm --gpus all -e HF_TOKEN -v ~/.cache/huggingface:/hf -v "$PWD":/work -w /work \
162
+ softcache --prompts prompts.json --out outputs
163
+ ```
164
+
165
+ Needs the NVIDIA Container Toolkit. The image runs the CLI, so every flag in *Options* works.
166
+
167
+ ## ComfyUI
168
+
169
+ FLUX nodes for ComfyUI: see [`comfyui/ComfyUI-SoftCache`](comfyui/ComfyUI-SoftCache/README.md).
170
+
171
+ ## Acknowledgements
172
+
173
+ This code is built on top of [SeaCache](https://github.com/jiwoogit/SeaCache) (used as the `third_party/SeaCache` submodule) and 🤗 [Diffusers](https://github.com/huggingface/diffusers).
174
+
175
+ ## License
176
+
177
+ The SoftCache code is released under the [MIT License](LICENSE). The SeaCache submodule is not
178
+ part of this repository and stays under its authors' terms.
179
+
180
+ ## Citation
181
+
182
+ ```bibtex
183
+ @misc{malnick2026softcacheadaptivestepsize,
184
+ title={SoftCache: Adaptive Step Size Caching for Diffusion Transformers},
185
+ author={Shimon Malnick and Nadav Orenstein and Ohad Fried and Shai Avidan},
186
+ year={2026},
187
+ eprint={2610.22369},
188
+ archivePrefix={arXiv},
189
+ primaryClass={cs.CV},
190
+ url={https://arxiv.org/abs/2610.22369},
191
+ }
192
+ ```
@@ -0,0 +1,165 @@
1
+ <h1 align="center">SoftCache</h1>
2
+ <h3 align="center">Adaptive Step Size Caching for Diffusion Transformers</h3>
3
+
4
+ <p align="center">
5
+ Shimon Malnick<sup>1</sup> ·
6
+ Nadav Orenstein<sup>1</sup> ·
7
+ Ohad Fried<sup>2</sup> ·
8
+ Shai Avidan<sup>1</sup>
9
+ <br>
10
+ <sup>1</sup>Tel Aviv University &nbsp;&nbsp; <sup>2</sup>Reichman University
11
+ </p>
12
+
13
+ <p align="center">
14
+ <a href="https://arxiv.org/abs/2610.22369"><img src="https://img.shields.io/badge/arXiv-2610.22369-b31b1b" alt="arXiv"></a>
15
+ <a href="https://www.malnick.net/softcache/"><img src="https://img.shields.io/badge/Project-Page-1B6898" alt="Project page"></a>
16
+ <a href="https://huggingface.co/spaces/ShimonM/softcache"><img src="https://img.shields.io/badge/%F0%9F%A4%97%20Demo-Hugging%20Face%20Space-ffd21e" alt="Hugging Face demo"></a>
17
+ <!-- add when the link exists: ComfyUI -->
18
+ </p>
19
+
20
+ <p align="center">
21
+ <picture>
22
+ <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/ShimonMalnick/softcache/main/assets/teaser_dark.png">
23
+ <img src="https://raw.githubusercontent.com/ShimonMalnick/softcache/main/assets/teaser.png" width="75%" alt="SoftCache sets how far each cached step goes: a reused step skips several scheduled nodes and lands between them">
24
+ </picture>
25
+ </p>
26
+
27
+ **Official implementation of [SoftCache](https://arxiv.org/abs/2610.22369).** Training-free, 3.5×–6.9× faster sampling for FLUX.1-dev, HunyuanVideo and Wan2.1.
28
+ Hard caching only decides whether to refresh or reuse. SoftCache also uses the cache's *headroom*
29
+ to set how far each cached step jumps, even between scheduled nodes, and it is ahead of every
30
+ baseline on all four fidelity metrics.
31
+
32
+ <p align="center">
33
+ <img src="https://raw.githubusercontent.com/ShimonMalnick/softcache/main/assets/qualitative.jpg" width="100%" alt="FLUX.1-dev on DrawBench at about 5.2x: reference, TeaCache, TaylorSeer, SeaCache, DPCache and SoftCache, with zoomed insets">
34
+ <br><sub>FLUX.1-dev on DrawBench at ≈5.2× (Fig. 4 of the paper). Red ellipses mark structural errors, and each inset enlarges one region.</sub>
35
+ </p>
36
+
37
+ ## Quick start
38
+
39
+ From a clone (the exact tested stack, pinned in `uv.lock`):
40
+
41
+ ```bash
42
+ git clone --recursive https://github.com/ShimonMalnick/softcache && cd softcache # SeaCache is a submodule
43
+ uv sync
44
+ uv run softcache --prompts prompts.json --out outputs # --model-family flux | hunyuan | wan
45
+ ```
46
+
47
+ Or with pip (newest compatible `torch`, `diffusers` and `transformers`):
48
+
49
+ ```bash
50
+ pip install softcache # or: pip install git+https://github.com/ShimonMalnick/softcache
51
+ softcache --prompts prompts.json --out outputs
52
+ ```
53
+
54
+ With pip, SeaCache's code is downloaded once from its repository into `~/.cache/softcache` on first use.
55
+
56
+ `prompts.json`: `[{"prompt": "A zebra to the right of a fire hydrant.", "seed": 0}]`
57
+
58
+ To use it from your own code, set the config once, then call `generate` for your model:
59
+
60
+ ```python
61
+ import torch
62
+ from softcache import Config
63
+ cfg = Config(tau=0.8, beta=0.5) # the paper's 5.2x FLUX band; lower tau = slower, closer to the reference
64
+ ```
65
+
66
+ FLUX.1-dev:
67
+ ```python
68
+ from diffusers import FluxPipeline
69
+ from softcache import flux
70
+
71
+ pipe = FluxPipeline.from_pretrained("black-forest-labs/FLUX.1-dev", torch_dtype=torch.bfloat16).to("cuda")
72
+ # stats: the step actions and node counts
73
+ image, stats = flux.generate(pipe, "A zebra to the right of a fire hydrant.", seed=0, cfg=cfg)
74
+ image.save("zebra.png")
75
+ ```
76
+
77
+ <p align="center">
78
+ <img src="https://raw.githubusercontent.com/ShimonMalnick/softcache/main/assets/demo.jpg" width="70%" alt="Reference and SoftCache on FLUX.1-dev for the prompt: A zebra to the right of a fire hydrant">
79
+ <br><sub>This prompt with <code>tau=0.8, beta=0.5</code>, the paper's 5.2× FLUX band (5.44× band mean).</sub>
80
+ </p>
81
+
82
+ HunyuanVideo:
83
+ ```python
84
+ from diffusers import HunyuanVideoPipeline
85
+ from diffusers.utils import export_to_video
86
+ from softcache import hunyuan
87
+
88
+ pipe = HunyuanVideoPipeline.from_pretrained("hunyuanvideo-community/HunyuanVideo", torch_dtype=torch.bfloat16).to("cuda")
89
+ pipe.vae.enable_tiling()
90
+ frames, stats = hunyuan.generate(pipe, "A cat walks on grass.", seed=0, cfg=cfg)
91
+ export_to_video(frames, "cat.mp4", fps=8)
92
+ ```
93
+
94
+ Wan2.1:
95
+ ```python
96
+ from diffusers import WanPipeline
97
+ from diffusers.utils import export_to_video
98
+ from softcache import wan
99
+
100
+ pipe = WanPipeline.from_pretrained("Wan-AI/Wan2.1-T2V-1.3B-Diffusers", torch_dtype=torch.bfloat16).to("cuda")
101
+ pipe.vae.enable_tiling()
102
+ frames, stats = wan.generate(pipe, "A cat walks on grass.", seed=0, cfg=cfg)
103
+ export_to_video(frames, "cat.mp4", fps=16)
104
+ ```
105
+
106
+ ## Options
107
+
108
+ | flag | default | |
109
+ |---|---|---|
110
+ | `--tau` | 0.30 | higher = faster; `0` = no caching (the baseline to time against) |
111
+ | `--beta` | 1.0 | 1.0 below ~4x speedup, 0.5 above |
112
+ | `--jf-max` | 8.0 | max jump length |
113
+ | `--device` | `cuda:0` | GPU to run on |
114
+ | `--low-memory` | off | encode all prompts first, then move the text encoders to the CPU |
115
+ | `--model`, `--steps`, `--height`, `--width`, `--num-frames`, `--guidance` | per model | |
116
+
117
+ FLUX.1-dev is gated on Hugging Face: accept its license and run `huggingface-cli login`.
118
+ Wan uses first-order Euler instead of its default UniPC scheduler.
119
+ ## Gradio demo
120
+
121
+ FLUX only. Fits a 32 GB GPU (the text encoders and the transformer take turns on it).
122
+
123
+ ```bash
124
+ uv run --with gradio python app.py # add --share for a temporary public link
125
+ ```
126
+
127
+ It opens with the zebra prompt at the ~5.4× preset. Pick a speed (3.8×, 5.4×, 6.9×), tick *Also run
128
+ uncached FLUX* to see the measured speedup on your GPU. Renders are cached in `demo_cache/`.
129
+
130
+ ## Docker
131
+
132
+ ```bash
133
+ docker build -t softcache . # clone with --recursive first (SeaCache submodule)
134
+ docker run --rm --gpus all -e HF_TOKEN -v ~/.cache/huggingface:/hf -v "$PWD":/work -w /work \
135
+ softcache --prompts prompts.json --out outputs
136
+ ```
137
+
138
+ Needs the NVIDIA Container Toolkit. The image runs the CLI, so every flag in *Options* works.
139
+
140
+ ## ComfyUI
141
+
142
+ FLUX nodes for ComfyUI: see [`comfyui/ComfyUI-SoftCache`](comfyui/ComfyUI-SoftCache/README.md).
143
+
144
+ ## Acknowledgements
145
+
146
+ This code is built on top of [SeaCache](https://github.com/jiwoogit/SeaCache) (used as the `third_party/SeaCache` submodule) and 🤗 [Diffusers](https://github.com/huggingface/diffusers).
147
+
148
+ ## License
149
+
150
+ The SoftCache code is released under the [MIT License](LICENSE). The SeaCache submodule is not
151
+ part of this repository and stays under its authors' terms.
152
+
153
+ ## Citation
154
+
155
+ ```bibtex
156
+ @misc{malnick2026softcacheadaptivestepsize,
157
+ title={SoftCache: Adaptive Step Size Caching for Diffusion Transformers},
158
+ author={Shimon Malnick and Nadav Orenstein and Ohad Fried and Shai Avidan},
159
+ year={2026},
160
+ eprint={2610.22369},
161
+ archivePrefix={arXiv},
162
+ primaryClass={cs.CV},
163
+ url={https://arxiv.org/abs/2610.22369},
164
+ }
165
+ ```
@@ -0,0 +1,56 @@
1
+ [project]
2
+ name = "softcache"
3
+ version = "0.1.0"
4
+ description = "SoftCache: training-free caching with adaptive jumps for FLUX.1-dev, HunyuanVideo and Wan2.1."
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ license-files = ["LICENSE"]
8
+ keywords = ["diffusion", "caching", "acceleration", "flux", "wan", "hunyuanvideo", "diffusers"]
9
+ classifiers = [
10
+ "Programming Language :: Python :: 3",
11
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
12
+ ]
13
+ requires-python = ">=3.10"
14
+ dependencies = [
15
+ "torch>=2.5",
16
+ "diffusers>=0.39",
17
+ "transformers>=5.13",
18
+ "accelerate",
19
+ "sentencepiece",
20
+ "protobuf",
21
+ "numpy",
22
+ "pillow",
23
+ "imageio",
24
+ "imageio-ffmpeg",
25
+ "ftfy", # Wan tokenizer
26
+ ]
27
+
28
+ [project.urls]
29
+ Homepage = "https://www.malnick.net/softcache/"
30
+ Repository = "https://github.com/ShimonMalnick/softcache"
31
+ Paper = "https://arxiv.org/abs/2610.22369"
32
+ Demo = "https://huggingface.co/spaces/ShimonM/softcache"
33
+
34
+ [project.scripts]
35
+ softcache = "softcache.generate:main"
36
+
37
+ # pip installs the newest compatible versions; uv (and the Dockerfile) resolve to the exact stack the
38
+ # release was gated on (H100, CUDA 12.1 wheels; see experiments/paper_release_bitexact).
39
+ [tool.uv]
40
+ constraint-dependencies = ["torch==2.5.1", "diffusers==0.39.0", "transformers==5.13.1"]
41
+
42
+ [tool.uv.sources]
43
+ torch = { index = "pytorch-cu121" }
44
+
45
+ [[tool.uv.index]]
46
+ name = "pytorch-cu121"
47
+ url = "https://download.pytorch.org/whl/cu121"
48
+ explicit = true
49
+
50
+ [build-system]
51
+ requires = ["hatchling"]
52
+ build-backend = "hatchling.build"
53
+
54
+ # PyPI sdist = the package only; assets, the Gradio app, Docker and ComfyUI stay in the repo.
55
+ [tool.hatch.build.targets.sdist]
56
+ include = ["/softcache", "/README.md", "/LICENSE", "/pyproject.toml"]
@@ -0,0 +1,40 @@
1
+ import os
2
+ import sys
3
+ import tarfile
4
+ import tempfile
5
+ import urllib.request
6
+ from pathlib import Path
7
+
8
+ SEACACHE_COMMIT = "8dcf49097fcd37e39774fe7409cb3b9e0fdb4fe2"
9
+
10
+
11
+ def _seacache_dir() -> Path:
12
+ """SeaCache's filter and staleness metric are its authors' code and are never copied into this
13
+ package: a repo clone uses the pinned git submodule, anything else (pip install, or a clone made
14
+ without --recursive) downloads the same commit once from upstream into ~/.cache/softcache."""
15
+ submodule = Path(__file__).resolve().parents[1] / "third_party" / "SeaCache"
16
+ if (submodule / "FLUX").exists():
17
+ return submodule
18
+ home = Path(os.environ.get("SOFTCACHE_HOME", Path.home() / ".cache" / "softcache"))
19
+ target = home / f"SeaCache-{SEACACHE_COMMIT[:7]}"
20
+ if not (target / "FLUX").exists():
21
+ home.mkdir(parents=True, exist_ok=True)
22
+ print(f"softcache: downloading SeaCache {SEACACHE_COMMIT[:7]} to {target}", file=sys.stderr)
23
+ url = f"https://github.com/jiwoogit/SeaCache/archive/{SEACACHE_COMMIT}.tar.gz"
24
+ with tempfile.TemporaryDirectory(dir=home) as tmp, urllib.request.urlopen(url) as response:
25
+ with tarfile.open(fileobj=response, mode="r|gz") as tar:
26
+ for member in tar: # the archive is one top-level dir; refuse anything that escapes it
27
+ if member.name.startswith(("/", "..")) or ".." in Path(member.name).parts:
28
+ raise RuntimeError(f"unsafe path in the SeaCache archive: {member.name}")
29
+ tar.extract(member, tmp)
30
+ try:
31
+ (Path(tmp) / f"SeaCache-{SEACACHE_COMMIT}").rename(target)
32
+ except OSError: # another process finished the same download first
33
+ if not (target / "FLUX").exists():
34
+ raise
35
+ return target
36
+
37
+
38
+ sys.path.insert(0, str(_seacache_dir() / "FLUX"))
39
+
40
+ from .method import Config # noqa: E402
@@ -0,0 +1,139 @@
1
+ """SoftCache sampling for FLUX.1-dev on a stock diffusers `FluxPipeline`."""
2
+
3
+ import numpy as np
4
+ import torch
5
+ from diffusers.pipelines.flux.pipeline_flux import calculate_shift, retrieve_timesteps
6
+
7
+ from .method import Config, decide, euler, execution_device, moved_residual, regrid_tail
8
+ from util_seacache import apply_sea_from_ab, rel_l1 # SeaCache submodule, see __init__.py
9
+
10
+
11
+
12
+ @torch.no_grad() # without it the autograd graph keeps the text encoders' GPU weights alive
13
+ def encode(pipe, prompt: str, max_sequence_length: int = 512):
14
+ """(prompt_embeds, pooled_prompt_embeds, text_ids) on the text encoders' device."""
15
+ return pipe.encode_prompt(prompt=prompt, prompt_2=None, device=execution_device(pipe, pipe.text_encoder),
16
+ num_images_per_prompt=1, max_sequence_length=max_sequence_length)
17
+
18
+
19
+ def generate(pipe, prompt, seed: int, cfg: Config, num_steps: int = 50, height: int = 1024,
20
+ width: int = 1024, guidance: float = 3.5):
21
+ """One image. `prompt` is a string, or the output of `encode`. Returns (PIL image, stats dict)."""
22
+ tr = pipe.transformer
23
+ embeds = encode(pipe, prompt) if isinstance(prompt, str) else prompt
24
+ device = execution_device(pipe, tr)
25
+ tr.to(device) # no-op unless diffusers' offload hooks parked it; the loop bypasses them
26
+ prompt_embeds, pooled, text_ids = (t.to(device) for t in embeds)
27
+ generator = torch.Generator("cpu").manual_seed(seed)
28
+ latents, image_ids = pipe.prepare_latents(1, tr.config.in_channels // 4, height, width,
29
+ prompt_embeds.dtype, device, generator)
30
+ sc = pipe.scheduler.config
31
+ mu = calculate_shift(latents.shape[1], sc.get("base_image_seq_len", 256),
32
+ sc.get("max_image_seq_len", 4096), sc.get("base_shift", 0.5),
33
+ sc.get("max_shift", 1.15))
34
+ retrieve_timesteps(pipe.scheduler, num_steps, device,
35
+ sigmas=np.linspace(1.0, 1.0 / num_steps, num_steps), mu=mu)
36
+ sigmas = [float(s) for s in pipe.scheduler.sigmas.cpu()]
37
+ guidance_t = (torch.full([1], guidance, device=device, dtype=torch.float32)
38
+ if tr.config.guidance_embeds else None)
39
+
40
+ latents, stats = denoise(tr, latents, sigmas, prompt_embeds, pooled, text_ids, image_ids,
41
+ guidance_t, cfg)
42
+ image = decode(pipe, latents, height, width)
43
+ pipe.maybe_free_model_hooks()
44
+ return image, stats
45
+
46
+
47
+ @torch.no_grad()
48
+ def denoise(tr, latents, sigmas, prompt_embeds, pooled, text_ids, image_ids, guidance, cfg):
49
+ """The sampling loop: per node, measure staleness, decide fresh / cache / jump, predict the
50
+ velocity, and take an Euler step (a jump also shortens the remaining schedule)."""
51
+ img_ids = image_ids[0] if image_ids.ndim == 3 else image_ids
52
+ txt_ids = text_ids[0] if text_ids.ndim == 3 else text_ids
53
+ grid_h, grid_w = int(img_ids[:, 1].max().item() + 1), int(img_ids[:, 2].max().item() + 1)
54
+ enc = tr.context_embedder(prompt_embeds)
55
+ rotary = tr.pos_embed(torch.cat((txt_ids, img_ids), dim=0))
56
+
57
+ num_steps = len(sigmas) - 1
58
+ acc = 0.0 # SeaCache staleness accumulated since the last refresh
59
+ prev_h = None # previous node's filtered block-0 input
60
+ r_anchor = r_prev = None # block residuals of the last two fresh nodes
61
+ sigma_anchor = sigma_prev = None
62
+ actions, n_full, n_cached, n_skipped = [], 0, 0, 0
63
+
64
+ i = 0
65
+ while sigmas[i] > 0:
66
+ sigma, sigma_next = sigmas[i], sigmas[i + 1]
67
+ hs, temb = _embed(tr, latents, sigma, pooled, guidance)
68
+
69
+ # staleness signal: rel-L1 change of the Wiener-filtered, modulated block-0 input
70
+ modulated = tr.transformer_blocks[0].norm1(hs, emb=temb)[0]
71
+ h = _sea_filter(modulated, grid_h, grid_w, sigma)
72
+ raw = rel_l1(h, prev_h) if i > 0 else 0.0
73
+ acc += raw
74
+ # at sigma=1 the filter output is ~0, so SeaCache compares against the unfiltered input
75
+ prev_h = (modulated if i == 0 else h).detach()
76
+
77
+ action, jf = decide(cfg, i, sigma, raw, acc)
78
+ if action == "fresh":
79
+ acc = 0.0
80
+ out = _blocks(tr, hs, enc, temb, rotary)
81
+ if r_anchor is not None:
82
+ r_prev, sigma_prev = r_anchor, sigma_anchor
83
+ r_anchor, sigma_anchor = (out - hs).detach(), sigma
84
+ n_full += 1
85
+ else:
86
+ if r_prev is None: # a single anchor so far: reuse its residual as is
87
+ out = hs + r_anchor
88
+ else:
89
+ out = hs + moved_residual(r_anchor, r_prev, sigma, sigma_anchor, sigma_prev,
90
+ cfg.beta)
91
+ n_cached += 1
92
+ v = tr.proj_out(tr.norm_out(out, temb))
93
+
94
+ if action == "jump":
95
+ sigma_next = max(0.0, sigma + jf * (sigma_next - sigma))
96
+ n_before = len(sigmas)
97
+ sigmas = regrid_tail(sigmas, i, sigma_next)
98
+ n_skipped += n_before - len(sigmas)
99
+ latents = euler(latents, sigma_next - sigma, v)
100
+ actions.append(action[0].upper())
101
+ i += 1
102
+
103
+ stats = {"actions": "".join(actions), "full": n_full, "cached": n_cached,
104
+ "jumps": actions.count("J"), "skipped_nodes": n_skipped,
105
+ "sigmas": sigmas}
106
+ return latents, stats
107
+
108
+
109
+ def _embed(tr, latents, sigma, pooled, guidance):
110
+ """Token embedding + timestep/guidance embedding, with the scheduler's exact dtype rounding."""
111
+ t = torch.tensor(sigma * 1000.0, dtype=torch.float32, device=latents.device)
112
+ timestep = (t.to(latents.dtype) / 1000).expand(latents.shape[0])
113
+ hs = tr.x_embedder(latents)
114
+ ts = timestep.to(hs.dtype) * 1000
115
+ if guidance is None:
116
+ return hs, tr.time_text_embed(ts, pooled)
117
+ return hs, tr.time_text_embed(ts, guidance.to(hs.dtype) * 1000, pooled)
118
+
119
+
120
+ def _sea_filter(x, grid_h, grid_w, sigma):
121
+ grid = x.reshape(x.shape[0], grid_h, grid_w, x.shape[-1])
122
+ y = apply_sea_from_ab(grid, 1.0 - sigma, sigma, dims=(-2, -3), norm_mode="mean")
123
+ return y.reshape(x.shape[0], -1, x.shape[-1])
124
+
125
+
126
+ def _blocks(tr, hs, enc, temb, rotary):
127
+ """Full forward through every transformer block."""
128
+ for block in list(tr.transformer_blocks) + list(tr.single_transformer_blocks):
129
+ enc, hs = block(hidden_states=hs, encoder_hidden_states=enc, temb=temb,
130
+ image_rotary_emb=rotary, joint_attention_kwargs=None)
131
+ return hs
132
+
133
+
134
+ @torch.no_grad()
135
+ def decode(pipe, latents, height, width):
136
+ x = pipe._unpack_latents(latents, height, width, pipe.vae_scale_factor)
137
+ x = x / pipe.vae.config.scaling_factor + pipe.vae.config.shift_factor
138
+ image = pipe.vae.decode(x.to(pipe.vae.dtype), return_dict=False)[0]
139
+ return pipe.image_processor.postprocess(image, output_type="pil")[0]
@@ -0,0 +1,88 @@
1
+ """Generate FLUX.1-dev images, or HunyuanVideo / Wan2.1 videos, with SoftCache for every
2
+ prompt in a JSON file."""
3
+ import argparse
4
+ import json
5
+ from pathlib import Path
6
+
7
+ import torch
8
+ from diffusers import FluxPipeline, HunyuanVideoPipeline, WanPipeline
9
+ from diffusers.utils import export_to_video
10
+
11
+ from . import flux, hunyuan, wan
12
+ from .method import Config
13
+
14
+ # family -> (pipeline class, sampler module, default model, default size + guidance, video fps)
15
+ FAMILIES = {
16
+ "flux": (FluxPipeline, flux, "black-forest-labs/FLUX.1-dev",
17
+ dict(height=1024, width=1024, guidance=3.5), None),
18
+ "hunyuan": (HunyuanVideoPipeline, hunyuan, "hunyuanvideo-community/HunyuanVideo",
19
+ dict(height=480, width=640, num_frames=65, guidance=6.0), 8),
20
+ "wan": (WanPipeline, wan, "Wan-AI/Wan2.1-T2V-1.3B-Diffusers",
21
+ dict(height=480, width=832, num_frames=81, guidance=6.0), 16),
22
+ }
23
+
24
+
25
+ def main():
26
+ ap = argparse.ArgumentParser(description=__doc__)
27
+ ap.add_argument("--model-family", choices=FAMILIES, default="flux")
28
+ ap.add_argument("--prompts", default="prompts.json",
29
+ help='JSON list of {"prompt": str, "seed": int}')
30
+ ap.add_argument("--out", default="outputs")
31
+ ap.add_argument("--model", help="model id or local snapshot directory")
32
+ ap.add_argument("--steps", type=int, default=50)
33
+ ap.add_argument("--height", type=int)
34
+ ap.add_argument("--width", type=int)
35
+ ap.add_argument("--num-frames", type=int, help="video only")
36
+ ap.add_argument("--guidance", type=float)
37
+ ap.add_argument("--tau", type=float, default=0.30,
38
+ help="staleness threshold; higher is faster. 0 = no caching (reference)")
39
+ ap.add_argument("--jf-max", type=float, default=8.0, help="cap on the jump factor")
40
+ ap.add_argument("--beta", type=float, default=1.0, help="Residual Motion step")
41
+ ap.add_argument("--device", default="cuda:0", help="GPU to run on")
42
+ ap.add_argument("--low-memory", action="store_true",
43
+ help="encode all prompts first, then move the text encoders to the CPU")
44
+ args = ap.parse_args()
45
+
46
+ pipeline_cls, sampler, default_model, defaults, fps = FAMILIES[args.model_family]
47
+ options = {k: getattr(args, k) if getattr(args, k) is not None else v
48
+ for k, v in defaults.items()}
49
+ items = json.loads(Path(args.prompts).read_text())
50
+ out = Path(args.out)
51
+ out.mkdir(parents=True, exist_ok=True)
52
+ cfg = Config(tau=args.tau, jf_max=args.jf_max, beta=args.beta)
53
+ pipe = pipeline_cls.from_pretrained(args.model or default_model, torch_dtype=torch.bfloat16)
54
+
55
+ prompts = [item["prompt"] for item in items]
56
+ if args.low_memory:
57
+ # Encode every prompt first, then move the text encoders off the GPU, so the transformer
58
+ # fits next to the VAE.
59
+ encoders = [m for m in (pipe.text_encoder, getattr(pipe, "text_encoder_2", None))
60
+ if m is not None]
61
+ for m in encoders:
62
+ m.to(args.device)
63
+ prompts = [sampler.encode(pipe, p) for p in prompts]
64
+ for m in encoders:
65
+ m.to("cpu")
66
+ torch.cuda.empty_cache()
67
+ pipe.transformer.to(args.device)
68
+ pipe.vae.to(args.device)
69
+ else:
70
+ pipe.to(args.device)
71
+ if fps:
72
+ pipe.vae.enable_tiling()
73
+
74
+ for k, (item, prompt) in enumerate(zip(items, prompts)):
75
+ seed = item.get("seed", 0)
76
+ sample, stats = sampler.generate(pipe, prompt, seed, cfg, args.steps, **options)
77
+ name = f"{k:03d}_seed{seed}"
78
+ if fps:
79
+ export_to_video(sample, str(out / f"{name}.mp4"), fps=fps)
80
+ else:
81
+ sample.save(out / f"{name}.png")
82
+ stats = {"prompt": item["prompt"], "seed": seed, **stats}
83
+ (out / f"{name}.json").write_text(json.dumps(stats, indent=1))
84
+ print(f"{name}: actions {stats['actions']}")
85
+
86
+
87
+ if __name__ == "__main__":
88
+ main()
@@ -0,0 +1,146 @@
1
+ """SoftCache sampling for HunyuanVideo on a stock diffusers `HunyuanVideoPipeline`."""
2
+
3
+ import numpy as np
4
+ import torch
5
+ from diffusers.pipelines.hunyuan_video.pipeline_hunyuan_video import retrieve_timesteps
6
+
7
+ from .method import Config, decide, euler, execution_device, moved_residual, regrid_tail
8
+ from util_seacache import apply_sea_from_ab, rel_l1 # SeaCache submodule, see __init__.py
9
+
10
+
11
+
12
+ @torch.no_grad() # without it the autograd graph keeps the text encoders' GPU weights alive
13
+ def encode(pipe, prompt: str):
14
+ """(prompt_embeds, pooled_prompt_embeds, attention_mask) in the transformer's dtype."""
15
+ dtype = pipe.transformer.dtype
16
+ embeds = pipe.encode_prompt(prompt=prompt, prompt_2=None, device=execution_device(pipe, pipe.text_encoder))
17
+ return tuple(t.to(dtype) for t in embeds)
18
+
19
+
20
+ def generate(pipe, prompt, seed: int, cfg: Config, num_steps: int = 50, height: int = 480,
21
+ width: int = 640, num_frames: int = 65, guidance: float = 6.0):
22
+ """One video. `prompt` is a string, or the output of `encode`. Returns (list of PIL frames, stats dict)."""
23
+ tr = pipe.transformer
24
+ embeds = encode(pipe, prompt) if isinstance(prompt, str) else prompt
25
+ device = execution_device(pipe, tr)
26
+ tr.to(device) # no-op unless diffusers' offload hooks parked it; the loop bypasses them
27
+ prompt_embeds, pooled, attn_mask = (t.to(device) for t in embeds)
28
+ generator = torch.Generator("cpu").manual_seed(seed)
29
+ latents = pipe.prepare_latents(1, tr.config.in_channels, height, width, num_frames,
30
+ torch.float32, device, generator)
31
+ retrieve_timesteps(pipe.scheduler, num_steps, device,
32
+ sigmas=np.linspace(1.0, 0.0, num_steps + 1)[:-1])
33
+ sigmas = [float(s) for s in pipe.scheduler.sigmas.cpu()]
34
+ guidance_t = torch.tensor([guidance], dtype=tr.dtype, device=device) * 1000.0
35
+
36
+ latents, stats = denoise(tr, latents, sigmas, prompt_embeds, pooled, attn_mask, guidance_t,
37
+ cfg)
38
+ image = decode(pipe, latents)
39
+ pipe.maybe_free_model_hooks()
40
+ return image, stats
41
+
42
+
43
+ @torch.no_grad()
44
+ def denoise(tr, latents, sigmas, prompt_embeds, pooled, attn_mask, guidance, cfg):
45
+ """The sampling loop: per node, measure staleness, decide fresh / cache / jump, predict the
46
+ velocity, and take an Euler step (a jump also shortens the remaining schedule)."""
47
+ p, p_t = tr.config.patch_size, tr.config.patch_size_t
48
+ _, _, frames, height, width = latents.shape
49
+ grid = (frames // p_t, height // p, width // p)
50
+ rotary = tr.rope(latents)
51
+ attention = _attention_mask(grid, attn_mask)
52
+
53
+ num_steps = len(sigmas) - 1
54
+ acc = 0.0 # SeaCache staleness accumulated since the last refresh
55
+ prev_h = None # previous node's filtered block-0 input
56
+ r_anchor = r_prev = None # block residuals of the last two fresh nodes
57
+ sigma_anchor = sigma_prev = None
58
+ actions, n_full, n_cached, n_skipped = [], 0, 0, 0
59
+
60
+ i = 0
61
+ while sigmas[i] > 0:
62
+ sigma, sigma_next = sigmas[i], sigmas[i + 1]
63
+ # sigma * 1000 cast to the running latents' dtype (fp32 at the first node, then the
64
+ # model dtype), as HunyuanVideoPipeline does; no /1000 round trip as in FLUX
65
+ timestep = torch.tensor(sigma * 1000.0, dtype=torch.float32, device=latents.device)
66
+ timestep = timestep.to(latents.dtype).expand(latents.shape[0])
67
+ hs = tr.x_embedder(latents.to(tr.dtype))
68
+ temb, token_replace = tr.time_text_embed(timestep, pooled, guidance)
69
+
70
+ # staleness signal: rel-L1 change of the Wiener-filtered, modulated block-0 input
71
+ modulated = tr.transformer_blocks[0].norm1(hs, emb=temb)[0]
72
+ h = _sea_filter(modulated, grid, sigma)
73
+ raw = rel_l1(h, prev_h) if i > 0 else 0.0
74
+ acc += raw
75
+ # at sigma=1 the filter output is ~0, so SeaCache compares against the unfiltered input
76
+ prev_h = (modulated if i == 0 else h).detach()
77
+
78
+ action, jf = decide(cfg, i, sigma, raw, acc)
79
+ if action == "fresh":
80
+ acc = 0.0
81
+ enc = tr.context_embedder(prompt_embeds, timestep, attn_mask)
82
+ out = _blocks(tr, hs, enc, temb, attention, rotary, token_replace, grid)
83
+ if r_anchor is not None:
84
+ r_prev, sigma_prev = r_anchor, sigma_anchor
85
+ r_anchor, sigma_anchor = (out - hs).detach(), sigma
86
+ n_full += 1
87
+ else:
88
+ if r_prev is None: # a single anchor so far: reuse its residual as is
89
+ out = hs + r_anchor
90
+ else:
91
+ out = hs + moved_residual(r_anchor, r_prev, sigma, sigma_anchor, sigma_prev,
92
+ cfg.beta)
93
+ n_cached += 1
94
+ v = _unpatchify(tr.proj_out(tr.norm_out(out, temb)), grid, p, p_t)
95
+
96
+ if action == "jump":
97
+ sigma_next = max(0.0, sigma + jf * (sigma_next - sigma))
98
+ n_before = len(sigmas)
99
+ sigmas = regrid_tail(sigmas, i, sigma_next)
100
+ n_skipped += n_before - len(sigmas)
101
+ latents = euler(latents, sigma_next - sigma, v)
102
+ actions.append(action[0].upper())
103
+ i += 1
104
+
105
+ stats = {"actions": "".join(actions), "full": n_full, "cached": n_cached,
106
+ "jumps": actions.count("J"), "skipped_nodes": n_skipped,
107
+ "sigmas": sigmas}
108
+ return latents, stats
109
+
110
+
111
+ def _sea_filter(x, grid, sigma):
112
+ """SeaCache's video filter: over the full frames x height x width token grid, power 3."""
113
+ y = apply_sea_from_ab(x.reshape(x.shape[0], *grid, x.shape[-1]), 1.0 - sigma, sigma,
114
+ power_exp=3.0, dims=(-2, -3, -4), norm_mode="mean")
115
+ return y.reshape(x.shape[0], -1, x.shape[-1])
116
+
117
+
118
+ def _attention_mask(grid, text_mask):
119
+ """Joint video+text mask, as HunyuanVideoTransformer3DModel.forward builds it: every video
120
+ token, then the prompt's valid text tokens; the text padding is masked out."""
121
+ n_video = grid[0] * grid[1] * grid[2]
122
+ seq_len = n_video + text_mask.shape[1]
123
+ valid = n_video + text_mask.sum(dim=1, dtype=torch.int)
124
+ indices = torch.arange(seq_len, device=text_mask.device).unsqueeze(0)
125
+ return (indices < valid.unsqueeze(1)).unsqueeze(1).unsqueeze(1)
126
+
127
+
128
+ def _blocks(tr, hs, enc, temb, attention, rotary, token_replace, grid):
129
+ """Full forward through every transformer block."""
130
+ first_frame_tokens = grid[1] * grid[2]
131
+ for block in list(tr.transformer_blocks) + list(tr.single_transformer_blocks):
132
+ hs, enc = block(hs, enc, temb, attention, rotary, token_replace, first_frame_tokens)
133
+ return hs
134
+
135
+
136
+ def _unpatchify(x, grid, p, p_t):
137
+ """Tokens [B, N, C*p_t*p*p] back to a [B, C, F, H, W] latent."""
138
+ x = x.reshape(x.shape[0], *grid, -1, p_t, p, p).permute(0, 4, 1, 5, 2, 6, 3, 7)
139
+ return x.flatten(6, 7).flatten(4, 5).flatten(2, 3)
140
+
141
+
142
+ @torch.no_grad()
143
+ def decode(pipe, latents):
144
+ video = pipe.vae.decode(latents.to(pipe.vae.dtype) / pipe.vae.config.scaling_factor,
145
+ return_dict=False)[0]
146
+ return pipe.video_processor.postprocess_video(video, output_type="pil")[0]
@@ -0,0 +1,67 @@
1
+ """SoftCache, model-independent: the per-node decision, Residual Motion, and the jump regrid."""
2
+ from dataclasses import dataclass
3
+
4
+ import torch
5
+
6
+
7
+ @dataclass(frozen=True)
8
+ class Config:
9
+ tau: float = 0.30 # refresh when the accumulated SeaCache rel-L1 reaches tau
10
+ jf_max: float = 8.0 # cap on the jump factor
11
+ beta: float = 1.0 # Residual Motion step; the paper uses 1.0 below ~4x speedup (tau ~0.3-0.5) and 0.5 above
12
+ # jump gate (paper app:gate): no jump in the volatile early sigmas (sigma > 0.9) or when the
13
+ # probe changes sharply at this node
14
+ sigma_hi: float = 0.90
15
+ raw_rel_l1_max: float = 0.18
16
+
17
+
18
+ def decide(cfg: Config, i: int, sigma: float, raw: float, acc: float) -> tuple[str, float | None]:
19
+ """Return ("fresh", None), ("cache", None) or ("jump", jump_factor).
20
+
21
+ Fresh at the first node and whenever the staleness budget is spent (SeaCache). Otherwise,
22
+ if the gate allows, jump with a stride that grows with the unspent budget (headroom):
23
+ jf = 1 + (jf_max - 1) * (1 - acc / tau)."""
24
+ if i == 0 or acc >= cfg.tau:
25
+ return "fresh", None
26
+ if sigma <= cfg.sigma_hi and raw <= cfg.raw_rel_l1_max:
27
+ headroom = max(0.0, 1.0 - acc / max(1e-9, cfg.tau))
28
+ jf = 1.0 + (cfg.jf_max - 1.0) * headroom
29
+ if jf > 1.01: # a stride under 1.01 skips no scheduled node, so it is not a jump
30
+ return "jump", jf
31
+ return "cache", None
32
+
33
+
34
+ def moved_residual(r_anchor: torch.Tensor, r_prev: torch.Tensor, sigma: float,
35
+ sigma_anchor: float, sigma_prev: float, beta: float) -> torch.Tensor:
36
+ """Residual Motion: extrapolate the block residual along the secant of the last two fresh
37
+ anchors, r = r_a + beta * lam * (r_a - r_{a-1}), lam = (sigma - sigma_a) / (sigma_a - sigma_{a-1})."""
38
+ # sigma decreases along the schedule, so the denominator is negative; the 1e-8 guard is
39
+ # inherited from the paper runs and kept for bit-exactness, as is the (beta * lam) grouping.
40
+ lam = (sigma - sigma_anchor) / (sigma_anchor - sigma_prev - 1e-8)
41
+ return r_anchor + (beta * lam) * (r_anchor - r_prev)
42
+
43
+
44
+ def regrid_tail(sigmas: list[float], i: int, target: float) -> list[float]:
45
+ """After jumping from node i to sigma=`target`, re-space the rest of the schedule linearly
46
+ from target to 0 with only as many nodes as the old schedule had below target. The nodes
47
+ this removes are the compute a jump saves."""
48
+ n_tail = len(sigmas) - (i + 1)
49
+ n_below = sum(1 for s in sigmas if 0.0 < s < target) + 1 # +1 for the terminal 0
50
+ n_new = min(n_tail - 1, n_below)
51
+ if n_new <= 1: # no node left below target: still take the final step target -> 0
52
+ return sigmas[: i + 1] + ([target, 0.0] if target > 0 else [0.0])
53
+ tail = [target * (1.0 - k / (n_new - 1)) for k in range(n_new)]
54
+ tail[0], tail[-1] = target, 0.0
55
+ return sigmas[: i + 1] + tail
56
+
57
+
58
+ def euler(latents: torch.Tensor, dsigma: float, v: torch.Tensor) -> torch.Tensor:
59
+ """Euler step, identical to diffusers' FlowMatchEulerDiscreteScheduler.step."""
60
+ dt = torch.tensor(dsigma, dtype=torch.float32, device=v.device)
61
+ return (latents.to(torch.float32) + dt * v).to(v.dtype)
62
+
63
+
64
+ def execution_device(pipe, module) -> torch.device:
65
+ """Where `module` computes: its own device, or the GPU when diffusers' offload hooks park it
66
+ on the CPU between calls."""
67
+ return pipe._execution_device if hasattr(module, "_hf_hook") else module.device
@@ -0,0 +1,167 @@
1
+ """SoftCache sampling for Wan2.1-T2V on a stock diffusers `WanPipeline`.
2
+
3
+ Wan runs real classifier-free guidance: two transformer forwards per node (prompt and negative
4
+ prompt). One staleness signal and one decision serve both, since block 0's modulation depends
5
+ on the timestep only; each branch keeps its own block residuals for Residual Motion."""
6
+
7
+ import torch
8
+ from diffusers import FlowMatchEulerDiscreteScheduler
9
+
10
+ from .method import Config, decide, euler, execution_device, moved_residual, regrid_tail
11
+ from util_seacache import apply_sea_from_ab, rel_l1 # SeaCache submodule, see __init__.py
12
+
13
+
14
+
15
+ @torch.no_grad() # without it the autograd graph keeps the text encoder's GPU weights alive
16
+ def encode(pipe, prompt: str, negative_prompt: str = ""):
17
+ """(prompt_embeds, negative_prompt_embeds) in the transformer's dtype."""
18
+ dtype = pipe.transformer.dtype
19
+ embeds = pipe.encode_prompt(prompt=prompt, negative_prompt=negative_prompt,
20
+ do_classifier_free_guidance=True, device=execution_device(pipe, pipe.text_encoder))
21
+ # clone: the embeds are views into the text encoder's activations, which they would pin
22
+ return tuple(t.to(dtype).clone() for t in embeds)
23
+
24
+
25
+ def generate(pipe, prompt, seed: int, cfg: Config, num_steps: int = 50, height: int = 480,
26
+ width: int = 832, num_frames: int = 81, guidance: float = 6.0):
27
+ """One video. `prompt` is a string, or the output of `encode`. Returns (list of PIL frames, stats dict)."""
28
+ tr = pipe.transformer
29
+ embeds = encode(pipe, prompt) if isinstance(prompt, str) else prompt
30
+ device = execution_device(pipe, tr)
31
+ tr.to(device) # no-op unless diffusers' offload hooks parked it; the loop bypasses them
32
+ prompt_embeds, negative_embeds = (t.to(device) for t in embeds)
33
+ # Wan ships a UniPC scheduler; SoftCache takes first-order Euler steps on its shifted grid
34
+ if not isinstance(pipe.scheduler, FlowMatchEulerDiscreteScheduler):
35
+ pipe.scheduler = FlowMatchEulerDiscreteScheduler(
36
+ num_train_timesteps=pipe.scheduler.config.num_train_timesteps,
37
+ shift=pipe.scheduler.config.flow_shift)
38
+ pipe.scheduler.set_timesteps(num_steps, device=device)
39
+ sigmas = [float(s) for s in pipe.scheduler.sigmas.cpu()]
40
+ generator = torch.Generator("cpu").manual_seed(seed)
41
+ latents = pipe.prepare_latents(1, tr.config.in_channels, height, width, num_frames,
42
+ torch.float32, device, generator)
43
+
44
+ latents, stats = denoise(tr, latents, sigmas, pipe.scheduler.timesteps, prompt_embeds,
45
+ negative_embeds, guidance, cfg)
46
+ image = decode(pipe, latents)
47
+ pipe.maybe_free_model_hooks()
48
+ return image, stats
49
+
50
+
51
+ @torch.no_grad()
52
+ def denoise(tr, latents, sigmas, timesteps, prompt_embeds, negative_embeds, guidance, cfg):
53
+ """The sampling loop: per node, measure staleness, decide fresh / cache / jump, predict the
54
+ guided velocity, and take an Euler step (a jump also shortens the remaining schedule).
55
+ `timesteps` are the scheduler's, one per node of the original `sigmas`."""
56
+ p_t, p_h, p_w = tr.config.patch_size
57
+ _, _, frames, height, width = latents.shape
58
+ grid = (frames // p_t, height // p_h, width // p_w)
59
+ rotary = tr.rope(latents)
60
+ # On the grid, the scheduler's own timestep; a jump's landing is off the grid, and there
61
+ # the timestep is sigma times the grid's timestep/sigma ratio (~1000).
62
+ on_grid = dict(zip(sigmas, timesteps))
63
+ scale = float(timesteps[0]) / sigmas[0]
64
+
65
+ num_steps = len(sigmas) - 1
66
+ acc = 0.0 # SeaCache staleness accumulated since the last refresh
67
+ prev_h = None # previous node's filtered block-0 input
68
+ r_anchor = r_prev = None # (prompt, negative) block residuals of the last two fresh nodes
69
+ sigma_anchor = sigma_prev = None
70
+ actions, n_full, n_cached, n_skipped = [], 0, 0, 0
71
+
72
+ i = 0
73
+ while sigmas[i] > 0:
74
+ sigma, sigma_next = sigmas[i], sigmas[i + 1]
75
+ timestep = on_grid.get(sigma)
76
+ if timestep is None:
77
+ timestep = torch.tensor(sigma * scale, dtype=timesteps.dtype, device=timesteps.device)
78
+ timestep = timestep.expand(latents.shape[0])
79
+ hs = tr.patch_embedding(latents.to(tr.dtype)).flatten(2).transpose(1, 2)
80
+ temb, temb_proj, enc, _ = tr.condition_embedder(timestep, prompt_embeds, None)
81
+ temb_proj = temb_proj.unflatten(1, (6, -1))
82
+
83
+ # staleness signal: rel-L1 change of the Wiener-filtered, modulated block-0 input
84
+ modulated = _block0_modulated(tr.blocks[0], hs, temb_proj)
85
+ h = _sea_filter(modulated, grid, sigma)
86
+ raw = rel_l1(h, prev_h) if i > 0 else 0.0
87
+ acc += raw
88
+ # at sigma=1 the filter output is ~0, so SeaCache compares against the unfiltered input
89
+ prev_h = (modulated if i == 0 else h).detach()
90
+
91
+ action, jf = decide(cfg, i, sigma, raw, acc)
92
+ if action == "fresh":
93
+ acc = 0.0
94
+ enc_negative = tr.condition_embedder(timestep, negative_embeds, None)[2]
95
+ outs = [_blocks(tr, hs, e, temb_proj, rotary) for e in (enc, enc_negative)]
96
+ if r_anchor is not None:
97
+ r_prev, sigma_prev = r_anchor, sigma_anchor
98
+ r_anchor, sigma_anchor = tuple((out - hs).detach() for out in outs), sigma
99
+ n_full += 1
100
+ else:
101
+ if r_prev is None: # a single anchor so far: reuse its residuals as they are
102
+ outs = [hs + r for r in r_anchor]
103
+ else:
104
+ outs = [hs + moved_residual(ra, rp, sigma, sigma_anchor, sigma_prev, cfg.beta)
105
+ for ra, rp in zip(r_anchor, r_prev)]
106
+ n_cached += 1
107
+ v_cond, v_uncond = (_velocity(tr, out, temb, grid) for out in outs)
108
+ v = v_uncond + guidance * (v_cond - v_uncond)
109
+
110
+ if action == "jump":
111
+ sigma_next = max(0.0, sigma + jf * (sigma_next - sigma))
112
+ n_before = len(sigmas)
113
+ sigmas = regrid_tail(sigmas, i, sigma_next)
114
+ n_skipped += n_before - len(sigmas)
115
+ latents = euler(latents, sigma_next - sigma, v)
116
+ actions.append(action[0].upper())
117
+ i += 1
118
+
119
+ stats = {"actions": "".join(actions), "full": n_full, "cached": n_cached,
120
+ "jumps": actions.count("J"), "skipped_nodes": n_skipped,
121
+ "sigmas": sigmas}
122
+ return latents, stats
123
+
124
+
125
+ def _block0_modulated(block, hs, temb_proj):
126
+ """Block 0's input after its self-attention AdaLN modulation. Wan computes it inline in
127
+ WanTransformerBlock.forward (there is no norm1(hs, emb) module to call), so it is restated."""
128
+ shift, scale, *_ = (block.scale_shift_table + temb_proj.float()).chunk(6, dim=1)
129
+ return (block.norm1(hs.float()) * (1 + scale) + shift).type_as(hs)
130
+
131
+
132
+ def _sea_filter(x, grid, sigma):
133
+ """SeaCache's video filter over the frames x height x width token grid, in 640-channel
134
+ chunks (the filter is per channel, so chunking is exact and caps the FFT's memory)."""
135
+ x5 = x.reshape(x.shape[0], *grid, x.shape[-1])
136
+ y = torch.cat([apply_sea_from_ab(x5[..., c:c + 640], 1.0 - sigma, sigma, power_exp=3.0,
137
+ dims=(-2, -3, -4), norm_mode="mean")
138
+ for c in range(0, x.shape[-1], 640)], dim=-1)
139
+ return y.reshape(x.shape[0], -1, x.shape[-1])
140
+
141
+
142
+ def _blocks(tr, hs, enc, temb_proj, rotary):
143
+ """Full forward through every transformer block."""
144
+ for block in tr.blocks:
145
+ hs = block(hs, enc, temb_proj, rotary)
146
+ return hs
147
+
148
+
149
+ def _velocity(tr, out, temb, grid):
150
+ """Output norm + projection, then tokens back to a [B, C, F, H, W] latent."""
151
+ shift, scale = (tr.scale_shift_table.to(temb.device) + temb.unsqueeze(1)).chunk(2, dim=1)
152
+ out = tr.proj_out((tr.norm_out(out.float()) * (1 + scale) + shift).type_as(out))
153
+ p_t, p_h, p_w = tr.config.patch_size
154
+ out = out.reshape(out.shape[0], *grid, p_t, p_h, p_w, -1).permute(0, 7, 1, 4, 2, 5, 3, 6)
155
+ return out.flatten(6, 7).flatten(4, 5).flatten(2, 3)
156
+
157
+
158
+ @torch.no_grad()
159
+ def decode(pipe, latents):
160
+ """Un-normalize with the VAE's latent mean/std, as WanPipeline does, then decode."""
161
+ vae = pipe.vae
162
+ x = latents.to(vae.dtype)
163
+ shape = (1, vae.config.z_dim, 1, 1, 1)
164
+ mean = torch.tensor(vae.config.latents_mean).view(shape).to(x.device, x.dtype)
165
+ inv_std = 1.0 / torch.tensor(vae.config.latents_std).view(shape).to(x.device, x.dtype)
166
+ video = vae.decode(x / inv_std + mean, return_dict=False)[0]
167
+ return pipe.video_processor.postprocess_video(video, output_type="pil")[0]