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

address review (self): patch the extend module, not retake, so TeaCache actually runs

[._.]/ Adam Eivy4336bb7a2dcc
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 33851ead61..4b3964b572 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -12,6 +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.
+- **[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 `extend` and `a2vid_two_stage` denoise-loop import sites (the modules where `ExtendPipeline`/`AudioToVideoPipeline` actually call `guided_denoise_loop`), 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` to opt out and `--teacache-thresh` to trade fidelity for speed (~1.2× at the 0.5 default, up to ~3× at 1.5).
## Removed
diff --git a/scripts/generate_ltx2.py b/scripts/generate_ltx2.py
index b8f27e23e0..0ee15d1f0b 100644
--- a/scripts/generate_ltx2.py
+++ b/scripts/generate_ltx2.py
@@ -79,28 +79,37 @@ _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.
+ `ExtendPipeline` (ltx_pipelines_mlx.extend) and `AudioToVideoPipeline`
+ (ltx_pipelines_mlx.a2vid_two_stage) each `from ...samplers import
+ guided_denoise_loop` into their OWN module namespace and call it without a
+ `teacache=` argument. We must patch the symbol on *those two modules*
+ specifically — patching any other module (e.g. `retake`) leaves the real
+ call site untouched and silently no-ops. We 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
+ import ltx_pipelines_mlx.extend as extend_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_extend_guided_denoise_loop = extend_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
+ # `sigmas` carries num_steps+1 values, so len(sigmas)-1 is the real
+ # step count. fallback_steps (the pipeline's native Stage-1 default)
+ # only applies if a caller ever omits sigmas.
n_steps = len(sigmas) - 1 if sigmas is not None else config.get("num_steps", fallback_steps)
try:
+ # thresh=None lets _build_teacache_controller apply its own
+ # LTX2_TEACACHE_THRESH default (0.5 at the current pin).
return build_stage1_teacache(n_steps, config.get("thresh"))
except Exception:
return None
@@ -108,14 +117,14 @@ def _install_guided_denoise_teacache_patches() -> 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)
+ return original_extend_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"))
+ teacache = build_controller(_A2V_TC_CONFIG, 30, kwargs.get("sigmas"))
return original_a2v_guided_denoise_loop(*args, teacache=teacache, **kwargs)
- retake_mod.guided_denoise_loop = guided_denoise_loop_with_extend_teacache
+ extend_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
@@ -124,14 +133,19 @@ def _install_guided_denoise_teacache_patches() -> None:
_install_guided_denoise_teacache_patches()
-def _teacache_config(enabled: bool, patch_ok: bool, num_steps: int) -> dict:
+def _teacache_config(enabled: bool, patch_ok: bool, num_steps: int,
+ thresh: float | None = None) -> dict:
return {
"enable": bool(enabled) and patch_ok,
- "thresh": None,
+ "thresh": thresh,
"num_steps": num_steps,
}
+def _teacache_thresh_label(thresh: float | None) -> str:
+ return f"{thresh}" if thresh is not None else "upstream default 0.5"
+
+
def configure_negative_prompt(negative_prompt: str) -> None:
"""Thread PortOS' negative prompt into ltx-2-mlx's CFG encoder.
@@ -220,6 +234,10 @@ def parse_args() -> argparse.Namespace:
p.add_argument("--no-teacache", action="store_true",
help="Disable TeaCache acceleration for supported LTX-2 denoise loops "
"(extend and a2v Stage 1).")
+ p.add_argument("--teacache-thresh", type=float, default=None,
+ help="rel_l1_thresh for TeaCache on extend/a2v Stage 1. Higher = more "
+ "skipping = faster but lower fidelity (~1.2x at 0.5, up to ~3x at 1.5). "
+ "Omit to use the pipeline default (0.5).")
return p.parse_args()
@@ -443,9 +461,10 @@ def run_extend(args: argparse.Namespace) -> str:
emit_stage(1, 1, 1, "Loaded")
emit_status(f"Extending video {args.extend_direction} by {args.extend_frames} latent frames…")
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)
+ _EXTEND_TC_CONFIG = _teacache_config(not args.no_teacache, _EXTEND_TC_PATCH_OK, num_steps,
+ args.teacache_thresh)
if _EXTEND_TC_CONFIG["enable"]:
- emit_status("TeaCache active on extend (thresh=default 0.5)")
+ emit_status(f"TeaCache active on extend (thresh={_teacache_thresh_label(args.teacache_thresh)})")
try:
video_latent, audio_latent = pipe.extend_from_video(
prompt=args.prompt,
@@ -495,9 +514,10 @@ def run_a2v(args: argparse.Namespace) -> str:
emit_stage(1, 1, 1, "Loaded")
emit_status(f"Generating A2V from {Path(args.audio).name}…")
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)
+ _A2V_TC_CONFIG = _teacache_config(not args.no_teacache, _A2V_TC_PATCH_OK, stage1_steps,
+ args.teacache_thresh)
if _A2V_TC_CONFIG["enable"]:
- emit_status("TeaCache active on A2V Stage 1 (thresh=default 0.5)")
+ emit_status(f"TeaCache active on A2V Stage 1 (thresh={_teacache_thresh_label(args.teacache_thresh)})")
try:
return pipe.generate_and_save(
prompt=args.prompt,
diff --git a/scripts/generate_ltx2_teacache_test.py b/scripts/generate_ltx2_teacache_test.py
index 011e196c91..2c08df21e9 100644
--- a/scripts/generate_ltx2_teacache_test.py
+++ b/scripts/generate_ltx2_teacache_test.py
@@ -6,6 +6,7 @@ import importlib.util
import sys
import types
import unittest
+from types import SimpleNamespace
from pathlib import Path
@@ -15,12 +16,15 @@ HELPER_PATH = Path(__file__).with_name("generate_ltx2.py")
class GenerateLtx2TeaCacheTest(unittest.TestCase):
def setUp(self):
self.module_name = "generate_ltx2_under_test"
+ # ExtendPipeline actually lives in ltx_pipelines_mlx.extend (NOT
+ # retake), so that is the import site the patch must target — fake the
+ # same module the production patch hooks.
self.original_modules = {
name: sys.modules.get(name)
for name in [
self.module_name,
"ltx_pipelines_mlx",
- "ltx_pipelines_mlx.retake",
+ "ltx_pipelines_mlx.extend",
"ltx_pipelines_mlx.a2vid_two_stage",
"ltx_pipelines_mlx.ti2vid_two_stages",
]
@@ -30,13 +34,13 @@ class GenerateLtx2TeaCacheTest(unittest.TestCase):
root = types.ModuleType("ltx_pipelines_mlx")
root.__path__ = []
- retake = types.ModuleType("ltx_pipelines_mlx.retake")
+ extend = types.ModuleType("ltx_pipelines_mlx.extend")
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 extend_loop(*args, teacache=None, **kwargs):
+ return {"caller": "extend", "teacache": teacache, "kwargs": kwargs}
def a2v_loop(*args, teacache=None, **kwargs):
return {"caller": "a2v", "teacache": teacache, "kwargs": kwargs}
@@ -45,15 +49,15 @@ class GenerateLtx2TeaCacheTest(unittest.TestCase):
self.calls.append((num_steps, thresh))
return {"num_steps": num_steps, "thresh": thresh}
- retake.guided_denoise_loop = retake_loop
+ extend.guided_denoise_loop = extend_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.extend"] = extend
sys.modules["ltx_pipelines_mlx.a2vid_two_stage"] = a2v
sys.modules["ltx_pipelines_mlx.ti2vid_two_stages"] = two_stages
- self.retake = retake
+ self.extend = extend
self.a2v = a2v
spec = importlib.util.spec_from_file_location(self.module_name, HELPER_PATH)
@@ -68,10 +72,23 @@ class GenerateLtx2TeaCacheTest(unittest.TestCase):
else:
sys.modules[name] = module
+ def test_patch_targets_the_extend_module_call_site(self):
+ # Regression guard: the patch must replace guided_denoise_loop on the
+ # extend module (where ExtendPipeline calls it), not some other module.
+ self.assertTrue(self.helper._EXTEND_TC_PATCH_OK)
+ self.assertEqual(
+ self.extend.guided_denoise_loop.__name__,
+ "guided_denoise_loop_with_extend_teacache",
+ )
+ self.assertEqual(
+ self.a2v.guided_denoise_loop.__name__,
+ "guided_denoise_loop_with_a2v_teacache",
+ )
+
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])
+ result = self.extend.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)])
@@ -87,11 +104,76 @@ class GenerateLtx2TeaCacheTest(unittest.TestCase):
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])
+ result = self.extend.guided_denoise_loop(sigmas=[1.0, 0.0])
+
+ self.assertIsNone(result["teacache"])
+ self.assertEqual(self.calls, [])
+
+ def test_config_disabled_when_patch_unavailable(self):
+ # patch_ok=False is the "import failed, patch never installed" gate —
+ # enable must collapse to False so we never claim acceleration the
+ # patched loop can't deliver.
+ config = self.helper._teacache_config(True, False, 30)
+ self.assertFalse(config["enable"])
+
+ self.helper._EXTEND_TC_CONFIG = config
+ result = self.extend.guided_denoise_loop(sigmas=[1.0, 0.5, 0.0])
self.assertIsNone(result["teacache"])
self.assertEqual(self.calls, [])
+ def test_explicit_thresh_overrides_upstream_default(self):
+ self.helper._A2V_TC_CONFIG = self.helper._teacache_config(True, True, 10, thresh=1.5)
+
+ result = self.a2v.guided_denoise_loop(sigmas=[1.0, 0.5, 0.0])
+
+ self.assertEqual(result["teacache"], {"num_steps": 2, "thresh": 1.5})
+ self.assertEqual(self.calls, [(2, 1.5)])
+
+ def test_run_extend_clears_config_even_when_pipeline_raises(self):
+ # The per-call config gate must reset on every exit path so it can't
+ # leak TeaCache activation into a later, unrelated call.
+ memory = types.ModuleType("ltx_core_mlx.utils.memory")
+ memory.aggressive_cleanup = lambda: None
+ utils = types.ModuleType("ltx_core_mlx.utils")
+ utils.memory = memory
+ core = types.ModuleType("ltx_core_mlx")
+ core.utils = utils
+ injected = {
+ "ltx_core_mlx": core,
+ "ltx_core_mlx.utils": utils,
+ "ltx_core_mlx.utils.memory": memory,
+ }
+ saved = {name: sys.modules.get(name) for name in injected}
+ sys.modules.update(injected)
+
+ class BoomPipeline:
+ def __init__(self, **kwargs):
+ pass
+
+ def extend_from_video(self, **kwargs):
+ raise RuntimeError("boom")
+
+ self.extend.guided_denoise_loop # ensure patched module is loaded
+ sys.modules["ltx_pipelines_mlx"].ExtendPipeline = BoomPipeline
+
+ args = SimpleNamespace(
+ model="m", gemma="g", extend_from_video="in.mp4", prompt="p",
+ extend_frames=2, extend_direction="after", seed=0, steps=None,
+ cfg_scale=None, no_teacache=False, teacache_thresh=None,
+ )
+ try:
+ self.helper._EXTEND_TC_CONFIG = None
+ with self.assertRaises(RuntimeError):
+ self.helper.run_extend(args)
+ self.assertIsNone(self.helper._EXTEND_TC_CONFIG)
+ finally:
+ for name, module in saved.items():
+ if module is None:
+ sys.modules.pop(name, None)
+ else:
+ sys.modules[name] = module
+
if __name__ == "__main__":
unittest.main()