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.

Y1.021 wire LTX latent x2 upscaler with Fast/Sharp method choice

mrbizarro0a265ac0267f
diff --git a/VERSION b/VERSION
index 18fb969..a5101dc 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-Y1.020
+Y1.021
diff --git a/mlx_ltx_panel.py b/mlx_ltx_panel.py
index 9da49c6..67b4670 100644
--- a/mlx_ltx_panel.py
+++ b/mlx_ltx_panel.py
@@ -2278,31 +2278,52 @@ def compute_pad(w: int, h: int) -> tuple[int, int, str | None]:
return target_w, target_h, f"pad={target_w}:{target_h}:{pad_x}:{pad_y}:color=black"
-def compute_upscale_plan(w: int, h: int, mode: str | None) -> dict | None:
+def compute_upscale_plan(w: int, h: int, mode: str | None,
+ helper_did_model_upscale: bool = False) -> dict | None:
+ """Plan a panel-side ffmpeg upscale pass. Returns None when no further
+ work is needed (helper already produced the target dims, or target is off).
+
+ `helper_did_model_upscale=True` means the helper already ran the LTX latent
+ x2 upscaler; the file on disk is at 2× the requested W/H. We use this to
+ avoid double-upscaling and to plan a downscale-only pass for the
+ fit_720p target on a model-upscaled source."""
mode = (mode or "off").strip().lower()
if mode in ("", "off", "native"):
return None
+ # Effective dims of the file the helper actually wrote. The model-based
+ # upscale (Sharper) doubles them inside the helper before VAE decode.
+ eff_w = w * 2 if helper_did_model_upscale else w
+ eff_h = h * 2 if helper_did_model_upscale else h
if mode == "fit_720p":
# No crop, no distortion: fit inside standard 720p canvas and pad any
- # remainder. 1024x576 fills 1280x720 exactly; 1280x704 becomes 1280x704
- # with 8px bars top/bottom; 704x1280 becomes 704x1280 with side bars.
- if w >= h:
+ # remainder. 1024×576 fills 1280×720 exactly; 1280×704 becomes 1280×704
+ # with 8px bars top/bottom; 704×1280 becomes 704×1280 with side bars.
+ if eff_w >= eff_h:
target_w, target_h, tag = 1280, 720, "720p"
else:
target_w, target_h, tag = 720, 1280, "v720p"
+ # If the helper already produced the exact target size, skip the pass.
+ if eff_w == target_w and eff_h == target_h:
+ return None
vf = (
f"scale={target_w}:{target_h}:"
"force_original_aspect_ratio=decrease:flags=lanczos,"
f"pad={target_w}:{target_h}:(ow-iw)/2:(oh-ih)/2:color=black"
)
+ method = "ffmpeg_lanczos_downscale" if helper_did_model_upscale else "ffmpeg_lanczos"
elif mode == "x2":
+ # If the helper already did model x2, the file is already at the
+ # x2 target — no further panel-side work needed.
+ if helper_did_model_upscale:
+ return None
target_w, target_h, tag = w * 2, h * 2, "up2x"
vf = f"scale={target_w}:{target_h}:flags=lanczos"
+ method = "ffmpeg_lanczos"
else:
raise RuntimeError(f"unknown upscale mode: {mode}")
return {
"mode": mode,
- "method": "ffmpeg_lanczos",
+ "method": method,
"target_w": target_w,
"target_h": target_h,
"tag": tag,
@@ -2423,6 +2444,7 @@ def make_job(form: dict[str, list[str]] | dict[str, str], *,
"quality": quality, # quick / balanced / standard / high
"accel": f("accel", "off"), # off / boost / turbo
"upscale": upscale, # off / fit_720p / x2
+ "upscale_method": f("upscale_method", "lanczos"), # lanczos / model
# LoRAs the user has enabled for this job. The UI submits a
# JSON-encoded array via the `loras` form field; we parse +
# validate here so the worker / helper layers receive a clean
@@ -2809,7 +2831,13 @@ def run_job_inner(job: dict) -> None:
final_target = final_out
native_target = final_target
- upscale_plan = compute_upscale_plan(width, height, p.get("upscale", "off"))
+ helper_did_model_upscale = (result.get("upscale_applied") == "model_x2")
+ if helper_did_model_upscale:
+ push(f"Helper produced model-upscaled output ({width*2}×{height*2}, sharper).")
+ upscale_plan = compute_upscale_plan(
+ width, height, p.get("upscale", "off"),
+ helper_did_model_upscale=helper_did_model_upscale,
+ )
if upscale_plan:
codec = output_codec_settings()
mux_pix_fmt = codec["pix_fmt"]
@@ -2862,6 +2890,19 @@ def run_job_inner(job: dict) -> None:
k: v for k, v in upscale_plan.items()
if k not in ("vf",)
} | {"source": str(native_target), "codec": output_codec_settings()}
+ if helper_did_model_upscale:
+ sidecar["upscale"]["pre_pass"] = "ltx_latent_x2"
+ elif helper_did_model_upscale:
+ # Helper produced the final 2× output already; record that for the
+ # info modal so users see "Sharper (model x2)" on the card.
+ sidecar["upscale"] = {
+ "mode": p.get("upscale", "x2"),
+ "method": "ltx_latent_x2",
+ "target_w": width * 2,
+ "target_h": height * 2,
+ "source": str(native_target),
+ "codec": output_codec_settings(),
+ }
write_sidecar(final_target.with_suffix(final_target.suffix + ".json"), sidecar)
job["output_path"] = str(final_target)
push(f"Done in {sidecar['elapsed_sec']}s → {final_target.name}")
@@ -5598,9 +5639,10 @@ HTML = r"""<!doctype html>
</div>
</div>
- <!-- Export upscale — lightweight ffmpeg Lanczos pass after render.
- "720p fit" preserves aspect ratio: exact 16:9 fills the canvas,
- LTX-wide 1280×704 gets tiny letterbox padding, never crop. -->
+ <!-- Export upscale — target dims after render. "720p fit"
+ preserves aspect ratio (no crop, no distortion). 2× doubles
+ each side. Native skips the upscale entirely. The "Method"
+ row below picks how the upscaling is done. -->
<div class="cz-control">
<div class="cz-label">Export
<span class="cz-label-hint">post-render, no crop</span>
@@ -5611,6 +5653,23 @@ HTML = r"""<!doctype html>
<button type="button" class="pill-btn" data-upscale="x2"><span>2×</span><span class="sub">same ratio</span></button>
</div>
</div>
+
+ <!-- Upscale method (Y1.021). Hidden when Export = Native. Fast
+ = ffmpeg Lanczos resize, no detail recovery, near-instant.
+ Sharp = LTX 2.3 latent upscaler (~1 GB model), invents real
+ detail in latent space before VAE decode, ~30-60s slower.
+ Sharp is auto-disabled on tiers without enough RAM, and
+ falls back to Fast at runtime if the model file is missing. -->
+ <div class="cz-control" id="upscaleMethodRow" style="display:none;">
+ <div class="cz-label">Method
+ <span class="cz-label-hint">how the upscale is done</span>
+ </div>
+ <div class="pill-group cols-2" id="upscaleMethodGroup">
+ <button type="button" class="pill-btn active" data-method="lanczos"><span>Fast</span><span class="sub">ffmpeg Lanczos · instant</span></button>
+ <button type="button" class="pill-btn" data-method="model"><span>Sharp</span><span class="sub">LTX upscaler · +30-60 s · real detail</span></button>
+ </div>
+ <input type="hidden" name="upscale_method" id="upscale_method" value="lanczos">
+ </div>
</div>
</details>
@@ -6071,6 +6130,19 @@ function setUpscale(u) {
const v = ['off', 'fit_720p', 'x2'].includes(u) ? u : 'off';
document.getElementById('upscale').value = v;
document.querySelectorAll('#upscaleGroup .pill-btn').forEach(b => b.classList.toggle('active', b.dataset.upscale === v));
+ // Show / hide the Method pill row — only relevant when an upscale is
+ // actually being applied. When toggled to "off", revert method to Fast
+ // so a later toggle back to fit_720p starts from the safe default.
+ const methodRow = document.getElementById('upscaleMethodRow');
+ if (methodRow) methodRow.style.display = (v === 'off') ? 'none' : '';
+ if (v === 'off') setUpscaleMethod('lanczos');
+ updateCustomizeSummary();
+ updateDerived();
+}
+function setUpscaleMethod(m) {
+ const v = ['lanczos', 'model'].includes(m) ? m : 'lanczos';
+ document.getElementById('upscale_method').value = v;
+ document.querySelectorAll('#upscaleMethodGroup .pill-btn').forEach(b => b.classList.toggle('active', b.dataset.method === v));
updateCustomizeSummary();
updateDerived();
}
@@ -6114,8 +6186,10 @@ function updateCustomizeSummary() {
}
// Speed
parts.push(accel === 'off' ? 'exact speed' : (accel === 'boost' ? 'boost' : 'turbo'));
- if (upscale === 'fit_720p') parts.push('720p export');
- else if (upscale === 'x2') parts.push('2× export');
+ const method = (document.getElementById('upscale_method')?.value || 'lanczos');
+ const methodTag = method === 'model' ? ' sharp' : '';
+ if (upscale === 'fit_720p') parts.push('720p export' + methodTag);
+ else if (upscale === 'x2') parts.push('2× export' + methodTag);
el.textContent = parts.join(' · ');
}
function setExtendMode(m) {
@@ -6134,6 +6208,7 @@ document.querySelectorAll('#modeGroup .pill-btn').forEach(b => b.onclick = () =>
document.querySelectorAll('#qualityGroup .pill-btn').forEach(b => b.onclick = () => { if (!b.classList.contains('disabled')) setQuality(b.dataset.quality); });
document.querySelectorAll('#accelGroup .pill-btn').forEach(b => b.onclick = () => { if (!b.classList.contains('disabled')) setAccel(b.dataset.accel); });
document.querySelectorAll('#upscaleGroup .pill-btn').forEach(b => b.onclick = () => { if (!b.classList.contains('disabled')) setUpscale(b.dataset.upscale); });
+document.querySelectorAll('#upscaleMethodGroup .pill-btn').forEach(b => b.onclick = () => { if (!b.classList.contains('disabled')) setUpscaleMethod(b.dataset.method); });
document.querySelectorAll('#aspectGroup .pill-btn').forEach(b => b.onclick = () => setAspect(b.dataset.aspect));
document.querySelectorAll('#extendModeGroup .pill-btn').forEach(b => b.onclick = () => setExtendMode(b.dataset.extendMode));
@@ -6903,6 +6978,7 @@ async function loadParams() {
if (p.height) document.getElementById('height').value = p.height;
if (p.accel) setAccel(p.accel);
if (p.upscale) setUpscale(p.upscale);
+ if (p.upscale_method) setUpscaleMethod(p.upscale_method);
document.getElementById('prompt').value = p.prompt || '';
document.getElementById('negative_prompt').value = p.negative_prompt || '';
if (p.frames) { document.getElementById('frames').value = p.frames; document.getElementById('duration').value = framesToDuration(p.frames); }
@@ -7059,7 +7135,9 @@ function renderOutputInfoBody(path, data) {
if (p.upscale && p.upscale !== 'off') {
const up = data.upscale || {};
const target = up.target_w && up.target_h ? ` → ${up.target_w} × ${up.target_h}` : '';
- const label = p.upscale === 'fit_720p' ? '720p fit (no crop)' : (p.upscale === 'x2' ? '2× Lanczos' : p.upscale);
+ const isModel = p.upscale_method === 'model' || (data.upscale && (data.upscale.method === 'ltx_latent_x2' || (data.upscale.pre_pass === 'ltx_latent_x2')));
+ const baseLabel = p.upscale === 'fit_720p' ? '720p fit (no crop)' : (p.upscale === 'x2' ? '2×' : p.upscale);
+ const label = isModel ? `${baseLabel} · Sharp (LTX upscaler)` : `${baseLabel} · Fast (Lanczos)`;
genRows.push(`<dt>Upscale</dt><dd>${escapeHtml(label + target)}</dd>`);
}
const codec = data.output_codec || (data.upscale && data.upscale.codec);
diff --git a/mlx_warm_helper.py b/mlx_warm_helper.py
index 7900c2b..d7e784a 100644
--- a/mlx_warm_helper.py
+++ b/mlx_warm_helper.py
@@ -495,6 +495,99 @@ def cover_crop_to_size(src_path: str, w: int, h: int) -> str:
return out_path
+# ---- LTX 2.3 spatial latent upscaler (Y1.021+) ------------------------------
+# Optional model-based ×2 upscale that runs on the video latent BEFORE the VAE
+# decode, giving real detail recovery instead of the ffmpeg Lanczos resize that
+# the panel's lightweight export path uses. The model file is a 1 GB
+# safetensors that ships in mlx_models/ltx-2.3-mlx-q8/ (downloaded by
+# install.js, retryable via Pinokio's "Download LTX upscaler" menu item).
+# We hand-roll the loader rather than instantiating the HQ pipeline because
+# we only want the upsampler — not the Q8 dev transformer that costs ~25 GB.
+_UPSCALER_CACHE = None
+_UPSCALER_CACHE_DIR = None
+
+
+def _upscaler_dir() -> Path:
+ # The upscaler weights live in the Q8 weights folder (HF repo organization),
+ # but downloading them is independent of the full Q8 bundle — install.js
+ # pulls the single safetensors. LTX_Q8_LOCAL is set by the panel.
+ explicit = os.environ.get("LTX_Q8_LOCAL")
+ if explicit:
+ return Path(explicit)
+ # Fall back to MODEL_ID's sibling dir (LTX_MODEL points at the Q4 dir
+ # under mlx_models/ at install time, so swap the trailing folder).
+ q4 = Path(MODEL_ID)
+ if q4.is_dir():
+ return q4.parent / "ltx-2.3-mlx-q8"
+ return Path("mlx_models/ltx-2.3-mlx-q8")
+
+
+def upscaler_available() -> bool:
+ return (_upscaler_dir() / "spatial_upscaler_x2_v1_1.safetensors").exists()
+
+
+def _load_upscaler():
+ """Lazy-load + cache the spatial latent upscaler. Returns the model
+ instance, or None if the weights aren't on disk (caller falls back to
+ ffmpeg Lanczos)."""
+ global _UPSCALER_CACHE, _UPSCALER_CACHE_DIR
+ model_dir = _upscaler_dir()
+ if _UPSCALER_CACHE is not None and _UPSCALER_CACHE_DIR == str(model_dir):
+ return _UPSCALER_CACHE
+ weights_path = model_dir / "spatial_upscaler_x2_v1_1.safetensors"
+ if not weights_path.exists():
+ return None
+ from ltx_core_mlx.model.upsampler import LatentUpsampler
+ from ltx_core_mlx.utils.weights import load_split_safetensors
+ config_path = model_dir / "spatial_upscaler_x2_v1_1_config.json"
+ if config_path.exists():
+ cfg = json.loads(config_path.read_text()).get("config", {})
+ ups = LatentUpsampler.from_config(cfg)
+ else:
+ ups = LatentUpsampler()
+ sd = load_split_safetensors(weights_path, prefix="spatial_upscaler_x2_v1_1.")
+ ups.load_weights(list(sd.items()))
+ _UPSCALER_CACHE = ups
+ _UPSCALER_CACHE_DIR = str(model_dir)
+ return ups
+
+
+def _free_upscaler():
+ global _UPSCALER_CACHE, _UPSCALER_CACHE_DIR
+ _UPSCALER_CACHE = None
+ _UPSCALER_CACHE_DIR = None
+ try:
+ from ltx_core_mlx.utils.memory import aggressive_cleanup
+ aggressive_cleanup()
+ except Exception:
+ pass
+
+
+def _model_upscale_video_latent(pipe, video_latent):
+ """Run the loaded latent x2 upscaler against the post-denoise video latent.
+ Mirrors the dance from upstream's TwoStageHQPipeline so the upsampler
+ gets the same denormalized input it was trained on. Returns the upscaled
+ latent in the same (B, C, F, H, W) layout."""
+ import mlx.core as mx
+ upsampler = _load_upscaler()
+ if upsampler is None:
+ raise RuntimeError("LTX spatial upscaler weights not on disk")
+ if pipe.vae_encoder is None:
+ pipe._load_vae_encoder()
+ # (B, C, F, H, W) -> (B, F, H, W, C) for denormalize_latent
+ video_mlx = video_latent.transpose(0, 2, 3, 4, 1)
+ video_denorm = pipe.vae_encoder.denormalize_latent(video_mlx)
+ # back to (B, C, F, H, W) for the upsampler
+ video_denorm = video_denorm.transpose(0, 4, 1, 2, 3)
+ video_upscaled = upsampler(video_denorm)
+ # renormalize for the VAE decoder
+ video_up_mlx = video_upscaled.transpose(0, 2, 3, 4, 1)
+ video_upscaled = pipe.vae_encoder.normalize_latent(video_up_mlx)
+ video_upscaled = video_upscaled.transpose(0, 4, 1, 2, 3)
+ mx.eval(video_upscaled)
+ return video_upscaled
+
+
# ---- one-stage acceleration --------------------------------------------------
# Experimental but useful: standard Q4 T2V/I2V spends most wall time inside the
# denoise loop's X0Model call. The "boost" and "turbo" modes below reuse the
@@ -857,15 +950,78 @@ for line in sys.__stdin__:
else:
kwargs["image"] = None
- emit({"event": "log", "line": f"step:generate_and_save mode={mode} {kwargs['width']}x{kwargs['height']} {kwargs['num_frames']}f steps={kwargs['num_steps']} accel={accel_mode}"})
- out_path = pipe.generate_and_save(**kwargs)
- emit({"event": "log", "line": "step:generate_and_save done"})
+ # Y1.021: model-based latent upscale path. When the user picks
+ # the "Sharper" method on a non-Native target, we run the
+ # spatial latent upscaler between denoise and VAE decode so the
+ # decoder hallucinates real detail at 2× — vs. the cheaper
+ # ffmpeg Lanczos path (which the panel applies after the helper
+ # returns). Only fires when the upscaler weights are on disk;
+ # otherwise we fall back silently to the normal path.
+ upscale_method = (p.get("upscale_method") or "lanczos").strip().lower()
+ upscale_target = (p.get("upscale") or "off").strip().lower()
+ use_model_upscale = (
+ upscale_method == "model"
+ and upscale_target in ("fit_720p", "x2")
+ and upscaler_available()
+ )
+ if upscale_method == "model" and upscale_target in ("fit_720p", "x2") and not upscaler_available():
+ emit({"event": "log", "line": "Sharper upscale requested but model weights missing — falling back to Lanczos."})
+
+ if use_model_upscale:
+ emit({"event": "log", "line": f"step:generate mode={mode} {kwargs['width']}x{kwargs['height']} {kwargs['num_frames']}f steps={kwargs['num_steps']} accel={accel_mode} upscale=model"})
+ # Step 1: generate latents (no save)
+ if needs_image:
+ src_image = kwargs.get("image")
+ video_latent, audio_latent = pipe.generate_from_image(
+ prompt=kwargs["prompt"],
+ image=src_image,
+ height=kwargs["height"],
+ width=kwargs["width"],
+ num_frames=kwargs["num_frames"],
+ seed=kwargs["seed"],
+ num_steps=kwargs["num_steps"],
+ )
+ else:
+ video_latent, audio_latent = pipe.generate(
+ prompt=kwargs["prompt"],
+ height=kwargs["height"],
+ width=kwargs["width"],
+ num_frames=kwargs["num_frames"],
+ seed=kwargs["seed"],
+ num_steps=kwargs["num_steps"],
+ )
+ emit({"event": "log", "line": "step:generate done"})
+ # Free DiT + text encoder before the upscale + VAE decode peak.
+ if pipe.low_memory:
+ pipe.dit = None
+ pipe.text_encoder = None
+ pipe.feature_extractor = None
+ pipe._loaded = False
+ try:
+ from ltx_core_mlx.utils.memory import aggressive_cleanup
+ aggressive_cleanup()
+ except Exception:
+ pass
+ # Step 2: latent x2 upscale
+ emit({"event": "log", "line": "step:latent_upscale_x2 start"})
+ video_latent = _model_upscale_video_latent(pipe, video_latent)
+ emit({"event": "log", "line": f"step:latent_upscale_x2 done — latent {video_latent.shape[-2]}×{video_latent.shape[-1]}"})
+ # Free the upscaler before VAE decode (can be ~2-3 GB peak).
+ _free_upscaler()
+ # Step 3: VAE decode + save (decoder loads inside _decode_and_save_video).
+ out_path = pipe._decode_and_save_video(video_latent, audio_latent, kwargs["output_path"])
+ emit({"event": "log", "line": "step:decode_and_save done"})
+ else:
+ emit({"event": "log", "line": f"step:generate_and_save mode={mode} {kwargs['width']}x{kwargs['height']} {kwargs['num_frames']}f steps={kwargs['num_steps']} accel={accel_mode}"})
+ out_path = pipe.generate_and_save(**kwargs)
+ emit({"event": "log", "line": "step:generate_and_save done"})
elapsed = round(time.time() - t0, 2)
_last_activity = time.time()
done_event = {
"event": "done", "id": job_id,
"output": str(out_path), "elapsed_sec": elapsed,
"seed_used": seed,
+ "upscale_applied": "model_x2" if use_model_upscale else None,
}
if accel_mode != "off" and _LAST_ACCEL_STATS:
done_event["accel_metrics"] = _LAST_ACCEL_STATS
@@ -878,6 +1034,10 @@ for line in sys.__stdin__:
configure_acceleration("off")
except Exception:
pass
+ try:
+ _free_upscaler()
+ except Exception:
+ pass
_is_busy = False
continue