Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat: enable TeaCache for ltx2 extend and a2v

[._.]/ Adam Eivy2f2663381961
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 60962d0f45..33851ead61 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -12,5 +12,6 @@
## Fixed
- **[ltx2-fflf-skips-last-image-resize-when-both-frames-set] ltx2 FFLF now resizes both anchor frames.** The two-keyframe ltx2 FFLF path passes both `--image` and `--last-image` into `scripts/generate_ltx2.py`, but Video Gen only resized the start image when both anchors were present. The end frame could therefore reach `KeyframeInterpolationPipeline.generate_and_save()` at its original dimensions. `videoGen/local.js` now treats ltx2 true-FFLF as a real last-image consumer and runs the same ffmpeg resize/crop pass used for multi-keyframes, with a regression test asserting the helper receives resized start and end paths.
+- **[ref-watch-phosphene-teacache-extend-a2v-denoise] TeaCache now accelerates ltx2 Extend and A2V Stage 1.** `scripts/generate_ltx2.py` now patches the LTX-2 `retake` and `a2vid_two_stage` denoise-loop import sites, activating the existing Stage-1 TeaCache controller only around Extend and A2V calls and clearing the gate afterward. TeaCache stays default-on for those slow paths, with `--no-teacache` available as a helper-level opt-out.
## Removed
diff --git a/PLAN.md b/PLAN.md
index fc103bf57c..6936bdf414 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -5,8 +5,6 @@ For project goals, see [GOALS.md](./GOALS.md). For completed work, see [.changel
## Next Up
1. **[video-resume-restore-keyframes]** **VideoGen resume: restore keyframes from the active job.** `ACTIVE_JOB_PARAM_FIELDS` in `server/routes/videoGen.js` (~line 739) intentionally omits `keyframes` (gallery filename + frame-index pairs for multi-keyframe FFLF) because the v1 resume effect doesn't repopulate the picker UI for them. A user who reloads mid-render on a keyframe job loses the keyframe-picker state even though every other form field is restored. Whitelist `keyframes` in the route AND wire a `setKeyframes()`-style setter in `client/src/pages/VideoGen.jsx`'s resume effect (~line 507). Independent of the SSE re-attach.
-2. **[ref-watch-phosphene-teacache-extend-a2v-denoise]** **TeaCache through Extend + A2V Stage-1 denoise loops.** From `reference-watch` review of phosphene (commits `ea98aad8` + `17be2a79`, 2026-05-28). PortOS's `scripts/generate_ltx2.py` invokes `ExtendPipeline.extend_from_video(...)` (~line 378) and `AudioToVideoPipeline.generate_and_save(...)` (~line 417) directly without passing a TeaCache controller, so the slowest two modes in the panel run full denoise. Phosphene reuses the existing Stage-1 calibration (`ti2vid_two_stages._build_teacache_controller(n_steps, thresh=0.5)`) by monkey-patching `guided_denoise_loop` on the `ltx_pipelines_mlx.retake` and `ltx_pipelines_mlx.a2vid_two_stage` modules, gating activation on a per-call module-level config dict, set before the pipeline call and cleared in `finally`. Predicted ~1.2× on extend at default threshold (up to ~3× at 1.5); similar for A2V Stage 1. Fix: install both monkey-patches at the top of `generate_ltx2.py`, wire `_EXTEND_TC_CONFIG` / `_A2V_TC_CONFIG` from the helper's `run_extend`/`run_a2v` paths, and add a `--no-teacache` CLI flag (default-on). **Decision (resolved 2026-05-30): land independently** against today's pin — the calibration helper `_build_teacache_controller` already exists at the current pin, so there's no need to couple this to the risky rename in `[ref-watch-phosphene-bump-ltx2-pin-v0148]`. Scope: small/medium.
-
## Backlog
Claimable, well-specified, no decision needed — `/claim`-able. Unordered.
diff --git a/scripts/generate_ltx2.py b/scripts/generate_ltx2.py
index 93479b97b8..b8f27e23e0 100644
--- a/scripts/generate_ltx2.py
+++ b/scripts/generate_ltx2.py
@@ -70,6 +70,68 @@ def emit_download(msg: str) -> None:
print(f"DOWNLOAD:{msg}", file=sys.stderr, flush=True)
+_EXTEND_TC_CONFIG: dict | None = None
+_A2V_TC_CONFIG: dict | None = None
+_EXTEND_TC_PATCH_OK = False
+_A2V_TC_PATCH_OK = False
+
+
+def _install_guided_denoise_teacache_patches() -> None:
+ """Wire TeaCache into Extend and A2V Stage-1 denoise loops.
+
+ Those modules import `guided_denoise_loop` into local symbols and do not
+ pass `teacache=` themselves. Patch the two import sites, then activate
+ the controller only while the matching runner has a per-call config set.
+ """
+ global _EXTEND_TC_PATCH_OK, _A2V_TC_PATCH_OK
+ try:
+ import ltx_pipelines_mlx.a2vid_two_stage as a2v_mod
+ import ltx_pipelines_mlx.retake as retake_mod
+ from ltx_pipelines_mlx.ti2vid_two_stages import (
+ _build_teacache_controller as build_stage1_teacache,
+ )
+ except Exception:
+ return
+
+ original_retake_guided_denoise_loop = retake_mod.guided_denoise_loop
+ original_a2v_guided_denoise_loop = a2v_mod.guided_denoise_loop
+
+ def build_controller(config: dict | None, fallback_steps: int, sigmas):
+ if not config or not config.get("enable"):
+ return None
+ n_steps = len(sigmas) - 1 if sigmas is not None else config.get("num_steps", fallback_steps)
+ try:
+ return build_stage1_teacache(n_steps, config.get("thresh"))
+ except Exception:
+ return None
+
+ def guided_denoise_loop_with_extend_teacache(*args, teacache=None, **kwargs):
+ if teacache is None:
+ teacache = build_controller(_EXTEND_TC_CONFIG, 30, kwargs.get("sigmas"))
+ return original_retake_guided_denoise_loop(*args, teacache=teacache, **kwargs)
+
+ def guided_denoise_loop_with_a2v_teacache(*args, teacache=None, **kwargs):
+ if teacache is None:
+ teacache = build_controller(_A2V_TC_CONFIG, 10, kwargs.get("sigmas"))
+ return original_a2v_guided_denoise_loop(*args, teacache=teacache, **kwargs)
+
+ retake_mod.guided_denoise_loop = guided_denoise_loop_with_extend_teacache
+ a2v_mod.guided_denoise_loop = guided_denoise_loop_with_a2v_teacache
+ _EXTEND_TC_PATCH_OK = True
+ _A2V_TC_PATCH_OK = True
+
+
+_install_guided_denoise_teacache_patches()
+
+
+def _teacache_config(enabled: bool, patch_ok: bool, num_steps: int) -> dict:
+ return {
+ "enable": bool(enabled) and patch_ok,
+ "thresh": None,
+ "num_steps": num_steps,
+ }
+
+
def configure_negative_prompt(negative_prompt: str) -> None:
"""Thread PortOS' negative prompt into ltx-2-mlx's CFG encoder.
@@ -155,6 +217,9 @@ def parse_args() -> argparse.Namespace:
p.add_argument("--no-audio", action="store_true",
help="Strip audio from output. The dgrauet pipeline always generates A/V; "
"we re-mux without the audio stream when requested.")
+ p.add_argument("--no-teacache", action="store_true",
+ help="Disable TeaCache acceleration for supported LTX-2 denoise loops "
+ "(extend and a2v Stage 1).")
return p.parse_args()
@@ -367,6 +432,7 @@ def run_extend(args: argparse.Namespace) -> str:
flow into the new frames. Mirrors dgrauet's CLI `_cmd_extend` memory pattern:
free DiT + text encoder before decode (otherwise OOMs at the VAE pass).
"""
+ global _EXTEND_TC_CONFIG
from ltx_pipelines_mlx import ExtendPipeline
from ltx_core_mlx.utils.memory import aggressive_cleanup
if not args.extend_from_video:
@@ -376,15 +442,22 @@ def run_extend(args: argparse.Namespace) -> str:
pipe = ExtendPipeline(model_dir=args.model, gemma_model_id=args.gemma)
emit_stage(1, 1, 1, "Loaded")
emit_status(f"Extending video {args.extend_direction} by {args.extend_frames} latent frames…")
- video_latent, audio_latent = pipe.extend_from_video(
- prompt=args.prompt,
- video_path=args.extend_from_video,
- extend_frames=args.extend_frames,
- direction=args.extend_direction,
- seed=args.seed,
- num_steps=args.steps if args.steps is not None else 30,
- cfg_scale=args.cfg_scale if args.cfg_scale is not None else 3.0,
- )
+ num_steps = args.steps if args.steps is not None else 30
+ _EXTEND_TC_CONFIG = _teacache_config(not args.no_teacache, _EXTEND_TC_PATCH_OK, num_steps)
+ if _EXTEND_TC_CONFIG["enable"]:
+ emit_status("TeaCache active on extend (thresh=default 0.5)")
+ try:
+ video_latent, audio_latent = pipe.extend_from_video(
+ prompt=args.prompt,
+ video_path=args.extend_from_video,
+ extend_frames=args.extend_frames,
+ direction=args.extend_direction,
+ seed=args.seed,
+ num_steps=num_steps,
+ cfg_scale=args.cfg_scale if args.cfg_scale is not None else 3.0,
+ )
+ finally:
+ _EXTEND_TC_CONFIG = None
# Mirror cli._decode_and_save: drop the DiT + text encoder before the VAE
# decode — otherwise full-res decode + the still-resident transformer OOMs
# the unified-memory budget. Then load_decoders() pulls the VAE back in
@@ -412,6 +485,7 @@ def run_a2v(args: argparse.Namespace) -> str:
--image is optional: when provided, conditions the FIRST frame the same
way ImageToVideoPipeline does, so motion + audio sync to a chosen still.
"""
+ global _A2V_TC_CONFIG
from ltx_pipelines_mlx import AudioToVideoPipeline
if not args.audio:
raise SystemExit("--audio is required for a2v mode")
@@ -420,21 +494,28 @@ def run_a2v(args: argparse.Namespace) -> str:
pipe = AudioToVideoPipeline(model_dir=args.model, gemma_model_id=args.gemma)
emit_stage(1, 1, 1, "Loaded")
emit_status(f"Generating A2V from {Path(args.audio).name}…")
- return pipe.generate_and_save(
- prompt=args.prompt,
- output_path=args.output,
- audio_path=args.audio,
- image=args.image,
- height=args.height,
- width=args.width,
- num_frames=args.num_frames,
- fps=args.fps,
- seed=args.seed,
- stage1_steps=args.steps,
- stage2_steps=args.stage2_steps,
- cfg_scale=args.cfg_scale if args.cfg_scale is not None else 3.0,
- audio_start_time=args.audio_start,
- )
+ stage1_steps = args.steps if args.steps is not None else 30
+ _A2V_TC_CONFIG = _teacache_config(not args.no_teacache, _A2V_TC_PATCH_OK, stage1_steps)
+ if _A2V_TC_CONFIG["enable"]:
+ emit_status("TeaCache active on A2V Stage 1 (thresh=default 0.5)")
+ try:
+ return pipe.generate_and_save(
+ prompt=args.prompt,
+ output_path=args.output,
+ audio_path=args.audio,
+ image=args.image,
+ height=args.height,
+ width=args.width,
+ num_frames=args.num_frames,
+ fps=args.fps,
+ seed=args.seed,
+ stage1_steps=stage1_steps,
+ stage2_steps=args.stage2_steps,
+ cfg_scale=args.cfg_scale if args.cfg_scale is not None else 3.0,
+ audio_start_time=args.audio_start,
+ )
+ finally:
+ _A2V_TC_CONFIG = None
def maybe_strip_audio(output_path: str) -> None:
diff --git a/scripts/generate_ltx2_teacache_test.py b/scripts/generate_ltx2_teacache_test.py
new file mode 100644
index 0000000000..011e196c91
--- /dev/null
+++ b/scripts/generate_ltx2_teacache_test.py
@@ -0,0 +1,97 @@
+#!/usr/bin/env python3
+"""Unit tests for generate_ltx2 TeaCache monkey patches."""
+from __future__ import annotations
+
+import importlib.util
+import sys
+import types
+import unittest
+from pathlib import Path
+
+
+HELPER_PATH = Path(__file__).with_name("generate_ltx2.py")
+
+
+class GenerateLtx2TeaCacheTest(unittest.TestCase):
+ def setUp(self):
+ self.module_name = "generate_ltx2_under_test"
+ self.original_modules = {
+ name: sys.modules.get(name)
+ for name in [
+ self.module_name,
+ "ltx_pipelines_mlx",
+ "ltx_pipelines_mlx.retake",
+ "ltx_pipelines_mlx.a2vid_two_stage",
+ "ltx_pipelines_mlx.ti2vid_two_stages",
+ ]
+ }
+ for name in self.original_modules:
+ sys.modules.pop(name, None)
+
+ root = types.ModuleType("ltx_pipelines_mlx")
+ root.__path__ = []
+ retake = types.ModuleType("ltx_pipelines_mlx.retake")
+ a2v = types.ModuleType("ltx_pipelines_mlx.a2vid_two_stage")
+ two_stages = types.ModuleType("ltx_pipelines_mlx.ti2vid_two_stages")
+ self.calls = []
+
+ def retake_loop(*args, teacache=None, **kwargs):
+ return {"caller": "retake", "teacache": teacache, "kwargs": kwargs}
+
+ def a2v_loop(*args, teacache=None, **kwargs):
+ return {"caller": "a2v", "teacache": teacache, "kwargs": kwargs}
+
+ def build_teacache(num_steps, thresh):
+ self.calls.append((num_steps, thresh))
+ return {"num_steps": num_steps, "thresh": thresh}
+
+ retake.guided_denoise_loop = retake_loop
+ a2v.guided_denoise_loop = a2v_loop
+ two_stages._build_teacache_controller = build_teacache
+
+ sys.modules["ltx_pipelines_mlx"] = root
+ sys.modules["ltx_pipelines_mlx.retake"] = retake
+ sys.modules["ltx_pipelines_mlx.a2vid_two_stage"] = a2v
+ sys.modules["ltx_pipelines_mlx.ti2vid_two_stages"] = two_stages
+ self.retake = retake
+ self.a2v = a2v
+
+ spec = importlib.util.spec_from_file_location(self.module_name, HELPER_PATH)
+ self.helper = importlib.util.module_from_spec(spec)
+ sys.modules[self.module_name] = self.helper
+ spec.loader.exec_module(self.helper)
+
+ def tearDown(self):
+ for name, module in self.original_modules.items():
+ if module is None:
+ sys.modules.pop(name, None)
+ else:
+ sys.modules[name] = module
+
+ def test_extend_patch_builds_stage1_teacache_from_sigmas(self):
+ self.helper._EXTEND_TC_CONFIG = self.helper._teacache_config(True, True, 30)
+
+ result = self.retake.guided_denoise_loop(sigmas=[1.0, 0.5, 0.0])
+
+ self.assertEqual(result["teacache"], {"num_steps": 2, "thresh": None})
+ self.assertEqual(self.calls, [(2, None)])
+
+ def test_a2v_patch_uses_configured_step_count_without_sigmas(self):
+ self.helper._A2V_TC_CONFIG = self.helper._teacache_config(True, True, 17)
+
+ result = self.a2v.guided_denoise_loop()
+
+ self.assertEqual(result["teacache"], {"num_steps": 17, "thresh": None})
+ self.assertEqual(self.calls, [(17, None)])
+
+ def test_patch_respects_disabled_config(self):
+ self.helper._EXTEND_TC_CONFIG = self.helper._teacache_config(False, True, 30)
+
+ result = self.retake.guided_denoise_loop(sigmas=[1.0, 0.0])
+
+ self.assertIsNone(result["teacache"])
+ self.assertEqual(self.calls, [])
+
+
+if __name__ == "__main__":
+ unittest.main()