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.
Python ai-filmmakingai-videoai-video-generatorapple-siliconhailuoimage-to-videolip-synclocal-ailora-trainingltx-2ltx-2-5ltx-videomacosminimax-h3mlxmusic-generationoffline-aipinokiotext-to-videovideo-generation
feat: vendor lora_lab into the panel for installer-only users
mrbizarroe9ce8536ca18
diff --git a/lora_lab/__init__.py b/lora_lab/__init__.pynew file mode 100644index 0000000..e69de29diff --git a/lora_lab/character_runtime.py b/lora_lab/character_runtime.pynew file mode 100644index 0000000..7a72a9a--- /dev/null+++ b/lora_lab/character_runtime.py@@ -0,0 +1,327 @@+"""Character bundle runtime — the panel imports this to drive the+character picker, the auto-router, and the dialogue helper.++Reads `mlx_models/characters/<trigger>/bundle.json` files. Also scans+`mlx_models/loras/*.safetensors` for legacy flat LoRAs (one per file)+and presents them as synthetic face-only characters so the picker+shows everything.++Public surface:++ list_characters() → list[CharacterRow]+ resolve_character(id) → CharacterBundle+ auto_route(p, character) → mutated params dict (LoRAs + quality)+ build_dialogue_snippet(bundle, line, action=None) → str++This module is import-safe with no side effects. Designed to be copied+into mlx_ltx_panel.py or imported via sys.path. Has no dependencies on+phosphene-dev itself (only on the filesystem layout).+"""++from __future__ import annotations++import json+from dataclasses import dataclass+from pathlib import Path+from typing import Any, Optional+++# Default locations — override at module import if needed.+CHARACTERS_DIR = Path("/Users/salo/pinokio/api/phosphene-dev.git/mlx_models/characters")+LORAS_DIR = Path("/Users/salo/pinokio/api/phosphene-dev.git/mlx_models/loras")+++@dataclass+class CharacterRow:+ """One row in the character picker UI."""+ id: str+ name: str+ has_face: bool+ has_voice: bool+ preview_path: Optional[str] # absolute, or None+ source: str # "bundle" | "legacy_flat"+++@dataclass+class CharacterBundle:+ """Resolved bundle ready for generation. All paths absolute."""+ id: str+ name: str+ pronoun: str # "he" | "she" | "they"+ subject_noun: str # "man" | "woman" | "person"+ default_action: str+ face_lora_path: str+ face_strength: float+ audio_lora_path: Optional[str]+ audio_strength: float+ voice_clip_path: Optional[str]+ preview_path: Optional[str]+ bundle_json: dict # the full manifest, for advanced consumers+++# ---------------------------------------------------------------------------+# Listing++def list_characters(+ characters_dir: Path = CHARACTERS_DIR,+ loras_dir: Path = LORAS_DIR,+) -> list[CharacterRow]:+ """Walk both bundle and legacy-flat locations. Return one row per character."""+ rows: list[CharacterRow] = []++ # Bundle directories+ if characters_dir.is_dir():+ for sub in sorted(characters_dir.iterdir()):+ if not sub.is_dir():+ continue+ manifest = sub / "bundle.json"+ if not manifest.is_file():+ continue+ try:+ bundle = json.loads(manifest.read_text())+ except Exception:+ continue+ if bundle.get("schema") != "phosphene/character_bundle@1":+ continue+ preview = bundle.get("preview")+ preview_path = (+ str(sub / preview["path"])+ if (preview and preview.get("path") and (sub / preview["path"]).exists())+ else None+ )+ rows.append(CharacterRow(+ id=bundle["id"],+ name=bundle.get("name", bundle["id"]),+ has_face=bool(bundle.get("face")),+ has_voice=bool(bundle.get("voice")),+ preview_path=preview_path,+ source="bundle",+ ))++ # Legacy flat LoRAs — scan .safetensors that aren't part of a bundle and+ # don't look like internal/utility files (skip *.video_attn_only.safetensors+ # which are individual bundle inputs, not standalone character LoRAs).+ bundle_ids = {r.id for r in rows}+ if loras_dir.is_dir():+ for fp in sorted(loras_dir.glob("*.safetensors")):+ name = fp.stem+ # Skip files that look like bundle inputs already represented in a bundle+ if name.endswith(".video_attn_only"):+ continue+ base = name.split(".")[0] # bizarrotrn.voice -> bizarrotrn; bizarrotrn -> bizarrotrn+ if base in bundle_ids:+ continue+ rows.append(CharacterRow(+ id=name,+ name=name,+ has_face=True,+ has_voice=False,+ preview_path=None,+ source="legacy_flat",+ ))++ return rows+++def resolve_character(+ character_id: str,+ characters_dir: Path = CHARACTERS_DIR,+ loras_dir: Path = LORAS_DIR,+) -> CharacterBundle:+ """Look up a character by ID. Returns a resolved bundle with absolute paths.++ Raises FileNotFoundError if neither a bundle nor a legacy flat LoRA matches.+ """+ bundle_dir = characters_dir / character_id+ manifest = bundle_dir / "bundle.json"+ if manifest.is_file():+ bundle = json.loads(manifest.read_text())+ face = bundle["face"]+ voice = bundle.get("voice")+ preview = bundle.get("preview")+ return CharacterBundle(+ id=bundle["id"],+ name=bundle.get("name", bundle["id"]),+ pronoun=bundle.get("pronoun", "they"),+ subject_noun=bundle.get("subject_noun", "person"),+ default_action=bundle.get("default_action", "smiles softly"),+ face_lora_path=str(bundle_dir / face["path"]),+ face_strength=float(face.get("recommended_strength", 1.0)),+ audio_lora_path=str(bundle_dir / voice["path"]) if voice else None,+ audio_strength=float(voice.get("recommended_strength", 1.0)) if voice else 0.0,+ voice_clip_path=(+ str(bundle_dir / voice["voice_clip"])+ if (voice and voice.get("voice_clip"))+ else None+ ),+ preview_path=(+ str(bundle_dir / preview["path"])+ if (preview and preview.get("path"))+ else None+ ),+ bundle_json=bundle,+ )++ # Legacy flat fallback+ flat = loras_dir / f"{character_id}.safetensors"+ if flat.is_file():+ return CharacterBundle(+ id=character_id,+ name=character_id,+ pronoun="they",+ subject_noun="person",+ default_action="smiles softly",+ face_lora_path=str(flat),+ face_strength=1.0,+ audio_lora_path=None,+ audio_strength=0.0,+ voice_clip_path=None,+ preview_path=None,+ bundle_json={"source": "legacy_flat", "id": character_id},+ )++ raise FileNotFoundError(f"character not found: {character_id}")+++# ---------------------------------------------------------------------------+# Auto-router — picks pipeline + LoRA set based on bundle + mode + WAV input++def auto_route(p: dict, character_id: str, **kwargs) -> dict:+ """Mutate `p` to attach LoRAs + force HQ quality based on the bundle.++ Args:+ p: the generation params dict (mode, audio, mode_override, ...)+ character_id: the character to use+ characters_dir, loras_dir (kwargs): override default locations++ Returns:+ A NEW dict with `loras` set, `quality="high"`, `character_id` recorded.+ Doesn't mutate the caller's dict.+ """+ bundle = resolve_character(+ character_id,+ characters_dir=kwargs.get("characters_dir", CHARACTERS_DIR),+ loras_dir=kwargs.get("loras_dir", LORAS_DIR),+ )++ mode = p.get("mode") or "t2v"+ wav_input = (+ p.get("audio") and Path(p["audio"]).exists()+ and mode in ("a2v", "i2v")+ )++ loras: list[dict] = [{+ "path": bundle.face_lora_path,+ "strength": bundle.face_strength,+ }]++ # Attach voice LoRA only when:+ # - bundle has a voice LoRA+ # - mode is t2v or i2v+ # - user did NOT provide a WAV input (in which case the WAV wins)+ if bundle.audio_lora_path and mode in ("t2v", "i2v") and not wav_input:+ loras.append({+ "path": bundle.audio_lora_path,+ "strength": bundle.audio_strength,+ })++ return {+ **p,+ "loras": loras,+ "character_id": bundle.id,+ "quality": "high", # dev-trained LoRAs require the HQ dev path+ }+++# ---------------------------------------------------------------------------+# Dialogue helper — splice "<line> + <action>" into a prompt cleanly++def build_dialogue_snippet(+ bundle: CharacterBundle | dict,+ line: str,+ action: Optional[str] = None,+ delivery: Optional[str] = None, # e.g. "deadpan", "softly", "dry and amused"+) -> str:+ """Build the canonical dialogue snippet:++ The {subject_noun} says aloud{', ' + delivery}: "<line>". After speaking, {pronoun} {action}.++ The subject_noun comes from the bundle ("man" / "woman" / "person").+ If `action` is None, uses bundle's default_action.++ Pass either a CharacterBundle or a dict (the panel may have only the json).+ """+ if isinstance(bundle, CharacterBundle):+ pronoun = bundle.pronoun+ subject = bundle.subject_noun+ default_action = bundle.default_action+ else:+ pronoun = bundle.get("pronoun", "they")+ subject = bundle.get("subject_noun", "person")+ default_action = bundle.get("default_action", "smiles softly")++ action_text = action.strip() if action and action.strip() else default_action.strip()+ line_text = line.strip()+ # Strip surrounding quotes if user pasted them+ if line_text.startswith('"') and line_text.endswith('"'):+ line_text = line_text[1:-1]+ if line_text.startswith("'") and line_text.endswith("'"):+ line_text = line_text[1:-1]++ delivery_part = f", {delivery.strip()}" if delivery and delivery.strip() else ""++ pronoun_capitalized = pronoun.capitalize() if pronoun not in ("they",) else pronoun.capitalize()+ return (+ f'The {subject} says aloud{delivery_part}: "{line_text}". '+ f'After speaking, {pronoun} {action_text}.'+ )+++# ---------------------------------------------------------------------------+# Self-test++def _self_test() -> int:+ print("=== character_runtime self-test ===")+ print(f"characters_dir: {CHARACTERS_DIR}")+ print()++ rows = list_characters()+ print(f"list_characters() → {len(rows)} entries:")+ for r in rows:+ chips = []+ if r.has_face: chips.append("face")+ if r.has_voice: chips.append("voice")+ print(f" [{r.source:13s}] {r.id:30s} [{', '.join(chips):12s}] preview={'yes' if r.preview_path else '—'}")++ print()+ for row in rows:+ if row.source != "bundle":+ continue+ bundle = resolve_character(row.id)+ print(f"resolve_character({row.id!r}):")+ print(f" face: {Path(bundle.face_lora_path).name}")+ if bundle.audio_lora_path:+ print(f" voice: {Path(bundle.audio_lora_path).name}")+ if bundle.preview_path:+ print(f" preview: {Path(bundle.preview_path).name}")+ print(f" pronoun: {bundle.pronoun}, subject: {bundle.subject_noun}")+ print(f" default_action: {bundle.default_action}")++ # auto_route smoke+ p = {"mode": "t2v", "prompt": "test"}+ routed = auto_route(p, row.id)+ print(f" auto_route(mode=t2v) → {len(routed['loras'])} LoRA(s), quality={routed['quality']}")++ # dialogue snippet smoke+ snippet = build_dialogue_snippet(+ bundle, "Hello, world", delivery="deadpan"+ )+ print(f" dialogue snippet: {snippet[:120]}...")+ print()++ return 0+++if __name__ == "__main__":+ import sys+ sys.exit(_self_test())diff --git a/lora_lab/contact_sheet.py b/lora_lab/contact_sheet.pynew file mode 100644index 0000000..d9e4d1b--- /dev/null+++ b/lora_lab/contact_sheet.py@@ -0,0 +1,120 @@+"""Build a simple HTML contact sheet over one or more eval folders.++Each eval folder is expected to contain `manifest.json` (written by+`evaluate.py`) and a matching `.png` per render entry.++Usage::++ ./scripts/run.sh python -m lora_lab.contact_sheet \+ --tags lora_step1500_str10_n9 lora_step1500_str15_n9 \+ --output outputs/morning/index.html \+ --title "lora-lab — overnight evaluation"+"""++from __future__ import annotations++import argparse+import html+import json+import sys+from pathlib import Path+++def _render(tags: list[str], eval_root: Path, output: Path, title: str) -> int:+ cells = []+ for tag in tags:+ folder = eval_root / tag+ manifest_path = folder / "manifest.json"+ if not manifest_path.exists():+ print(f"skip: no manifest in {folder}", file=sys.stderr)+ continue+ manifest = json.loads(manifest_path.read_text())+ lora = manifest.get("lora") or "(no LoRA — baseline)"+ strength = manifest.get("strength")+ header_label = f"<b>{html.escape(tag)}</b><br><span class='meta'>lora={html.escape(Path(str(lora)).name)} · str={strength}</span>"+ for entry in manifest["renders"]:+ if entry.get("error"):+ continue+ png_name = entry.get("png")+ if not png_name:+ # fall back to mp4 stem.png (post-render ffmpeg extraction)+ mp4_name = entry.get("mp4")+ if mp4_name:+ png_name = mp4_name.rsplit(".", 1)[0] + ".png"+ if not png_name:+ continue+ png_path = (folder / png_name)+ if not png_path.exists():+ continue+ rel_png = png_path.relative_to(output.parent.resolve()) if output.parent.resolve() in png_path.resolve().parents else png_path.resolve()+ cells.append({+ "img": str(rel_png),+ "prompt": entry["prompt"],+ "seed": entry["seed"],+ "tag_header": header_label,+ "wall_s": entry.get("wall_s"),+ })++ # Group cells by tag header so each iteration block is visually grouped.+ blocks = {}+ for c in cells:+ blocks.setdefault(c["tag_header"], []).append(c)++ parts = [f"""<!doctype html>+<html><head>+<meta charset="utf-8">+<title>{html.escape(title)}</title>+<style>+body {{ font-family: -apple-system, BlinkMacSystemFont, 'Helvetica Neue', sans-serif;+ background: #0d0d10; color: #e6e6ea; margin: 24px; }}+h1 {{ font-weight: 600; }}+.block {{ margin-top: 32px; padding: 16px; background: #15151a; border-radius: 10px; }}+.block-header {{ font-size: 13px; color: #aab; margin-bottom: 12px; }}+.meta {{ color: #8a8a96; font-weight: 400; font-size: 12px; }}+.grid {{ display: grid; grid-template-columns: repeat(auto-fill, minmax(260px, 1fr)); gap: 14px; }}+.cell {{ background: #1d1d24; border-radius: 8px; overflow: hidden; }}+.cell img {{ width: 100%; display: block; }}+.cap {{ padding: 8px 10px; font-size: 12px; line-height: 1.4; }}+.cap .p {{ color: #d6d6e0; }}+.cap .s {{ color: #6f6f7a; font-size: 11px; margin-top: 4px; }}+</style></head><body>+<h1>{html.escape(title)}</h1>"""]++ for header, items in blocks.items():+ parts.append(f"<div class='block'><div class='block-header'>{header}</div><div class='grid'>")+ for c in items:+ parts.append(+ f"<div class='cell'>"+ f"<img loading='lazy' src='{html.escape(c['img'])}'>"+ f"<div class='cap'><div class='p'>{html.escape(c['prompt'])}</div>"+ f"<div class='s'>seed {c['seed']}"+ + (f" · {c['wall_s']}s" if c.get('wall_s') is not None else "")+ + "</div></div></div>"+ )+ parts.append("</div></div>")+ parts.append("</body></html>")++ output.parent.mkdir(parents=True, exist_ok=True)+ output.write_text("\n".join(parts))+ print(f"wrote {output} ({len(cells)} cells across {len(blocks)} blocks)")+ return 0+++def main() -> int:+ p = argparse.ArgumentParser()+ p.add_argument("--tags", nargs="+", required=True, help="eval tag folder names under outputs/eval/")+ p.add_argument("--eval-root", default="outputs/eval")+ p.add_argument("--output", default="outputs/morning/index.html")+ p.add_argument("--title", default="lora-lab — eval contact sheet")+ args = p.parse_args()++ return _render(+ tags=args.tags,+ eval_root=Path(args.eval_root).resolve(),+ output=Path(args.output).resolve(),+ title=args.title,+ )+++if __name__ == "__main__":+ sys.exit(main())diff --git a/lora_lab/evaluate.py b/lora_lab/evaluate.pynew file mode 100644index 0000000..2e3cc8d--- /dev/null+++ b/lora_lab/evaluate.py@@ -0,0 +1,197 @@+"""Generate LoRA evaluation samples (text-to-frame) for the trained character.++Loads `BasePipeline` once, fuses a LoRA checkpoint via `_pending_loras`, then+runs each prompt at `num_frames=1` (single-frame T2V — the LoRA was trained on+1-frame samples, so this matches the training distribution exactly).++Outputs to `outputs/eval/<run_tag>/`:+ NN_<prompt-slug>_seedSSS_strSS.png # generated frame (extracted from mp4)+ NN_<prompt-slug>_seedSSS_strSS.mp4 # the actual pipeline output+ manifest.json # prompt/seed/strength/timing per render++Usage:+ ./scripts/run.sh python -m lora_lab.evaluate \+ --lora outputs/char_image_lora/checkpoints/lora_weights_step_01500.safetensors \+ --strength 1.0 \+ --tag step1500_str10 \+ --width 512 --height 512 \+ --frames 1 --num-steps 8++Pass `--lora ""` for a baseline (no LoRA fused). Same prompts + seeds, so+outputs are directly comparable to LoRA runs.+"""++from __future__ import annotations++import argparse+import json+import logging+import os+import re+import subprocess+import sys+import time+from pathlib import Path++import mlx.core as mx+from ltx_pipelines_mlx import BasePipeline++logger = logging.getLogger(__name__)+++DEFAULT_MODEL_DIR = (+ Path.home()+ / ".cache/huggingface/hub/models--dgrauet--ltx-2.3-mlx-q4"+ / "snapshots/53a6f5f39d9c074bc73e6a18ba391f40ddffaa68"+)++DEFAULT_PROMPTS = [+ "salotrn, close-up portrait, facing camera, neutral expression, soft daylight, blurred indoor background",+ "salotrn, medium shot, three-quarter angle, slight smile, warm indoor lighting, dark t-shirt",+ "salotrn, half-body, looking up, outdoor sunny afternoon, light shirt, blue sky",+ "salotrn, close-up portrait, looking away, evening light, profile view",+ "salotrn, medium shot, big grin, outdoor tropical balcony, daytime, dark t-shirt, palm trees background",+ "salotrn, close-up selfie, facing camera, deadpan expression, gray t-shirt, indoor home gym",+ "salotrn, half-body shot, facing camera, hands in pockets, autumn forest, soft overcast light",+ "salotrn, close-up portrait, three-quarter angle, contemplative expression, cafe interior, golden hour",+ "salotrn, full-body shot, facing camera, walking, urban street, daytime",+ "salotrn, close-up portrait, looking down, dramatic backlight, dark background",+ "salotrn, medium shot, slight smile, library shelves behind, warm indoor light",+ "salotrn, close-up selfie, big grin, beach background, bright outdoor light",+ "salotrn, half-body, facing camera, sitting at desk with computer, screen lighting, indoor",+ "salotrn, three-quarter angle, looking out window, overcast daylight, indoor",+ "salotrn, close-up portrait, facing camera, serious expression, neutral background, studio lighting",+]+++def _slugify(text: str, max_len: int = 40) -> str:+ s = re.sub(r"[^a-z0-9]+", "-", text.lower()).strip("-")+ return s[:max_len]+++def _load_lora_pairs(lora_path: Path, strength: float) -> list:+ """Build the list expected by `pipeline._pending_loras`.++ The upstream hook is:+ pipe._pending_loras = [(state_dict_loader_result, strength), ...]+ where each "state_dict_loader_result" is whatever `SafetensorsStateDictLoader`+ yields. The simplest way is to pass a `(path_str, strength)` and let+ `_fuse_pending_loras` handle loading — but the exact shape depends on the+ pipeline's `_fuse_pending_loras`. We use the same pattern Phosphene uses+ in mlx_warm_helper:_attach_loras: pass `(str(local_path), float)` pairs.+ """+ return [(str(lora_path), float(strength))]+++def _extract_first_frame_png(mp4_path: Path, png_path: Path) -> None:+ """Pull frame 0 from an mp4 into a png using ffmpeg (already on PATH via run.sh)."""+ subprocess.run(+ ["ffmpeg", "-y", "-loglevel", "error", "-i", str(mp4_path),+ "-frames:v", "1", "-update", "1", str(png_path)],+ check=True,+ )+++def main() -> int:+ p = argparse.ArgumentParser()+ p.add_argument("--lora", default="", help="path to LoRA .safetensors; empty string = baseline (no LoRA)")+ p.add_argument("--strength", type=float, default=1.0)+ p.add_argument("--tag", required=True, help="subfolder under outputs/eval/")+ p.add_argument("--width", type=int, default=512)+ p.add_argument("--height", type=int, default=512)+ p.add_argument("--frames", type=int, default=1, help="num_frames (1 = single image, 25 = ~1s clip)")+ p.add_argument("--num-steps", type=int, default=8)+ p.add_argument("--seed-start", type=int, default=1000)+ p.add_argument("--prompts-file", default=None, help="optional .txt file with one prompt per line; else use DEFAULT_PROMPTS")+ p.add_argument("--limit", type=int, default=None, help="only run the first N prompts")+ p.add_argument("--model-dir", default=str(DEFAULT_MODEL_DIR))+ p.add_argument("--low-memory", action="store_true",+ help="reload transformer between renders (cuts peak RAM, slower); default keeps loaded across renders")+ p.add_argument("-v", "--verbose", action="store_true")+ args = p.parse_args()++ logging.basicConfig(+ level=logging.DEBUG if args.verbose else logging.INFO,+ format="%(asctime)s %(levelname)s %(name)s | %(message)s",+ )++ if args.prompts_file:+ prompts = [line.strip() for line in Path(args.prompts_file).read_text().splitlines() if line.strip()]+ else:+ prompts = list(DEFAULT_PROMPTS)+ if args.limit:+ prompts = prompts[: args.limit]+ print(f"running {len(prompts)} prompts | {args.width}x{args.height} {args.frames}f {args.num_steps}step")++ out_root = Path("outputs/eval") / args.tag+ out_root.mkdir(parents=True, exist_ok=True)++ pipe = BasePipeline(+ model_dir=args.model_dir,+ gemma_model_id="mlx-community/gemma-3-12b-it-4bit",+ low_memory=args.low_memory,+ low_ram_streaming=False,+ )++ if args.lora:+ lora_path = Path(args.lora).resolve()+ if not lora_path.exists():+ raise FileNotFoundError(f"LoRA file missing: {lora_path}")+ pipe._pending_loras = _load_lora_pairs(lora_path, args.strength)+ print(f"LoRA: {lora_path.name} strength={args.strength}")+ else:+ print("baseline run — NO LoRA")++ manifest = {+ "tag": args.tag,+ "lora": args.lora or None,+ "strength": args.strength if args.lora else None,+ "width": args.width,+ "height": args.height,+ "frames": args.frames,+ "num_steps": args.num_steps,+ "model_dir": args.model_dir,+ "renders": [],+ }++ for i, prompt in enumerate(prompts):+ seed = args.seed_start + i+ slug = _slugify(prompt, 40)+ name = f"{i:02d}_{slug}_seed{seed}_str{int(args.strength * 10):02d}"+ mp4 = out_root / f"{name}.mp4"+ png = out_root / f"{name}.png"+ print(f"\n[{i + 1}/{len(prompts)}] seed={seed} | {prompt[:70]}")+ t0 = time.time()+ try:+ pipe.generate_and_save(+ prompt=prompt,+ output_path=str(mp4),+ height=args.height,+ width=args.width,+ num_frames=args.frames,+ seed=seed,+ num_steps=args.num_steps,+ )+ wall = time.time() - t0+ if args.frames == 1 and mp4.exists():+ try:+ _extract_first_frame_png(mp4, png)+ except Exception as exc:+ logger.warning("png extract failed: %s", exc)+ manifest["renders"].append(+ {"idx": i, "prompt": prompt, "seed": seed, "mp4": mp4.name, "png": png.name if png.exists() else None, "wall_s": round(wall, 1)}+ )+ print(f" wrote {mp4.name} ({wall:.1f}s)")+ except Exception as exc:+ wall = time.time() - t0+ logger.exception("render %d failed", i)+ manifest["renders"].append({"idx": i, "prompt": prompt, "seed": seed, "error": str(exc), "wall_s": round(wall, 1)})++ (out_root / "manifest.json").write_text(json.dumps(manifest, indent=2))++ print(f"\ndone — manifest at {out_root / 'manifest.json'}")+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/lora_lab/evaluate_dev.py b/lora_lab/evaluate_dev.pynew file mode 100644index 0000000..ca165a4--- /dev/null+++ b/lora_lab/evaluate_dev.py@@ -0,0 +1,222 @@+"""Generate LoRA evaluation samples via the DEV one-stage pipeline (CFG + STG).++Matches the inference path the iter-4 LoRA was trained against (dev+transformer + full-range flow matching), not the 8-step distilled path. Per+LTX-2 Issue #175, a LoRA trained against dev MUST be inferred against dev for+the objective schedule to match — otherwise the trained weight deltas point+at the wrong target and identity won't realize.++Args mirror evaluate.py + adds CFG / STG / num_steps knobs for the dev path.++Usage::++ ./scripts/run.sh python -m lora_lab.evaluate_dev \\+ --lora outputs/char_image_lora_r32_dev/checkpoints/lora_weights_step_03000.safetensors \\+ --strength 1.0 --tag dev_r32_step3000_str10_n9 \\+ --width 576 --height 576 --frames 9 --num-steps 30 --cfg-scale 3.0 \\+ --limit 5+"""++from __future__ import annotations++import argparse+import json+import logging+import re+import subprocess+import sys+import time+from pathlib import Path++import mlx.core as mx+import mlx.utils+from ltx_pipelines_mlx import TI2VidOneStagePipeline+from ltx_core_mlx.loader.fuse_loras import apply_loras+from ltx_core_mlx.loader.primitives import LoraStateDictWithStrength, StateDict+from ltx_core_mlx.loader.sd_ops import LTXV_LORA_COMFY_RENAMING_MAP+from ltx_core_mlx.loader.sft_loader import SafetensorsStateDictLoader+from ltx_core_mlx.utils.memory import aggressive_cleanup++logger = logging.getLogger(__name__)+++DEFAULT_MODEL_DIR = (+ Path.home()+ / ".cache/huggingface/hub/models--dgrauet--ltx-2.3-mlx-q4"+ / "snapshots/53a6f5f39d9c074bc73e6a18ba391f40ddffaa68"+)++DEFAULT_PROMPTS = [+ "salotrn man, close-up portrait, facing camera, neutral expression, soft daylight",+ "salotrn man, medium shot, three-quarter angle, slight smile, warm indoor lighting",+ "salotrn man, half body shot, looking up, outdoor sunny afternoon",+ "salotrn man, close-up portrait, looking away, profile view, evening light",+ "salotrn man, medium shot, big grin, outdoor tropical balcony, daytime",+]+++def _slugify(text: str, max_len: int = 40) -> str:+ s = re.sub(r"[^a-z0-9]+", "-", text.lower()).strip("-")+ return s[:max_len]+++def _load_lora_pairs(lora_path: Path, strength: float) -> list:+ return [(str(lora_path), float(strength))]+++def _fuse_custom_lora_into_pipe_dit(pipe, lora_path: Path, strength: float) -> None:+ """Fuse a custom LoRA into the dev pipeline's already-loaded transformer.++ Workaround for an MLX-port bug: `TwoStagePipeline.load()` (and its subclass+ `TI2VidOneStagePipeline.load()`) override `BasePipeline.load()` but never+ call `_fuse_pending_loras`. So setting `pipe._pending_loras = [...]` on a+ dev pipeline is silently ignored — the dit loads with no LoRA fused.++ This helper replicates the in-place fusion pattern that+ `TwoStagePipeline._fuse_distilled_lora` uses for the distillation LoRA,+ but for an arbitrary user-provided LoRA file.+ """+ assert pipe.dit is not None, "pipe.dit must be loaded before fusing LoRA"++ flat_params = mlx.utils.tree_flatten(pipe.dit.parameters())+ flat_model = {k: v for k, v in flat_params if isinstance(v, mx.array)}+ model_sd = StateDict(sd=flat_model, size=0, dtype=set())++ loader = SafetensorsStateDictLoader()+ lora_sd = loader.load(str(lora_path), sd_ops=LTXV_LORA_COMFY_RENAMING_MAP)+ lora_with_strength = LoraStateDictWithStrength(state_dict=lora_sd, strength=float(strength))++ fused = apply_loras(model_sd, [lora_with_strength])+ pipe.dit.load_weights(list(fused.sd.items()))+ aggressive_cleanup()+ print(f" manually fused LoRA into dit ({Path(lora_path).name} @ strength={strength})")+++def _extract_first_frame_png(mp4_path: Path, png_path: Path) -> None:+ subprocess.run(+ ["ffmpeg", "-y", "-loglevel", "error", "-i", str(mp4_path),+ "-frames:v", "1", "-update", "1", str(png_path)],+ check=True,+ )+++def main() -> int:+ p = argparse.ArgumentParser()+ p.add_argument("--lora", default="")+ p.add_argument("--strength", type=float, default=1.0)+ p.add_argument("--tag", required=True)+ p.add_argument("--width", type=int, default=576)+ p.add_argument("--height", type=int, default=576)+ p.add_argument("--frames", type=int, default=9)+ p.add_argument("--num-steps", type=int, default=30)+ p.add_argument("--cfg-scale", type=float, default=3.0)+ p.add_argument("--stg-scale", type=float, default=0.0)+ p.add_argument("--seed-start", type=int, default=1000)+ p.add_argument("--prompts-file", default=None)+ p.add_argument("--limit", type=int, default=None)+ p.add_argument("--model-dir", default=str(DEFAULT_MODEL_DIR))+ p.add_argument("--low-memory", action="store_true")+ p.add_argument("-v", "--verbose", action="store_true")+ args = p.parse_args()++ logging.basicConfig(+ level=logging.DEBUG if args.verbose else logging.INFO,+ format="%(asctime)s %(levelname)s %(name)s | %(message)s",+ )++ if args.prompts_file:+ prompts = [line.strip() for line in Path(args.prompts_file).read_text().splitlines() if line.strip()]+ else:+ prompts = list(DEFAULT_PROMPTS)+ if args.limit:+ prompts = prompts[: args.limit]+ print(f"running {len(prompts)} prompts via DEV pipeline | {args.width}x{args.height} {args.frames}f "+ f"{args.num_steps}step CFG={args.cfg_scale} STG={args.stg_scale}")++ out_root = Path("outputs/eval") / args.tag+ out_root.mkdir(parents=True, exist_ok=True)++ pipe = TI2VidOneStagePipeline(+ model_dir=args.model_dir,+ gemma_model_id="mlx-community/gemma-3-12b-it-4bit",+ low_memory=args.low_memory,+ low_ram_streaming=False,+ )++ lora_path: Path | None = None+ if args.lora:+ lora_path = Path(args.lora).resolve()+ if not lora_path.exists():+ raise FileNotFoundError(f"LoRA file missing: {lora_path}")+ print(f"LoRA: {lora_path.name} strength={args.strength}")+ print("note: dev pipeline doesn't fuse _pending_loras; using manual post-load fusion")+ else:+ print("baseline run — NO LoRA")++ manifest = {+ "tag": args.tag,+ "pipeline": "TI2VidOneStagePipeline (dev transformer + CFG)",+ "lora": args.lora or None,+ "strength": args.strength if args.lora else None,+ "width": args.width,+ "height": args.height,+ "frames": args.frames,+ "num_steps": args.num_steps,+ "cfg_scale": args.cfg_scale,+ "stg_scale": args.stg_scale,+ "model_dir": args.model_dir,+ "renders": [],+ }++ for i, prompt in enumerate(prompts):+ seed = args.seed_start + i+ slug = _slugify(prompt, 40)+ name = f"{i:02d}_{slug}_seed{seed}_str{int(args.strength * 10):02d}"+ mp4 = out_root / f"{name}.mp4"+ png = out_root / f"{name}.png"+ print(f"\n[{i + 1}/{len(prompts)}] seed={seed} | {prompt[:70]}")+ t0 = time.time()+ try:+ if lora_path is not None:+ # Force a fresh dit load so we can manually fuse the LoRA before generate.+ pipe.load()+ _fuse_custom_lora_into_pipe_dit(pipe, lora_path, args.strength)+ pipe.generate_and_save(+ prompt=prompt,+ output_path=str(mp4),+ height=args.height,+ width=args.width,+ num_frames=args.frames,+ seed=seed,+ num_steps=args.num_steps,+ cfg_scale=args.cfg_scale,+ stg_scale=args.stg_scale,+ )+ wall = time.time() - t0+ if mp4.exists():+ try:+ _extract_first_frame_png(mp4, png)+ except Exception as exc:+ logger.warning("png extract failed: %s", exc)+ manifest["renders"].append({+ "idx": i, "prompt": prompt, "seed": seed,+ "mp4": mp4.name, "png": png.name if png.exists() else None,+ "wall_s": round(wall, 1),+ })+ print(f" wrote {mp4.name} ({wall:.1f}s)")+ except Exception as exc:+ wall = time.time() - t0+ logger.exception("render %d failed", i)+ manifest["renders"].append({+ "idx": i, "prompt": prompt, "seed": seed,+ "error": str(exc), "wall_s": round(wall, 1),+ })++ (out_root / "manifest.json").write_text(json.dumps(manifest, indent=2))++ print(f"\ndone — manifest at {out_root / 'manifest.json'}")+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/lora_lab/preprocess_audio.py b/lora_lab/preprocess_audio.pynew file mode 100644index 0000000..3b49479--- /dev/null+++ b/lora_lab/preprocess_audio.py@@ -0,0 +1,255 @@+"""Audio-side preprocessor for LTX-2 MLX trainer (lora-lab Phase B).++Encodes voice WAV slices into LTX audio VAE latents, written in the layout+the trainer expects (paired with image latents by index):++ output_dir/+ .precomputed/+ audio_latents/+ latent_0000.safetensors {latents: [1, 8, T, 16]}+ latent_0001.safetensors+ ...++When the audio sample count differs from the image sample count, slices+are cycled so every image index gets a paired audio latent. This keeps+the trainer happy when iterating across the dataset.++The trainer's ``TextToVideoStrategy`` reads ``audio_latents/`` when+``training_strategy.generate_audio: true`` is set in the YAML config —+that's what triggers joint audio-video training with the audio loss+contributing alongside the video loss.++Usage::++ ./scripts/run.sh python -m lora_lab.preprocess_audio \\+ --audio /path/to/bizarrotrn.voice.wav \\+ --output ./dataset_bizarro \\+ --slice-seconds 4.0 \\+ --match-image-count++The model dir defaults to the same LTX-2.3 Q4 snapshot as preprocess_images.+"""++from __future__ import annotations++import argparse+import logging+import sys+from pathlib import Path++import mlx.core as mx+import numpy as np+from safetensors.numpy import save_file as save_safetensors++from ltx_core_mlx.model.audio_vae import (+ AudioProcessor,+ AudioVAEEncoder,+ encode_audio,+)+from ltx_core_mlx.utils.audio import load_audio+from ltx_core_mlx.utils.memory import aggressive_cleanup+from ltx_core_mlx.utils.weights import (+ load_split_safetensors,+ remap_audio_vae_keys,+)+from ltx_trainer_mlx.preprocess import _resolve_model_dir++logger = logging.getLogger(__name__)++DEFAULT_MODEL_DIR = str(+ Path.home()+ / ".cache/huggingface/hub/models--dgrauet--ltx-2.3-mlx-q4"+ / "snapshots/53a6f5f39d9c074bc73e6a18ba391f40ddffaa68"+)++AUDIO_SAMPLE_RATE = 16000 # LTX audio VAE expects 16 kHz mono+++def _load_audio_vae_encoder(model_dir: Path) -> tuple[AudioVAEEncoder, AudioProcessor]:+ """Build + load the LTX audio VAE encoder, mirroring AudioConditioner.load().++ Same weight-loading pattern as ``utils.blocks.AudioConditioner``: strip+ the ``audio_vae.encoder.`` prefix, then layer in the+ ``per_channel_statistics.*`` keys from the full audio_vae blob, then+ run them through ``remap_audio_vae_keys``.+ """+ encoder = AudioVAEEncoder()+ weights = load_split_safetensors(+ model_dir / "audio_vae.safetensors", prefix="audio_vae.encoder."+ )+ all_audio = load_split_safetensors(+ model_dir / "audio_vae.safetensors", prefix="audio_vae."+ )+ for k, v in all_audio.items():+ if k.startswith("per_channel_statistics."):+ weights[k] = v+ weights = remap_audio_vae_keys(weights)+ encoder.load_weights(list(weights.items()))+ processor = AudioProcessor()+ return encoder, processor+++def _slice_waveform(waveform: mx.array, sample_rate: int, slice_seconds: float) -> list[mx.array]:+ """Cut waveform into fixed-length slices. Drops the trailing tail if shorter than slice_seconds.++ waveform shape: (1, channels, samples)+ """+ samples_per_slice = int(slice_seconds * sample_rate)+ total_samples = waveform.shape[-1]+ n_slices = total_samples // samples_per_slice+ if n_slices == 0:+ raise ValueError(+ f"Waveform ({total_samples / sample_rate:.2f}s) is shorter than slice ({slice_seconds:.1f}s)"+ )+ slices: list[mx.array] = []+ for i in range(n_slices):+ start = i * samples_per_slice+ end = start + samples_per_slice+ slices.append(waveform[:, :, start:end])+ return slices+++def _count_existing_image_latents(precomputed_dir: Path) -> int:+ latents_dir = precomputed_dir / "latents"+ if not latents_dir.exists():+ return 0+ return sum(1 for f in latents_dir.glob("latent_*.safetensors"))+++def preprocess_audio(+ audio_path: str,+ output_dir: str,+ model_dir: str = DEFAULT_MODEL_DIR,+ slice_seconds: float = 4.0,+ match_image_count: bool = True,+ start_offset_seconds: float = 0.0,+) -> None:+ """Encode a voice WAV into LTX audio latents, paired with the existing image latents.++ Args:+ audio_path: Path to the source WAV.+ output_dir: Dataset root — preprocessed data goes to ``<output>/.precomputed/``.+ Must already contain ``latents/`` from a prior image-preprocess run if+ ``match_image_count`` is True.+ model_dir: LTX model dir (for ``audio_vae.safetensors``).+ slice_seconds: Length of each audio slice. Codex's smoke pipeline used 4.0s.+ match_image_count: If True, cycle slices to produce one audio latent per+ image latent (so every training sample has a paired voice clip).+ start_offset_seconds: Skip this many seconds at the start of the WAV+ (use to trim silence / breath).+ """+ mx.set_cache_limit(mx.device_info()["memory_size"])+ model_dir_path = Path(_resolve_model_dir(model_dir))++ src = Path(audio_path)+ if not src.exists():+ raise FileNotFoundError(f"audio file not found: {src}")++ precomputed = Path(output_dir) / ".precomputed"+ audio_latents_dir = precomputed / "audio_latents"+ audio_latents_dir.mkdir(parents=True, exist_ok=True)++ print(f"loading WAV: {src}")+ audio_data = load_audio(+ str(src),+ target_sample_rate=AUDIO_SAMPLE_RATE,+ start_time=start_offset_seconds,+ max_duration=None,+ )+ if audio_data is None:+ raise ValueError(f"no audio found in {src}")+ waveform = audio_data.waveform # (1, channels, samples)+ duration_s = waveform.shape[-1] / audio_data.sample_rate+ print(f" duration: {duration_s:.2f}s @ {audio_data.sample_rate} Hz, channels={waveform.shape[1]}")++ slices = _slice_waveform(waveform, audio_data.sample_rate, slice_seconds)+ print(f" cut into {len(slices)} slice(s) of {slice_seconds:.1f}s each")++ if match_image_count:+ n_images = _count_existing_image_latents(precomputed)+ if n_images == 0:+ print(+ " warning: no image latents found in .precomputed/latents/ — "+ "writing one audio latent per slice without pairing."+ )+ target_count = len(slices)+ else:+ print(f" matching image latent count: {n_images}")+ target_count = n_images+ else:+ target_count = len(slices)++ print(f"loading audio VAE encoder from {model_dir_path}")+ encoder, processor = _load_audio_vae_encoder(model_dir_path)++ # Encode each unique slice once, then cycle/replicate to fill target_count.+ encoded_unique: list[mx.array] = []+ for i, slice_wf in enumerate(slices):+ print(f" [{i + 1}/{len(slices)}] encoding {slice_seconds:.1f}s slice...")+ latent = encode_audio(slice_wf, audio_data.sample_rate, encoder, processor)+ mx.eval(latent)+ encoded_unique.append(latent)+ if (i + 1) % 4 == 0:+ aggressive_cleanup()++ del encoder, processor+ aggressive_cleanup()+ print(f" encoded {len(encoded_unique)} unique slices, shape={encoded_unique[0].shape}")++ # Strip the leading B=1 from each encoded latent: the trainer's dataset class+ # adds a batch dim when collating, so the on-disk per-file shape must NOT+ # include batch. encode_audio returns (1, 8, T, 16); we save (8, T, 16).+ # (Matches preprocess_images.py which writes latent[0] for the same reason.)+ #+ # Write one .safetensors per training-sample index, cycling through encoded slices.+ for i in range(target_count):+ latent = encoded_unique[i % len(encoded_unique)]+ out_path = audio_latents_dir / f"latent_{i:04d}.safetensors"+ save_safetensors(+ {"latents": np.array(latent[0].astype(mx.float32))},+ str(out_path),+ )++ print(f"\npreprocessing complete. {target_count} audio latents written to:")+ print(f" {audio_latents_dir}")+ print(f" (sourced from {len(encoded_unique)} unique slice(s) via cycling)")+++def main() -> int:+ p = argparse.ArgumentParser(description="LTX-2 audio-only LoRA preprocessor")+ p.add_argument("--audio", required=True, help="source WAV file")+ p.add_argument("--output", required=True, help="dataset root (contains .precomputed/)")+ p.add_argument(+ "--slice-seconds", type=float, default=4.0,+ help="length of each audio slice (default: 4.0 — matches Codex's smoke pipeline)",+ )+ p.add_argument(+ "--match-image-count", action="store_true",+ help="cycle audio slices to produce one audio latent per existing image latent",+ )+ p.add_argument(+ "--start-offset", type=float, default=0.0,+ help="skip this many seconds at the start of the WAV (default: 0)",+ )+ p.add_argument("--model-dir", default=DEFAULT_MODEL_DIR)+ p.add_argument("-v", "--verbose", action="store_true")+ args = p.parse_args()++ logging.basicConfig(+ level=logging.DEBUG if args.verbose else logging.INFO,+ format="%(asctime)s %(levelname)s %(name)s | %(message)s",+ )++ preprocess_audio(+ audio_path=args.audio,+ output_dir=args.output,+ model_dir=args.model_dir,+ slice_seconds=args.slice_seconds,+ match_image_count=args.match_image_count,+ start_offset_seconds=args.start_offset,+ )+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/lora_lab/preprocess_images.py b/lora_lab/preprocess_images.pynew file mode 100644index 0000000..9f78461--- /dev/null+++ b/lora_lab/preprocess_images.py@@ -0,0 +1,282 @@+"""Image-only preprocessor for LTX-2 MLX trainer.++Encodes still images into 1-frame VAE latents and captions into Gemma+embeddings, written in the layout `PrecomputedDataset` expects:++ output_dir/+ .precomputed/+ latents/+ latent_0000.safetensors {latents:[128,1,h,w], num_frames=1, height, width, fps}+ latent_0001.safetensors+ conditions/+ condition_0000.safetensors {video_prompt_embeds, audio_prompt_embeds, prompt_attention_mask}+ ...++Caption encoding is delegated to the existing video preprocessor's helper —+the path is identical and we don't fork that code.++Usage::++ ./scripts/run.sh python -m lora_lab.preprocess_images \+ --images dataset/images \+ --captions dataset/captions \+ --output dataset \+ --width 512 --height 320++The model dir defaults to the same LTX-2.3 Q4 snapshot Phosphene uses.+"""++from __future__ import annotations++import argparse+import logging+import os+import sys+from pathlib import Path++import mlx.core as mx+import numpy as np+from PIL import Image+from safetensors.numpy import save_file as save_safetensors++from ltx_core_mlx.components.patchifiers import compute_video_latent_shape+from ltx_core_mlx.utils.memory import aggressive_cleanup+from ltx_trainer_mlx.preprocess import _encode_all_captions, _resolve_model_dir++logger = logging.getLogger(__name__)++IMAGE_EXTENSIONS = {".jpg", ".jpeg", ".png", ".webp", ".bmp"}++DEFAULT_MODEL_DIR = str(+ Path.home()+ / ".cache/huggingface/hub/models--dgrauet--ltx-2.3-mlx-q4"+ / "snapshots/53a6f5f39d9c074bc73e6a18ba391f40ddffaa68"+)+++def _force_eval(*arrays: mx.array) -> None:+ mx.eval(*arrays)+++def _resolve_captions(image_files: list[Path], captions_dir: Path | None, caption_ext: str) -> list[str]:+ captions: list[str] = []+ if captions_dir is None:+ for img in image_files:+ captions.append(img.stem.replace("_", " ").replace("-", " "))+ print(" no captions dir provided; using filenames as captions")+ return captions++ for img in image_files:+ cap_file = captions_dir / f"{img.stem}{caption_ext}"+ if cap_file.exists():+ captions.append(cap_file.read_text().strip())+ else:+ fallback = img.stem.replace("_", " ").replace("-", " ")+ logger.warning("no caption file for %s, using filename: '%s'", img.name, fallback)+ captions.append(fallback)+ return captions+++def _load_image_as_1frame_tensor(image_path: Path, target_h: int, target_w: int, crop_anchor: str = "center") -> mx.array:+ """Load `image_path`, scale-and-crop to (target_h, target_w), return shape (1, C, 1, H, W) in [-1, 1].++ Critical: this is a CROP (preserves face aspect ratio), not a stretch. Earlier+ versions used Image.resize() directly, which non-uniformly scaled portrait+ selfies into squares — squashed the face geometry, and the LoRA only worked+ at inference aspect ratios that undid the same distortion. Center-crop is+ the right fix.++ `crop_anchor` controls vertical positioning when source is taller than target+ after scale-fit (i.e. portrait sources cropped to landscape target):+ - "center" (default): symmetric crop top+bottom — backward-compatible+ - "top": anchor at top — keeps upper portion (face for portrait sources)+ - "bottom": anchor at bottom — keeps lower portion++ For character LoRAs trained at landscape from portrait sources, "top" is+ usually right: faces sit in the upper third of portraits, legs in the lower+ third. Center-crop on a 3:4 portrait → 16:9 landscape can clip the top of+ the head AND the chin simultaneously.+ """+ img = Image.open(image_path).convert("RGB")+ src_w, src_h = img.size+ # Resize so the SHORTER side fits the target, preserving aspect ratio.+ scale = max(target_w / src_w, target_h / src_h)+ new_w = int(round(src_w * scale))+ new_h = int(round(src_h * scale))+ img = img.resize((new_w, new_h), Image.LANCZOS)+ # Crop the LONGER side down to target. Horizontal always centers;+ # vertical position is controlled by crop_anchor.+ left = (new_w - target_w) // 2+ if crop_anchor == "top":+ top = 0+ elif crop_anchor == "bottom":+ top = new_h - target_h+ else: # "center"+ top = (new_h - target_h) // 2+ img = img.crop((left, top, left + target_w, top + target_h))+ arr = np.array(img, dtype=np.float32) / 255.0 # (H, W, 3) in [0, 1]+ arr = arr.transpose(2, 0, 1) # (3, H, W)+ arr = arr[:, None, :, :] # (3, 1, H, W) — F=1+ arr = arr[None] # (1, 3, 1, H, W)+ arr = arr * 2.0 - 1.0 # to [-1, 1] for VAE+ return mx.array(arr).astype(mx.bfloat16)+++def _encode_all_images(+ image_files: list[Path],+ latents_dir: Path,+ model_dir: str,+ target_height: int,+ target_width: int,+ crop_anchor: str = "center",+) -> None:+ from ltx_trainer_mlx.model_loader import load_video_vae_encoder++ if target_height % 32 != 0 or target_width % 32 != 0:+ raise ValueError(f"width ({target_width}) and height ({target_height}) must be divisible by 32")++ needed: list[int] = []+ for i in range(len(image_files)):+ out_path = latents_dir / f"latent_{i:04d}.safetensors"+ if out_path.exists():+ print(f" [{i + 1}/{len(image_files)}] skipping (exists): {out_path.name}")+ else:+ needed.append(i)+ if not needed:+ print(" all image latents already encoded")+ return++ vae_encoder = load_video_vae_encoder(model_dir=model_dir)+ vae_encoder.freeze()++ F_lat, H_lat, W_lat = compute_video_latent_shape(1, target_height, target_width)+ assert F_lat == 1, f"expected F_lat=1 for F=1, got {F_lat}"+ print(f" target latent shape per image: [128, {F_lat}, {H_lat}, {W_lat}]")++ for i in needed:+ img_path = image_files[i]+ out_path = latents_dir / f"latent_{i:04d}.safetensors"+ print(f" [{i + 1}/{len(image_files)}] encoding: {img_path.name}")+ try:+ video = _load_image_as_1frame_tensor(img_path, target_height, target_width, crop_anchor=crop_anchor)+ latent = vae_encoder.encode(video)+ _force_eval(latent)+ save_safetensors(+ {+ "latents": np.array(latent[0].astype(mx.float32)), # [128, 1, H_lat, W_lat]+ "num_frames": np.array([F_lat], dtype=np.int32),+ "height": np.array([H_lat], dtype=np.int32),+ "width": np.array([W_lat], dtype=np.int32),+ "fps": np.array([24.0], dtype=np.float32),+ },+ str(out_path),+ )+ except Exception as exc:+ logger.error("failed to encode %s: %s", img_path.name, exc)+ continue+ if i % 5 == 0:+ aggressive_cleanup()++ del vae_encoder+ aggressive_cleanup()+ print(" image encoding complete")+++def preprocess_images(+ images_dir: str,+ output_dir: str,+ model_dir: str = DEFAULT_MODEL_DIR,+ gemma_model_id: str = "mlx-community/gemma-3-12b-it-4bit",+ target_height: int = 320,+ target_width: int = 512,+ captions_dir: str | None = None,+ caption_ext: str = ".txt",+ crop_anchor: str = "center",+) -> None:+ mx.set_cache_limit(mx.device_info()["memory_size"])+ model_dir = _resolve_model_dir(model_dir)++ images_path = Path(images_dir)+ if not images_path.exists():+ raise FileNotFoundError(f"images dir not found: {images_path}")++ image_files = sorted(+ f for f in images_path.iterdir() if f.suffix.lower() in IMAGE_EXTENSIONS and f.is_file()+ )+ if not image_files:+ raise ValueError(f"no images found in {images_path}")+ print(f"found {len(image_files)} images in {images_path}")++ precomputed = Path(output_dir) / ".precomputed"+ latents_dir = precomputed / "latents"+ conditions_dir = precomputed / "conditions"+ latents_dir.mkdir(parents=True, exist_ok=True)+ conditions_dir.mkdir(parents=True, exist_ok=True)++ captions = _resolve_captions(+ image_files,+ Path(captions_dir) if captions_dir else None,+ caption_ext,+ )++ print("Phase 1: encoding text captions (Gemma)...")+ _encode_all_captions(+ captions=captions,+ conditions_dir=conditions_dir,+ model_dir=model_dir,+ gemma_model_id=gemma_model_id,+ )++ print(f"Phase 2: encoding image latents at {target_width}x{target_height} (1 frame each, crop_anchor={crop_anchor})...")+ _encode_all_images(+ image_files=image_files,+ latents_dir=latents_dir,+ model_dir=model_dir,+ target_height=target_height,+ target_width=target_width,+ crop_anchor=crop_anchor,+ )++ print(f"\npreprocessing complete. {len(image_files)} samples written to {precomputed}")+ print(f" latents: {latents_dir}")+ print(f" conditions: {conditions_dir}")+++def main() -> int:+ p = argparse.ArgumentParser(description="LTX-2 image-only LoRA preprocessor")+ p.add_argument("--images", required=True, help="directory of source images")+ p.add_argument("--captions", default=None, help="directory of caption .txt files (one per image stem)")+ p.add_argument("--caption-ext", default=".txt")+ p.add_argument("--output", required=True, help="output root — preprocessed data goes to <output>/.precomputed/")+ p.add_argument("--width", type=int, default=512, help="target width (divisible by 32)")+ p.add_argument("--height", type=int, default=320, help="target height (divisible by 32)")+ p.add_argument("--crop-anchor", default="center", choices=["center", "top", "bottom"],+ help="vertical crop position when source is taller than target after scale-fit "+ "(center=default+backward-compatible; top=preserves face on portrait sources "+ "going to landscape target; bottom=preserves lower body)")+ p.add_argument("--model-dir", default=DEFAULT_MODEL_DIR)+ p.add_argument("--gemma", default="mlx-community/gemma-3-12b-it-4bit")+ p.add_argument("-v", "--verbose", action="store_true")+ args = p.parse_args()++ logging.basicConfig(+ level=logging.DEBUG if args.verbose else logging.INFO,+ format="%(asctime)s %(levelname)s %(name)s | %(message)s",+ )++ preprocess_images(+ images_dir=args.images,+ captions_dir=args.captions,+ caption_ext=args.caption_ext,+ output_dir=args.output,+ target_height=args.height,+ target_width=args.width,+ model_dir=args.model_dir,+ gemma_model_id=args.gemma,+ crop_anchor=args.crop_anchor,+ )+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/lora_lab/smoke_test.py b/lora_lab/smoke_test.pynew file mode 100644index 0000000..2df4218--- /dev/null+++ b/lora_lab/smoke_test.py@@ -0,0 +1,237 @@+"""M1 — gradient-flow smoke test for LoRA on LTX-2 (MLX).++Run with:+ ./scripts/run.sh python -m lora_lab.smoke_test++What this checks+----------------+1. Tier A — wrap a tiny QuantizedLinear with `LoRALinear`, prove `value_and_grad`+ emits non-zero gradients on the LoRA params and zero/None on the base.+2. Tier B — load one real LTX transformer block (Q4), wrap its attention+ projections using the same helpers `ltx-trainer-mlx` uses, freeze base,+ forward random hidden states through self-attention, prove gradients flow+ to LoRA params and not to base.++Tier A is the must-pass mechanism check. Tier B confirms the mechanism works+against a real quantized transformer block — the harder case.++If both pass, the trainer's LoRA setup is wired correctly for our environment+and we can move to M2 (preprocessor) without surprises.+"""++from __future__ import annotations++import os+import sys+import time+from pathlib import Path++import mlx.core as mx+import mlx.nn as nn+from mlx_lm.tuner.lora import LoRALinear++from ltx_trainer_mlx.trainer import _find_lora_targets, _set_module_by_path++# Optional: only load the transformer for Tier B if it's available.+MODEL_DIR = Path(+ os.environ.get(+ "LORA_LAB_MODEL_DIR",+ str(+ Path.home()+ / ".cache/huggingface/hub/models--dgrauet--ltx-2.3-mlx-q4"+ / "snapshots/53a6f5f39d9c074bc73e6a18ba391f40ddffaa68"+ ),+ )+)+++# ---------------------------------------------------------------------------+# Tier A — tiny QuantizedLinear + LoRA+# ---------------------------------------------------------------------------+++def _quantize_linear(layer: nn.Linear, bits: int = 4, group_size: int = 64) -> nn.QuantizedLinear:+ """Quantize an nn.Linear in place and return the equivalent nn.QuantizedLinear.++ Mirrors what `apply_quantization` does at load time, but for one layer.+ """+ return nn.QuantizedLinear.from_linear(layer, group_size=group_size, bits=bits)+++def tier_a() -> bool:+ print("\n=== Tier A: tiny QuantizedLinear + LoRA ===")+ mx.random.seed(0)++ in_dim, out_dim, rank = 64, 64, 8+ base_linear = nn.Linear(in_dim, out_dim, bias=True)+ qlinear = _quantize_linear(base_linear, bits=4, group_size=64)++ lora = LoRALinear(input_dims=in_dim, output_dims=out_dim, r=rank, scale=1.0, bias=True)+ lora.linear = qlinear # swap the inner Linear for the quantized one++ # Freeze everything, then unfreeze only LoRA params (this is what the trainer does).+ lora.freeze()+ lora.unfreeze(keys=["lora_a", "lora_b"], strict=False)++ trainable = dict(nn.utils.tree_flatten(lora.trainable_parameters()))+ print(f" trainable params: {list(trainable.keys())}")+ assert "lora_a" in trainable and "lora_b" in trainable, "LoRA params not trainable"+ assert all("weight" not in k for k in trainable.keys()), "base weight should be frozen"++ x = mx.random.normal((4, in_dim))+ target = mx.random.normal((4, out_dim))++ def loss_fn(m, x, t):+ return mx.mean((m(x) - t) ** 2)++ loss_and_grad = nn.value_and_grad(lora, loss_fn)+ loss, grads = loss_and_grad(lora, x, target)+ mx.eval(loss, grads)++ flat_grads = dict(nn.utils.tree_flatten(grads))+ print(f" loss: {float(loss.item()):.4f}")+ print(f" grad keys: {list(flat_grads.keys())}")++ lora_a_grad = flat_grads.get("lora_a")+ lora_b_grad = flat_grads.get("lora_b")+ assert lora_a_grad is not None and lora_b_grad is not None, "missing LoRA grads"++ a_norm = float(mx.linalg.norm(lora_a_grad).item())+ b_norm = float(mx.linalg.norm(lora_b_grad).item())+ print(f" ||grad lora_a|| = {a_norm:.6f}")+ print(f" ||grad lora_b|| = {b_norm:.6f}")+ # lora_b is initialized to zero in standard LoRA, so its grad CAN be nonzero+ # after one step. lora_a's grad starts at zero (because B is zero) — that's+ # the standard LoRA initialization. We don't assert nonzero on `a` here.+ assert b_norm > 0.0, "lora_b grad is zero — backprop did not reach LoRA"++ base_grad = flat_grads.get("linear.weight")+ if base_grad is not None:+ base_norm = float(mx.linalg.norm(base_grad).item())+ print(f" ||grad base.weight|| = {base_norm:.6f} (expected ~0)")+ assert base_norm < 1e-8, "frozen base received gradients"+ else:+ print(" base.weight: no grad entry (expected)")++ print(" Tier A PASS")+ return True+++# ---------------------------------------------------------------------------+# Tier B — one real LTX transformer block (Q4)+# ---------------------------------------------------------------------------+++def tier_b() -> bool:+ print("\n=== Tier B: one real LTX transformer block (Q4) ===")+ if not MODEL_DIR.exists():+ print(f" model dir missing: {MODEL_DIR}")+ print(" skipping Tier B")+ return False++ t0 = time.time()+ from ltx_trainer_mlx.model_loader import load_transformer++ model = load_transformer(MODEL_DIR)+ print(f" transformer loaded in {time.time() - t0:.1f}s")++ block = model.transformer_blocks[0]+ print(f" block class: {type(block).__name__}")++ # Scope the LoRA wrap to JUST this block. We use the same helpers the+ # trainer uses, but rooted at the block (not the whole model).+ targets = _find_lora_targets(block, target_names=["to_q", "to_k", "to_v", "to_out"])+ print(f" found {len(targets)} LoRA targets on block[0]:")+ for path, mod in targets[:8]:+ kind = "Quant" if isinstance(mod, nn.QuantizedLinear) else "Linear"+ print(f" {path} ({kind})")+ if len(targets) > 8:+ print(f" ... and {len(targets) - 8} more")++ rank = 8+ for path, module in targets:+ if isinstance(module, nn.QuantizedLinear):+ in_dims = module.scales.shape[-1] * module.group_size+ out_dims = module.weight.shape[0]+ has_bias = hasattr(module, "bias") and module.bias is not None+ else:+ in_dims = module.weight.shape[-1]+ out_dims = module.weight.shape[0]+ has_bias = hasattr(module, "bias") and module.bias is not None+ lora_linear = LoRALinear(+ input_dims=in_dims,+ output_dims=out_dims,+ r=rank,+ scale=1.0,+ bias=has_bias,+ )+ lora_linear.linear = module+ _set_module_by_path(block, path, lora_linear)++ block.freeze()+ block.unfreeze(keys=["lora_a", "lora_b"], strict=False)++ trainable = dict(nn.utils.tree_flatten(block.trainable_parameters()))+ lora_keys = [k for k in trainable.keys() if "lora_" in k]+ base_keys = [k for k in trainable.keys() if "lora_" not in k]+ print(f" trainable param count: {len(trainable)} ({len(lora_keys)} LoRA, {len(base_keys)} other)")+ assert len(lora_keys) > 0, "no LoRA params became trainable"+ assert len(base_keys) == 0, f"unexpected trainable base params: {base_keys[:3]}"++ # Drive a tiny forward through ONLY the video self-attention path of the+ # block. We don't need the full block call (which expects audio, text,+ # positions, etc.) — we just need any path through the LoRA-wrapped layers.+ attn = block.attn1+ bs, seq, dim = 1, 16, attn.to_q.linear.weight.shape[0]+ x = mx.random.normal((bs, seq, dim)).astype(mx.bfloat16)++ def loss_fn(_attn, x):+ q = _attn.to_q(x)+ k = _attn.to_k(x)+ v = _attn.to_v(x)+ out = _attn.to_out(q + k + v) # synthetic: not real attention, just exercises all 4 LoRAs+ return mx.mean(out.astype(mx.float32) ** 2)++ loss_and_grad = nn.value_and_grad(attn, loss_fn)+ t0 = time.time()+ loss, grads = loss_and_grad(attn, x)+ mx.eval(loss, grads)+ print(f" fwd+bwd on block[0] attn: {time.time() - t0:.2f}s, loss={float(loss.item()):.4f}")++ flat = dict(nn.utils.tree_flatten(grads))+ lora_b_grads = {k: v for k, v in flat.items() if k.endswith(".lora_b")}+ assert lora_b_grads, "no lora_b gradients emitted"++ any_nonzero = False+ for k, g in lora_b_grads.items():+ if g is None:+ continue+ norm = float(mx.linalg.norm(g).item())+ if norm > 0.0:+ any_nonzero = True+ print(f" ||grad {k}|| = {norm:.6f}")+ assert any_nonzero, "all lora_b grads are zero"++ # Sample a base-weight grad — should not appear (frozen).+ base_grads = {k: v for k, v in flat.items() if k.endswith(".linear.weight") and v is not None}+ print(f" frozen base weight grad entries: {len(base_grads)} (expected 0)")+ assert len(base_grads) == 0, f"frozen base received gradients: {list(base_grads)[:3]}"++ print(" Tier B PASS")+ return True+++def main() -> int:+ print(f"mlx {mx.__version__ if hasattr(mx, '__version__') else 'n/a'}")+ print(f"model dir: {MODEL_DIR}")+ a_ok = tier_a()+ b_ok = tier_b()+ if a_ok and b_ok:+ print("\nM1 SMOKE TEST PASS")+ return 0+ print("\nM1 SMOKE TEST FAIL")+ return 1+++if __name__ == "__main__":+ sys.exit(main())diff --git a/lora_lab/train.py b/lora_lab/train.pynew file mode 100644index 0000000..9f13578--- /dev/null+++ b/lora_lab/train.py@@ -0,0 +1,231 @@+"""Thin CLI wrapper around ``LtxvTrainer`` for image-only character LoRAs.++Why a wrapper instead of using ``ltx-2-mlx`` directly:++- The default ``TextToVideoConfig.first_frame_conditioning_p`` is 0.1. With+ 1-frame image samples, when this triggers the entire image is treated as+ conditioning, the loss mask becomes all-zero, ``mean(loss_mask) == 0``, and+ the masked-MSE loss in ``TextToVideoStrategy.compute_loss`` divides by zero+ → NaN. We force it to 0.0 for image-only training.+- We want first/last training-step timing logged to stdout so M3 prints a+ honest per-step number on this machine.++Usage::++ ./scripts/run.sh python -m lora_lab.train --config configs/char_image_lora.yaml+"""++from __future__ import annotations++import argparse+import logging+import sys+import time+from pathlib import Path++import yaml++import ltx_trainer_mlx.model_loader as ml_module+import ltx_trainer_mlx.training_strategies as ts_module+from ltx_trainer_mlx.config import LtxTrainerConfig+from ltx_trainer_mlx.trainer import LtxvTrainer++logger = logging.getLogger(__name__)+++def _patch_loader_prefer_dev_transformer() -> None:+ """Force `load_transformer` to pick `transformer-dev.safetensors` when present.++ Default auto-detect order is `transformer.safetensors` → `transformer-distilled.safetensors`+ → `transformer-dev.safetensors`. In the `dgrauet/ltx-2.3-mlx-q4` model dir, the+ distilled file exists, so dev never gets picked.++ Per LTX-2 issue #175 (Lightricks/LTX-2): the distilled checkpoint uses a different+ sigma schedule (8-step DISTILLED_SIGMAS) than the standard flow-matching trainer+ objective. Training a character LoRA against the distilled weights produces gradients+ that point toward the wrong target — coarse features (hair/age/beard) survive the+ mismatch but fine face geometry doesn't. Switching the trainer to the dev transformer+ eliminates the objective mismatch.+ """+ from pathlib import Path+ _orig = ml_module.load_transformer++ def patched(model_dir, transformer_file=None):+ if transformer_file is None:+ dev = Path(model_dir) / "transformer-dev.safetensors"+ if dev.exists():+ transformer_file = "transformer-dev.safetensors"+ logger.info("training-side override: using transformer-dev.safetensors (not distilled)")+ return _orig(model_dir, transformer_file=transformer_file)++ ml_module.load_transformer = patched+++def _patch_compute_video_positions_fps_kwarg() -> None:+ """Translate ``fps=`` → ``frame_rate=`` across the trainer.++ Upstream rename 2026-05-14 (same family as the rename in+ ``_decode_and_save_video``): ``ltx_core_mlx.utils.positions`` renamed+ ``fps`` → ``frame_rate`` on both ``compute_video_positions`` and+ ``compute_audio_token_count``. The trainer still calls with ``fps=``+ in multiple places (base_strategy, trainer, validation_sampler,+ text_to_video, video_to_video), so training raises+ ``TypeError: ... unexpected keyword argument 'fps'`` at the first+ training step.++ We wrap both functions to accept either kwarg name, then rebind the+ symbols in every trainer-side module that imported them by name.+ Lora-lab CLAUDE rule 1 says don't modify phosphene's tree — so we+ monkey-patch at runtime instead.+ """+ import ltx_core_mlx.utils.positions as _pos++ _orig_vid = _pos.compute_video_positions+ _orig_aud = _pos.compute_audio_token_count++ def patched_video(num_frames, height, width, *, fps=None, frame_rate=None):+ if frame_rate is None:+ frame_rate = fps if fps is not None else 24.0+ return _orig_vid(num_frames=num_frames, height=height, width=width,+ frame_rate=frame_rate)++ def patched_audio(num_video_frames, *, fps=None, frame_rate=None):+ if frame_rate is None:+ frame_rate = fps if fps is not None else 24.0+ return _orig_aud(num_video_frames=num_video_frames, frame_rate=frame_rate)++ # Patch the source module.+ _pos.compute_video_positions = patched_video+ _pos.compute_audio_token_count = patched_audio++ # Rebind in every trainer-side module that imported the names directly.+ _consumer_modules = (+ "ltx_trainer_mlx.trainer",+ "ltx_trainer_mlx.validation_sampler",+ "ltx_trainer_mlx.training_strategies.base_strategy",+ "ltx_trainer_mlx.training_strategies.text_to_video",+ "ltx_trainer_mlx.training_strategies.video_to_video",+ )+ import importlib+ for name in _consumer_modules:+ try:+ mod = importlib.import_module(name)+ except ImportError:+ continue+ if hasattr(mod, "compute_video_positions"):+ mod.compute_video_positions = patched_video+ if hasattr(mod, "compute_audio_token_count"):+ mod.compute_audio_token_count = patched_audio+++def _patch_lora_target_exclude_audio() -> None:+ """Exclude audio attention/FF layers from LoRA target matching.++ The trainer's ``_find_lora_targets`` (trainer.py:917) does suffix matching:+ it splits each module path by ``.`` and checks if ANY part is in+ ``target_modules``. With the canonical face-LoRA target_modules+ ``[to_q, to_k, to_v, to_out]``, the matcher catches both+ ``transformer_blocks.N.attn1.to_q`` (video attention — wanted) AND+ ``transformer_blocks.N.audio_attn1.to_q`` (audio attention — unwanted).++ Training on still images with no audio signal pushes random gradients+ into the audio attention layers. The saved face LoRA then carries those+ random "audio_attn" deltas. When stacked with the audio LoRA at inference,+ those random deltas corrupt the model's audio attention path → lips don't+ animate during dialogue, voice is distorted. Discovered 2026-05-15 on+ Aria v2 — face LoRA had 1152 audio_attn deltas that broke lip-sync until+ they were filtered out post-hoc.++ Fix: wrap ``_find_lora_targets`` so any path containing an ``audio_*``+ submodule is skipped at training time. The LoRA never includes those+ weights, never wastes gradient updates on them, and the saved file is+ clean by construction (no post-hoc filter needed).++ Lora-lab CLAUDE rule 1 says don't mutate phosphene's tree — so we+ monkey-patch at runtime instead.+ """+ import ltx_trainer_mlx.trainer as _trainer+ _orig = _trainer._find_lora_targets++ EXCLUDE_SUBSTRINGS = ("audio_attn", "audio_ff")++ def patched(model, target_names):+ results = _orig(model, target_names)+ filtered = [(path, mod) for (path, mod) in results+ if not any(s in path for s in EXCLUDE_SUBSTRINGS)]+ dropped = len(results) - len(filtered)+ if dropped:+ logger.info(+ "lora target filter: kept %d video targets, "+ "dropped %d audio targets (audio_attn / audio_ff)",+ len(filtered), dropped,+ )+ return filtered++ _trainer._find_lora_targets = patched+++def _patch_strategy_for_image_only() -> None:+ """Force `first_frame_conditioning_p=0.0` for image-only training.++ The Pydantic config doesn't expose this knob; intercept the factory to+ rebuild the strategy config with our override.+ """+ _orig = ts_module.get_training_strategy++ def patched(config):+ name = getattr(config, "name", None)+ if name == "text_to_video":+ generate_audio = bool(getattr(config, "generate_audio", False))+ native_cfg = ts_module.TextToVideoConfig(+ first_frame_conditioning_p=0.0,+ with_audio=generate_audio,+ )+ strategy = ts_module.TextToVideoStrategy(native_cfg)+ logger.info(+ "image-only override: first_frame_conditioning_p=0.0, with_audio=%s",+ generate_audio,+ )+ return strategy+ return _orig(config)++ ts_module.get_training_strategy = patched+++def main() -> int:+ p = argparse.ArgumentParser(description="LTX-2 image-only character LoRA trainer")+ p.add_argument("--config", required=True, help="path to YAML config (see configs/char_image_lora.yaml)")+ p.add_argument("-v", "--verbose", action="store_true")+ args = p.parse_args()++ logging.basicConfig(+ level=logging.DEBUG if args.verbose else logging.INFO,+ format="%(asctime)s %(levelname)s %(name)s | %(message)s",+ )++ cfg_path = Path(args.config).resolve()+ with cfg_path.open() as f:+ cfg_dict = yaml.safe_load(f)++ config = LtxTrainerConfig.model_validate(cfg_dict)++ _patch_loader_prefer_dev_transformer()+ _patch_strategy_for_image_only()+ _patch_compute_video_positions_fps_kwarg()+ _patch_lora_target_exclude_audio()++ t0 = time.time()+ trainer = LtxvTrainer(config)+ print(f"trainer init complete in {time.time() - t0:.1f}s")++ t0 = time.time()+ saved_path, stats = trainer.train(disable_progress_bars=False)+ print(f"\ntraining wall: {time.time() - t0:.1f}s")+ print(f"checkpoint: {saved_path}")+ print(f"per-step: {1.0 / stats.steps_per_second:.2f}s ({stats.steps_per_second:.3f} steps/s)")+ print(f"peak memory: {stats.peak_memory_gb:.2f} GB")+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/lora_lab/train_audio.py b/lora_lab/train_audio.pynew file mode 100644index 0000000..bd9047c--- /dev/null+++ b/lora_lab/train_audio.py@@ -0,0 +1,629 @@+"""Single-shot CLI: run the audio-side Character LoRA pipeline from a spec JSON.++This is the audio-side companion to :mod:`lora_lab.train_character`. Where the+character module owns face/image training, this module owns voice training:+slice a clip into VAE audio latents, build a small LoRA on the audio attention++ feed-forward paths, and drop the final ``.safetensors`` at the path the+Phosphene panel requested.++The panel writes a spec JSON and invokes this module as a subprocess:++ ./scripts/run.sh python -m lora_lab.train_audio \\+ --spec /abs/path/to/spec.json --job-id <id>++The CLI streams JSON-lines progress to stdout (one JSON object per line) so+the panel can tail it.++------------------------------------------------------------------------+Stdout protocol (one JSON object per line; ordered, append-only):++ {"event":"start","job_id":"..."}+ {"event":"phase","phase":"audio","label":"Training voice LoRA"}+ {"event":"plan","rank":16,"alpha":16,"steps":250,"lr":0.0001,+ "slice_seconds":4.0,"image_count":17}+ {"event":"preprocess_start"}+ {"event":"log","msg":"..."}+ ...+ {"event":"preprocess_done"}+ {"event":"train_start","total_steps":250}+ {"event":"step","phase":"audio","step":50,"total":250,"loss":0.41,"eta_s":...}+ ...+ {"event":"checkpoint","path":"/path/to/lora.safetensors"}+ {"event":"done","path":"/abs/path/to/<trigger>.audio.safetensors"}++On any failure:++ {"event":"error","stage":"preprocess","message":"..."}+ -> exit code 1 (or 2 for input-validation errors)++------------------------------------------------------------------------+Spec JSON schema (everything is required):++ {+ "schema": "phosphene/train_audio@1",+ "job_id": "char_20260515_120000_ab12",+ "trigger": "newchartrn",+ "audio_path": "/abs/path/to/voice.wav",+ "dataset_dir": "/abs/path/to/state/train_character/<job_id>",+ "image_count": 17,+ "audio_steps": 250,+ "audio_rank": 16,+ "audio_lr": 1.0e-4,+ "audio_slice_seconds": 4.0,+ "output_path": "/abs/path/to/mlx_models/loras/<trigger>.audio.safetensors"+ }++The face training pipeline (``train_character``) MUST have run first, so the+image latents at ``<dataset_dir>/.precomputed/latents/`` exist — the audio+preprocessor pairs each audio slice to an image latent by index.+"""++from __future__ import annotations++import argparse+import json+import logging+import shutil+import sys+import time+import traceback+from pathlib import Path+from typing import Any++import yaml++logger = logging.getLogger(__name__)+++# ----------------------------------------------------------------------+# Constants (kept in lockstep with the Phase B audio configs)+# ----------------------------------------------------------------------++# Same Q4 snapshot the rest of the lab uses (matches preprocess_audio ++# train_character + configs/char_audio_lora_*.yaml).+DEFAULT_MODEL_PATH = (+ "/Users/salo/.cache/huggingface/hub/models--dgrauet--ltx-2.3-mlx-q4"+ "/snapshots/53a6f5f39d9c074bc73e6a18ba391f40ddffaa68"+)+DEFAULT_TEXT_ENCODER = "mlx-community/gemma-3-12b-it-4bit"++# The trainer's ``_find_lora_targets`` substring-matches against module paths+# in LTXModel. These three names cover the audio attention + audio FF paths,+# leaving the (face-LoRA-owned) video attention untouched.+AUDIO_TARGET_MODULES = ["audio_attn1", "audio_attn2", "audio_ff"]++AUDIO_EXTENSIONS = {".wav", ".mp3", ".m4a"}++# Reasonable guardrails — fail loud if the panel hands us nonsense.+_MIN_AUDIO_STEPS = 50+_MAX_AUDIO_STEPS = 2000+++# ----------------------------------------------------------------------+# Stdout JSON-lines emitter (mirrors train_character.emit so the panel+# parses both pipelines uniformly).+# ----------------------------------------------------------------------++# Capture the ORIGINAL stdout at import time. Training stages temporarily swap+# sys.stdout to silence the trainer's prints; emit() must keep writing to the+# real panel-facing stream regardless of those swaps.+_REAL_STDOUT = sys.stdout+++def emit(event: str, **kwargs: Any) -> None:+ """Write one JSON event line to the real stdout, flushed."""+ obj = {"event": event, **kwargs}+ _REAL_STDOUT.write(json.dumps(obj, separators=(",", ":")) + "\n")+ _REAL_STDOUT.flush()+++def emit_error_and_exit(stage: str, message: str, code: int = 1) -> None:+ emit("error", stage=stage, message=message)+ sys.exit(code)+++# ----------------------------------------------------------------------+# Spec validation+# ----------------------------------------------------------------------++_REQUIRED_SPEC_KEYS = (+ "job_id",+ "trigger",+ "audio_path",+ "dataset_dir",+ "image_count",+ "audio_steps",+ "audio_rank",+ "audio_lr",+ "audio_slice_seconds",+ "output_path",+)++_EXPECTED_SCHEMA = "phosphene/train_audio@1"+++def load_spec(spec_path: Path) -> dict[str, Any]:+ if not spec_path.exists():+ raise FileNotFoundError(f"spec not found: {spec_path}")+ spec = json.loads(spec_path.read_text())++ # Schema check is soft — log a warning if missing/unexpected but don't+ # bail out, so an older panel build can still drive this CLI.+ schema = spec.get("schema")+ if schema and schema != _EXPECTED_SCHEMA:+ logger.warning(+ "spec.schema=%r does not match expected %r — continuing",+ schema, _EXPECTED_SCHEMA,+ )++ for k in _REQUIRED_SPEC_KEYS:+ if k not in spec:+ raise ValueError(f"spec missing required key: {k!r}")+ return spec+++def validate_inputs(spec: dict[str, Any]) -> None:+ """Fail loud + early on bad inputs (exit code 2 for validation errors)."""+ audio_path = Path(spec["audio_path"])+ if not audio_path.exists():+ emit_error_and_exit(+ "validate",+ f"audio file not found: {audio_path}",+ code=2,+ )+ if audio_path.suffix.lower() not in AUDIO_EXTENSIONS:+ emit_error_and_exit(+ "validate",+ f"unsupported audio format {audio_path.suffix!r}; "+ f"expected one of {sorted(AUDIO_EXTENSIONS)}",+ code=2,+ )++ dataset_dir = Path(spec["dataset_dir"])+ # Face training (train_character.py) copies images into a `training_data/`+ # subdir before preprocessing, so the image latents land at+ # `<job_dir>/training_data/.precomputed/latents/`, not directly under the+ # job dir. Detect both layouts and re-point `spec["dataset_dir"]` at the+ # effective root so every downstream step (preprocess, config, train) sees+ # the right path.+ candidate_a = dataset_dir / ".precomputed" / "latents"+ candidate_b = dataset_dir / "training_data" / ".precomputed" / "latents"+ if candidate_b.exists():+ image_latents_dir = candidate_b+ spec["dataset_dir"] = str(dataset_dir / "training_data")+ elif candidate_a.exists():+ image_latents_dir = candidate_a+ else:+ emit_error_and_exit(+ "validate",+ f"image latents not found at {candidate_a} or {candidate_b}. "+ f"Face training (train_character) must run first to produce image "+ f"latents — audio preprocessing pairs each slice to an image latent.",+ code=2,+ )+ n_image_latents = sum(1 for _ in image_latents_dir.glob("latent_*.safetensors"))+ if n_image_latents == 0:+ emit_error_and_exit(+ "validate",+ f"no image latents found in {image_latents_dir} (directory empty). "+ f"Re-run face training before training the audio LoRA.",+ code=2,+ )++ try:+ steps = int(spec["audio_steps"])+ except (TypeError, ValueError):+ emit_error_and_exit("validate", f"audio_steps must be int, got {spec['audio_steps']!r}", code=2)+ if not (_MIN_AUDIO_STEPS <= steps <= _MAX_AUDIO_STEPS):+ emit_error_and_exit(+ "validate",+ f"audio_steps={steps} outside allowed range [{_MIN_AUDIO_STEPS}, {_MAX_AUDIO_STEPS}]",+ code=2,+ )+++# ----------------------------------------------------------------------+# Phase 2: preprocess (call the existing module — same env, same audio VAE)+# ----------------------------------------------------------------------++def run_preprocess(+ *,+ audio_path: Path,+ dataset_dir: Path,+ slice_seconds: float,+) -> int:+ """Slice the WAV and encode VAE audio latents into ``<dataset_dir>/.precomputed/audio_latents/``.++ Always uses ``match_image_count=True`` so the audio latent count equals the+ image latent count (the trainer iterates paired image + audio latents by+ index). Returns the number of audio latents written.+ """+ from lora_lab import preprocess_audio as pa # local — heavy deps++ emit("preprocess_start")++ # Pipe the inner module's bare ``print()`` calls into stderr so our+ # JSON-lines stream on stdout stays clean.+ orig_stdout = sys.stdout+ try:+ sys.stdout = sys.stderr+ pa.preprocess_audio(+ audio_path=str(audio_path),+ output_dir=str(dataset_dir),+ slice_seconds=float(slice_seconds),+ match_image_count=True,+ )+ finally:+ sys.stdout = orig_stdout++ audio_latents_dir = dataset_dir / ".precomputed" / "audio_latents"+ written = sorted(audio_latents_dir.glob("latent_*.safetensors"))+ if not written:+ raise RuntimeError(+ f"preprocess wrote no audio latents into {audio_latents_dir}"+ )+ emit("preprocess_done")+ emit("log", msg=f"wrote {len(written)} audio latents to {audio_latents_dir}")+ return len(written)+++# ----------------------------------------------------------------------+# Phase 3: build the audio YAML config (template = char_audio_lora_bizarro.yaml)+# ----------------------------------------------------------------------++def build_audio_config(+ *,+ rank: int,+ steps: int,+ lr: float,+ dataset_dir: Path,+ output_dir: Path,+) -> dict[str, Any]:+ """Compose the audio LoRA YAML config dict.++ Mirrors ``configs/char_audio_lora_bizarro.yaml``:+ - target_modules = audio_attn1/2 + audio_ff (NO video targets)+ - rank == alpha (per Codex's tiny-adapter recipe)+ - generate_audio: true (enables audio loss + reads audio_latents/)+ - validation.generate_audio: false (don't vocode val samples — saves mem)+ """+ return {+ "model": {+ "model_path": DEFAULT_MODEL_PATH,+ "text_encoder_path": DEFAULT_TEXT_ENCODER,+ "training_mode": "lora",+ },+ "lora": {+ "rank": int(rank),+ "alpha": int(rank),+ "dropout": 0.0,+ "target_modules": list(AUDIO_TARGET_MODULES),+ },+ "optimization": {+ "learning_rate": float(lr),+ "steps": int(steps),+ "batch_size": 1,+ "gradient_accumulation_steps": 1,+ "max_grad_norm": 1.0,+ "weight_decay": 0.0,+ "scheduler_type": "constant",+ },+ "data": {+ "preprocessed_data_root": str(dataset_dir),+ },+ "training_strategy": {+ "name": "text_to_video",+ "generate_audio": True, # the knob: enables audio loss + audio_latents/+ },+ "flow_matching": {+ "timestep_sampling_mode": "shifted_logit_normal",+ },+ "validation": {+ "prompts": [],+ "interval": None,+ "skip_initial_validation": True,+ "generate_audio": False,+ },+ "checkpoints": {+ # Save every ~10% of total steps so the user has fallbacks if a+ # long run is interrupted, but keep at least one mid-run checkpoint.+ "interval": max(1, int(steps) // 5),+ "keep_last_n": 2,+ },+ "seed": 42,+ "output_dir": str(output_dir),+ }+++def write_audio_yaml(config_dict: dict[str, Any], yaml_path: Path) -> None:+ yaml_path.parent.mkdir(parents=True, exist_ok=True)+ yaml_path.write_text(yaml.safe_dump(config_dict, sort_keys=False))+++# ----------------------------------------------------------------------+# Phase 4: train (in-process, same patch set as train.py / train_character.py)+# ----------------------------------------------------------------------++def run_training(+ *,+ config_dict: dict[str, Any],+ output_dir: Path,+) -> tuple[Path, float]:+ """Run the trainer in-process. Returns (final_checkpoint_path, wall_seconds).++ Forwards per-step events to stdout under ``event=step`` with+ ``phase=audio`` so the panel can distinguish face-phase from audio-phase+ progress in the same log stream.+ """+ # Late imports — keep CLI start cheap and let validation/preprocess fail+ # before we pay the trainer's import cost.+ from ltx_trainer_mlx.config import LtxTrainerConfig+ from ltx_trainer_mlx.trainer import LtxvTrainer+ from lora_lab import train as lab_train++ config = LtxTrainerConfig.model_validate(config_dict)++ # Same patch set train.py / train_character.py apply: dev transformer ++ # image-only safety + fps→frame_rate kwarg shim + audio-attn exclusion.+ # The audio-attn exclusion filter inside train.py drops audio_* matches —+ # but here we WANT those targets, so we deliberately re-monkey-patch the+ # filter AFTER lab_train's patch to restore the audio paths.+ lab_train._patch_loader_prefer_dev_transformer()+ lab_train._patch_strategy_for_image_only()+ lab_train._patch_compute_video_positions_fps_kwarg()+ _restore_audio_lora_targets()++ total_steps = int(config_dict["optimization"]["steps"])+ emit("train_start", total_steps=total_steps)++ train_start = time.time()+ last_emit_step = 0+ emit_every = max(5, min(50, total_steps // 25 or 5))+ last_loss: float | None = None++ # Sniff per-step loss the same way train_character does — patch+ # TrainingProgress.update_training to record the most recent loss.+ import ltx_trainer_mlx.progress as tp_mod # type: ignore++ _orig_update = tp_mod.TrainingProgress.update_training++ def _sniff_update(self, *, loss, lr, step_time, advance=True): # noqa: ANN001+ nonlocal last_loss+ try:+ last_loss = float(loss)+ except Exception: # noqa: BLE001+ pass+ return _orig_update(self, loss=loss, lr=lr, step_time=step_time, advance=advance)++ tp_mod.TrainingProgress.update_training = _sniff_update++ def _cb(step: int, total: int, _videos: list[Path]) -> None:+ nonlocal last_emit_step+ if step - last_emit_step < emit_every and step != total:+ return+ last_emit_step = step+ elapsed = time.time() - train_start+ eta = 0+ if step > 0:+ per_step = elapsed / step+ eta = max(0, int(per_step * (total - step)))+ loss_val = round(last_loss, 4) if last_loss is not None else None+ # Panel parses {"event":"step"} with {step, total, loss}. Tagging+ # phase=audio lets the panel render an "audio phase" progress bar+ # distinct from the face phase.+ emit("step", phase="audio", step=step, total=total, loss=loss_val, eta_s=eta)++ # Silence the trainer's own logging to stdout — only JSON-lines reach it.+ for noisy in (+ "ltx_trainer_mlx",+ "ltx_trainer_mlx.trainer",+ "ltx_core_mlx",+ ):+ logging.getLogger(noisy).propagate = False++ # Redirect generic prints from the trainer to stderr.+ orig_stdout = sys.stdout+ try:+ sys.stdout = sys.stderr+ trainer = LtxvTrainer(config)+ saved_path, _stats = trainer.train(disable_progress_bars=True, step_callback=_cb)+ finally:+ sys.stdout = orig_stdout++ train_wall = time.time() - train_start+ emit("checkpoint", path=str(saved_path))+ return Path(saved_path), train_wall+++def _restore_audio_lora_targets() -> None:+ """Undo ``train._patch_lora_target_exclude_audio``.++ The face-side patch drops any LoRA target whose path contains+ ``audio_attn`` or ``audio_ff`` — that's correct for face training (random+ gradients corrupt the audio path). For AUDIO training those are exactly+ the targets we want to keep, so we re-bind ``_find_lora_targets`` to the+ underlying upstream implementation.+ """+ import ltx_trainer_mlx.trainer as _trainer++ # The original was captured via closure in the face patch; we can't reach+ # back into it, so re-import the upstream module fresh.+ import importlib+ importlib.reload(_trainer)+ logger.info("audio LoRA: restored upstream _find_lora_targets (audio paths preserved)")+++# ----------------------------------------------------------------------+# Phase 5: discover the final checkpoint + copy to output_path+# ----------------------------------------------------------------------++def find_final_checkpoint(output_dir: Path, expected_step: int) -> Path:+ """Locate ``lora_weights_step_<N>.safetensors`` matching the final step.++ The trainer writes checkpoints under ``<output_dir>/checkpoints/``, named+ ``lora_weights_step_NNNNN.safetensors`` (5-digit zero-padded step).+ """+ ckpt_root = output_dir / "checkpoints"+ if not ckpt_root.exists():+ # Some trainer paths nest checkpoints one level deeper; recurse.+ candidates = list(output_dir.rglob("lora_weights_step_*.safetensors"))+ else:+ candidates = list(ckpt_root.glob("lora_weights_step_*.safetensors"))+ if not candidates:+ candidates = list(output_dir.rglob("lora_weights_step_*.safetensors"))++ if not candidates:+ raise FileNotFoundError(+ f"no lora_weights_step_*.safetensors under {output_dir}"+ )++ def _step_of(p: Path) -> int:+ try:+ return int(p.stem.split("step_")[1])+ except (IndexError, ValueError):+ return -1++ # Prefer the checkpoint matching the final step. If it's missing (e.g. a+ # rounding mismatch between checkpoints.interval and total steps), fall+ # back to the maximum step number we found.+ by_step = {_step_of(p): p for p in candidates}+ if expected_step in by_step:+ return by_step[expected_step]+ max_step = max(by_step)+ logger.warning(+ "exact step %d checkpoint not found; using max step %d (%s)",+ expected_step, max_step, by_step[max_step].name,+ )+ return by_step[max_step]+++# ----------------------------------------------------------------------+# Main pipeline+# ----------------------------------------------------------------------++def run_pipeline(spec_path: Path) -> int:+ spec = load_spec(spec_path)+ job_id: str = spec["job_id"]+ trigger: str = spec["trigger"]++ emit("start", job_id=job_id)+ emit("phase", phase="audio", label="Training voice LoRA")++ # ---- phase 1: validate ----+ validate_inputs(spec)++ audio_path = Path(spec["audio_path"]).resolve()+ dataset_dir = Path(spec["dataset_dir"]).resolve()+ output_path = Path(spec["output_path"]).resolve()+ image_count = int(spec["image_count"])+ audio_steps = int(spec["audio_steps"])+ audio_rank = int(spec["audio_rank"])+ audio_lr = float(spec["audio_lr"])+ slice_seconds = float(spec["audio_slice_seconds"])++ emit(+ "plan",+ trigger=trigger,+ rank=audio_rank,+ alpha=audio_rank,+ steps=audio_steps,+ lr=audio_lr,+ slice_seconds=slice_seconds,+ image_count=image_count,+ target_modules=list(AUDIO_TARGET_MODULES),+ )++ # ---- phase 2: preprocess ----+ try:+ run_preprocess(+ audio_path=audio_path,+ dataset_dir=dataset_dir,+ slice_seconds=slice_seconds,+ )+ except Exception as exc: # noqa: BLE001+ traceback.print_exc(file=sys.stderr)+ emit_error_and_exit("preprocess", str(exc))++ # ---- phase 3: generate audio YAML ----+ audio_train_out_dir = dataset_dir / "audio_train_output"+ audio_yaml_path = dataset_dir / "audio_config.yaml"+ try:+ config_dict = build_audio_config(+ rank=audio_rank,+ steps=audio_steps,+ lr=audio_lr,+ dataset_dir=dataset_dir,+ output_dir=audio_train_out_dir,+ )+ write_audio_yaml(config_dict, audio_yaml_path)+ emit("log", msg=f"wrote audio config: {audio_yaml_path}")+ except Exception as exc: # noqa: BLE001+ traceback.print_exc(file=sys.stderr)+ emit_error_and_exit("config", str(exc))++ # ---- phase 4: train ----+ try:+ checkpoint_path, _train_wall = run_training(+ config_dict=config_dict,+ output_dir=audio_train_out_dir,+ )+ except Exception as exc: # noqa: BLE001+ traceback.print_exc(file=sys.stderr)+ emit_error_and_exit("train", str(exc))++ # ---- phase 5: publish final checkpoint ----+ # trainer.train() already returns the last-saved checkpoint path; double-+ # check by walking the output dir for the exact step number, falling back+ # gracefully if the interval rounding didn't hit the final step exactly.+ try:+ if not checkpoint_path.exists():+ checkpoint_path = find_final_checkpoint(audio_train_out_dir, audio_steps)+ except Exception as exc: # noqa: BLE001+ emit_error_and_exit("publish", f"failed to locate checkpoint: {exc}")++ output_path.parent.mkdir(parents=True, exist_ok=True)+ try:+ shutil.copy2(str(checkpoint_path), str(output_path))+ except Exception as exc: # noqa: BLE001+ emit_error_and_exit("publish", f"failed to copy checkpoint: {exc}")++ emit("done", path=str(output_path))+ return 0+++def main(argv: list[str] | None = None) -> int:+ p = argparse.ArgumentParser(description="LoRA-lab Train Audio pipeline (Phase B)")+ p.add_argument("spec", nargs="?", help="path to job-spec JSON (positional)")+ p.add_argument(+ "--spec", dest="spec_flag",+ help="path to job-spec JSON (flag form, used by Phosphene panel)",+ )+ p.add_argument(+ "--job-id", dest="job_id", default=None,+ help="optional job id label (the spec JSON's own job_id is authoritative)",+ )+ p.add_argument("-v", "--verbose", action="store_true")+ args = p.parse_args(argv)+ if args.spec_flag and not args.spec:+ args.spec = args.spec_flag+ if not args.spec:+ p.error("must provide a job-spec JSON path (positional or via --spec)")++ logging.basicConfig(+ level=logging.DEBUG if args.verbose else logging.INFO,+ format="%(asctime)s %(levelname)s %(name)s | %(message)s",+ stream=sys.stderr, # NEVER pollute stdout — JSON-lines protocol+ )++ try:+ return run_pipeline(Path(args.spec))+ except SystemExit:+ raise+ except Exception as exc: # noqa: BLE001+ traceback.print_exc(file=sys.stderr)+ emit("error", stage="unknown", message=str(exc))+ return 1+++if __name__ == "__main__":+ sys.exit(main())diff --git a/lora_lab/train_character.py b/lora_lab/train_character.pynew file mode 100644index 0000000..1a1bc9f--- /dev/null+++ b/lora_lab/train_character.py@@ -0,0 +1,798 @@+"""Single-shot CLI: run the full Character LoRA pipeline from a job-spec JSON.++This is the orchestration backend for Phosphene's "Train Character" panel.+The panel writes a spec JSON and invokes this module as a subprocess:++ ./scripts/run.sh python -m lora_lab.train_character path/to/spec.json++The CLI streams JSON-lines progress to stdout (one JSON object per line) so+the panel can tail it. The final `.safetensors` is written to the path in+the spec, with a `<lora>.safetensors.json` sidecar of training metadata.++------------------------------------------------------------------------+Stdout protocol (one JSON object per line; ordered, append-only):++ {"event":"start","job_id":"..."}+ {"event":"plan","preset":"medium","rank":32,"alpha":32,"steps":3000,+ "lr":0.0001,"resolution":576,"caption_strategy":"class_word",+ "estimated_wall_s":7234,"image_count":24}+ {"event":"crop_start","total":24}+ {"event":"crop_progress","done":1,"total":24,"path":"..."}+ ...+ {"event":"crop_done"}+ {"event":"preprocess_start","total":24}+ {"event":"preprocess_progress","done":1,"total":24}+ ...+ {"event":"preprocess_done"}+ {"event":"train_start","total_steps":3000,"estimated_wall_s":7200}+ {"event":"train_progress","step":250,"loss":0.512,"eta_s":6300}+ ...+ {"event":"train_done","checkpoint":"/path/to/lora.safetensors"}+ {"event":"sidecar_written","path":"/path/to/lora.safetensors.json"}+ {"event":"done"}++On any failure:++ {"event":"error","stage":"preprocess","message":"..."}+ -> exit code 1++------------------------------------------------------------------------+Spec JSON schema (everything except `advanced` is required):++ {+ "job_id": "char_20260511_134552",+ "trigger": "mrbz07",+ "preset": "quick" | "medium" | "high",+ "images_dir": ".../state/train_character/<job_id>/images",+ "output_lora_path": ".../mlx_models/loras_local/<job_id>/<job_id>.safetensors",+ "advanced": {+ "rank": null | int,+ "alpha": null | int,+ "steps": null | int,+ "lr": null | float,+ "resolution": null | int,+ "caption_strategy": null | "class_word" | "trigger_only" | "auto_caption",+ "crop_strategy": null | "center" // "face_centered" not yet implemented+ }+ }++Null fields fall back to the preset defaults below.++------------------------------------------------------------------------+Presets (validated recipes — do not invent new ones):++ | Field | quick | medium | high |+ |-------------------|------------|------------|------------|+ | rank | 16 | 32 | 32 |+ | alpha | 16 | 32 | 32 |+ | steps | 1500 | 3000 | 5000 |+ | lr | 1.0e-4 | 1.0e-4 | 1.0e-4 |+ | resolution | 576 | 576 | 576 |+ | caption_strategy | class_word | class_word | class_word |+ | target_modules | to_q/k/v/out (all) |++------------------------------------------------------------------------+Wall-time estimator (panel must mirror this byte-for-byte):++ base_step_s = 2.4 # M4 Max 64 GB, 576x576 rank 32+ res_scale = (res / 576.0) ** 2 # per-step time ~ tokens ~ res^2+ rank_scale = 0.95 if rank <= 16 else 1.0+ per_step_s = base_step_s * res_scale * rank_scale++ preprocess_s = 90 + 2.0 * image_count # model load + VAE encode + Gemma+ train_s = steps * per_step_s+ total_s = preprocess_s + train_s+"""++from __future__ import annotations++import argparse+import datetime as _dt+import json+import logging+import os+import shutil+import subprocess+import sys+import tempfile+import time+import traceback+from pathlib import Path+from typing import Any++import yaml++logger = logging.getLogger(__name__)+++# ----------------------------------------------------------------------+# Presets + estimator (both must stay in lockstep with the panel JS mirror)+# ----------------------------------------------------------------------++PRESETS: dict[str, dict[str, Any]] = {+ "quick": {+ "rank": 16, "alpha": 16, "steps": 1500, "lr": 1.0e-4,+ "resolution": 576, "caption_strategy": "class_word",+ },+ "medium": {+ "rank": 32, "alpha": 32, "steps": 3000, "lr": 1.0e-4,+ "resolution": 576, "caption_strategy": "class_word",+ },+ "high": {+ "rank": 32, "alpha": 32, "steps": 5000, "lr": 1.0e-4,+ "resolution": 576, "caption_strategy": "class_word",+ },+}++TARGET_MODULES = ["to_q", "to_k", "to_v", "to_out"]++# Estimator constants — keep in sync with panel mirror.+_BASE_STEP_S = 2.4 # M4 Max 64 GB, 576x576 rank 32+_PREPROCESS_FIXED_S = 90.0 # model load + Gemma init+_PREPROCESS_PER_IMAGE_S = 2.0 # VAE encode per image+++def resolve_preset(preset: str, advanced: dict[str, Any] | None) -> dict[str, Any]:+ """Merge a preset with optional `advanced` overrides. None values fall through."""+ if preset not in PRESETS:+ raise ValueError(f"unknown preset {preset!r}; expected one of {list(PRESETS)}")+ cfg = dict(PRESETS[preset])+ if advanced:+ for k, v in advanced.items():+ if v is not None and k in cfg:+ cfg[k] = v+ return cfg+++def estimate_wall_seconds(image_count: int, preset: str, advanced: dict[str, Any] | None) -> float:+ """Estimate end-to-end wall seconds for a job.++ Formula (panel JS must mirror this exactly):+ per_step_s = 2.4 * (res/576)^2 * (0.95 if rank <= 16 else 1.0)+ preprocess_s = 90 + 2.0 * image_count+ total_s = preprocess_s + steps * per_step_s+ """+ cfg = resolve_preset(preset, advanced)+ res = int(cfg["resolution"])+ rank = int(cfg["rank"])+ steps = int(cfg["steps"])+ res_scale = (res / 576.0) ** 2+ rank_scale = 0.95 if rank <= 16 else 1.0+ per_step_s = _BASE_STEP_S * res_scale * rank_scale+ preprocess_s = _PREPROCESS_FIXED_S + _PREPROCESS_PER_IMAGE_S * image_count+ return preprocess_s + steps * per_step_s+++# ----------------------------------------------------------------------+# Stdout JSON-lines emitter+# ----------------------------------------------------------------------++# Capture the ORIGINAL stdout at import time. The training stage temporarily+# swaps sys.stdout to silence the trainer's prints; emit() must keep writing+# to the real panel-facing stream regardless of those swaps.+_REAL_STDOUT = sys.stdout+++def emit(event: str, **kwargs: Any) -> None:+ """Write one JSON event line to the real stdout, flushed."""+ obj = {"event": event, **kwargs}+ _REAL_STDOUT.write(json.dumps(obj, separators=(",", ":")) + "\n")+ _REAL_STDOUT.flush()+++def emit_error_and_exit(stage: str, message: str, code: int = 1) -> None:+ emit("error", stage=stage, message=message)+ sys.exit(code)+++# ----------------------------------------------------------------------+# Spec validation+# ----------------------------------------------------------------------++_REQUIRED_SPEC_KEYS = ("job_id", "trigger", "preset", "images_dir", "output_lora_path")+++def load_spec(spec_path: Path) -> dict[str, Any]:+ if not spec_path.exists():+ raise FileNotFoundError(f"spec not found: {spec_path}")+ spec = json.loads(spec_path.read_text())++ # ---- compat shim: Phosphene's panel emits a flat-spec shape with+ # different key names than this CLI's canonical schema. Normalize+ # without losing data so both shapes work end-to-end.+ #+ # Panel writes: CLI canonical:+ # output_path → output_lora_path+ # rank/steps/lr/... → advanced.{rank,steps,lr,...} (flat → nested)+ # caption_strategy: → caption_strategy in {class_word, trigger_only,+ # "trigger_simple" auto_caption}; "trigger_simple" was the+ # panel agent's name for class_word.+ if "output_lora_path" not in spec and "output_path" in spec:+ spec["output_lora_path"] = spec["output_path"]+ if not isinstance(spec.get("advanced"), dict):+ spec["advanced"] = {}+ for k in ("rank", "alpha", "steps", "lr", "resolution",+ "caption_strategy", "crop_strategy"):+ if k in spec and k not in spec["advanced"]:+ spec["advanced"][k] = spec[k]+ cs = spec["advanced"].get("caption_strategy")+ if cs == "trigger_simple":+ # Panel-side alias; means "trigger word + a tiny framing hint",+ # which is what class_word does ("salotrn man, close-up portrait").+ spec["advanced"]["caption_strategy"] = "class_word"++ for k in _REQUIRED_SPEC_KEYS:+ if k not in spec:+ raise ValueError(f"spec missing required key: {k!r}")+ return spec+++# ----------------------------------------------------------------------+# Cropping + caption authoring+# ----------------------------------------------------------------------++IMAGE_EXTENSIONS = {".jpg", ".jpeg", ".png", ".webp", ".bmp"}+++def list_source_images(images_dir: Path) -> list[Path]:+ """Sorted list of source image files. Sort by filename to be deterministic."""+ if not images_dir.exists():+ raise FileNotFoundError(f"images dir does not exist: {images_dir}")+ files = sorted(+ f for f in images_dir.iterdir()+ if f.is_file() and f.suffix.lower() in IMAGE_EXTENSIONS+ )+ if not files:+ raise ValueError(f"no images found in {images_dir}")+ return files+++def _framing_for_image(width: int, height: int) -> str:+ return "close-up portrait" if height > width else "medium shot"+++def _make_caption(trigger: str, strategy: str, width: int, height: int) -> str:+ if strategy == "trigger_only":+ return f"a photo of {trigger}"+ # class_word (default) and auto_caption fallback+ framing = _framing_for_image(width, height)+ return f"{trigger} man, {framing}"+++def crop_and_caption(+ source_files: list[Path],+ cropped_dir: Path,+ captions_dir: Path,+ images_renamed_dir: Path,+ trigger: str,+ caption_strategy: str,+ resolution: int,+) -> tuple[list[Path], list[str]]:+ """Center-crop sources to `resolution`x`resolution`, rename sequentially, write captions.++ Returns (renamed_image_paths, caption_strings) in matching order.++ Writes:+ images_renamed_dir/char_NNN.png full-resolution training input (lossless)+ cropped_dir/char_NNN.jpg 1:1 thumbnail (256px) for the UI gallery+ captions_dir/char_NNN.txt caption matching each image stem+ """+ from PIL import Image++ cropped_dir.mkdir(parents=True, exist_ok=True)+ captions_dir.mkdir(parents=True, exist_ok=True)+ images_renamed_dir.mkdir(parents=True, exist_ok=True)++ emit("crop_start", total=len(source_files))++ out_paths: list[Path] = []+ out_captions: list[str] = []++ for i, src in enumerate(source_files, start=1):+ try:+ img = Image.open(src).convert("RGB")+ src_w, src_h = img.size++ # Scale-and-center-crop to a SQUARE at `resolution`. Mirrors the+ # logic in preprocess_images._load_image_as_1frame_tensor (square+ # crop is the right call for char training — the preprocessor will+ # re-crop to whatever target_h/target_w is configured downstream;+ # we keep this square + lossless so the same source can be reused+ # for any preset).+ target = resolution+ scale = max(target / src_w, target / src_h)+ new_w = int(round(src_w * scale))+ new_h = int(round(src_h * scale))+ scaled = img.resize((new_w, new_h), Image.LANCZOS)+ left = (new_w - target) // 2+ top = (new_h - target) // 2+ cropped_full = scaled.crop((left, top, left + target, top + target))++ stem = f"char_{i:03d}"+ png_path = images_renamed_dir / f"{stem}.png"+ cropped_full.save(png_path, format="PNG")++ # Thumbnail for the UI gallery (256x256, jpg, compact).+ thumb = cropped_full.copy()+ thumb.thumbnail((256, 256), Image.LANCZOS)+ thumb_path = cropped_dir / f"{stem}.jpg"+ thumb.save(thumb_path, format="JPEG", quality=88)++ # Honour user-provided captions written to captions_dir by the+ # panel (filename matches the source image stem OR the renamed+ # `char_NNN` stem the panel pre-mapped to). This lets the Train+ # tab ship industry-standard `image_001.png` + `image_001.txt`+ # pairs in LTX `[VISUAL]:` / `[TEXT]:` format without the+ # trainer stomping them with the dumbest-strongest fallback.+ user_cap_paths = [+ captions_dir / f"{stem}.txt", # post-rename match+ captions_dir / f"{src.stem}.txt", # original-stem match+ ]+ user_cap = next((p for p in user_cap_paths if p.is_file()), None)+ if user_cap is not None:+ caption = user_cap.read_text(encoding="utf-8", errors="replace")+ # Re-write at the renamed stem so the preprocess step finds it.+ (captions_dir / f"{stem}.txt").write_text(caption, encoding="utf-8")+ else:+ caption = _make_caption(trigger, caption_strategy, src_w, src_h)+ (captions_dir / f"{stem}.txt").write_text(caption)++ out_paths.append(png_path)+ out_captions.append(caption)++ emit("crop_progress", done=i, total=len(source_files), path=str(png_path))+ except Exception as exc: # noqa: BLE001+ raise RuntimeError(f"failed to crop {src.name}: {exc}") from exc++ emit("crop_done")+ return out_paths, out_captions+++# ----------------------------------------------------------------------+# Preprocess (call the existing module — same env, same VAE encode + Gemma)+# ----------------------------------------------------------------------++def run_preprocess(+ images_dir: Path,+ captions_dir: Path,+ output_root: Path,+ resolution: int,+ total: int,+) -> None:+ """Encode images + captions into the layout PrecomputedDataset expects.++ Calls preprocess_images.preprocess_images() in-process so progress lines+ can be intermixed cleanly. We emit a coarse start/end pair; the inner+ preprocessor logs its own prints to stderr (we route them away from+ stdout to keep the JSON-lines stream pure).+ """+ from lora_lab import preprocess_images as pp # local import — heavy deps++ emit("preprocess_start", total=total)++ # Pipe inner module's stdout into stderr so JSON-lines on our stdout+ # stay clean. The preprocessor uses bare print(); duplicate fd2.+ orig_stdout = sys.stdout+ try:+ sys.stdout = sys.stderr # redirect prints inside the call+ pp.preprocess_images(+ images_dir=str(images_dir),+ output_dir=str(output_root),+ target_height=resolution,+ target_width=resolution,+ captions_dir=str(captions_dir),+ caption_ext=".txt",+ )+ finally:+ sys.stdout = orig_stdout++ # The inner module already wrote one latent_NNNN.safetensors per image+ # into output_root/.precomputed/latents/. Verify count.+ latents_dir = output_root / ".precomputed" / "latents"+ written = sorted(latents_dir.glob("latent_*.safetensors"))+ if len(written) != total:+ raise RuntimeError(+ f"preprocess wrote {len(written)} latents; expected {total}"+ )+ emit("preprocess_progress", done=total, total=total)+ emit("preprocess_done")+++# ----------------------------------------------------------------------+# Training (build a temp YAML, hand to the existing trainer wrapper logic)+# ----------------------------------------------------------------------++DEFAULT_MODEL_PATH = (+ "/Users/salo/.cache/huggingface/hub/models--dgrauet--ltx-2.3-mlx-q4"+ "/snapshots/53a6f5f39d9c074bc73e6a18ba391f40ddffaa68"+)+DEFAULT_TEXT_ENCODER = "mlx-community/gemma-3-12b-it-4bit"+++def build_trainer_config(+ *,+ cfg: dict[str, Any],+ data_root: Path,+ output_dir: Path,+) -> dict[str, Any]:+ """Compose the LtxTrainerConfig dict from a resolved preset + paths."""+ return {+ "model": {+ "model_path": DEFAULT_MODEL_PATH,+ "text_encoder_path": DEFAULT_TEXT_ENCODER,+ "training_mode": "lora",+ },+ "lora": {+ "rank": int(cfg["rank"]),+ "alpha": int(cfg["alpha"]),+ "dropout": 0.0,+ "target_modules": list(TARGET_MODULES),+ },+ "optimization": {+ "learning_rate": float(cfg["lr"]),+ "steps": int(cfg["steps"]),+ "batch_size": 1,+ "gradient_accumulation_steps": 1,+ "max_grad_norm": 1.0,+ "weight_decay": 0.0,+ "scheduler_type": "constant",+ },+ "data": {+ "preprocessed_data_root": str(data_root),+ },+ "training_strategy": {+ "name": "text_to_video",+ "generate_audio": False,+ },+ "flow_matching": {+ "timestep_sampling_mode": "shifted_logit_normal",+ },+ "validation": {+ "prompts": [],+ "interval": None,+ "skip_initial_validation": True,+ "generate_audio": False,+ },+ "checkpoints": {+ # Save every ~10% of total steps so the user has fallbacks if a long+ # run is interrupted, but keep at least one mid-run checkpoint.+ "interval": max(1, int(cfg["steps"]) // 5),+ "keep_last_n": 2,+ },+ "seed": 42,+ "output_dir": str(output_dir),+ }+++def run_training(+ *,+ cfg: dict[str, Any],+ data_root: Path,+ output_dir: Path,+ estimated_wall_s: float,+) -> tuple[Path, float]:+ """Run the trainer in-process. Returns (final_checkpoint_path, wall_seconds).++ We call the trainer with a step_callback so we can emit per-step progress+ without parsing tqdm output.+ """+ # Late imports — keep CLI start cheap.+ from ltx_trainer_mlx.config import LtxTrainerConfig+ from ltx_trainer_mlx.trainer import LtxvTrainer+ from lora_lab import train as lab_train++ config_dict = build_trainer_config(cfg=cfg, data_root=data_root, output_dir=output_dir)+ config = LtxTrainerConfig.model_validate(config_dict)++ # Apply the same patches train.py uses: dev transformer + image-only safety+ # + fps→frame_rate kwarg shim + audio-attn exclusion. These all run as+ # cheap monkey-patches before LtxvTrainer is instantiated.+ lab_train._patch_loader_prefer_dev_transformer()+ lab_train._patch_strategy_for_image_only()+ lab_train._patch_compute_video_positions_fps_kwarg()+ lab_train._patch_lora_target_exclude_audio()++ total_steps = int(cfg["steps"])+ emit("train_start", total_steps=total_steps, estimated_wall_s=int(estimated_wall_s))++ train_start = time.time()+ last_emit_step = 0+ # Roughly every ~2% of total steps, with bounds [10, 250].+ emit_every = max(10, min(250, total_steps // 50 or 10))+ last_loss: float | None = None++ # Sniff per-step loss without forking the trainer: monkey-patch+ # TrainingProgress.update_training. It always gets called (even with+ # disable_progress_bars=True the method runs and just no-ops the UI).+ import ltx_trainer_mlx.progress as tp_mod # type: ignore++ _orig_update = tp_mod.TrainingProgress.update_training++ def _sniff_update(self, *, loss, lr, step_time, advance=True): # noqa: ANN001+ nonlocal last_loss+ try:+ last_loss = float(loss)+ except Exception: # noqa: BLE001+ pass+ return _orig_update(self, loss=loss, lr=lr, step_time=step_time, advance=advance)++ tp_mod.TrainingProgress.update_training = _sniff_update++ def _cb(step: int, total: int, _videos: list[Path]) -> None:+ nonlocal last_emit_step+ if step - last_emit_step < emit_every and step != total:+ return+ last_emit_step = step+ elapsed = time.time() - train_start+ # Defensive: avoid div-by-zero on step 0.+ eta = 0+ if step > 0:+ per_step = elapsed / step+ eta = max(0, int(per_step * (total - step)))+ loss_val = round(last_loss, 4) if last_loss is not None else None+ emit(+ "train_progress",+ step=step,+ loss=loss_val,+ eta_s=eta,+ )+ # Panel-side alias: mlx_ltx_panel.py parses {"event":"step"} with+ # {step, total, loss} fields and renders the progress bar from it.+ emit("step", step=step, total=total, loss=loss_val, eta_s=eta)++ # Silence the trainer's own logging to stdout — only our JSON-lines should+ # reach stdout. Send everything else to stderr so it's still capturable.+ for noisy in (+ "ltx_trainer_mlx",+ "ltx_trainer_mlx.trainer",+ "ltx_core_mlx",+ ):+ logging.getLogger(noisy).propagate = False++ # Redirect generic prints from the trainer to stderr.+ orig_stdout = sys.stdout+ try:+ sys.stdout = sys.stderr+ trainer = LtxvTrainer(config)+ saved_path, _stats = trainer.train(disable_progress_bars=True, step_callback=_cb)+ finally:+ sys.stdout = orig_stdout++ train_wall = time.time() - train_start+ emit("train_done", checkpoint=str(saved_path))+ # Panel-side alias for the same milestone.+ emit("checkpoint", path=str(saved_path))+ return Path(saved_path), train_wall+++# ----------------------------------------------------------------------+# Sidecar+# ----------------------------------------------------------------------++def write_sidecar(+ *,+ lora_path: Path,+ cfg: dict[str, Any],+ trigger: str,+ image_count: int,+ training_wall_s: float,+) -> Path:+ sidecar_path = lora_path.with_suffix(lora_path.suffix + ".json")+ payload = {+ "trigger": trigger,+ "preset": cfg.get("preset_name"),+ "rank": int(cfg["rank"]),+ "alpha": int(cfg["alpha"]),+ "steps": int(cfg["steps"]),+ "lr": float(cfg["lr"]),+ "resolution": int(cfg["resolution"]),+ "image_count": image_count,+ "caption_strategy": cfg["caption_strategy"],+ "training_wall_seconds": round(float(training_wall_s), 1),+ "created_at": _dt.datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ"),+ "base_model": "Lightricks/LTX-2.3 (dgrauet/ltx-2.3-mlx-q4 dev transformer)",+ "training_resolution": [int(cfg["resolution"]), int(cfg["resolution"])],+ "lora_lab_version": "iter5",+ "loadable_via": "ltx_core_mlx.loader.fuse_loras.apply_loras",+ }+ sidecar_path.write_text(json.dumps(payload, indent=2))+ emit("sidecar_written", path=str(sidecar_path))+ return sidecar_path+++# ----------------------------------------------------------------------+# Main pipeline+# ----------------------------------------------------------------------++def run_pipeline(spec_path: Path) -> int:+ spec = load_spec(spec_path)+ job_id: str = spec["job_id"]+ trigger: str = spec["trigger"]+ preset: str = spec["preset"]+ images_dir = Path(spec["images_dir"]).resolve()+ output_lora_path = Path(spec["output_lora_path"]).resolve()+ advanced = spec.get("advanced") or {}++ emit("start", job_id=job_id)++ # Resolve preset + overrides.+ cfg = resolve_preset(preset, advanced)+ cfg["preset_name"] = preset+ caption_strategy = cfg["caption_strategy"]+ # The Phosphene panel speaks a slightly different caption_strategy+ # vocabulary than the trainer (historical reasons — panel evolved+ # around CivitAI conventions; trainer around dreambooth). Map the+ # panel names to ours:+ # * 'trigger_simple' — panel's name for the fallback that writes+ # `<trigger> man` for every image. Equivalent to our 'class_word'.+ # * 'user_provided' — panel asserts every image has a `.txt`+ # sidecar (verified in /train/start). The crop step above already+ # honors those files; `caption_strategy` here only governs the+ # fallback path for images WITHOUT a sidecar, which by definition+ # won't fire when 'user_provided' is set. Aliasing to 'class_word'+ # keeps the fallback sensible if the contract is ever broken+ # (e.g. a sidecar is deleted between /train/start validation and+ # the crop loop reading it).+ _PANEL_CAPTION_STRATEGY_ALIASES = {+ "trigger_simple": "class_word",+ "user_provided": "class_word",+ }+ if caption_strategy in _PANEL_CAPTION_STRATEGY_ALIASES:+ original = caption_strategy+ caption_strategy = _PANEL_CAPTION_STRATEGY_ALIASES[caption_strategy]+ cfg["caption_strategy"] = caption_strategy+ emit(+ "log",+ line=f"caption_strategy: panel-alias {original!r} → {caption_strategy!r}",+ )+ if caption_strategy == "auto_caption":+ # Deferred — fall back to class_word with a warning.+ emit(+ "warning",+ stage="caption",+ message="auto_caption deferred; falling back to class_word",+ )+ cfg["caption_strategy"] = "class_word"+ caption_strategy = "class_word"+ if caption_strategy not in {"class_word", "trigger_only"}:+ emit_error_and_exit(+ "caption", f"unknown caption_strategy: {caption_strategy!r}"+ )++ crop_strategy = advanced.get("crop_strategy") or "center"+ if crop_strategy != "center":+ emit(+ "warning",+ stage="crop",+ message=f"crop_strategy={crop_strategy!r} not implemented; using center",+ )++ # Validate resolution.+ resolution = int(cfg["resolution"])+ if resolution % 32 != 0:+ emit_error_and_exit(+ "config", f"resolution {resolution} must be divisible by 32"+ )++ # Source images.+ try:+ source_files = list_source_images(images_dir)+ except Exception as exc: # noqa: BLE001+ emit_error_and_exit("ingest", str(exc))++ image_count = len(source_files)++ estimated_wall_s = estimate_wall_seconds(image_count, preset, advanced)+ emit(+ "plan",+ preset=preset,+ rank=int(cfg["rank"]),+ alpha=int(cfg["alpha"]),+ steps=int(cfg["steps"]),+ lr=float(cfg["lr"]),+ resolution=resolution,+ caption_strategy=caption_strategy,+ estimated_wall_s=int(estimated_wall_s),+ image_count=image_count,+ )++ # Lay out the job workspace alongside the source images. The panel writes+ # spec.json into state/train_character/<job_id>/, and `images_dir` lives+ # at .../<job_id>/images. We park our derived data under the same parent.+ job_root = images_dir.parent+ cropped_dir = job_root / "cropped"+ captions_dir = job_root / "captions"+ images_renamed_dir = job_root / "images_renamed"+ data_root = job_root / "training_data"+ train_out_dir = job_root / "train_output"++ try:+ renamed, _captions = crop_and_caption(+ source_files=source_files,+ cropped_dir=cropped_dir,+ captions_dir=captions_dir,+ images_renamed_dir=images_renamed_dir,+ trigger=trigger,+ caption_strategy=caption_strategy,+ resolution=resolution,+ )+ except Exception as exc: # noqa: BLE001+ traceback.print_exc(file=sys.stderr)+ emit_error_and_exit("crop", str(exc))++ try:+ run_preprocess(+ images_dir=images_renamed_dir,+ captions_dir=captions_dir,+ output_root=data_root,+ resolution=resolution,+ total=len(renamed),+ )+ except Exception as exc: # noqa: BLE001+ traceback.print_exc(file=sys.stderr)+ emit_error_and_exit("preprocess", str(exc))++ try:+ checkpoint_path, training_wall_s = run_training(+ cfg=cfg,+ data_root=data_root,+ output_dir=train_out_dir,+ estimated_wall_s=estimated_wall_s,+ )+ except Exception as exc: # noqa: BLE001+ traceback.print_exc(file=sys.stderr)+ emit_error_and_exit("train", str(exc))++ # Move the checkpoint to the spec's output path.+ output_lora_path.parent.mkdir(parents=True, exist_ok=True)+ try:+ shutil.copy2(str(checkpoint_path), str(output_lora_path))+ except Exception as exc: # noqa: BLE001+ emit_error_and_exit("publish", f"failed to copy checkpoint: {exc}")++ try:+ write_sidecar(+ lora_path=output_lora_path,+ cfg=cfg,+ trigger=trigger,+ image_count=image_count,+ training_wall_s=training_wall_s,+ )+ except Exception as exc: # noqa: BLE001+ emit_error_and_exit("sidecar", str(exc))++ emit("done")+ return 0+++def main(argv: list[str] | None = None) -> int:+ p = argparse.ArgumentParser(description="LoRA-lab Train Character pipeline")+ p.add_argument("spec", nargs="?", help="path to job-spec JSON (positional)")+ p.add_argument("--spec", dest="spec_flag", help="path to job-spec JSON (flag form, used by Phosphene panel)")+ p.add_argument("--job-id", dest="job_id", default=None,+ help="optional job id label (used by Phosphene panel; the spec JSON's own job_id field is authoritative)")+ p.add_argument("-v", "--verbose", action="store_true")+ args = p.parse_args(argv)+ if args.spec_flag and not args.spec:+ args.spec = args.spec_flag+ if not args.spec:+ p.error("must provide a job-spec JSON path (positional or via --spec)")++ logging.basicConfig(+ level=logging.DEBUG if args.verbose else logging.INFO,+ format="%(asctime)s %(levelname)s %(name)s | %(message)s",+ stream=sys.stderr, # NEVER pollute stdout — JSON-lines protocol+ )++ try:+ return run_pipeline(Path(args.spec))+ except SystemExit:+ raise+ except Exception as exc: # noqa: BLE001+ traceback.print_exc(file=sys.stderr)+ emit("error", stage="unknown", message=str(exc))+ return 1+++if __name__ == "__main__":+ sys.exit(main())diff --git a/mlx_ltx_panel.py b/mlx_ltx_panel.pyindex 32f3c6c..7495425 100644--- a/mlx_ltx_panel.py+++ b/mlx_ltx_panel.py@@ -712,8 +712,21 @@ def _safe_loras_dir() -> Path:# so the existing Now / Queue / Recent / Logs surfaces light up.TRAIN_DIR = STATE_DIR / "train_character"-LORA_LAB_ROOT = Path("/Users/salo/AI/projects/lora-lab")-LORA_LAB_RUN_SH = LORA_LAB_ROOT / "scripts" / "run.sh"+# Vendored 2026-05-17: lora_lab is now a top-level package shipped with+# the panel (lora_lab/), so installer-only users get training out of+# the box without cloning a separate repo. The env shim+# (scripts/lora_lab_run.sh) sets PYTHONPATH=$PANEL_ROOT so `python -m+# lora_lab.train_character` resolves the vendored copy.+#+# `LTX_LORA_LAB_ROOT` env var still lets a power user point at an+# external lora-lab checkout (e.g. the AI/projects/lora-lab dev tree)+# without editing this file — useful while iterating on the lab code+# without re-vendoring.+LORA_LAB_ROOT = Path(os.environ.get("LTX_LORA_LAB_ROOT", str(ROOT)))+LORA_LAB_RUN_SH = Path(+ os.environ.get("LTX_LORA_LAB_RUN_SH",+ str(ROOT / "scripts" / "lora_lab_run.sh"))+)# Quality preset → training hyperparams. The lab's train_character.py reads# these out of the spec JSON; the values here are the contract surface. Thediff --git a/scripts/lora_lab_run.sh b/scripts/lora_lab_run.shnew file mode 100755index 0000000..f65d85c--- /dev/null+++ b/scripts/lora_lab_run.sh@@ -0,0 +1,65 @@+#!/usr/bin/env bash+# Env shim for the panel-vendored lora_lab module. Sets the right+# PYTHONPATH + ffmpeg PATH + LTX-2.3 GPU watchdog overrides, then execs+# whatever command was passed.+#+# Was previously sourced from a separate lora-lab repo on Salo's dev+# machine; vendored into the panel tree 2026-05-17 so an installer-only+# user gets training out of the box without cloning a second repo.+#+# Example:+# ./scripts/lora_lab_run.sh python -m lora_lab.train_character \+# --spec <spec.json> --job-id <id>++set -euo pipefail++# PANEL_ROOT = the phosphene-dev.git checkout this script lives in.+PANEL_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"+LTX_ROOT="$PANEL_ROOT/ltx-2-mlx"+LTX_PY="$LTX_ROOT/env/bin/python"++# ffmpeg is shipped with Pinokio at this fixed path on the dev machine.+# Allow override for non-Pinokio installs.+FFMPEG_DIR="${PHOSPHENE_FFMPEG_DIR:-/Users/salo/pinokio/bin/ffmpeg-env/bin}"++if [[ ! -x "$LTX_PY" ]]; then+ echo "fatal: ltx-2-mlx env python not found at $LTX_PY" >&2+ exit 1+fi+if [[ ! -x "$FFMPEG_DIR/ffmpeg" ]]; then+ echo "fatal: ffmpeg not found at $FFMPEG_DIR/ffmpeg (override with PHOSPHENE_FFMPEG_DIR)" >&2+ exit 1+fi++export PATH="$FFMPEG_DIR:$PATH"+# Vendored lora_lab sits at $PANEL_ROOT/lora_lab/, importable as a+# top-level package when $PANEL_ROOT is on PYTHONPATH. ltx-trainer-mlx+# stays where it is inside the ltx-2-mlx package tree.+export PYTHONPATH="$PANEL_ROOT:$LTX_ROOT/packages/ltx-trainer/src:${PYTHONPATH:-}"++# Disable the lazy-graph eval splitters added in ltx-2-mlx 0897e7d.+# That commit forces mx.eval() every 8 DiT blocks (and every Gemma+# layer) to dodge the macOS GPU watchdog on M2 Max 64 GB. For inference+# on those machines it's a real fix.+#+# But for training on this M4 Max it's catastrophic: every forced+# materialization allocates+evicts Metal buffers mid-graph, the working+# set never settles, RSS stays tiny while the whole 11 GB transformer+# thrashes through mmap. Per-step time goes from 3 s to >10 min.+#+# The commit's own message documents the escape hatch:+# LTX2_GEMMA_EVAL_EVERY=0 and LTX2_DIT_EVAL_EVERY=0 recover full+# lazy-graph pipelining on Mac Studio / M-series Ultra. Default both to+# 0 for any lora_lab command; caller can still override (e.g. for a+# smaller-RAM render).+export LTX2_GEMMA_EVAL_EVERY="${LTX2_GEMMA_EVAL_EVERY:-0}"+export LTX2_DIT_EVAL_EVERY="${LTX2_DIT_EVAL_EVERY:-0}"++# If the first arg is "python" / "python3", swap it for the ltx env's+# python. Lets callers write `./scripts/lora_lab_run.sh python -m ...`+# without knowing the full env path.+if [[ "${1:-}" == "python" || "${1:-}" == "python3" ]]; then+ shift+ exec "$LTX_PY" "$@"+fi+exec "$@"