Skip to content

Free, open-source AI video generator for Mac. Run LTX-2.5 and MiniMax H3 (Hailuo) locally on Apple Silicon: text-to-video and image-to-video with sound, lip-sync, character LoRA training, songs from lyrics (YuE2) and image editing (Qwen-Image-Edit). One-click install via Pinokio. Offline: no cloud, no API key, no NVIDIA GPU.

ltx-2-mlx: catch-up pin v0.14.0 -> v0.14.8, drop 6 of 7 runtime patches

mrbizarroaaf1ba805924
diff --git a/CLAUDE.md b/CLAUDE.md
index 482dc49..28e30db 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -197,7 +197,7 @@ These are not arbitrary — every pin is a paid lesson:
| `mlx==0.31.1` | mlx 0.31.2 introduced a numerical regression that attenuates LTX 2.3 vocoder output by ~22 dB. Verified: same model + same prompt + same seed → -42 dB peak on 0.31.2 vs -9 dB peak on 0.31.1. |
| `mlx-lm==0.31.1` `mlx-metal==0.31.1` | Same release line, kept consistent with mlx. |
| `huggingface-hub>=1.0` | `hf` CLI replaced `huggingface-cli`; older Pinokio bundles ship < 1.0. |
-| `ltx-2-mlx` PINNED to **`v0.14.0`** (commit `b35254a`) | install.js + update.js do `git checkout v0.14.0`. This is NOT "main HEAD" — that was the old pre-pin policy and is wrong now (corrected 2026-05-31). v0.14.0 ("ultra-strict iso on frame_rate") is the last tag the panel + helper + patch_ltx_codec.py were validated against; dgrauet asked to lock onto a tag 2026-05-12 before pushing breaking changes. Bumping the pin (e.g. → v0.14.8, deep-review Phase 4) is a deliberate, tested operation — read the release notes, smoke-test on beta, bump BOTH install.js and update.js in one commit. The historic `dcd639e (0.1.0)` detour broke the Extend `cfg_scale` API; do not revisit. |
+| `ltx-2-mlx` PINNED to **`v0.14.8`** (commit `d2ad8e9`) | install.js + update.js do `git checkout v0.14.8` (2026-06-01 catch-up from v0.14.0). **STAY PINNED** — this is NOT "main HEAD". v0.14.8 is the tag the panel + helper + patch_ltx_codec.py were validated against (full modality matrix smoke-tested on dev). The bump pulled dgrauet's native `_pre_denoise_flush` (the Metal-watchdog fix that resolves the I2V "mosaic" on memory-pressured Macs, #17), budget-aware VAE decode tiling, and first-class `frame_rate` — which let us drop 6 of 7 runtime patches (codec-only now). Bumping the pin further is a deliberate, tested operation — read the release notes, bump `_LTX_EXPECTED_VERSION` in mlx_warm_helper.py, smoke-test the matrix on dev, then bump BOTH install.js and update.js in one commit. The historic `dcd639e (0.1.0)` detour broke the Extend `cfg_scale` API; do not revisit. |
When changing a version, document the test that proved the new pin is OK.
@@ -208,7 +208,9 @@ are idempotent and fail loud on upstream drift (don't silently ship a
broken pipeline). Each patch has an `OLD` text it expects to find and a
`NEW` text it replaces with, plus a `marker` to detect "already patched."
-Currently shipped patches:
+As of the **v0.14.8** pin (2026-06-01 catch-up) only ONE patch remains —
+upstream absorbed the other six natively, so we dropped them and cut our
+divergence from 7 patches to 1 (the whole reason for the catch-up):
1. **Codec (`yuv444p crf 0` + `+faststart`)** — required.
Patches `ltx_core_mlx/model/video_vae/video_vae.py`. Default ffmpeg
@@ -216,37 +218,28 @@ Currently shipped patches:
to the front of the file so gallery thumbnails render the first
frame without downloading the full clip.
-2. **I2V free DiT before VAE decode** — optional (warns if upstream changed).
- Patches `ImageToVideoPipeline.generate_and_save` in
- `ltx_pipelines_mlx/ti2vid_one_stage.py`. Frees DiT + text encoder +
- feature extractor before the VAE decode step.
-
-3. **I2V free vae_encoder + feature_extractor BEFORE denoise** — optional.
- Patches `generate_from_image` to null `self.vae_encoder` and
- `self.feature_extractor` right after `_encode_text_and_load`
- returns. The connector inside feature_extractor is ~5.91 GiB on Q4
- and was sitting resident through denoise for no reason.
-
-4. **Base `load()` also clears feature_extractor** — optional.
- Patches `TextToVideoPipeline.load`. Drops one extra ~5.91 GiB blob
- from the peak when the DiT loads.
-
-5. **VAE temporal streaming with auto-skip on short clips** (Y1.035 +
- Y1.037). Patches `VideoDecoder.decode_and_stream` in
- `ltx_core_mlx/model/video_vae/video_vae.py`. Upstream's method
- *advertised* streaming but actually called `self.decode(latent)` on
- the full video volume before iterating frames — caused multi-minute
- end-of-render stalls / jetsam on long 720p clips. The patch routes
- through `tiled_decode()` with a `TemporalTilingConfig` (default
- tile = 64 latent frames, overlap = 24). Default mode is `auto`:
- tiling is applied only when latent length > `LTX_VAE_STREAMING_AUTO_MAX_FRAMES`
- (default 121 video frames ≈ 5 s). Short clips skip tiling and gain
- ~30 s on 5-sec Standard renders. `LTX_VAE_STREAMING=0` forces
- full-decode fallback; `=1` forces always-stream. Helper-side
- `_apply_vae_streaming_decision()` in `mlx_warm_helper.py` sets the
- env var per-job based on `num_frames`, so even pre-2.0 patched
- installs that haven't re-run `patch_ltx_codec.py` get the right
- behavior.
+**Dropped at v0.14.8 (now native upstream — do NOT re-add):**
+
+- **I2V / pre-denoise / base-load memory frees** (old patches 2,3,4) →
+ native `low_memory` path. v0.14.8 frees generation components via
+ composition-block `.free()` (`prompt_encoder`/`image_conditioner`) in
+ `ti2vid_one_stage.py` + `_base.py` before loading decoders.
+- **VAE temporal streaming** (old patch 5) → native budget-aware tiled
+ `decode_and_stream` in `video_vae.py` (`LTX2_VAE_DECODE_BUDGET_GB`,
+ default 8 GB; single-pass for short clips). Strictly better than ours.
+- **Metal-watchdog DiT-eval-cadence fix** (old patch 7) → native
+ `_pre_denoise_flush` (an `mx.eval` barrier before every denoise loop).
+ `_DIT_EVAL_EVERY` no longer exists. The flush is wired into the Q4
+ one-stage path (`ti2vid_one_stage.py`) — the exact path that produced
+ the I2V "mosaic" on memory-pressured Macs (#17) — plus all pipelines.
+- **one-stage `frame_rate` / 12→24 fps long clips** (old patch 6) →
+ native, first-class, keyword-only `frame_rate` threaded end-to-end.
+
+The helper calls the new API defensively (`hasattr` guard on
+`generate`/`generate_from_image`, `inspect.signature` probing, and
+`_filter_unsupported_kwargs`), so nothing depends on the dropped patches.
+Re-implementing any of them against v0.14.8 would only re-introduce the
+divergence the catch-up removed.
The "upgrade" path in `apply_patch()` lets old patched installs receive
new patch versions without a venv rebuild — used when we added
diff --git a/README.md b/README.md
index 2c09b15..591c261 100644
--- a/README.md
+++ b/README.md
@@ -110,11 +110,11 @@ If you have a Hugging Face token, paste it under **Settings** in the panel. Down
### Manual install
```bash
-# 1. Clone Phosphene + the upstream MLX port (pinned to v0.14.0).
+# 1. Clone Phosphene + the upstream MLX port (pinned to v0.14.8).
git clone https://github.com/mrbizarro/phosphene.git
cd phosphene
git clone https://github.com/dgrauet/ltx-2-mlx.git ltx-2-mlx
-cd ltx-2-mlx && git checkout v0.14.0 && cd ..
+cd ltx-2-mlx && git checkout v0.14.8 && cd ..
# 2. Create the Python 3.11 venv inside ltx-2-mlx (uv-managed).
cd ltx-2-mlx
@@ -158,7 +158,7 @@ HF_HUB_ENABLE_HF_TRANSFER=1 ./ltx-2-mlx/env/bin/hf download \
./ltx-2-mlx/env/bin/python3.11 mlx_ltx_panel.py
```
-About the version pins: `mlx 0.31.2` attenuates the LTX vocoder by 22 dB. Stay on 0.31.1. `ltx-2-mlx` is pinned to `v0.14.0` — upstream is about to ship breaking changes. `mflux 0.17.5` is the version `patch_mflux_fbcache.py` is line-targeted against.
+About the version pins: `mlx 0.31.2` attenuates the LTX vocoder by 22 dB. Stay on 0.31.1. `ltx-2-mlx` is pinned to `v0.14.8` — we track a known-good tag, never upstream `main`. `mflux 0.17.5` is the version `patch_mflux_fbcache.py` is line-targeted against.
## Interface
@@ -210,7 +210,7 @@ Behavioral changes worth noting in 3.0:
- `mlx_ltx_panel.py` is the panel HTTP server. One file, around 22k lines, with HTML, CSS, and JS inlined as the page string. Worker thread plus helper subprocess management plus capability tier detection.
- `mlx_warm_helper.py` is the long-running inference subprocess. Holds T2V, I2V, Extend, HQ, and Keyframe pipelines. Reads job specs from stdin, emits events to stdout.
- `image_engine.py` dispatches the Image tab. Backends `hidream`, `mflux`, `mock`. Each spawns its own subprocess with `start_new_session=True` so `/stop` kills the whole tree.
-- `patch_ltx_codec.py` applies idempotent runtime patches: lossless H.264, free-DiT-before-decode, VAE temporal streaming for long clips.
+- `patch_ltx_codec.py` applies one idempotent runtime patch: lossless H.264 output (yuv444p). As of the v0.14.8 pin the memory-frees, VAE streaming, Metal-watchdog and frame_rate patches are all native upstream.
- `lora_lab/` is vendored from the [`lora-lab`](https://github.com/mrbizarro/lora-lab) authoring tree. Training works out of the box; set `LTX_LORA_LAB_ROOT` to iterate against an external clone.
- `mlx_models/` and `mlx_outputs/` both persist across Pinokio Reset via fs.link.
diff --git a/install.js b/install.js
index 6a2212f..c766607 100644
--- a/install.js
+++ b/install.js
@@ -82,18 +82,23 @@ module.exports = {
}
},
- // ---- ltx-2-mlx version: PIN to v0.14.0. dgrauet asked on 2026-05-12
+ // ---- ltx-2-mlx version: PIN to v0.14.8 (2026-06-01 catch-up). dgrauet asked on 2026-05-12
// to lock onto a tag because he's about to push breaking changes
// upstream to sync with the official Lightricks repo. Without a
// tag pin, every fresh install (and every Update) would pull the
// next breaking push and Phosphene would fail to start.
//
- // v0.14.0 (commit b35254a, the "ultra-strict iso on frame_rate
- // kwarg" release) is the last known-good tag against which the
- // current panel + helper + patch_ltx_codec.py were validated.
- // Tag-bumps from here are a deliberate decision — read his
- // release notes first, smoke-test on dev, then bump this pin
- // AND the matching pin in update.js in one commit.
+ // v0.14.8 is the pinned tag against which the current panel +
+ // helper + patch_ltx_codec.py were validated (2026-06-01 catch-up
+ // from v0.14.0). The bump pulled dgrauet's native fixes —
+ // `_pre_denoise_flush` (the Metal-watchdog fix that resolves the
+ // I2V "mosaic" on memory-pressured Macs, #17), budget-aware VAE
+ // decode tiling, and first-class `frame_rate` — which let us DROP
+ // 6 of our 7 runtime patches (only the lossless-codec patch remains).
+ // STAY PINNED here: do not auto-track upstream main. Tag-bumps are a
+ // deliberate decision — read his release notes, smoke-test the full
+ // modality matrix on dev, bump `_LTX_EXPECTED_VERSION` in
+ // mlx_warm_helper.py, then bump this pin AND update.js in one commit.
//
// Idempotent — works on a fresh clone (already on the cloned
// branch's tip) AND on a re-install where the clone exists.
@@ -103,7 +108,7 @@ module.exports = {
path: "ltx-2-mlx",
message: [
"git fetch --tags origin",
- "git checkout v0.14.0",
+ "git checkout v0.14.8",
"git rev-parse --short HEAD"
]
}
diff --git a/mlx_warm_helper.py b/mlx_warm_helper.py
index 58d849e..bfef4a8 100644
--- a/mlx_warm_helper.py
+++ b/mlx_warm_helper.py
@@ -569,7 +569,7 @@ def _install_a2v_frame_rate_patch() -> None:
because their explicit kwarg overrides the default.
Why a wrapper instead of editing the vendored file: the ltx-2-mlx
- checkout is pinned to v0.14.0 and any direct edit gets clobbered on
+ checkout is pinned to v0.14.8 and any direct edit gets clobbered on
re-clone. The patch is idempotent so repeated helper boots are safe.
"""
global _A2V_FRAME_RATE_PATCH_INSTALLED
@@ -1726,7 +1726,7 @@ def configure_acceleration(mode: str) -> str:
# the pin Phosphene's patches are written against, and makes ANY skew loud +
# visible in the ready event (so every remote bug report carries it) instead
# of letting it surface as an un-triageable TypeError mid-render.
-_LTX_EXPECTED_VERSION = "0.14.0"
+_LTX_EXPECTED_VERSION = "0.14.8"
def _detect_ltx_version() -> dict:
@@ -1769,7 +1769,7 @@ def _detect_ltx_version() -> dict:
_LTX_VERSION_INFO = _detect_ltx_version()
if not _LTX_VERSION_INFO["match"]:
emit({"event": "log",
- "line": (f"⚠️ ltx-2-mlx VERSION SKEW: installed={_LTX_VERSION_INFO['version']} "
+ "line": (f"WARNING ltx-2-mlx VERSION SKEW: installed={_LTX_VERSION_INFO['version']} "
f"expected={_LTX_EXPECTED_VERSION} — runtime patches are written "
f"against {_LTX_EXPECTED_VERSION}; behavior on this version is "
f"unvalidated. {_LTX_VERSION_INFO['note']}".strip())})
diff --git a/patch_ltx_codec.py b/patch_ltx_codec.py
index 0592706..77de49b 100644
--- a/patch_ltx_codec.py
+++ b/patch_ltx_codec.py
@@ -1,35 +1,49 @@
#!/usr/bin/env python3
-"""Idempotent patches against the ltx-core-mlx + ltx-pipelines-mlx packages.
-
-Upstream issues we patch around:
-
-1. Output codec is `yuv420p crf 18` — 4:2:0 chroma subsampling produces
- visible JPEG-style block artifacts on faces / skin. Patched to
- `yuv444p crf 0` (lossless, no chroma subsampling) with env-var overrides
- (`LTX_OUTPUT_PIX_FMT`, `LTX_OUTPUT_CRF`).
-
-2. ImageToVideoPipeline.generate_and_save doesn't free the DiT + text
- encoder before VAE decode (the parent T2V version does). On Q8 / 64 GB
- Macs this OOMs the helper subprocess on the I2V code path. Patched to
- add the same low_memory cleanup the parent has.
-
-3. VideoDecoder.decode_and_stream advertises temporal streaming but still
- full-decodes the video tensor before writing frames. Patched to use
- temporal tiled_decode() automatically for longer clips, with
- LTX_VAE_STREAMING=0/1 override.
-
-4. TextToVideoPipeline / ImageToVideoPipeline have fps-aware position helpers
- in ltx-core-mlx, but the one-stage pipeline hardcodes 24fps at the call
- site. Patched to expose frame_rate so Phosphene can offer an explicit
- "12 → 24fps" long-clip mode without desynchronizing generated audio.
-
-Known unfixed: KeyframeInterpolationPipeline OOMs at the stage-1 → stage-2
-transition on 64 GB Macs at full resolution. We tried freeing/reloading
-the DiT around the upscale and it didn't help. Worked around in the panel
-by clamping keyframe-mode resolution to 768×432 by default — see the
-`mode == "keyframe"` block in mlx_ltx_panel.py.
-
-Safe to re-run — each patch checks for its marker before touching anything.
+"""Idempotent patch against ltx-core-mlx — the ONLY edit Phosphene still needs.
+
+History: through ltx-2-mlx **v0.14.0** this script carried SEVEN patches,
+working around upstream gaps. As of the **v0.14.8** pin (2026-06-01 catch-up)
+dgrauet has absorbed all but one of them upstream, so they were DROPPED:
+
+ - I2V OOM / pre-denoise / base-load memory frees (old Patches 2,3,4)
+ → native `low_memory` path. v0.14.8 frees generation components via
+ composition-block `.free()` (`prompt_encoder`/`image_conditioner`) in
+ `ti2vid_one_stage.py` + `_base.py` before loading decoders.
+ - VAE decode streaming (old Patch 5)
+ → native budget-aware tiled `decode_and_stream` in `video_vae.py`
+ (`LTX2_VAE_DECODE_BUDGET_GB`, default 8 GB; falls through to a single
+ pass for short clips). Strictly better than our hand-rolled version.
+ - Metal-watchdog DiT-eval-cadence fix (old Patch 7)
+ → native `_pre_denoise_flush` (an `mx.eval` barrier before every
+ denoise loop). `_DIT_EVAL_EVERY` no longer exists. The flush is wired
+ into the Q4 one-stage path (`ti2vid_one_stage.py:239`) — the exact path
+ that produced the I2V "mosaic" on memory-pressured Macs (#17) — plus
+ every other pipeline. This is dgrauet's fix for the same
+ MTLCommandBufferErrorInternal code 14 we were fighting from our side.
+ - one-stage frame_rate / 12→24 fps long clips (old Patch 6)
+ → native, first-class, keyword-only `frame_rate` threaded end-to-end
+ (generate_one_stage_dev / generate_and_save / compute_*_positions /
+ combined_image_conditionings / decode_and_stream).
+
+The helper already calls the new API defensively (`hasattr` guard on
+`generate`/`generate_from_image`, `inspect.signature` probing, and
+`_filter_unsupported_kwargs`), so nothing depends on the dropped patches.
+Re-implementing them against v0.14.8 would only re-introduce divergence — the
+whole point of the catch-up was to let pinned-upstream own this behaviour.
+
+What REMAINS is the one preference upstream doesn't share:
+
+1. Output codec. Upstream emits `yuv420p crf 18` — 4:2:0 chroma subsampling
+ produces visible JPEG-style block artifacts on faces / skin. We patch to
+ `yuv444p crf 0` (lossless, no chroma subsampling) plus `+faststart` (moov
+ atom at the front of the file so gallery thumbnails decode the first frame
+ without downloading the whole clip). Override via `LTX_OUTPUT_PIX_FMT` /
+ `LTX_OUTPUT_CRF`.
+
+If a future pin restructures `decode_and_stream`'s ffmpeg line, this fails
+LOUD (exit non-zero) rather than silently shipping a 4:2:0 install.
+
+Safe to re-run — checks for its marker before touching anything.
"""
from __future__ import annotations
@@ -53,7 +67,7 @@ def _find(rel: str) -> Path | None:
return None
-# ---- Patch 1: lossless h264 codec --------------------------------------------
+# ---- Patch: lossless h264 codec ----------------------------------------------
PATCH_CODEC_OLD = 'cmd.extend(["-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "18", output_path])'
PATCH_CODEC_NEW = (
'# PATCHED (LTX23MLX): default to lossless yuv444p crf 0 (no chroma\n'
@@ -69,236 +83,6 @@ PATCH_CODEC_NEW = (
' "-movflags", "+faststart", output_path])'
)
-# ---- Patch 2: I2V free-DiT-before-VAE-decode (OOM fix) -----------------------
-# The parent T2V's generate_and_save does this; the I2V override forgot to.
-# On Q8 / 64 GB Macs the I2V path OOMs because dev transformer + Gemma + VAE
-# coexist during stage-2 decode.
-PATCH_I2V_OOM_OLD = ''' video_latent, audio_latent = self.generate_from_image(
- prompt=prompt,
- image=image,
- height=height,
- width=width,
- num_frames=num_frames,
- seed=seed,
- num_steps=num_steps,
- )
-
- return self._decode_and_save_video(video_latent, audio_latent, output_path)'''
-PATCH_I2V_OOM_NEW = ''' video_latent, audio_latent = self.generate_from_image(
- prompt=prompt,
- image=image,
- height=height,
- width=width,
- num_frames=num_frames,
- seed=seed,
- num_steps=num_steps,
- )
-
- # PATCHED (LTX23MLX): mirror the parent T2V cleanup before VAE decode.
- # Without this, dev transformer + Gemma + VAE all live in memory during
- # decode and OOM the helper on Q8 / 64 GB Macs.
- if self.low_memory:
- self.dit = None
- self.text_encoder = None
- self.feature_extractor = None
- self._loaded = False
- try:
- from ltx_core_mlx.utils.memory import aggressive_cleanup
- aggressive_cleanup()
- except Exception:
- pass
-
- return self._decode_and_save_video(video_latent, audio_latent, output_path)'''
-
-
-# ---- Patch 3: I2V free vae_encoder + feature_extractor BEFORE denoise --------
-# Credit: cocktailpeanut review. The existing Patch 2 only frees memory
-# right before the VAE *decode* step. By that point we've already paid the
-# peak: during the denoise loop we have DiT (~10.54 GiB Q4 / ~19 GiB Q8 dev)
-# + feature_extractor with connector (~5.91 GiB) + vae_encoder (still
-# resident because ImageToVideoPipeline.load() reloads it after super().
-# load() finishes) + denoise activations. That overlap is what kills the
-# helper "10 seconds in" silently.
-#
-# Fix: right after _encode_text_and_load() returns inside generate_from_image,
-# explicitly null out vae_encoder + feature_extractor. They aren't needed
-# during denoise — vae_encoder was used in step 1 and reload happens via
-# the I2V load(); feature_extractor only mattered for the text-encoding
-# step that just completed.
-PATCH_I2V_PREDENOISE_OLD = ''' # Step 2: Encode text, then load remaining components
- video_embeds, audio_embeds = self._encode_text_and_load(prompt)
- assert self.dit is not None'''
-PATCH_I2V_PREDENOISE_NEW = ''' # Step 2: Encode text, then load remaining components
- video_embeds, audio_embeds = self._encode_text_and_load(prompt)
-
- # PATCHED (LTX23MLX, peanut review): free vae_encoder +
- # feature_extractor BEFORE the denoise loop, not just before VAE
- # decode. The old patch (Patch 2) freed too late — denoise itself
- # was the peak. With DiT (10.5 GB Q4) + connector (5.9 GB) + vae_enc
- # + activations all overlapping during the loop, the helper was
- # being SIGKILL'd by jetsam on memory-pressured Macs (cocktailpeanut
- # repro: "I2V started, ~10s in stopped with no error").
- if self.low_memory:
- self.vae_encoder = None
- self.feature_extractor = None
- try:
- from ltx_core_mlx.utils.memory import aggressive_cleanup as _cleanup
- _cleanup()
- except Exception:
- pass
-
- assert self.dit is not None'''
-
-# ---- Patch 4: Base load() also clears feature_extractor before DiT -----------
-# Same diagnosis. Base TextToVideoPipeline.load() only clears self.text_encoder
-# before loading the transformer; feature_extractor (which holds the connector,
-# ~5.9 GiB on Q4) stays resident through the DiT load. Two big weight blobs
-# coexisting in MLX memory at peak load is exactly the avoidable overlap.
-PATCH_BASE_LOAD_OLD = ''' # Stage 2: DiT (largest component — load after text encoding frees Gemma)
- if self.dit is None:
- if self.low_memory:
- # Free text encoder before loading transformer to fit in RAM
- self.text_encoder = None
- aggressive_cleanup()'''
-PATCH_BASE_LOAD_NEW = ''' # Stage 2: DiT (largest component — load after text encoding frees Gemma)
- if self.dit is None:
- if self.low_memory:
- # PATCHED (LTX23MLX, peanut review): also clear feature_extractor
- # alongside text_encoder before loading the transformer. The
- # connector lives inside feature_extractor (~5.9 GiB Q4) and
- # without this it stays resident through the 10.5 GiB DiT load,
- # peaking around 16+ GiB just for weights before activations.
- self.text_encoder = None
- self.feature_extractor = None
- aggressive_cleanup()'''
-
-# ---- Patch 5: stream VAE decode in temporal chunks -----------------------------
-# Upstream VideoDecoder.decode_and_stream() says it decodes one temporal chunk at
-# a time, but the implementation still calls self.decode(latent) for the full
-# video volume before writing frames to ffmpeg. On long 720p-ish clips this is
-# exactly the "denoise is done, now it freezes at the end" memory-pressure tail.
-# The decoder already has tiled_decode(); use temporal tiling automatically for
-# longer clips while keeping LTX_VAE_STREAMING=0/1 as explicit fallback/force.
-PATCH_VAE_STREAM_OLD = ''' try:
- # Decode full volume and stream frames
- pixels = self.decode(latent)
- mx.async_eval(pixels)
-
- num_frames = pixels.shape[2]
- for i in range(num_frames):
- frame = pixels[:, :, i, :, :] # (B, 3, H, W)
- frame = mx.clip(frame, -1.0, 1.0)
- frame = ((frame + 1.0) * 127.5).astype(mx.uint8)
- # (1, 3, H, W) -> (H, W, 3)
- frame_hwc = frame[0].transpose(1, 2, 0)
- mx.eval(frame_hwc) # must be sync — async_eval can write before data is ready
- proc.stdin.write(bytes(memoryview(frame_hwc)))
- del frame, frame_hwc
- if i % 8 == 0:
- aggressive_cleanup()'''
-
-PATCH_VAE_STREAM_NEW = ''' try:
- # PATCHED (LTX23MLX): temporal streaming decode. The old code
- # decoded the full video tensor before writing frames, causing
- # multi-minute end-of-render stalls or jetsam on long/high-res jobs.
- import os as _os
- _streaming = _os.environ.get("LTX_VAE_STREAMING", "auto").strip().lower()
- _frames_est = 1 + (int(latent.shape[2]) - 1) * 8
- _auto_max = int(_os.environ.get("LTX_VAE_STREAMING_AUTO_MAX_FRAMES", "121"))
- if _streaming in ("1", "true", "yes", "on", "stream", "streaming", "chunked"):
- _streaming_enabled = True
- elif _streaming in ("0", "false", "no", "off", "full"):
- _streaming_enabled = False
- else:
- # Auto: short 5 s clips are faster as a single decode; long clips
- # keep temporal chunks to avoid memory-pressure stalls.
- _streaming_enabled = _frames_est > _auto_max
-
- if _streaming_enabled:
- from ltx_core_mlx.model.video_vae.tiling import TilingConfig, TemporalTilingConfig
-
- _tile_frames = int(_os.environ.get("LTX_VAE_TILE_FRAMES", "64"))
- _overlap_frames = int(_os.environ.get("LTX_VAE_TILE_OVERLAP_FRAMES", "24"))
- _tile_frames = max(16, (_tile_frames // 8) * 8)
- _overlap_frames = max(0, (_overlap_frames // 8) * 8)
- if _overlap_frames >= _tile_frames:
- _overlap_frames = max(0, _tile_frames - 8)
- _tiling = TilingConfig(
- spatial_config=None,
- temporal_config=TemporalTilingConfig(
- tile_size_in_frames=_tile_frames,
- tile_overlap_in_frames=_overlap_frames,
- ),
- )
- _frame_index = 0
- for pixels in self.tiled_decode(latent, _tiling):
- mx.async_eval(pixels)
- num_frames = pixels.shape[2]
- for i in range(num_frames):
- frame = pixels[:, :, i, :, :] # (B, 3, H, W)
- frame = mx.clip(frame, -1.0, 1.0)
- frame = ((frame + 1.0) * 127.5).astype(mx.uint8)
- # (1, 3, H, W) -> (H, W, 3)
- frame_hwc = frame[0].transpose(1, 2, 0)
- mx.eval(frame_hwc) # must be sync — async_eval can write before data is ready
- proc.stdin.write(bytes(memoryview(frame_hwc)))
- del frame, frame_hwc
- _frame_index += 1
- if _frame_index % 8 == 0:
- aggressive_cleanup()
- del pixels
- aggressive_cleanup()
- else:
- # Emergency fallback: original full-volume decode.
- pixels = self.decode(latent)
- mx.async_eval(pixels)
-
- num_frames = pixels.shape[2]
- for i in range(num_frames):
- frame = pixels[:, :, i, :, :] # (B, 3, H, W)
- frame = mx.clip(frame, -1.0, 1.0)
- frame = ((frame + 1.0) * 127.5).astype(mx.uint8)
- # (1, 3, H, W) -> (H, W, 3)
- frame_hwc = frame[0].transpose(1, 2, 0)
- mx.eval(frame_hwc) # must be sync — async_eval can write before data is ready
- proc.stdin.write(bytes(memoryview(frame_hwc)))
- del frame, frame_hwc
- if i % 8 == 0:
- aggressive_cleanup()'''
-
-
-# ---- Patch 6: distilled generate_from_image — tighten DiT eval cadence for I2V ----
-# Why: DistilledPipeline.generate_from_image() sets
-# _DIT_EVAL_EVERY = min(2, orig)
-# to limit Metal command-buffer size. That value was calibrated for T2V at
-# ~4800 tokens (16×15×20 at 121f, 640×480). I2V prepends a conditioning frame
-# (+15×20 = 300 tokens), pushing the total to 5100. The first cold-compile
-# Metal kernel at 5100 tokens consistently exceeds the 10-second watchdog
-# (MTLCommandBufferErrorInternal code 0x0e / 14) and crashes the helper.
-# Fix: use min(1, orig) — 1 block per buffer halves per-buffer compute cost.
-# ~48 extra mx.eval() syncs per step add ~20 ms total (negligible vs. ~2 min).
-# Reference: 640×480 × 121f I2V with ≥1 LoRA (extra VRAM → tighter watchdog
-# budget) is the reliably-reproducible trigger. Smaller resolutions or fewer
-# frames sit under the threshold with min(2).
-PATCH_DISTILLED_EVAL_OLD = ' _dit_mod._DIT_EVAL_EVERY = min(2, _orig_eval_every) if _orig_eval_every > 0 else _orig_eval_every'
-PATCH_DISTILLED_EVAL_NEW = (
- ' # PATCHED (LTX23MLX): I2V at 121f adds conditioning-frame tokens on top of\n'
- ' # generation tokens (4800 + 300 = 5100 at 640×480). The upstream min(2, ...)\n'
- ' # means 2 DiT blocks per Metal command buffer; at 5100 tokens the first\n'
- ' # cold-compile buffer consistently exceeds the 10-second Metal watchdog\n'
- ' # (MTLCommandBufferErrorInternal code 0x0e). Using 1 block/buffer halves\n'
- ' # per-buffer compute; ~48 extra mx.eval() syncs add ~20 ms total.\n'
- ' _dit_mod._DIT_EVAL_EVERY = min(1, _orig_eval_every) if _orig_eval_every > 0 else _orig_eval_every'
-)
-
-# NOTE: Keyframe interpolation OOMs at the stage-1 → stage-2 transition on
-# 64 GB Macs. We tried free-DiT-before-upscale + reload-after-upscale; that
-# *didn't* help (the reload hit the same memory peak from a different angle
-# and added ~30s of wall time). Workaround is now in the panel side: keyframe
-# mode runs at half resolution (640×352 stage-1, 1280×704 stage-2 still goes
-# OOM; 384×216 stage-1 / 768×432 stage-2 fits). Looking for a real upstream
-# fix later. Keep this comment so we don't re-introduce the failed patch.
-
# Outcome codes for apply_patch — three-valued (vs the old True/False) so
# main() can distinguish a genuinely missing target / drifted upstream from
@@ -357,24 +141,9 @@ def apply_patch(target: Path, old: str, new: str, marker: str, label: str,
return OUTCOME_ALREADY
# Marker but no upgrade_marker → old patch version on disk. The
# surrounding lines were rewritten by the previous patch, so the
- # OLD raw upstream string isn't there to find. Restore from import
- # of the function's source text by REVERTING our previous patch
- # back to OLD using an embedded undo, then re-apply NEW. We do
- # this by re-reading the upstream commit-pinned source.
+ # OLD raw upstream string isn't there to find. Find the old codec
+ # line (without faststart) and replace with the new one.
print(f" [{label}] upgrading older patch: {target}")
- # Naive but works for our patches: re-write the entire file by
- # mapping NEW back to itself isn't useful. Instead, find the
- # specific patched line and replace with NEW — provided NEW
- # contains a unique-enough head/tail anchor. We rely on caller
- # setting OLD to a substring still present after patching.
- # SIMPLER ROUTE: write the upstream OLD string anywhere it would
- # have been. Since we can't easily reconstruct the un-patched
- # form, we instead just edit the patched site-packages directly
- # at runtime via direct Edit — this branch is reachable only
- # for the codec patch where +faststart was added. The narrow
- # marker-pair (old=cmd.extend without faststart, new=cmd.extend
- # with faststart) lets us find and replace.
- # Find the old line (without faststart) and replace with new line.
old_one_liner = ('cmd.extend(["-c:v", "libx264", "-pix_fmt", _pix, '
'"-crf", _crf, output_path])')
new_one_liner = ('cmd.extend(["-c:v", "libx264", "-pix_fmt", _pix, '
@@ -403,95 +172,9 @@ def apply_patch(target: Path, old: str, new: str, marker: str, label: str,
return OUTCOME_APPLIED
-def apply_one_stage_fps_patch(target: Path | None) -> str:
- """Expose frame_rate on the one-stage T2V/I2V pipeline.
-
- This is a multi-anchor patch because older installs may already have our
- I2V memory patches applied, which changes the exact generate_and_save()
- body. Keep it narrow and verify the final required markers instead of
- replacing one large fragile block.
- """
- label = "one-stage frame_rate (12→24fps long clips)"
- if target is None or not target.exists():
- print(f" [{label}] MISSING — target file not found", file=sys.stderr)
- return OUTCOME_MISSING
- text = target.read_text()
- required = (
- "frame_rate: float = 24.0",
- "compute_audio_token_count(num_frames, fps=frame_rate)",
- "compute_video_positions(F, H, W, fps=frame_rate)",
- "fps=frame_rate",
- )
- if all(marker in text for marker in required):
- print(f" [{label}] already patched: {target}")
- return OUTCOME_ALREADY
-
- original = text
- replacements = [
- (
- " num_steps: int | None = None,\n"
- " ) -> tuple[mx.array, mx.array]:",
- " num_steps: int | None = None,\n"
- " frame_rate: float = 24.0,\n"
- " ) -> tuple[mx.array, mx.array]:",
- ),
- (
- " num_steps: int | None = None,\n"
- " ) -> str:",
- " num_steps: int | None = None,\n"
- " frame_rate: float = 24.0,\n"
- " ) -> str:",
- ),
- (
- " audio_T = compute_audio_token_count(num_frames)",
- " audio_T = compute_audio_token_count(num_frames, fps=frame_rate)",
- ),
- (
- " video_positions = compute_video_positions(F, H, W)",
- " video_positions = compute_video_positions(F, H, W, fps=frame_rate)",
- ),
- (
- " num_steps=num_steps,\n"
- " )",
- " num_steps=num_steps,\n"
- " frame_rate=frame_rate,\n"
- " )",
- ),
- (
- "return super().generate_and_save(prompt, output_path, height, width, num_frames, seed, num_steps)",
- "return super().generate_and_save(prompt, output_path, height, width, num_frames, seed, num_steps, frame_rate)",
- ),
- (
- "return self._decode_and_save_video(video_latent, audio_latent, output_path)",
- "return self._decode_and_save_video(video_latent, audio_latent, output_path, fps=frame_rate)",
- ),
- ]
- for old, new in replacements:
- text = text.replace(old, new)
-
- if text == original:
- print(
- f" [{label}] DRIFT — no fps anchors matched in {target}.",
- file=sys.stderr,
- )
- return OUTCOME_DRIFT
- if not all(marker in text for marker in required):
- missing = [marker for marker in required if marker not in text]
- print(
- f" [{label}] DRIFT — patch incomplete in {target}; missing {missing}",
- file=sys.stderr,
- )
- return OUTCOME_DRIFT
- _atomic_write(target, text)
- print(f" [{label}] patched {target}")
- return OUTCOME_APPLIED
-
-
def main() -> int:
- print("Applying LTX23MLX patches:")
- outcomes: list[tuple[str, str]] = []
+ print("Applying LTX23MLX codec patch (ltx-2-mlx v0.14.8 — only the codec edit remains):")
- # Patch 1: codec
# `upgrade_marker="+faststart"` lets us upgrade installs where the
# earlier version of this patch was applied (LTX_OUTPUT_PIX_FMT marker
# present, but the +faststart movflag missing). Without the upgrade
@@ -499,159 +182,29 @@ def main() -> int:
# gallery thumbnails render the first frame without downloading the
# full clip.
codec_target = _find("ltx_core_mlx/model/video_vae/video_vae.py")
- outcomes.append(("codec (yuv444p crf 0 + faststart)", apply_patch(
+ outcome = apply_patch(
codec_target, PATCH_CODEC_OLD, PATCH_CODEC_NEW,
marker="LTX_OUTPUT_PIX_FMT",
upgrade_marker="+faststart",
label="codec (yuv444p crf 0 + faststart)",
- )))
-
- # Patch 2: I2V OOM cleanup before decode
- # SHIP-BLOCKER history: install.js pins ltx-2-mlx to commit dcd639e
- # (the 0.1.0 audio baseline) because newer 0.2.0 commits regressed
- # audio amplitude by 22 dB. At dcd639e the I2V function inlines the
- # decode steps instead of calling _decode_and_save_video, so this
- # patch's old/new strings don't match. Mark it OPTIONAL — DRIFT is
- # treated as a warning (the patch only helps Q8 / 64 GB I2V runs;
- # T2V works fine without it). The codec patch above is REQUIRED.
- i2v_target = _find("ltx_pipelines_mlx/ti2vid_one_stage.py")
- i2v_outcome = apply_patch(
- i2v_target, PATCH_I2V_OOM_OLD, PATCH_I2V_OOM_NEW,
- marker="PATCHED (LTX23MLX): mirror the parent T2V cleanup",
- label="I2V OOM (free DiT before decode)",
)
- if i2v_outcome == OUTCOME_DRIFT:
- print(
- " [I2V OOM] note: this patch only matches the 0.2.0+ I2V "
- "structure. On the pinned 0.1.0 baseline (dcd639e) it's a no-op. "
- "T2V output is unaffected; HQ I2V on Q8 may OOM without it.",
- file=sys.stderr,
- )
- # Treat as ALREADY for the rollup so install doesn't fail.
- i2v_outcome = OUTCOME_ALREADY
- outcomes.append(("I2V OOM (free DiT before decode)", i2v_outcome))
-
- # Patch 3: free vae_encoder + feature_extractor BEFORE the I2V denoise loop.
- # Same target file as Patch 2; different anchor. Optional like Patch 2 —
- # if dgrauet refactors generate_from_image upstream this becomes a no-op
- # warning instead of a hard install failure.
- pre_outcome = apply_patch(
- i2v_target, PATCH_I2V_PREDENOISE_OLD, PATCH_I2V_PREDENOISE_NEW,
- marker="PATCHED (LTX23MLX, peanut review): free vae_encoder",
- label="I2V free pre-denoise (peanut)",
- )
- if pre_outcome in (OUTCOME_DRIFT, OUTCOME_MISSING):
- print(
- " [I2V free pre-denoise] note: anchor not found — pipeline may have "
- "been refactored upstream. Generation still works, just without the "
- "memory-overlap cleanup. T2V users unaffected.",
- file=sys.stderr,
- )
- pre_outcome = OUTCOME_ALREADY
- outcomes.append(("I2V free pre-denoise (peanut)", pre_outcome))
- # Patch 4: base TextToVideoPipeline.load() also clears feature_extractor
- # alongside text_encoder before loading the transformer. Affects T2V/I2V/
- # Extend — they all go through the same base load(). Strict subset of the
- # peanut-review fix: even when generate_from_image has its own cleanup,
- # the base load() reload-then-free-then-load-DiT path benefits from the
- # extra clear (no point holding feature_extractor through a 10 GiB DiT load).
- base_outcome = apply_patch(
- i2v_target, PATCH_BASE_LOAD_OLD, PATCH_BASE_LOAD_NEW,
- marker="PATCHED (LTX23MLX, peanut review): also clear feature_extractor",
- label="base load() free feature_extractor (peanut)",
- )
- if base_outcome in (OUTCOME_DRIFT, OUTCOME_MISSING):
- print(
- " [base load() free feature_extractor] note: anchor not found — "
- "base load() may have been refactored upstream. Memory peak slightly "
- "higher than with this patch but generation is unaffected.",
- file=sys.stderr,
- )
- base_outcome = OUTCOME_ALREADY
- outcomes.append(("base load() free feature_extractor (peanut)", base_outcome))
-
- # Patch 5: temporal streaming VAE decode. Required for long/high-res renders:
- # without it, decode_and_stream still materializes the whole video tensor and
- # can look like a frozen final step under memory pressure.
- vae_stream_outcome = apply_patch(
- codec_target, PATCH_VAE_STREAM_OLD, PATCH_VAE_STREAM_NEW,
- marker="PATCHED (LTX23MLX): temporal streaming decode",
- label="VAE temporal streaming decode",
- )
- outcomes.append(("VAE temporal streaming decode", vae_stream_outcome))
-
- # Patch 6: expose frame_rate in the one-stage T2V/I2V path. This is the
- # shippable hook for the panel's explicit Long Clip Boost mode: generate
- # fewer semantic frames at 12fps, keep LTX audio duration aligned, then
- # interpolate the delivered export back to 24fps.
- #
- # Treat upstream drift as ADVISORY (same convention as patches 2/3/4):
- # when dgrauet refactors `ti2vid_one_stage.py`, the anchor disappears
- # and a hard install failure here would block every new user even
- # though the codec patch (the only one that actually affects T2V/I2V
- # correctness) applied. Without this patch, generation still works at
- # the engine's native frame rate; only the panel's explicit "Long Clip
- # Boost (12→24fps)" mode is unavailable until the patch is updated.
- fps_outcome = apply_one_stage_fps_patch(i2v_target)
- if fps_outcome in (OUTCOME_DRIFT, OUTCOME_MISSING):
- print(
- " [one-stage frame_rate] note: anchor not found — pipeline may "
- "have been refactored upstream. T2V / I2V at native fps work fine; "
- "the panel's Long Clip Boost (12→24fps interpolation) mode is "
- "unavailable until the patch is updated.",
- file=sys.stderr,
- )
- fps_outcome = OUTCOME_ALREADY
- outcomes.append(("one-stage frame_rate (12→24fps long clips)", fps_outcome))
-
- # Patch 7: tighten DiT eval cadence in generate_from_image for I2V.
- # Optional — if dgrauet changes the block structure or removes the explicit
- # _DIT_EVAL_EVERY override, DRIFT is a warning rather than a hard failure;
- # the worst case is the upstream behavior (min(2,...)) which crashes on 121f
- # I2V at 640×480 but works at smaller resolutions.
- distilled_target = _find("ltx_pipelines_mlx/distilled.py")
- eval_outcome = apply_patch(
- distilled_target, PATCH_DISTILLED_EVAL_OLD, PATCH_DISTILLED_EVAL_NEW,
- marker="PATCHED (LTX23MLX): I2V at 121f adds conditioning-frame tokens",
- label="distilled DiT eval cadence (I2V watchdog fix)",
- )
- if eval_outcome in (OUTCOME_DRIFT, OUTCOME_MISSING):
- print(
- " [distilled DiT eval cadence] note: anchor not found — upstream may have "
- "changed _DIT_EVAL_EVERY handling. 121f I2V at 640×480 may crash with "
- "MTLCommandBufferErrorInternal code 14. T2V unaffected.",
- file=sys.stderr,
- )
- eval_outcome = OUTCOME_ALREADY
- outcomes.append(("distilled DiT eval cadence (I2V watchdog fix)", eval_outcome))
-
- # (Keyframe OOM patch was removed — see NOTE in the patches block above.
- # The fix is currently a panel-side resolution clamp, not a pipeline edit.)
-
- applied = sum(1 for _, o in outcomes if o == OUTCOME_APPLIED)
- already = sum(1 for _, o in outcomes if o == OUTCOME_ALREADY)
- failed = [(label, o) for label, o in outcomes if o in (OUTCOME_MISSING, OUTCOME_DRIFT)]
-
- if failed:
- print(
- f"\nERROR: {len(failed)} patch(es) failed to apply:",
- file=sys.stderr,
- )
- for label, o in failed:
- print(f" - [{label}] {o}", file=sys.stderr)
+ if outcome in (OUTCOME_MISSING, OUTCOME_DRIFT):
print(
- "\nThis exits non-zero so install.js / update.js fail loud. "
- "The runtime depends on these patches; running with them missing "
- "produces broken output (chroma artifacts, mid-job OOMs).",
+ f"\nERROR: codec patch failed to apply ({outcome}).\n"
+ "This exits non-zero so install.js / update.js fail loud rather than\n"
+ "silently ship a 4:2:0 yuv420p install (visible block artifacts on\n"
+ "faces/skin). If a pin-bump restructured decode_and_stream's ffmpeg\n"
+ "line, update PATCH_CODEC_OLD in patch_ltx_codec.py to match the new\n"
+ "upstream text, then re-run.",
file=sys.stderr,
)
return 2
- if applied == 0:
- print(f"All patches already applied ({already} already-patched, 0 changed).")
+ if outcome == OUTCOME_APPLIED:
+ print("Done — codec patch applied.")
else:
- print(f"Done — {applied} patch(es) newly applied, {already} already-patched.")
+ print("Codec patch already applied (no change).")
return 0
diff --git a/update.js b/update.js
index 673a711..51bac30 100644
--- a/update.js
+++ b/update.js
@@ -38,20 +38,24 @@ module.exports = {
]
}
},
- // ltx-2-mlx is PINNED to v0.14.0 (dgrauet's request 2026-05-12 — he
- // is pushing breaking changes upstream to sync with the official
- // Lightricks repo). Update no longer tracks main; it fetches tags
- // and re-checks-out the pinned tag so a previously-installed user
- // converges to a known-good state, never to a moving HEAD. To bump
- // the pin: edit BOTH install.js and update.js to a new tag, smoke-
- // test on dev, push.
+ // ltx-2-mlx is PINNED to v0.14.8 (2026-06-01 catch-up from v0.14.0;
+ // dgrauet's original tag-pin request 2026-05-12 — he pushes breaking
+ // changes upstream to sync with the official Lightricks repo). Update
+ // no longer tracks main; it fetches tags and re-checks-out the pinned
+ // tag so a previously-installed user converges to a known-good state,
+ // never to a moving HEAD. The ltx-package re-install step below then
+ // force-copies the v0.14.8 source into site-packages (non-editable),
+ // so an existing user's runtime actually moves to 0.14.8 — a bare
+ // checkout alone would leave the old copy installed. To bump the pin:
+ // edit BOTH install.js and update.js to the new tag, bump
+ // _LTX_EXPECTED_VERSION in mlx_warm_helper.py, smoke-test on dev, push.
{
method: "shell.run",
params: {
path: "ltx-2-mlx",
message: [
"git fetch --tags origin",
- "git checkout v0.14.0",
+ "git checkout v0.14.8",
"git rev-parse --short HEAD"
]
}