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

add LoRA fusion for the bf16 LTX-2.3 Unified Beta (mlx_video) video runtime

[._.]/ Adam Eivyb24559b846ac
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 1d29e0e68b..53b1cff85d 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,6 +2,8 @@
## Added
+- **Video LoRAs now fuse on the bf16 LTX-2.3 Unified Beta (mlx_video runtime), not just dgrauet** — Previously a video LoRA like `ltx2.3-audio-reactive-lora` only worked on the dgrauet `ltx2` runtime; selecting the higher-quality **LTX-2.3 Unified Beta** (notapalindrome's `mlx_video` runtime) silently hid the LoRA picker. The stock `mlx_video.generate_av` CLI has no `--lora` flag, but the `mlx-video-with-audio` package ships an LTX-aware LoRA subsystem (`mlx_video.lora`) that's simply never called from the AV generator. A new wrapper (`scripts/generate_av_lora.py`) closes that gap without reimplementing the ~1000-line generation loop: it loads the user LoRAs, monkeypatches generate_av's two transformer-weight load seams to merge the LoRA deltas into the transformer (bf16, `quantization_bits=0`), then runs generate_av's own `main()` — so the SSE progress protocol is byte-for-byte identical to the non-LoRA path. The VideoGen picker now appears for non-quantized LTX-2.x `mlx_video` models too (gated by `isMlxVideoLtxLoraCapable`); if a LoRA's keys don't match the model the render fails loudly rather than silently producing a base video. Scoped to bf16 — the quantized Distilled Q4/Q8 variants stay on the dgrauet path for now and show an inline hint pointing at the supported models. (`scripts/generate_av_lora.py`, `server/lib/runners.js`, `server/services/videoGen/local.js`, `server/routes/videoGen.js`, `client/src/lib/runnerFamilies.js`, `client/src/pages/VideoGen.jsx`)
+
## Changed
## Fixed
diff --git a/client/src/lib/runnerFamilies.js b/client/src/lib/runnerFamilies.js
index a7302457cc..324d7e13ff 100644
--- a/client/src/lib/runnerFamilies.js
+++ b/client/src/lib/runnerFamilies.js
@@ -26,12 +26,31 @@ export const VIDEO_LORA_FAMILIES = Object.freeze({
const VIDEO_LORA_FAMILY_SET = new Set(Object.values(VIDEO_LORA_FAMILIES));
export const isVideoLoraFamily = (family) => VIDEO_LORA_FAMILY_SET.has(family);
-// Map a video model (carries `runtime`, not `runner`) to its LoRA family. Only
-// the dgrauet `ltx2` runtime fuses arbitrary user LoRAs today; everything else
-// returns null so the VideoGen picker hides itself. Mirror of
-// server/lib/runners.js#videoLoraFamily.
+// A LoRA-quantization marker (`q4` / `q8`) in a model's id/repo/name, bounded
+// so it doesn't match inside unrelated tokens. Mirror of server/lib/runners.js.
+const QUANTIZED_LTX_RE = /(?:^|[-_/\s])q(?:4|8)(?:[-_./\s]|$)/i;
+
+// True when an mlx_video-runtime model is a non-quantized LTX-2.x model whose
+// LoRAs PortOS can fuse offline (scripts/generate_av_lora.py merges the deltas
+// into the transformer before generation). Excludes quantized q4/q8 variants
+// (bf16-only scope) and the Windows LTX-Video 0.9.5 model. Mirror of
+// server/lib/runners.js#isMlxVideoLtxLoraCapable.
+export const isMlxVideoLtxLoraCapable = (model) => {
+ if (model?.runtime !== 'mlx_video') return false;
+ const hay = `${model?.id || ''} ${model?.repo || ''} ${model?.name || ''}`;
+ if (!/ltx-?2/i.test(hay)) return false;
+ if (QUANTIZED_LTX_RE.test(hay)) return false;
+ return true;
+};
+
+// Map a video model (carries `runtime`, not `runner`) to its LoRA family. Both
+// the dgrauet `ltx2` runtime and non-quantized LTX-2.x `mlx_video` models fuse
+// user LoRAs; everything else returns null so the VideoGen picker hides itself.
+// Mirror of server/lib/runners.js#videoLoraFamily.
export const videoLoraFamily = (model) =>
- model?.runtime === 'ltx2' ? VIDEO_LORA_FAMILIES.LTX_VIDEO : null;
+ (model?.runtime === 'ltx2' || isMlxVideoLtxLoraCapable(model))
+ ? VIDEO_LORA_FAMILIES.LTX_VIDEO
+ : null;
// FLUX.2 Klein ships in two sizes with different transformer hidden dims (4B =
// 3072, 9B = 4096), so a LoRA trained for one can't load on the other. The
diff --git a/client/src/pages/VideoGen.jsx b/client/src/pages/VideoGen.jsx
index 6111962480..3efe3e4a11 100644
--- a/client/src/pages/VideoGen.jsx
+++ b/client/src/pages/VideoGen.jsx
@@ -742,6 +742,19 @@ export default function VideoGen() {
? availableLoras.filter((l) => (l.loraCompatKey || l.runnerFamily) === loraFamily)
: [];
+ // Installed LTX-video LoRAs regardless of the selected model's runtime. When
+ // the user picks an LTX-2.x model whose runtime can't fuse LoRAs (a quantized
+ // mlx_video model — loraFamily is null), the picker is correctly hidden, but
+ // silently doing so reads as a bug. Use this to explain *why* the LoRA is
+ // unavailable and point at the models that CAN run it. The `/ltx-?2/i` scope
+ // matches the server's LTX-2.x capability family (see isMlxVideoLtxLoraCapable)
+ // so the hint never fires for a non-LTX-2.x model where the advice wouldn't apply.
+ const installedVideoLoras = availableLoras.filter(
+ (l) => (l.loraCompatKey || l.runnerFamily) === VIDEO_LORA_FAMILIES.LTX_VIDEO,
+ );
+ const showLtxLoraUnsupportedHint = !loraFamily && installedVideoLoras.length > 0
+ && /ltx-?2/i.test(`${currentModel?.id || ''} ${currentModel?.repo || ''} ${currentModel?.name || ''}`);
+
// Multi-keyframe availability + validation. Keyframes are an ltx2-runtime
// primitive (the route 400s with KEYFRAMES_REQUIRE_LTX2 otherwise), so the
// picker only offers itself when the selected model runs on ltx2. Mirror
@@ -1531,6 +1544,15 @@ export default function VideoGen() {
</div>
)}
+ {/* LTX model that can't fuse LoRAs (quantized mlx_video — q4/q8) with
+ compatible LoRAs on disk: explain the absence instead of hiding
+ silently, and point at the models that CAN run them. */}
+ {showLtxLoraUnsupportedHint && (
+ <div className="col-span-2 sm:col-span-3 rounded-lg border border-port-warning/40 bg-port-warning/10 px-3 py-2 text-xs text-port-warning leading-snug">
+ You have {installedVideoLoras.length} LTX video LoRA{installedVideoLoras.length === 1 ? '' : 's'} installed, but <strong className="font-semibold">{currentModel?.name}</strong> can't fuse LoRAs (its quantized <code>mlx_video</code> runtime isn't supported yet). Switch to the <strong className="font-semibold">LTX-2.3 Unified Beta</strong> (bf16) or an <strong className="font-semibold">LTX-2.3 dgrauet (Q4/Q8)</strong> model to use them.
+ </div>
+ )}
+
<div>
<label className="block text-xs font-medium text-gray-400 mb-1">Resolution</label>
<select
diff --git a/scripts/generate_av_lora.py b/scripts/generate_av_lora.py
new file mode 100644
index 0000000000..8a74f8e111
--- /dev/null
+++ b/scripts/generate_av_lora.py
@@ -0,0 +1,160 @@
+#!/usr/bin/env python3
+"""PortOS LoRA wrapper for notapalindrome's `mlx_video.generate_av` runtime.
+
+The stock `python -m mlx_video.generate_av` CLI (used for video models with
+`runtime: 'mlx_video'` in data/media-models.json) has no `--lora` flag. But the
+`mlx-video-with-audio` package ships an LTX-aware LoRA subsystem (`mlx_video.lora`,
+with `_normalize_ltx_lora_key`) — it's just never called from the AV generator.
+
+This wrapper closes that gap WITHOUT reimplementing generate_av's ~1000-line
+generation loop:
+
+ 1. Parse `--user-loras` (a JSON list of {path, strength}) out of argv; everything
+ else passes through untouched to generate_av's own argparse.
+ 2. Load the LoRAs into the package's `module_to_loras` map.
+ 3. Monkeypatch the two transformer-weight load seams generate_av uses
+ (`load_unified_weights` for the single-file layout, `sanitize_transformer_weights`
+ for the split-weight layout) so the LoRA deltas merge into the transformer
+ weights as they're loaded.
+ 4. Run `generate_av.main()` — so the SSE protocol (STAGE:/STATUS:/DOWNLOAD: and
+ the final {"video_path": ...} JSON line) is byte-for-byte identical to the
+ non-LoRA path the Node videoGen service already parses.
+
+Scope: NON-quantized (bf16) LTX-2.x models only — the merge runs with
+`quantization_bits=0`. The Node side gates this via isMlxVideoLtxLoraCapable()
+(server/lib/runners.js), so a quantized q4/q8 model never reaches this script.
+
+Runs in the SAME venv as `mlx_video.generate_av` (the configured pythonPath), not
+a separate BYOV venv.
+"""
+from __future__ import annotations
+
+import argparse
+import json
+import sys
+from pathlib import Path
+
+
+def emit_status(msg: str) -> None:
+ """STATUS: line — routed to PortOS SSE as `status` (mirrors generate_ltx2.py)."""
+ print(f"STATUS:{msg}", file=sys.stderr, flush=True)
+
+
+def _parse_user_loras(raw: str | None) -> list[tuple[str, float]]:
+ """Parse --user-loras JSON into a list of (path, strength) tuples.
+
+ Strict validation so a Node-side bug surfaces here before any model load.
+ Each entry must be {path: str (existing file), strength: number}. Returns []
+ when --user-loras is unset.
+ """
+ if not raw:
+ return []
+ try:
+ data = json.loads(raw)
+ except json.JSONDecodeError as e:
+ raise SystemExit(f"--user-loras is not valid JSON: {e}")
+ if not isinstance(data, list):
+ raise SystemExit("--user-loras must be a JSON list of {path, strength}")
+ specs: list[tuple[str, float]] = []
+ for i, item in enumerate(data):
+ if not isinstance(item, dict) or "path" not in item:
+ raise SystemExit(f"user-loras[{i}] must be an object with 'path'")
+ path = item["path"]
+ if not isinstance(path, str) or not path:
+ raise SystemExit(f"user-loras[{i}].path must be a non-empty string")
+ if not Path(path).exists():
+ raise SystemExit(f"user-loras[{i}].path does not exist: {path}")
+ strength = item.get("strength", 1.0)
+ try:
+ strength = float(strength)
+ except (TypeError, ValueError):
+ raise SystemExit(f"user-loras[{i}].strength must be a number")
+ specs.append((path, strength))
+ return specs
+
+
+def _fuse(weights: dict, module_to_loras: dict) -> dict:
+ """Merge LoRA deltas into a transformer weights dict (bf16, no quantization).
+
+ apply_loras_to_weights normalizes the LoRA keys to LTX model keys
+ (_normalize_ltx_lora_key) and returns a NEW dict with the merged weights;
+ unchanged keys keep their original array identity, which is how we count how
+ many modules actually matched. Zero matches means the LoRA is incompatible
+ with this model — fail loudly rather than render a base video mislabeled as
+ LoRA-styled.
+ """
+ from mlx_video.lora.apply import apply_loras_to_weights
+
+ merged = apply_loras_to_weights(weights, module_to_loras, quantization_bits=0)
+ applied = sum(1 for k in merged if k in weights and merged[k] is not weights[k])
+ if applied == 0:
+ raise SystemExit(
+ "No LoRA modules matched the transformer weights — the LoRA is "
+ "incompatible with this model (key mismatch). Refusing to render a "
+ "base video mislabeled as LoRA-styled."
+ )
+ emit_status(f"Merged LoRA deltas into {applied} transformer module(s)")
+ return merged
+
+
+def _install_lora_patches(specs: list[tuple[str, float]]):
+ """Build the module→LoRA map and monkeypatch generate_av's weight loaders.
+
+ Returns the imported generate_av module so the caller can run its main().
+ """
+ from mlx_video.lora.types import LoRAConfig
+ from mlx_video.lora.loader import load_multiple_loras
+ import mlx_video.generate_av as gav
+
+ configs = [LoRAConfig(path=Path(p), strength=s) for p, s in specs]
+ module_to_loras = load_multiple_loras(configs)
+ names = ", ".join(Path(p).name for p, _ in specs)
+ emit_status(f"Fusing {len(specs)} user LoRA(s) into the transformer: {names}")
+
+ # Seam 1: single-file ("unified") layout. load_unified_weights is called for
+ # several prefixes (transformer., audio_vae., vocoder.) — only fuse the
+ # transformer.
+ _orig_load_unified = gav.load_unified_weights
+
+ def _patched_load_unified(model_path, prefix):
+ weights = _orig_load_unified(model_path, prefix)
+ if prefix == "transformer.":
+ return _fuse(weights, module_to_loras)
+ return weights
+
+ gav.load_unified_weights = _patched_load_unified
+
+ # Seam 2: split-weight layout. sanitize_transformer_weights is only ever
+ # called on the transformer, so fuse unconditionally.
+ _orig_sanitize = gav.sanitize_transformer_weights
+
+ def _patched_sanitize(raw_weights):
+ return _fuse(_orig_sanitize(raw_weights), module_to_loras)
+
+ gav.sanitize_transformer_weights = _patched_sanitize
+
+ return gav
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(add_help=False)
+ parser.add_argument("--user-loras", default=None)
+ ns, passthrough = parser.parse_known_args()
+
+ specs = _parse_user_loras(ns.user_loras)
+ if not specs:
+ raise SystemExit(
+ "generate_av_lora.py requires --user-loras; use `python -m "
+ "mlx_video.generate_av` directly for non-LoRA renders."
+ )
+
+ gav = _install_lora_patches(specs)
+
+ # Hand the remaining args to generate_av's own argparse and run it. Its
+ # stdout/stderr (STAGE:/STATUS:/DOWNLOAD: + final JSON) flow straight through.
+ sys.argv = [sys.argv[0], *passthrough]
+ gav.main()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/server/lib/runners.js b/server/lib/runners.js
index 18ad554b7b..6ab5770af9 100644
--- a/server/lib/runners.js
+++ b/server/lib/runners.js
@@ -46,14 +46,41 @@ export const VIDEO_LORA_FAMILIES = Object.freeze({
const VIDEO_LORA_FAMILY_SET = new Set(Object.values(VIDEO_LORA_FAMILIES));
export const isVideoLoraFamily = (family) => VIDEO_LORA_FAMILY_SET.has(family);
+// A LoRA-quantization marker (`q4` / `q8`) in a model's id/repo/name, bounded
+// so it doesn't match inside unrelated tokens. Used to scope mlx_video LoRA
+// fusion to the bf16 unified models (see isMlxVideoLtxLoraCapable).
+const QUANTIZED_LTX_RE = /(?:^|[-_/\s])q(?:4|8)(?:[-_./\s]|$)/i;
+
+// True when an mlx_video-runtime model is an LTX-2.x model whose LoRAs PortOS
+// can fuse. notapalindrome's `mlx_video.generate_av` CLI has no `--lora` flag,
+// but the package ships an LTX-aware LoRA subsystem (`mlx_video.lora`) — so
+// scripts/generate_av_lora.py drives generate_av and merges the LoRA deltas into
+// the transformer weights before generation. Scoped to NON-quantized (bf16)
+// LTX-2.x models for now: the quantized q4/q8 variants need a separate
+// dequantize→merge→requantize validation pass. The Windows LTX-Video 0.9.5
+// model ("ltx_video" / "LTX-Video 0.9.5") is excluded — it has no "ltx-2"
+// marker and runs through generate_win.py, not generate_av.
+export const isMlxVideoLtxLoraCapable = (model) => {
+ if (model?.runtime !== 'mlx_video') return false;
+ const hay = `${model?.id || ''} ${model?.repo || ''} ${model?.name || ''}`;
+ if (!/ltx-?2/i.test(hay)) return false; // must be an LTX-2.x model
+ if (QUANTIZED_LTX_RE.test(hay)) return false; // bf16-only scope (no q4/q8)
+ return true;
+};
+
// Map a video-model registry entry (which carries `runtime`, not `runner`) to
-// the LoRA family the picker filters on. Only dgrauet's `ltx2` runtime can
-// fuse arbitrary user LoRAs today — its `ltx_pipelines_mlx` pipelines honor a
-// `_pending_loras` hook (see scripts/generate_ltx2.py). The legacy mlx_video /
-// wan22 / hunyuan runtimes have no general LoRA path, so they return null
-// ("no LoRA support") and the VideoGen picker hides itself.
+// the LoRA family the picker filters on. Two runtimes can fuse user LoRAs:
+// - dgrauet's `ltx2` — its `ltx_pipelines_mlx` pipelines honor a
+// `_pending_loras` hook (see scripts/generate_ltx2.py), any LTX-2.3 quant.
+// - notapalindrome's `mlx_video` on a non-quantized LTX-2.x model — fused
+// offline into the transformer weights (see isMlxVideoLtxLoraCapable +
+// scripts/generate_av_lora.py).
+// The wan22 / hunyuan runtimes (and quantized mlx_video models) have no LoRA
+// path, so they return null ("no LoRA support") and the VideoGen picker hides.
export const videoLoraFamily = (model) =>
- model?.runtime === 'ltx2' ? VIDEO_LORA_FAMILIES.LTX_VIDEO : null;
+ (model?.runtime === 'ltx2' || isMlxVideoLtxLoraCapable(model))
+ ? VIDEO_LORA_FAMILIES.LTX_VIDEO
+ : null;
// Convenience predicate helpers — match the semantics of the existing
// `isFlux2()` / `isZImage()` / `isErnie()` exports in `mediaModels.js`
diff --git a/server/lib/runners.test.js b/server/lib/runners.test.js
index e6698f8ae3..94dbeca3a5 100644
--- a/server/lib/runners.test.js
+++ b/server/lib/runners.test.js
@@ -3,7 +3,7 @@ import { readFileSync } from 'fs';
import { dirname, join } from 'path';
import { fileURLToPath } from 'url';
-import { RUNNER_FAMILIES, VIDEO_LORA_FAMILIES, videoLoraFamily, isMflux, isFlux2, isZImage, isErnie, isHiDream, isQwen, flux2VariantFromModel, loraCompatKey, composeCompatKey } from './runners.js';
+import { RUNNER_FAMILIES, VIDEO_LORA_FAMILIES, videoLoraFamily, isMlxVideoLtxLoraCapable, isMflux, isFlux2, isZImage, isErnie, isHiDream, isQwen, flux2VariantFromModel, loraCompatKey, composeCompatKey } from './runners.js';
const __dirname_self = dirname(fileURLToPath(import.meta.url));
const CLIENT_MIRROR_PATH = join(__dirname_self, '..', '..', 'client', 'src', 'lib', 'runnerFamilies.js');
@@ -55,24 +55,47 @@ describe('VIDEO_LORA_FAMILIES / videoLoraFamily', () => {
expect(Object.isFrozen(VIDEO_LORA_FAMILIES)).toBe(true);
});
- it('maps only the ltx2 runtime to a LoRA family', () => {
+ it('maps the ltx2 runtime + non-quantized LTX-2.x mlx_video models to a LoRA family', () => {
expect(videoLoraFamily({ runtime: 'ltx2' })).toBe('ltx-video');
+ // bare mlx_video (no LTX-2.x identity) stays null
expect(videoLoraFamily({ runtime: 'mlx_video' })).toBe(null);
+ // the bf16 Unified Beta — now LoRA-capable
+ expect(videoLoraFamily({ runtime: 'mlx_video', id: 'ltx23_unified', repo: 'notapalindrome/ltx23-mlx-av', name: 'LTX-2.3 Unified Beta' })).toBe('ltx-video');
+ expect(videoLoraFamily({ runtime: 'mlx_video', id: 'ltx2_unified', name: 'LTX-2 Unified' })).toBe('ltx-video');
+ // quantized variants are out of scope → null
+ expect(videoLoraFamily({ runtime: 'mlx_video', id: 'ltx23_distilled_q4', repo: 'notapalindrome/ltx23-mlx-av-q4', name: 'LTX-2.3 Distilled Q4' })).toBe(null);
expect(videoLoraFamily({ runtime: 'wan22' })).toBe(null);
expect(videoLoraFamily({ runtime: 'hunyuan' })).toBe(null);
expect(videoLoraFamily({})).toBe(null);
expect(videoLoraFamily(null)).toBe(null);
});
+ it('isMlxVideoLtxLoraCapable gates on runtime + LTX-2.x + non-quantized', () => {
+ // capable: bf16 LTX-2.x mlx_video
+ expect(isMlxVideoLtxLoraCapable({ runtime: 'mlx_video', name: 'LTX-2.3 Unified Beta' })).toBe(true);
+ expect(isMlxVideoLtxLoraCapable({ runtime: 'mlx_video', repo: 'notapalindrome/ltx2-mlx-av' })).toBe(true);
+ // not capable: quantized (q4/q8 marker bounded so it doesn't match mid-token)
+ expect(isMlxVideoLtxLoraCapable({ runtime: 'mlx_video', name: 'LTX-2.3 Distilled Q4 (~22 GB)' })).toBe(false);
+ expect(isMlxVideoLtxLoraCapable({ runtime: 'mlx_video', repo: 'notapalindrome/ltx23-mlx-av-q8' })).toBe(false);
+ // not capable: wrong runtime
+ expect(isMlxVideoLtxLoraCapable({ runtime: 'ltx2', name: 'LTX-2.3 dgrauet Q4' })).toBe(false);
+ // not capable: the Windows LTX-Video 0.9.5 model (no LTX-2.x marker)
+ expect(isMlxVideoLtxLoraCapable({ runtime: 'mlx_video', id: 'ltx_video', name: 'LTX-Video 0.9.5' })).toBe(false);
+ // not capable: non-LTX mlx_video
+ expect(isMlxVideoLtxLoraCapable({ runtime: 'mlx_video' })).toBe(false);
+ expect(isMlxVideoLtxLoraCapable(null)).toBe(false);
+ });
+
it('composeCompatKey leaves the ltx-video family bare (no variant)', () => {
expect(composeCompatKey('ltx-video', null)).toBe('ltx-video');
expect(composeCompatKey('ltx-video', '9b')).toBe('ltx-video');
});
- it('client mirror carries the video family + helper', () => {
+ it('client mirror carries the video family + helpers', () => {
const text = readFileSync(CLIENT_MIRROR_PATH, 'utf-8');
expect(text).toMatch(/LTX_VIDEO:\s*'ltx-video'/);
expect(text).toMatch(/export const videoLoraFamily/);
+ expect(text).toMatch(/export const isMlxVideoLtxLoraCapable/);
});
});
diff --git a/server/routes/videoGen.js b/server/routes/videoGen.js
index 0825ea83a3..bddcd1765c 100644
--- a/server/routes/videoGen.js
+++ b/server/routes/videoGen.js
@@ -40,6 +40,7 @@ import {
} from '../services/videoGen/local.js';
import { enqueueJob, attachSseClient, cancelJob, listJobs } from '../services/mediaJobQueue/index.js';
import { repoForModel, getTextEncoderRepo, isHfRepoId } from '../lib/mediaModels.js';
+import { videoLoraFamily } from '../lib/runners.js';
import { inspectModelCache } from '../lib/hfCache.js';
import { startHfDownloadStream, openSseStream } from '../lib/sseDownload.js';
@@ -714,14 +715,16 @@ router.post('/', frameImageUpload, asyncHandler(async (req, res) => {
}))
: undefined;
- // Video LoRAs are an ltx2-runtime primitive — the dgrauet pipeline fuses
- // them via _pending_loras (see scripts/generate_ltx2.py). Reject up-front on
- // any other runtime so a bad modelId can't enqueue a doomed job that only
- // fails in the worker.
- if (loras && effectiveModel && effectiveModel.runtime !== 'ltx2') {
+ // Video LoRAs fuse on two runtimes: dgrauet's `ltx2` (via the pipeline's
+ // _pending_loras hook, see scripts/generate_ltx2.py) and non-quantized
+ // LTX-2.x `mlx_video` models (merged offline by scripts/generate_av_lora.py).
+ // videoLoraFamily() returns null for everything else (wan22 / hunyuan /
+ // quantized mlx_video) — reject up-front so a bad modelId can't enqueue a
+ // doomed job that only fails in the worker.
+ if (loras && effectiveModel && !videoLoraFamily(effectiveModel)) {
await cleanupAllStaged();
throw new ServerError(
- `LoRAs require an ltx2-runtime model. Model "${effectiveModelId}" runs on "${effectiveModel.runtime || 'mlx_video'}".`,
+ `LoRAs aren't supported on this model. Model "${effectiveModelId}" runs on "${effectiveModel.runtime || 'mlx_video'}" — use an LTX-2.x model (dgrauet ltx2, or the bf16 Unified Beta).`,
{ status: 400, code: 'LORAS_REQUIRE_LTX2' },
);
}
diff --git a/server/services/videoGen/local.js b/server/services/videoGen/local.js
index 7f21a7de73..b4d8ef796b 100644
--- a/server/services/videoGen/local.js
+++ b/server/services/videoGen/local.js
@@ -27,6 +27,7 @@ import { hfTokenEnv } from '../../lib/hfToken.js';
import { safeChildProcessEnv } from '../../lib/processEnv.js';
import { makeVideoGenLineHandler, finalizeGeneratedVideo, isWatchdogSuccess } from './generateVideoHelpers.js';
import { assertSafeLoraFilename } from '../loras.js';
+import { isMlxVideoLtxLoraCapable } from '../../lib/runners.js';
// Path to the dgrauet/ltx-2-mlx venv populated by `INSTALL_LTX2=1
// scripts/setup-image-video.sh`. Used when a model entry has
@@ -36,6 +37,15 @@ import { assertSafeLoraFilename } from '../loras.js';
const LTX2_VENV_PYTHON = join(homedir(), '.portos', 'ltx-2-mlx', '.venv', 'bin', 'python3');
const LTX2_HELPER_SCRIPT = join(PATHS.root, 'scripts', 'generate_ltx2.py');
+// LoRA wrapper for the notapalindrome `mlx_video` runtime. The stock
+// `mlx_video.generate_av` CLI has no --lora flag, but the package ships an
+// LTX-aware LoRA subsystem (`mlx_video.lora`) — this helper imports generate_av,
+// merges the user LoRAs into the transformer weights, then runs generate_av's
+// own main(), so it emits the identical STAGE:/STATUS:/DOWNLOAD: protocol. Runs
+// in the SAME venv as the bare `-m mlx_video.generate_av` path (the configured
+// pythonPath), not a separate BYOV venv. See isMlxVideoLtxLoraCapable.
+const AV_LORA_HELPER_SCRIPT = join(PATHS.root, 'scripts', 'generate_av_lora.py');
+
// Wan 2.2 MLX runtime — osama-ata/Wan2.2-mlx cloned at
// ~/.portos/wan2.2-mlx/. The wrapper at scripts/generate_wan22.py
// subprocesses upstream generate.py so PortOS releases don't drift from
@@ -590,13 +600,15 @@ const buildArgs = ({ pythonPath, modelId, model, prompt, negativePrompt, width,
if (model.runtime === 'ltx2') {
return buildLtx2Args({ model, prompt, negativePrompt, width, height, numFrames, fps, steps, stage2Steps, guidance, seed, sourceImagePath, lastImagePath, keyframes, extendFromVideoPath, audioFilePath, mode, imageStrength, disableAudio, outputPath, textEncoderRepo, loras });
}
- // Defense-in-depth: only the ltx2 runtime can fuse user LoRAs. The route
- // already rejects this combination, but a non-route caller (test, queue
- // replay) could reach here — fail clearly rather than silently dropping the
- // LoRAs and producing a base render the user thinks is LoRA-styled.
- if (Array.isArray(loras) && loras.length > 0) {
+ const hasLoras = Array.isArray(loras) && loras.length > 0;
+ // Defense-in-depth: LoRAs fuse only on ltx2 (handled above) or a non-quantized
+ // LTX-2.x mlx_video model (the wrapper below). The route already rejects other
+ // runtimes, but a non-route caller (test, queue replay) could reach here —
+ // fail clearly rather than silently dropping the LoRAs and producing a base
+ // render the user thinks is LoRA-styled.
+ if (hasLoras && !isMlxVideoLtxLoraCapable(model)) {
throw new ServerError(
- `LoRAs are only supported on the ltx2 runtime. Model "${modelId}" runs on "${model.runtime || 'mlx_video'}".`,
+ `LoRAs aren't supported on this model. Model "${modelId}" runs on "${model.runtime || 'mlx_video'}".`,
{ status: 400, code: 'LORAS_REQUIRE_LTX2' },
);
}
@@ -626,8 +638,9 @@ const buildArgs = ({ pythonPath, modelId, model, prompt, negativePrompt, width,
if (lastImagePath) args.push('--last-image', lastImagePath);
return { bin: pythonPath, args };
}
- const args = [
- '-m', 'mlx_video.generate_av',
+ // Flags shared by the bare `mlx_video.generate_av` CLI and the LoRA wrapper
+ // (scripts/generate_av_lora.py forwards these untouched to generate_av.main()).
+ const flags = [
'--prompt', prompt,
'--height', String(height),
'--width', String(width),
@@ -641,8 +654,8 @@ const buildArgs = ({ pythonPath, modelId, model, prompt, negativePrompt, width,
'--text-encoder-repo', textEncoderRepo,
'--tiling', tiling,
];
- if (negativePrompt) args.push('--negative-prompt', negativePrompt);
- if (disableAudio) args.push('--no-audio');
+ if (negativePrompt) flags.push('--negative-prompt', negativePrompt);
+ if (disableAudio) flags.push('--no-audio');
// Pick a single conditioning image and frame index. mlx_video.generate_av
// accepts only one --image so true FFLF (both keyframes) isn't supported;
@@ -659,15 +672,26 @@ const buildArgs = ({ pythonPath, modelId, model, prompt, negativePrompt, width,
console.log(`⚠️ FFLF requested but mlx_video CLI only supports single-frame conditioning — last image ignored`);
}
if (condImage) {
- args.push('--image', condImage);
- if (condFrameIdx != null) args.push('--image-frame-idx', String(condFrameIdx));
+ flags.push('--image', condImage);
+ if (condFrameIdx != null) flags.push('--image-frame-idx', String(condFrameIdx));
// --image-strength uses mask = 1.0 - strength: 1.0 preserves the source
// latent, 0.0 fully denoises (= T2V). mlx_video's help text describes
// this inverted. Omit when no caller value so mlx_video's default (1.0)
// applies.
- if (imageStrength != null) args.push('--image-strength', String(imageStrength));
+ if (imageStrength != null) flags.push('--image-strength', String(imageStrength));
+ }
+
+ // LoRA renders on a capable LTX-2.x mlx_video model go through the wrapper,
+ // which merges the LoRA deltas into the transformer before running
+ // generate_av.main(). `--user-loras` carries the resolved {path,strength}
+ // pairs — the same JSON shape buildLtx2Args emits for the dgrauet runtime.
+ if (hasLoras) {
+ return {
+ bin: pythonPath,
+ args: [AV_LORA_HELPER_SCRIPT, ...flags, '--user-loras', JSON.stringify(loras.map((l) => ({ path: l.path, strength: l.strength })))],
+ };
}
- return { bin: pythonPath, args };
+ return { bin: pythonPath, args: ['-m', 'mlx_video.generate_av', ...flags] };
};
// Default frame count for LTX renders, matching the 8k+1 latent-boundary
diff --git a/server/services/videoGen/local.test.js b/server/services/videoGen/local.test.js
index bd8fb2c685..3237411ec1 100644
--- a/server/services/videoGen/local.test.js
+++ b/server/services/videoGen/local.test.js
@@ -36,7 +36,13 @@ tryReadFile: vi.fn().mockResolvedValue(null),
}));
vi.mock('../../lib/mediaModels.js', () => ({
- getVideoModels: vi.fn(() => [{ id: 'ltx2_unified', name: 'LTX-2 Unified', runtime: 'ltx2', repo: 'Lightricks/LTX-Video', steps: 30, guidance: 3.5 }]),
+ getVideoModels: vi.fn(() => [
+ { id: 'ltx2_unified', name: 'LTX-2 Unified', runtime: 'ltx2', repo: 'Lightricks/LTX-Video', steps: 30, guidance: 3.5 },
+ // bf16 LTX-2.x mlx_video model — LoRA-capable via the generate_av wrapper.
+ { id: 'ltx23_unified', name: 'LTX-2.3 Unified Beta', runtime: 'mlx_video', repo: 'notapalindrome/ltx23-mlx-av', steps: 25, guidance: 3.0 },
+ // quantized mlx_video model — NOT LoRA-capable (out of scope).
+ { id: 'ltx23_distilled_q4', name: 'LTX-2.3 Distilled Q4', runtime: 'mlx_video', repo: 'notapalindrome/ltx23-mlx-av-q4', steps: 25, guidance: 3.0 },
+ ]),
getDefaultVideoModelId: vi.fn(() => 'ltx2_unified'),
getTextEncoderRepo: vi.fn(() => 'some/text-encoder'),
}));
@@ -927,6 +933,73 @@ describe('generateVideo — video LoRA (--user-loras) arg threading', () => {
);
expect(call[1]).not.toContain('--user-loras');
});
+
+ it('routes a bf16 mlx_video LTX model through the generate_av_lora.py wrapper with --user-loras', async () => {
+ const { spawn } = await import('child_process');
+ const spawnMock = vi.mocked(spawn);
+ spawnMock.mockClear();
+
+ await generateVideo({
+ jobId: 'mlx-lora-test',
+ pythonPath: '/usr/bin/python3',
+ modelId: 'ltx23_unified', // runtime: mlx_video, bf16 → LoRA-capable
+ prompt: 'audio reactive clip',
+ width: 512, height: 512, numFrames: 25, fps: 24,
+ mode: 'text',
+ loras: [{ filename: 'lora-fal-ltx2-3-audio-reactive-lora-hf.safetensors', scale: 0.8 }],
+ });
+
+ const call = spawnMock.mock.calls.find(
+ ([bin, args]) => String(bin) === '/usr/bin/python3'
+ && Array.isArray(args) && args.includes('--user-loras'),
+ );
+ expect(call).toBeTruthy();
+ const args = call[1];
+ // wrapper script, NOT the bare `-m mlx_video.generate_av` module path
+ expect(args[0]).toBe(join(MOCK_PATHS.root, 'scripts', 'generate_av_lora.py'));
+ expect(args).not.toContain('-m');
+ // the generate_av flags still flow through the wrapper
+ expect(args).toContain('--model-repo');
+ expect(args[args.indexOf('--model-repo') + 1]).toBe('notapalindrome/ltx23-mlx-av');
+ const payload = JSON.parse(args[args.indexOf('--user-loras') + 1]);
+ expect(payload).toEqual([
+ { path: join(MOCK_PATHS.loras, 'lora-fal-ltx2-3-audio-reactive-lora-hf.safetensors'), strength: 0.8 },
+ ]);
+ });
+
+ it('a non-LoRA mlx_video render still uses the bare generate_av module (no wrapper)', async () => {
+ const { spawn } = await import('child_process');
+ const spawnMock = vi.mocked(spawn);
+ spawnMock.mockClear();
+
+ await generateVideo({
+ jobId: 'mlx-no-lora',
+ pythonPath: '/usr/bin/python3',
+ modelId: 'ltx23_unified',
+ prompt: 'clip',
+ width: 512, height: 512, numFrames: 25, fps: 24,
+ mode: 'text',
+ });
+
+ const call = spawnMock.mock.calls.find(
+ ([bin, args]) => String(bin) === '/usr/bin/python3' && Array.isArray(args) && args.includes('mlx_video.generate_av'),
+ );
+ expect(call).toBeTruthy();
+ expect(call[1]).not.toContain('--user-loras');
+ expect(call[1]).not.toContain(join(MOCK_PATHS.root, 'scripts', 'generate_av_lora.py'));
+ });
+
+ it('rejects LoRAs on a quantized (out-of-scope) mlx_video model', async () => {
+ await expect(generateVideo({
+ jobId: 'mlx-q4-lora',
+ pythonPath: '/usr/bin/python3',
+ modelId: 'ltx23_distilled_q4', // runtime: mlx_video, quantized → NOT capable
+ prompt: 'clip',
+ width: 512, height: 512, numFrames: 25, fps: 24,
+ mode: 'text',
+ loras: [{ filename: 'style.safetensors', scale: 1.0 }],
+ })).rejects.toThrow(/LoRAs aren't supported/);
+ });
});
describe('generateVideo — LoRA history-record contract (Remix round-trip)', () => {