Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: implement the LTX-2.5 IC spatial upscale recipe on the Windows CUDA runner (#6513)
[._.]/ Adam Eivyee383fe2b193
diff --git a/scripts/_upscale_contract.py b/scripts/_upscale_contract.pynew file mode 100644index 0000000000..ae71e4f43d--- /dev/null+++ b/scripts/_upscale_contract.py@@ -0,0 +1,265 @@+"""The argv, grid and adapter contract both generative video-upscale runners share.++#6511 promises ONE argument set for both backends: `buildLtxUpscaleArgs()` in+`server/services/videoGen/renderArgs.js` emits a single argv whichever runtime+the plan resolved, and only the interpreter and script path differ. #6512 (MLX)+and #6513 (CUDA) each implement that contract against a different runtime, so a+second copy of it in each runner would be two tables free to drift — exactly the+failure the flag-passed reference bounds already exist to prevent.++What lives here is the part that is genuinely identical: the parser, the model+grid, and the header-only reads of the IC-LoRA adapter. What stays with each+runner is what actually differs — the runtime it imports, the host it gates on,+the pack layout it validates, and the rename maps its own loader fuses through.++Everything here is stdlib-only, deliberately. These are the checks that run+BEFORE a GPU, an MLX wheel, or a 68 GB model pack is committed, which is what+makes the whole contract testable on a machine that has none of them.+"""++from __future__ import annotations++import argparse+import json+import struct+from pathlib import Path++# The LTX-2.5 two-stage grid, mirrored from `LTX_GRID` in+# `server/services/videoGen/upscalePlan.js` and confirmed against both runtimes:+# stage 1 renders at `height // 2` / `width // 2` and the video VAE compresses+# spatially by 32, so the OUTPUT axis must be divisible by 64 (upstream's own+# `assert_resolution(..., is_two_stage=True)` asserts exactly that). Temporal+# compression is 8 and the reference encoder needs a (1 + 8k)-frame input, so+# `frames % 8 == 1` with a floor of 9.+SPATIAL_MULTIPLE = 64+FRAME_MODULUS = 8+FRAME_REMAINDER = 1+MIN_FRAMES = 9++# Stage 1 renders at half the requested output, and it is those halved dims the+# IC encoder divides by `reference_downscale_factor`.+STAGE1_DIVISOR = 2++# The upscale contract carries no prompt (#6511): the source clip is the whole+# conditioning signal, and inventing text steering would push synthesized detail+# toward content the user never asked for. The empty string is the neutral+# choice — the distilled schedule runs no CFG, so the prompt is pure+# conditioning rather than a guidance pole. `--prompt` exists so #6514's+# verification matrix can probe the effect without changing the argv contract.+DEFAULT_PROMPT = ""++# Full reference conditioning: unlike a control/pose IC render, the reference+# here is the picture itself, so there is nothing to attenuate.+REFERENCE_STRENGTH = 1.0++# A real safetensors header is a few KB to low-MB; anything past this is a+# corrupt length we refuse to allocate for. Mirrors the same bound in+# `server/lib/safetensors.js`.+MAX_HEADER_BYTES = 100 * 1024 * 1024++_LORA_HALVES = ("lora_A", "lora_B")+++def add_upscale_arguments(parser: argparse.ArgumentParser, *, model_help: str) -> argparse.ArgumentParser:+ """Declare the flags `buildLtxUpscaleArgs()` emits, in one place.++ The pass is an IC-LoRA render whose single reference IS the clip being+ upscaled, which is why the alphabet is the IC one rather than a second+ vocabulary. The reference-count bounds arrive as flags because+ `server/lib/icLoraWeights.js` is the single source of truth across both+ languages — a Python-side default would be a second table free to drift.++ Only `--model`'s help text differs between backends: one names an MLX pack,+ the other a split CUDA snapshot.+ """+ parser.add_argument("--model", required=True, help=model_help)+ parser.add_argument("--ic-lora-path", required=True,+ help="local .safetensors of the Pixel Spatial Upscaler adapter")+ parser.add_argument("--ic-reference", action="append", default=[],+ help="the clip being upscaled, already aligned to the model grid")+ parser.add_argument("--ic-min-references", type=int, required=True)+ parser.add_argument("--ic-max-references", type=int, required=True)+ parser.add_argument("--width", type=int, required=True)+ parser.add_argument("--height", type=int, required=True)+ parser.add_argument("--num-frames", type=int, required=True)+ parser.add_argument("--fps", type=float, required=True)+ parser.add_argument("--seed", type=int, required=True)+ parser.add_argument("--prompt", default=DEFAULT_PROMPT)+ parser.add_argument("--output", required=True)+ return parser+++def validate_args(args: argparse.Namespace) -> None:+ """Everything checkable before a GPU is committed.++ Both backends refuse the same sources, and both refuse them the same way a+ direct/script caller would hit — so a queue replay, a hand-run helper and+ the route all get one answer. Every refusal is a `SystemExit` string the+ queue surfaces verbatim.+ """+ if args.width % SPATIAL_MULTIPLE or args.height % SPATIAL_MULTIPLE:+ raise SystemExit(+ f"The two-stage LTX-2.5 pipeline requires width and height divisible by {SPATIAL_MULTIPLE}; "+ f"got {args.width}x{args.height}."+ )+ if args.num_frames < MIN_FRAMES or args.num_frames % FRAME_MODULUS != FRAME_REMAINDER:+ raise SystemExit(+ f"LTX-2.5 num-frames must be at least {MIN_FRAMES} and satisfy "+ f"frames % {FRAME_MODULUS} == {FRAME_REMAINDER}; got {args.num_frames}."+ )+ if not args.fps > 0:+ raise SystemExit(f"--fps must be positive; got {args.fps}.")+ if args.seed < 0:+ raise SystemExit(f"--seed must be non-negative; got {args.seed}.")++ lo, hi = args.ic_min_references, args.ic_max_references+ if lo < 1 or hi < lo:+ raise SystemExit(+ f"--ic-min-references/--ic-max-references must satisfy 1 <= min <= max; got {lo}/{hi}"+ )+ references = list(args.ic_reference or [])+ if not (lo <= len(references) <= hi):+ expected = f"exactly {lo}" if lo == hi else f"{lo}-{hi}"+ raise SystemExit(+ f"The upscale adapter needs {expected} --ic-reference clip(s); got {len(references)}"+ )+ for reference in references:+ if not Path(reference).is_file():+ raise SystemExit(f"--ic-reference does not exist: {reference}")++ # A path, never a repo id. Both runtimes' LoRA resolvers fall back to a+ # remote fetch for anything that is not an existing file, which for this+ # gated adapter is a 401 deep inside a render — and for any repo, a pull+ # PortOS never announced. The download surface owns every fetch.+ if not Path(args.ic_lora_path).is_file():+ raise SystemExit(+ f"The Pixel Spatial Upscaler adapter is not on disk at {args.ic_lora_path} — "+ "download it from the Video Gen model panel before upscaling."+ )+++def read_safetensors_header(path: str) -> "dict | None":+ """Parse a safetensors JSON header with the stdlib alone.++ Deliberately not `safetensors.safe_open`: this runs during validation, in a+ bare interpreter, before any runtime import — which is what keeps the whole+ argument contract testable without an MLX or torch wheel. Returns None for a+ missing, truncated, or non-safetensors file rather than raising, so the+ caller states the refusal in its own words.+ """+ try:+ with open(path, "rb") as handle:+ raw_len = handle.read(8)+ if len(raw_len) < 8:+ return None+ header_len = struct.unpack("<Q", raw_len)[0]+ if header_len <= 0 or header_len > MAX_HEADER_BYTES:+ return None+ raw = handle.read(header_len)+ if len(raw) < header_len:+ return None+ parsed = json.loads(raw.decode("utf-8"))+ return parsed if isinstance(parsed, dict) else None+ except (OSError, ValueError, struct.error):+ return None+++def reference_downscale_factor(header: "dict | None") -> int:+ """The adapter's declared `reference_downscale_factor`, defaulting to 1.++ Matches `read_lora_reference_downscale_factor` in both runtimes, which is+ what the pipeline uses as the real value. Read here too so the resolution+ rule can be stated BEFORE a multi-minute render commits to it — and so+ PortOS can record the measured factor rather than the `null` its registry+ honestly holds for a gated weight nobody has opened yet.+ """+ metadata = (header or {}).get("__metadata__")+ if not isinstance(metadata, dict):+ return 1+ try:+ scale = int(metadata.get("reference_downscale_factor", 1))+ except (TypeError, ValueError):+ return 1+ return scale if scale >= 1 else 1+++def assert_reference_scale_fits(scale: int, width: int, height: int) -> None:+ """Enforce the adapter's own resolution rule on the STAGE-1 dimensions.++ `append_ic_lora_reference_video_conditionings` divides the dims it is HANDED+ by the factor, and both pipelines hand it `height // 2` / `width // 2`.+ Stating the rule in OUTPUT terms is what makes the message actionable — the+ user picked an output size, not a stage size.+ """+ if scale <= 1:+ return+ stage_h, stage_w = height // STAGE1_DIVISOR, width // STAGE1_DIVISOR+ if stage_h % scale == 0 and stage_w % scale == 0:+ return+ required = scale * STAGE1_DIVISOR+ raise SystemExit(+ f"This adapter downscales its reference by {scale}, so the output dimensions must be "+ f"divisible by {required}; got {width}x{height}."+ )+++def lora_target_keys(names) -> "set[str]":+ """Base-weight keys an adapter can fuse into, from its ALREADY-RENAMED names.++ Both loaders pair `<prefix>.lora_A.weight` with `<prefix>.lora_B.weight` and+ skip a prefix missing either half (`_products_for_sd_key` on torch,+ `_prepare_deltas` on MLX), so a half-pair contributes nothing and must not+ count as coverage. Takes renamed names rather than raw ones on purpose: the+ ComfyUI rename table belongs to the runtime, and copying it here would be a+ second table free to drift from the one that actually fuses.+ """+ prefixes = {half: set() for half in _LORA_HALVES}+ for name in names:+ for half, bucket in prefixes.items():+ suffix = f".{half}.weight"+ if isinstance(name, str) and name.endswith(suffix):+ bucket.add(name[: -len(suffix)])+ return {f"{prefix}.weight" for prefix in prefixes["lora_A"] & prefixes["lora_B"]}+++def entry_shape(entry) -> "tuple[int, ...] | None":+ """One safetensors header entry's tensor shape, or None when it has no usable one.++ Total on purpose: a header is untrusted input read before any runtime+ validates it, so a malformed entry yields None and the caller decides+ whether that is a refusal or simply a key it does not care about.+ """+ shape = entry.get("shape") if isinstance(entry, dict) else None+ if not isinstance(shape, list) or not all(isinstance(n, int) for n in shape):+ return None+ return tuple(shape)+++def lora_delta_shapes(header: "dict | None", rename) -> "dict[str, tuple[int, int, int, int]]":+ """Per-target `(out_features, in_features, rank_a, rank_b)` for each fusable pair.++ A safetensors header carries every tensor's shape, so the delta `B @ A` a+ fusion would produce is fully described without reading one byte of tensor+ data. That is what lets a runner check an adapter NUMERICALLY — against the+ weights it claims to address — rather than settling for "the load raised+ nothing", which on both runtimes it never would.++ `rename` is the runtime's own key mapping; a key it rejects yields None and+ is dropped, exactly as the loader drops it.+ """+ renamed = {}+ for raw, entry in (header or {}).items():+ if raw == "__metadata__":+ continue+ name = rename(raw)+ if isinstance(name, str):+ renamed[name] = entry+ shapes = {}+ for target in lora_target_keys(renamed):+ prefix = target[: -len(".weight")]+ a = entry_shape(renamed.get(f"{prefix}.lora_A.weight"))+ b = entry_shape(renamed.get(f"{prefix}.lora_B.weight"))+ if a is None or b is None or len(a) != 2 or len(b) != 2:+ continue+ shapes[target] = (b[0], a[1], a[0], b[1])+ return shapesdiff --git a/scripts/upscale_ltx25.py b/scripts/upscale_ltx25.pyindex e960bc56cf..e205d81d79 100755--- a/scripts/upscale_ltx25.py+++ b/scripts/upscale_ltx25.py@@ -43,53 +43,31 @@ rules it fork-specific, and the current pins take no such arguments.from __future__ import annotationsimport argparse-import jsonimport platform-import structimport sysfrom pathlib import Pathsys.path.insert(0, str(Path(__file__).resolve().parent))from _runner_common import emit_runtime_fingerprint, heartbeat # noqa: E402+# The argv, grid and adapter contract this runner shares with the CUDA one+# (#6513). Re-exported names stay module attributes, so a caller — or a test —+# still reaches them as `upscale_ltx25.validate_args` / `.lora_target_keys`.+from _upscale_contract import ( # noqa: E402+ REFERENCE_STRENGTH,+ add_upscale_arguments,+ assert_reference_scale_fits,+ lora_target_keys,+ read_safetensors_header,+ reference_downscale_factor,+ validate_args,+)# The 2.5 pack's own prompt conditioner. Its absence is a hard refusal rather# than a fallback — see the module docstring.TEXT_ENCODER_DIRNAME = "text_encoder"-# The LTX-2.5 two-stage grid, mirrored from `LTX_GRID` in-# `server/services/videoGen/upscalePlan.js` and confirmed against the runtime:-# Stage 1 renders at `height // 2` / `width // 2` and the video VAE's spatial-# compression is 32 (`compute_video_latent_shape`), so the OUTPUT axis must be-# divisible by 64. The temporal compression is 8 and the reference encoder-# needs a (1 + 8k)-frame input, so `frames % 8 == 1` with a floor of 9.-SPATIAL_MULTIPLE = 64-FRAME_MODULUS = 8-FRAME_REMAINDER = 1-MIN_FRAMES = 9--# Stage 1 renders at half the requested output, and it is those halved dims the-# IC encoder divides by `reference_downscale_factor`.-STAGE1_DIVISOR = 2--# The upscale contract carries no prompt (#6511): the source clip is the whole-# conditioning signal, and inventing text steering would push synthesized-# detail toward content the user never asked for. The empty string is the-# neutral choice — the distilled schedule runs no CFG, so the prompt is pure-# conditioning rather than a guidance pole. `--prompt` exists so #6514's-# verification matrix can probe the effect without changing the argv contract.-DEFAULT_PROMPT = ""--# Full reference conditioning: unlike a control/pose IC render, the reference-# here is the picture itself, so there is nothing to attenuate.-REFERENCE_STRENGTH = 1.0-FINGERPRINT_PACKAGES = ["ltx_pipelines_mlx", "ltx_core_mlx", "mlx", "mlx_metal"]-# A real safetensors header is a few KB to low-MB; anything past this is a-# corrupt length we refuse to allocate for. Mirrors the same bound in-# `server/lib/safetensors.js`.-MAX_HEADER_BYTES = 100 * 1024 * 1024-def log(message: str) -> None:print(message, file=sys.stderr, flush=True)@@ -97,89 +75,12 @@ def log(message: str) -> None:def parse_args(argv: "list[str] | None" = None) -> argparse.Namespace:parser = argparse.ArgumentParser(description="LTX-2.5 MLX generative video upscale")- parser.add_argument("--model", required=True,- help="local snapshot directory of the pinned LTX-2.5 MLX pack "- "(resolved cache-only by PortOS; never a repo id)")- parser.add_argument("--ic-lora-path", required=True,- help="local .safetensors of the Pixel Spatial Upscaler adapter")- parser.add_argument("--ic-reference", action="append", default=[],- help="the clip being upscaled, already aligned to the model grid")- parser.add_argument("--ic-min-references", type=int, required=True)- parser.add_argument("--ic-max-references", type=int, required=True)- parser.add_argument("--width", type=int, required=True)- parser.add_argument("--height", type=int, required=True)- parser.add_argument("--num-frames", type=int, required=True)- parser.add_argument("--fps", type=float, required=True)- parser.add_argument("--seed", type=int, required=True)- parser.add_argument("--prompt", default=DEFAULT_PROMPT)- parser.add_argument("--output", required=True)+ add_upscale_arguments(parser, model_help=(+ "local snapshot directory of the pinned LTX-2.5 MLX pack "+ "(resolved cache-only by PortOS; never a repo id)"+ ))return parser.parse_args(argv)--def read_safetensors_header(path: str) -> "dict | None":- """Parse a safetensors JSON header with the stdlib alone.-- Deliberately not `safetensors.safe_open`: this runs during validation, in a- bare interpreter, before any runtime import — which is what keeps the whole- argument contract testable without an MLX wheel. Returns None for a missing,- truncated, or non-safetensors file rather than raising, so the caller states- the refusal in its own words.- """- try:- with open(path, "rb") as handle:- raw_len = handle.read(8)- if len(raw_len) < 8:- return None- header_len = struct.unpack("<Q", raw_len)[0]- if header_len <= 0 or header_len > MAX_HEADER_BYTES:- return None- raw = handle.read(header_len)- if len(raw) < header_len:- return None- parsed = json.loads(raw.decode("utf-8"))- return parsed if isinstance(parsed, dict) else None- except (OSError, ValueError, struct.error):- return None---def reference_downscale_factor(header: "dict | None") -> int:- """The adapter's declared `reference_downscale_factor`, defaulting to 1.-- Matches `iclora_utils.read_lora_reference_downscale_factor`, which the- pipeline uses as the real value. Read here too so the resolution rule can be- stated BEFORE a multi-minute render commits to it — and so PortOS can record- the measured factor rather than the `null` its registry honestly holds for a- gated weight nobody has opened yet.- """- metadata = (header or {}).get("__metadata__")- if not isinstance(metadata, dict):- return 1- try:- scale = int(metadata.get("reference_downscale_factor", 1))- except (TypeError, ValueError):- return 1- return scale if scale >= 1 else 1---def lora_target_keys(names) -> "set[str]":- """Base-weight keys an adapter can fuse into, from its ALREADY-RENAMED names.-- `apply_loras` pairs `<prefix>.lora_A.weight` with `<prefix>.lora_B.weight`- and skips a prefix missing either half, so a half-pair contributes nothing- and must not count as coverage. Takes renamed names rather than raw ones on- purpose: the ComfyUI rename table belongs to the runtime- (`LTXV_LORA_COMFY_RENAMING_MAP`), and copying it here would be a second- table free to drift from the one that actually fuses.- """- prefixes = {"lora_A": set(), "lora_B": set()}- for name in names:- for half, bucket in prefixes.items():- suffix = f".{half}.weight"- if isinstance(name, str) and name.endswith(suffix):- bucket.add(name[: -len(suffix)])- return {f"{prefix}.weight" for prefix in prefixes["lora_A"] & prefixes["lora_B"]}--def validate_host(system: str, machine: str) -> None:"""Capability gate: this runner is Apple-Silicon-only.@@ -194,55 +95,6 @@ def validate_host(system: str, machine: str) -> None:)-def validate_args(args: argparse.Namespace) -> None:- """Everything checkable before a GPU is committed.-- Mirrors `validate_args` in `scripts/generate_ltx25_cuda.py` on the grid so- both backends refuse the same sources, and mirrors `run_ic_lora` on the- reference contract so a direct/script caller gets the same guard the queue- does. Every refusal is a `SystemExit` string the queue surfaces verbatim.- """- if args.width % SPATIAL_MULTIPLE or args.height % SPATIAL_MULTIPLE:- raise SystemExit(- f"The two-stage LTX-2.5 pipeline requires width and height divisible by {SPATIAL_MULTIPLE}; "- f"got {args.width}x{args.height}."- )- if args.num_frames < MIN_FRAMES or args.num_frames % FRAME_MODULUS != FRAME_REMAINDER:- raise SystemExit(- f"LTX-2.5 num-frames must be at least {MIN_FRAMES} and satisfy "- f"frames % {FRAME_MODULUS} == {FRAME_REMAINDER}; got {args.num_frames}."- )- if not args.fps > 0:- raise SystemExit(f"--fps must be positive; got {args.fps}.")- if args.seed < 0:- raise SystemExit(f"--seed must be non-negative; got {args.seed}.")-- lo, hi = args.ic_min_references, args.ic_max_references- if lo < 1 or hi < lo:- raise SystemExit(- f"--ic-min-references/--ic-max-references must satisfy 1 <= min <= max; got {lo}/{hi}"- )- references = list(args.ic_reference or [])- if not (lo <= len(references) <= hi):- expected = f"exactly {lo}" if lo == hi else f"{lo}-{hi}"- raise SystemExit(- f"The upscale adapter needs {expected} --ic-reference clip(s); got {len(references)}"- )- for reference in references:- if not Path(reference).is_file():- raise SystemExit(f"--ic-reference does not exist: {reference}")-- # A path, never a repo id. `ICLoraPipeline._resolve_lora_path` falls back to- # `snapshot_download` for anything that is not an existing file, which for- # this gated adapter is a 401 deep inside a render — and for any repo, a pull- # PortOS never announced. The download surface owns every fetch.- if not Path(args.ic_lora_path).is_file():- raise SystemExit(- f"The Pixel Spatial Upscaler adapter is not on disk at {args.ic_lora_path} — "- "download it from the Video Gen model panel before upscaling."- )--def validate_model_dir(model_dir: str) -> Path:"""Resolve the pinned LTX-2.5 pack, refusing a pack without its conditioner.@@ -267,26 +119,6 @@ def validate_model_dir(model_dir: str) -> Path:return root-def assert_reference_scale_fits(scale: int, width: int, height: int) -> None:- """Enforce the adapter's own resolution rule on the STAGE-1 dimensions.-- `append_ic_lora_reference_video_conditionings` divides the dims it is HANDED- by the factor, and `ICLoraPipeline.generate` hands it `height // 2` /- `width // 2`. Stating the rule in OUTPUT terms is what makes the message- actionable — the user picked an output size, not a stage size.- """- if scale <= 1:- return- stage_h, stage_w = height // STAGE1_DIVISOR, width // STAGE1_DIVISOR- if stage_h % scale == 0 and stage_w % scale == 0:- return- required = scale * STAGE1_DIVISOR- raise SystemExit(- f"This adapter downscales its reference by {scale}, so the output dimensions must be "- f"divisible by {required}; got {width}x{height}."- )--def resolve_transformer_path(model_dir: Path) -> "Path | None":"""The DiT weight file `ICLoraPipeline.load()` would pick, or None.diff --git a/scripts/upscale_ltx25_cuda.py b/scripts/upscale_ltx25_cuda.pynew file mode 100644index 0000000000..f798ed3bb3--- /dev/null+++ b/scripts/upscale_ltx25_cuda.py@@ -0,0 +1,349 @@+#!/usr/bin/env python3+"""Generative 2x video upscale on the LTX-2.5 CUDA runtime (#6513).++The Windows/NVIDIA half of the pass #6512 established on MLX: the gated LTX-2.5+Pixel Spatial Upscaler IC-LoRA is fused into the distilled transformer and the+clip being upscaled is the single IC reference, at full strength. The argv, the+model grid and the header-only adapter guards are literally the same code —+`_upscale_contract.py` — because #6511 emits one argument set for both backends+and two copies of that contract would be two things free to drift.++Everything below was READ off the pinned runtime source+(`Lightricks/LTX-2 @ v1.2.0`, the ref `scripts/requirements-ltx25-cuda.txt`+installs), not inferred from the gated model card:++ - `ltx_pipelines.ic_lora.ICLoraPipeline` is the pipeline that fuses an+ IC-LoRA and conditions on a reference clip. It takes the same split+ `ModelPaths`, `spatial_upsampler_path`, `quantization` and `offload_mode`+ that `generate_ltx25_cuda.py` already drives `DistilledPipeline` with, so+ the FP8 cast policy and disk streaming that make a 22B model fit a consumer+ card carry over unchanged. It fuses the adapter into STAGE 1 only+ (`stage_2` is built with `loras=()`), which is correct here: stage 2 is the+ latent-upsample refinement pass, not the conditioned one.+ - The LoRA is a `LoraPathStrengthAndSDOps(path, strength, sd_ops)` and the+ `sd_ops` is the runtime's own `LTXV_LORA_COMFY_RENAMING_MAP`. Both come+ from `ltx_core.loader`; naming the map here rather than reimplementing it+ is what keeps the fusion guard honest.+ - Quantization-safe fusion is the runtime's contract: `fp8_cast.build_policy`+ ships an `fp8_cast_fuse_rule` that dequantizes the FP8 weight, adds the+ bf16 delta and re-rounds (and falls back to a plain bf16 fuse for the+ linears the downcast map leaves in bf16). So the FP8 policy does NOT break+ fusion — what breaks it silently is a KEY that does not match. `apply_loras`+ skips a weight `model_sd` lacks (`original_weight is None -> continue`), and+ `load_state_dict(..., strict=False)` swallows the rest, so an adapter that+ addresses nothing raises nothing and renders the plain base model.+ `assert_adapter_fuses` is the guard the issue asks for, and it checks+ NUMERICALLY: it intersects renamed keys AND verifies each delta's+ `B @ A` shape against the base weight the fuse would add it to.+ - The model-side key namespace is `LTXV_MODEL_COMFY_RENAMING_MAP`, which+ requires the raw `model.diffusion_model.` prefix and strips it; the LoRA+ map strips a bare `diffusion_model.`. The two meet on the same base names,+ which is exactly what the guard verifies rather than assumes.+ - The schedule is the fixed distilled one — `DISTILLED_SIGMAS` (8) and+ `STAGE_2_DISTILLED_SIGMAS` (3) are `__call__` defaults — which is why this+ runner, like the MLX one, exposes no steps flag.+ - `assert_resolution(..., is_two_stage=True)` enforces the same `% 64` rule+ the shared contract does, so a source is refused before a GPU rather than+ inside the pipeline.++Audio is deliberately NOT taken from the model. `encode_video` is called with+`audio=None` and `finalizeUpscaleOutput` (`upscaleFfmpeg.js`) re-muxes the+ORIGINAL clip's track at offset zero: the adapter is a spatial upscaler, so the+user's real audio is the correct audio, and round-tripping it through the audio+VAE would replace it with a re-synthesized one that also has to survive the+padded tail. A source with no audio yields a silent deliverable, not a failure.+"""++from __future__ import annotations++import argparse+import os+import sys+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parent))+from _runner_common import emit_runtime_fingerprint, establish_process_group, heartbeat # noqa: E402+# One pinned pack layout, not two: the upscale renders against the SAME split+# checkpoint the plain CUDA render does, so its file list is imported rather+# than restated. The import is side-effect-free — that module defers every+# heavy import into its own `main()`.+from generate_ltx25_cuda import MODEL_FILES # noqa: E402+# The argv, grid and adapter contract shared with the MLX runner (#6512).+from _upscale_contract import ( # noqa: E402+ REFERENCE_STRENGTH,+ add_upscale_arguments,+ assert_reference_scale_fits,+ entry_shape,+ lora_delta_shapes,+ read_safetensors_header,+ reference_downscale_factor,+ validate_args,+)++FINGERPRINT_PACKAGES = ["torch", "ltx-core", "ltx-pipelines", "transformers", "accelerate", "huggingface-hub"]++# The VRAM floor upstream supports for the 22B distilled pack under FP8 + disk+# streaming, expressed in decimal GB so a nominally-24 GB card clears it after+# the slice its driver reserves and never reports. An upscale renders at twice+# the source's linear dimensions, so it sits strictly above a plain render's+# peak — which is why this gate lives here and not in `generate_ltx25_cuda.py`.+MIN_VRAM_BYTES = 23 * 1000 ** 3++# The adapter fuses at full strength: it is the upscaler itself, not a style+# LoRA being blended in. Distinct from REFERENCE_STRENGTH, which happens to be+# the same number for the same reason and governs the reference conditioning.+ADAPTER_STRENGTH = 1.0+++def log(message: str) -> None:+ print(message, file=sys.stderr, flush=True)+++def parse_args(argv: "list[str] | None" = None) -> argparse.Namespace:+ parser = argparse.ArgumentParser(description="LTX-2.5 CUDA generative video upscale")+ add_upscale_arguments(parser, model_help=(+ "local snapshot directory of the pinned LTX-2.5 split checkpoint "+ "(resolved cache-only by PortOS; never a repo id)"+ ))+ return parser.parse_args(argv)+++def validate_device(available: bool, name: "str | None", total_memory: "int | None") -> None:+ """Capability gate: a visible NVIDIA card with enough VRAM to finish.++ Reaching this runner without CUDA is a routing bug in+ `ltxUpscaleRuntimeId()`, and reaching it on a card too small to hold the+ 22B pack is a render that dies with an allocator traceback 40 minutes in.+ Both are named here so the queue shows the actionable reason instead.++ An UNKNOWN capacity is not an insufficient one: a driver that does not+ report `total_memory` gets the benefit of the doubt rather than a refusal+ invented from a missing number.+ """+ if not available:+ raise SystemExit(+ "The LTX-2.5 CUDA upscale runner needs a visible NVIDIA device; torch reports none. "+ "Repair the LTX-2.5 CUDA runtime from Video Gen, or run the upscale on an Apple Silicon machine."+ )+ if total_memory is not None and total_memory < MIN_VRAM_BYTES:+ raise SystemExit(+ f"{name or 'This GPU'} reports {total_memory / 1000 ** 3:.1f} GB of VRAM. The LTX-2.5 22B "+ f"distilled upscale renders at twice the source's linear dimensions and needs at least "+ f"{MIN_VRAM_BYTES / 1000 ** 3:.0f} GB."+ )+++def validate_model_dir(model_dir: str) -> "dict[str, str]":+ """Resolve the pinned split checkpoint, refusing an incomplete snapshot.++ PortOS resolves the snapshot cache-only and hands over a directory, so a+ missing file means the pack was never fully downloaded (or was deleted+ underneath a queued job). Refusing HERE matters because the runner must+ never resolve its own weights: every LTX loader falls back to a remote+ fetch for a path it cannot stat, which for this pack is an unannounced+ ~68 GB pull inside a render.+ """+ root = Path(model_dir)+ if not root.is_dir():+ raise SystemExit(+ f"The LTX-2.5 model pack is not cached at {model_dir} — "+ "download or repair it in Video Gen before upscaling."+ )+ paths = {key: root / relative for key, relative in MODEL_FILES.items()}+ missing = sorted(str(relative) for key, relative in MODEL_FILES.items() if not paths[key].is_file())+ if missing:+ raise SystemExit(+ f"The LTX-2.5 snapshot at {model_dir} is incomplete: {', '.join(missing)}. "+ "Repair the model in Video Gen."+ )+ return {key: str(path) for key, path in paths.items()}+++def transformer_weight_shapes(transformer_path: str, rename) -> "dict[str, tuple[int, ...]]":+ """The transformer's fusable parameter names and shapes, from its header alone.++ `load_state_dict` applies `LTXV_MODEL_COMFY_RENAMING_MAP` to every key, so+ the model's parameter names are a deterministic function of the file's+ header — no tensor I/O and no model in memory. `rename` is that same map,+ passed in rather than restated so the guard can never disagree with the+ loader about which keys exist.++ Only `.weight` keys matter: `_affected_weight_keys` addresses a weight by+ `<prefix>.weight`, and a prequantized pack's sibling `*_scale` tensors are+ folded into their parent at load time rather than fused into.+ """+ header = read_safetensors_header(transformer_path)+ if not header:+ return {}+ shapes = {}+ for raw, entry in header.items():+ if raw == "__metadata__":+ continue+ name = rename(raw)+ if not isinstance(name, str) or not name.endswith(".weight"):+ continue+ shape = entry_shape(entry)+ if shape is not None:+ shapes[name] = shape+ return shapes+++def assert_adapter_fuses(adapter_path: str, model_shapes: "dict[str, tuple[int, ...]]", rename) -> int:+ """Refuse an adapter that would fuse into nothing, or into the wrong shape.++ This is the failure #6513 names: `apply_loras` reports nothing when a key+ does not match — the weight is skipped, `load_state_dict(strict=False)`+ swallows the rest, and the render is the un-adapted base model dressed as+ an upscale. "No exception" is not evidence, so the check is the numeric+ one the header already affords: every fusable pair must address a real+ weight AND its `B @ A` product must have that weight's shape, or the delta+ could not be added to it even if the key matched.++ Only headers are read, so this costs no tensor I/O and runs BEFORE the+ pipeline loads anything. Returns the number of weights the adapter will+ actually fuse into, so the render records real coverage.+ """+ header = read_safetensors_header(adapter_path)+ if not header:+ raise SystemExit(+ f"Could not read the adapter's safetensors header at {adapter_path} — "+ "the file is truncated or is not a safetensors weight. Repair it in Video Gen."+ )+ if not model_shapes:+ raise SystemExit(+ "Could not read the LTX-2.5 transformer's weight names, so there is no way to tell whether "+ "the upscale adapter would fuse into anything. Repair the model in Video Gen."+ )+ deltas = lora_delta_shapes(header, rename)+ matched = sorted(set(deltas) & set(model_shapes))+ if not matched:+ raise SystemExit(+ "The upscale adapter's tensors do not address any weight in this transformer, so fusing it "+ "would be a no-op and the 'upscale' would be an un-adapted render. The adapter and the "+ "LTX-2.5 pack are mismatched — repair both in Video Gen."+ )+ mismatched = []+ for key in matched:+ out_features, in_features, rank_a, rank_b = deltas[key]+ if rank_a != rank_b or model_shapes[key] != (out_features, in_features):+ mismatched.append(f"{key} (adapter {out_features}x{in_features}, model {model_shapes[key]})")+ if mismatched:+ raise SystemExit(+ "The upscale adapter's deltas do not match the shape of the weights they address, so the "+ f"fusion would corrupt them: {'; '.join(mismatched[:3])}. The adapter was trained against a "+ "different LTX-2.5 checkpoint — repair both in Video Gen."+ )+ return len(matched)+++def main() -> None:+ establish_process_group()+ args = parse_args()+ validate_args(args)+ paths = validate_model_dir(args.model)++ header = read_safetensors_header(args.ic_lora_path)+ scale = reference_downscale_factor(header)+ assert_reference_scale_fits(scale, args.width, args.height)+ # Recorded rather than guessed: `icLoraWeights.js` holds `null` for this+ # gated weight precisely because nobody had opened it, and this line is the+ # measurement (#6508's registry note points here).+ log(f"UPSCALE_REFERENCE_DOWNSCALE:{scale}")++ log("STAGE:verify-adapter")+ # LTX's documented allocator setting reduces fragmentation on cards that sit+ # close to the model's supported VRAM floor. It must be set before importing+ # torch so CUDA reads it during allocator initialization.+ os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")+ import torch++ # Gated before the runtime imports so a CPU-only torch — which installs+ # cleanly on Windows and hides the setup banner — is named as the reason.+ device_index = torch.cuda.current_device() if torch.cuda.is_available() else None+ validate_device(+ torch.cuda.is_available(),+ torch.cuda.get_device_name(device_index) if device_index is not None else None,+ torch.cuda.get_device_properties(device_index).total_memory if device_index is not None else None,+ )++ from ltx_core.loader import LTXV_LORA_COMFY_RENAMING_MAP, LoraPathStrengthAndSDOps+ from ltx_core.model.transformer.model_configurator import LTXV_MODEL_COMFY_RENAMING_MAP+ from ltx_core.model.video_vae import AUTO_TILING, get_video_chunks_number+ from ltx_core.quantization.fp8_cast import build_policy as build_fp8_cast_policy+ from ltx_pipelines.ic_lora import ICLoraPipeline+ from ltx_pipelines.utils.media_io import encode_video+ from ltx_pipelines.utils.model_paths import ModelPaths+ from ltx_pipelines.utils.types import OffloadMode++ emit_runtime_fingerprint("ltx25_cuda", FINGERPRINT_PACKAGES)++ # Both sides of the coverage check are header reads, so a mismatched pair+ # fails in milliseconds — before Gemma, before the DiT, before a GPU.+ fused = assert_adapter_fuses(+ args.ic_lora_path,+ transformer_weight_shapes(paths["transformer"], LTXV_MODEL_COMFY_RENAMING_MAP.apply_to_key),+ LTXV_LORA_COMFY_RENAMING_MAP.apply_to_key,+ )+ log(f"STATUS:Adapter fuses into {fused} transformer weights")++ model_paths = ModelPaths.from_split(+ transformer_path=paths["transformer"],+ text_encoder_path=paths["text_encoder"],+ video_vae_path=paths["video_vae"],+ audio_vae_path=paths["audio_vae"],+ duration_head_path=paths["duration_head"],+ )+ log("STAGE:load-pipeline")+ log(f"STATUS:Loading LTX-2.5 CUDA upscale pipeline ({args.width}x{args.height}, {args.num_frames} frames)")+ with heartbeat("ltx25-cuda-upscale-load"):+ pipe = ICLoraPipeline(+ model_paths=model_paths,+ spatial_upsampler_path=paths["upsampler"],+ loras=[+ LoraPathStrengthAndSDOps(args.ic_lora_path, ADAPTER_STRENGTH, LTXV_LORA_COMFY_RENAMING_MAP),+ ],+ device=torch.device("cuda"),+ quantization=build_fp8_cast_policy(paths["transformer"]),+ # CPU mode pins a model-sized prefetch buffer. The 24 GB VRAM /+ # 32 GB system-RAM tier can exhaust that buffer while Gemma is+ # resident; DISK is upstream's lowest-memory streaming mode.+ offload_mode=OffloadMode.DISK,+ )++ log("STAGE:inference")+ with heartbeat("ltx25-cuda-upscale-inference"):+ # No sigma overrides: `DISTILLED_SIGMAS` / `STAGE_2_DISTILLED_SIGMAS`+ # ARE the distilled schedule (8 + 3) and are this call's defaults.+ # `images=[]` because the reference is the clip, not a still.+ video, _audio, tiling = pipe(+ prompt=args.prompt,+ seed=args.seed,+ height=args.height,+ width=args.width,+ num_frames=args.num_frames,+ frame_rate=args.fps,+ images=[],+ video_conditioning=[(reference, REFERENCE_STRENGTH) for reference in args.ic_reference],+ tiling_config=AUTO_TILING,+ )++ output = Path(args.output)+ output.parent.mkdir(parents=True, exist_ok=True)+ log("STAGE:mux")+ # `audio=None`: the deliverable's track is re-muxed from the ORIGINAL clip+ # by `finalizeUpscaleOutput`, so keeping the model's re-synthesized one+ # would only replace the user's real audio. See the module docstring.+ encode_video(+ video=video,+ fps=int(args.fps),+ audio=None,+ output_path=str(output),+ video_chunks_number=int(get_video_chunks_number(args.num_frames, tiling)),+ )+ if not output.is_file():+ raise SystemExit(f"The LTX-2.5 upscale completed but did not write {output}.")+ log(f"STATUS:Upscaled {output.name} ({args.width}x{args.height}, {args.num_frames} frames)")+++if __name__ == "__main__":+ main()diff --git a/scripts/upscale_ltx25_cuda.test.js b/scripts/upscale_ltx25_cuda.test.jsnew file mode 100644index 0000000000..fac704c73a--- /dev/null+++ b/scripts/upscale_ltx25_cuda.test.js@@ -0,0 +1,331 @@+import { execFileSync } from 'node:child_process';+import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { fileURLToPath } from 'node:url';+import { dirname, join } from 'node:path';+import { describe, expect, it } from 'vitest';+import { resolveTestPython, PY_TEST_TIMEOUT_MS, PY_SUBPROCESS_TIMEOUT_MS } from '../server/lib/testHelper.js';++const scriptDir = dirname(fileURLToPath(import.meta.url));+const script = join(scriptDir, 'upscale_ltx25_cuda.py');++// Everything exercised here is import-free by design (stdlib only): #6513's+// acceptance requires the argument and capability gates to be testable on a+// machine with no CUDA card, no torch wheel, no ~68 GB pack and no gated+// adapter — which is every CI runner and every Mac.+const pyBin = resolveTestPython();+const runPython = (source, ...argv) => execFileSync(pyBin, ['-c', source, script, ...argv], {+ encoding: 'utf8',+ // Below the per-test budget on purpose, so a hung interpreter fails with the+ // spawn's own ETIMEDOUT naming the command rather than a bare vitest timeout.+ timeout: PY_SUBPROCESS_TIMEOUT_MS,+});++const importRunner = [+ 'import importlib.util, sys',+ 'from pathlib import Path',+ 'script = Path(sys.argv[1])',+ 'sys.path.insert(0, str(script.parent))',+ 'spec = importlib.util.spec_from_file_location("upscale_ltx25_cuda", script)',+ 'runner = importlib.util.module_from_spec(spec)',+ 'spec.loader.exec_module(runner)',+].join('\n');++// Python on Windows writes CRLF, so a trailing carriage return would otherwise+// ride along on every comparison below.+const trimmed = (output) => output.trim().split('\n').map((line) => line.trimEnd()).join('\n');++const call = (expression, ...argv) => trimmed(runPython(`${importRunner}\n${[+ 'try:',+ ` print(${expression})`,+ 'except SystemExit as exc:',+ ' print(f"REJECTED:{exc}")',+].join('\n')}`, ...argv));++// A scratch tree the fixtures live in — never a path from the developer's+// install, and never inside the repo.+const scratch = mkdtempSync(join(tmpdir(), 'portos-upscale-cuda-'));+const REFERENCE = join(scratch, 'source.mp4');+const ADAPTER = join(scratch, 'adapter.safetensors');+writeFileSync(REFERENCE, 'not really a video');++// A real safetensors file: 8-byte little-endian header length, then the JSON+// header. Written rather than mocked because the header parse IS the thing+// under test — the runner reads both the declared downscale factor and every+// delta SHAPE off this exact layout.+const writeSafetensors = (path, header) => {+ const json = Buffer.from(JSON.stringify(header), 'utf8');+ const len = Buffer.alloc(8);+ len.writeBigUInt64LE(BigInt(json.length));+ writeFileSync(path, Buffer.concat([len, json]));+};+const loraPair = (prefix, out, inn, rank) => ({+ [`${prefix}.lora_A.weight`]: { shape: [rank, inn] },+ [`${prefix}.lora_B.weight`]: { shape: [out, rank] },+});+writeSafetensors(ADAPTER, { __metadata__: { reference_downscale_factor: '2' } });++// The pinned split checkpoint's file list, from the runner's own MODEL_FILES —+// scraped rather than restated so a pack layout change cannot leave this suite+// building a "complete" snapshot the runner would reject.+const MODEL_FILES = JSON.parse(call('__import__("json").dumps(runner.MODEL_FILES)'));+const writePack = (files = Object.values(MODEL_FILES)) => {+ const pack = mkdtempSync(join(tmpdir(), 'portos-ltx25-cuda-pack-'));+ for (const relative of files) {+ const target = join(pack, ...relative.split('/'));+ mkdirSync(dirname(target), { recursive: true });+ writeFileSync(target, '');+ }+ return pack;+};++const ARG_DEFAULTS = {+ width: 1728,+ height: 1024,+ num_frames: 121,+ fps: 24,+ seed: 4242,+ ic_min_references: 1,+ ic_max_references: 1,+};+const validate = (overrides = {}) => {+ const fields = { ...ARG_DEFAULTS, ...overrides };+ const references = Object.hasOwn(overrides, 'ic_reference') ? overrides.ic_reference : [REFERENCE];+ const loraPath = Object.hasOwn(overrides, 'ic_lora_path') ? overrides.ic_lora_path : ADAPTER;+ return trimmed(runPython(`${importRunner}\n${[+ 'import argparse, json',+ `args = argparse.Namespace(**json.loads(${JSON.stringify(JSON.stringify(fields))}))`,+ `args.ic_reference = json.loads(${JSON.stringify(JSON.stringify(references))})`,+ `args.ic_lora_path = json.loads(${JSON.stringify(JSON.stringify(loraPath))})`,+ 'try:',+ ' runner.validate_args(args)',+ ' print("OK")',+ 'except SystemExit as exc:',+ ' print(f"REJECTED:{exc}")',+ ].join('\n')}`));+};++// The flag set a runner declares, read off a real parser rather than its source.+const flagsOf = (moduleFile) => trimmed(runPython([+ 'import importlib.util, sys, argparse',+ 'from pathlib import Path',+ 'script = Path(sys.argv[1]).parent / sys.argv[2]',+ 'sys.path.insert(0, str(script.parent))',+ 'spec = importlib.util.spec_from_file_location(script.stem, script)',+ 'mod = importlib.util.module_from_spec(spec)',+ 'spec.loader.exec_module(mod)',+ 'parser = argparse.ArgumentParser()',+ 'mod.add_upscale_arguments(parser, model_help="x")',+ 'print(" ".join(sorted(o for a in parser._actions for o in a.option_strings)))',+].join('\n'), moduleFile));++// #6511 emits ONE argv for both backends and only swaps the interpreter and the+// script path, so the two parsers agreeing IS the contract — not a stylistic+// preference. Compared as data rather than trusted to the shared helper they+// both happen to call today, because a runner stays free to add a flag.+describe.skipIf(!pyBin)('upscale_ltx25_cuda.py — one argv for both backends (#6513)', () => {+ it('declares exactly the flags the MLX runner declares', () => {+ const cuda = flagsOf('upscale_ltx25_cuda.py');+ expect(cuda).toBe(flagsOf('upscale_ltx25.py'));+ expect(cuda.split(' ')).toEqual([+ '--fps', '--height', '--help', '--ic-lora-path', '--ic-max-references',+ '--ic-min-references', '--ic-reference', '--model', '--num-frames', '--output',+ '--prompt', '--seed', '--width', '-h',+ ]);+ }, PY_TEST_TIMEOUT_MS);++ // The distilled schedule is fixed at 8 + 3 sigmas on both runtimes, so there+ // is nothing for a steps flag to select; and the pass carries no prompt,+ // because the source clip is the whole conditioning signal.+ it('exposes no steps flag and defaults the prompt to empty', () => {+ expect(flagsOf('upscale_ltx25_cuda.py')).not.toContain('--steps');+ expect(call(+ 'repr(runner.parse_args(["--model","m","--ic-lora-path","l","--ic-reference","r",'+ + '"--ic-min-references","1","--ic-max-references","1","--width","64","--height","64",'+ + '"--num-frames","9","--fps","24","--seed","0","--output","o"]).prompt)',+ )).toBe("''");+ }, PY_TEST_TIMEOUT_MS);+});++describe.skipIf(!pyBin)('upscale_ltx25_cuda.py — argument contract (#6513)', () => {+ it('accepts the argv renderArgs.buildLtxUpscaleArgs emits', () => {+ expect(validate()).toBe('OK');+ }, PY_TEST_TIMEOUT_MS);++ // `validate_args` in generate_ltx25_cuda.py already enforced this grid and+ // #6512 confirmed MLX imposes the same one, so a source that "nearly" fits+ // must be refused here rather than silently resized to fit.+ it.each([+ ['a width off the 64 grid', { width: 1700 }],+ ['a height off the 64 grid', { height: 1000 }],+ ])('refuses %s', (_label, overrides) => {+ expect(validate(overrides)).toMatch(/^REJECTED:.*divisible by 64/);+ }, PY_TEST_TIMEOUT_MS);++ it.each([+ ['a frame count off the 8n+1 grid', { num_frames: 120 }],+ ['a frame count under the floor', { num_frames: 5 }],+ ])('refuses %s', (_label, overrides) => {+ expect(validate(overrides)).toMatch(/^REJECTED:.*frames % 8 == 1/);+ }, PY_TEST_TIMEOUT_MS);++ it('refuses a reference count outside the weight registry bounds', () => {+ expect(validate({ ic_reference: [] })).toMatch(/^REJECTED:.*exactly 1 --ic-reference/);+ expect(validate({ ic_reference: [REFERENCE, REFERENCE] })).toMatch(/^REJECTED:.*exactly 1 --ic-reference/);+ }, PY_TEST_TIMEOUT_MS);++ it('refuses a repo id in place of a downloaded adapter file', () => {+ expect(validate({ ic_lora_path: 'Lightricks/LTX-2.5-22b-IC-LoRA-Pixel-Spatial-Upscaler' }))+ .toMatch(/^REJECTED:.*download it from the Video Gen model panel/);+ }, PY_TEST_TIMEOUT_MS);+});++describe.skipIf(!pyBin)('upscale_ltx25_cuda.py — capability gate (#6513)', () => {+ // A CPU-only torch installs cleanly on Windows and hides the setup banner, so+ // "no visible device" has to name itself rather than surface as an allocator+ // traceback minutes into a render.+ it('refuses a host with no visible CUDA device', () => {+ expect(call('runner.validate_device(False, None, None) or "OK"'))+ .toMatch(/^REJECTED:.*needs a visible NVIDIA device/);+ }, PY_TEST_TIMEOUT_MS);++ // An upscale renders at twice the source's linear dimensions, so it sits+ // above a plain render's peak — a card that can generate cannot necessarily+ // upscale, and finding that out 40 minutes in is the failure being prevented.+ it('refuses a card below the supported VRAM floor, naming what it measured', () => {+ expect(call('runner.validate_device(True, "GeForce RTX 4060 Ti", 16 * 1000 ** 3) or "OK"'))+ .toMatch(/^REJECTED:GeForce RTX 4060 Ti reports 16\.0 GB of VRAM.*at least 23 GB/);+ }, PY_TEST_TIMEOUT_MS);++ it('accepts a 24 GB card after the slice its driver reserves', () => {+ expect(call('runner.validate_device(True, "GeForce RTX 4090", 25_393_692_672) or "OK"')).toBe('OK');+ }, PY_TEST_TIMEOUT_MS);++ // Unknown is not insufficient: a driver that reports no capacity must not be+ // refused on a number the runner invented for it.+ it('accepts a device whose capacity the driver does not report', () => {+ expect(call('runner.validate_device(True, "Unknown Device", None) or "OK"')).toBe('OK');+ }, PY_TEST_TIMEOUT_MS);+});++describe.skipIf(!pyBin)('upscale_ltx25_cuda.py — pinned snapshot (#6513)', () => {+ // The runner must never resolve its own weights: every LTX loader falls back+ // to a remote fetch for a path it cannot stat, which for this pack is an+ // unannounced ~68 GB pull inside a render.+ it('refuses a snapshot directory that does not exist', () => {+ expect(call(`runner.validate_model_dir(${JSON.stringify(join(scratch, 'no-such-pack'))})`))+ .toMatch(/^REJECTED:.*not cached/);+ }, PY_TEST_TIMEOUT_MS);++ it('refuses a snapshot missing a pinned file, naming the file', () => {+ const partial = writePack(Object.values(MODEL_FILES).filter((f) => f !== MODEL_FILES.upsampler));+ expect(call(`runner.validate_model_dir(${JSON.stringify(partial)})`))+ .toMatch(new RegExp(`^REJECTED:.*incomplete: ${MODEL_FILES.upsampler.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}`));+ }, PY_TEST_TIMEOUT_MS);++ it('resolves every pinned file to an absolute path when the snapshot is complete', () => {+ const pack = writePack();+ expect(call(`sorted(runner.validate_model_dir(${JSON.stringify(pack)}))`))+ .toBe(`[${Object.keys(MODEL_FILES).sort().map((k) => `'${k}'`).join(', ')}]`);+ }, PY_TEST_TIMEOUT_MS);+});++describe.skipIf(!pyBin)('upscale_ltx25_cuda.py — adapter fusion guard (#6513)', () => {+ // The model side requires the raw `model.diffusion_model.` prefix+ // (LTXV_MODEL_COMFY_RENAMING_MAP) and strips it; the LoRA side strips a bare+ // `diffusion_model.`. Both maps are the runtime's own in production — stubbed+ // here so the intersection is exercised without a torch wheel.+ const MODEL_RENAME = 'lambda k: k[len("model.diffusion_model."):] if k.startswith("model.diffusion_model.") else None';+ const LORA_RENAME = 'lambda k: k.replace("diffusion_model.", "")';++ const writeDit = (header) => {+ const dit = join(scratch, `dit-${Math.random().toString(36).slice(2)}.safetensors`);+ writeSafetensors(dit, header);+ return dit;+ };++ it('keeps only prefixed .weight keys, with their shapes', () => {+ const dit = writeDit({+ 'model.diffusion_model.transformer_blocks.0.attn1.to_q.weight': { shape: [4096, 4096] },+ // A prequant sibling is folded into its parent at load time, never fused into.+ 'model.diffusion_model.transformer_blocks.0.attn1.to_q.weight_scale': { shape: [] },+ // Not under the raw prefix — the rename map rejects it outright.+ 'vae.encoder.conv_in.weight': { shape: [8, 8] },+ });+ expect(call(`sorted(runner.transformer_weight_shapes(${JSON.stringify(dit)}, ${MODEL_RENAME}).items())`))+ .toBe("[('transformer_blocks.0.attn1.to_q.weight', (4096, 4096))]");+ }, PY_TEST_TIMEOUT_MS);++ it('returns an empty map for an unreadable file rather than raising', () => {+ expect(call(`runner.transformer_weight_shapes(${JSON.stringify(REFERENCE)}, ${MODEL_RENAME})`)).toBe('{}');+ }, PY_TEST_TIMEOUT_MS);++ // The failure #6513 names: `apply_loras` skips a weight the model lacks and+ // `load_state_dict(strict=False)` swallows the rest, so an adapter that+ // addresses nothing raises nothing and renders the plain base model.+ it('refuses an adapter that would fuse into nothing, and reports coverage when it would', () => {+ const modelShapes = "{'transformer_blocks.0.attn1.to_q.weight': (4096, 4096)}";++ const foreign = join(scratch, 'foreign.safetensors');+ writeSafetensors(foreign, loraPair('diffusion_model.some.other.model.layer', 4096, 4096, 16));+ expect(call(`runner.assert_adapter_fuses(${JSON.stringify(foreign)}, ${modelShapes}, ${LORA_RENAME})`))+ .toMatch(/^REJECTED:.*do not address any weight/);++ const matching = join(scratch, 'matching.safetensors');+ writeSafetensors(matching, loraPair('diffusion_model.transformer_blocks.0.attn1.to_q', 4096, 4096, 16));+ expect(call(`runner.assert_adapter_fuses(${JSON.stringify(matching)}, ${modelShapes}, ${LORA_RENAME})`)).toBe('1');+ }, PY_TEST_TIMEOUT_MS);++ // "No exception" is not evidence on this runtime either, so the guard checks+ // the delta numerically: an adapter trained against a different-width+ // checkpoint matches by NAME and would corrupt the weight it addresses.+ it('refuses a matching key whose B@A product is the wrong shape', () => {+ const wrongWidth = join(scratch, 'wrong-width.safetensors');+ writeSafetensors(wrongWidth, loraPair('diffusion_model.transformer_blocks.0.attn1.to_q', 2048, 4096, 16));+ expect(call(`runner.assert_adapter_fuses(${JSON.stringify(wrongWidth)}, `+ + `{'transformer_blocks.0.attn1.to_q.weight': (4096, 4096)}, ${LORA_RENAME})`))+ .toMatch(/^REJECTED:.*do not match the shape.*adapter 2048x4096, model \(4096, 4096\)/);+ }, PY_TEST_TIMEOUT_MS);++ // A half-pair contributes nothing on this runtime too (`_products_for_sd_key`+ // skips a prefix missing either half), so it must not count as coverage — or+ // the no-op guard would pass on an adapter that fuses nothing.+ it('does not count a lora_A without its lora_B as coverage', () => {+ const halfPair = join(scratch, 'half-pair.safetensors');+ writeSafetensors(halfPair, {+ 'diffusion_model.transformer_blocks.0.attn1.to_q.lora_A.weight': { shape: [16, 4096] },+ });+ expect(call(`runner.assert_adapter_fuses(${JSON.stringify(halfPair)}, `+ + `{'transformer_blocks.0.attn1.to_q.weight': (4096, 4096)}, ${LORA_RENAME})`))+ .toMatch(/^REJECTED:.*do not address any weight/);+ }, PY_TEST_TIMEOUT_MS);++ // An unreadable transformer means the guard cannot answer its own question.+ // Reporting "fuses into nothing" would blame the adapter; reporting success+ // would defeat the guard — so it refuses on its own blindness instead.+ it('refuses when the transformer weight names could not be read at all', () => {+ const matching = join(scratch, 'matching.safetensors');+ expect(call(`runner.assert_adapter_fuses(${JSON.stringify(matching)}, {}, ${LORA_RENAME})`))+ .toMatch(/^REJECTED:.*Could not read the LTX-2\.5 transformer/);+ }, PY_TEST_TIMEOUT_MS);++ it('refuses an adapter file that is not safetensors at all', () => {+ expect(call(`runner.assert_adapter_fuses(${JSON.stringify(REFERENCE)}, `+ + `{'a.weight': (1, 1)}, ${LORA_RENAME})`))+ .toMatch(/^REJECTED:.*Could not read the adapter/);+ }, PY_TEST_TIMEOUT_MS);+});++// The adapter's declared factor applies to the STAGE-1 dims, which are half the+// output — so a factor of 2 really demands an output divisible by 4. Shared with+// the MLX runner, exercised here because this runner is the one that would+// commit a CUDA render to it.+describe.skipIf(!pyBin)('upscale_ltx25_cuda.py — reference downscale factor (#6513)', () => {+ it('reads the factor off the weight and enforces it against the stage-1 dims', () => {+ expect(call(`runner.reference_downscale_factor(runner.read_safetensors_header(${JSON.stringify(ADAPTER)}))`))+ .toBe('2');+ expect(call('runner.assert_reference_scale_fits(2, 1728, 1024) or "OK"')).toBe('OK');+ expect(call('runner.assert_reference_scale_fits(4, 1028, 1024) or "OK"'))+ .toMatch(/^REJECTED:.*divisible by 8/);+ }, PY_TEST_TIMEOUT_MS);+});diff --git a/server/services/videoGen/renderArgsUpscale.test.js b/server/services/videoGen/renderArgsUpscale.test.jsindex 09bf88ad3b..c58d3d5a77 100644--- a/server/services/videoGen/renderArgsUpscale.test.js+++ b/server/services/videoGen/renderArgsUpscale.test.js@@ -1,4 +1,5 @@import { describe, expect, it, vi } from 'vitest';+import { existsSync } from 'fs';import { fileURLToPath } from 'url';// The generative-upscale runtimes are BYO-venv checkouts that do not exist on@@ -112,6 +113,17 @@ describe('buildLtxUpscaleArgs (#6511)', () => {});});+// A renamed or missing helper is invisible to every argv test above — they all+// run against fixture paths — and would ship an argv whose interpreter cannot+// open the script. Asserted against the REAL constants, unmocked.+describe('generative-upscale helper scripts', () => {+ it('names a runner that exists on disk for every supported runtime', async () => {+ const actual = await vi.importActual('./runtimes.js');+ expect(existsSync(actual.LTX25_UPSCALE_HELPER_SCRIPT)).toBe(true);+ expect(existsSync(actual.LTX25_CUDA_UPSCALE_HELPER_SCRIPT)).toBe(true);+ });+});+describe('buildArgs upscale dispatch', () => {// The upscale carries no video model, no prompt and no reference mode, so it// has to decline before any of buildArgs' render guards dereference one.diff --git a/server/services/videoGen/runtimes.js b/server/services/videoGen/runtimes.jsindex 97ca20c4a7..c820adb964 100644--- a/server/services/videoGen/runtimes.js+++ b/server/services/videoGen/runtimes.js@@ -44,9 +44,10 @@ export const LTX25_ENCODER_SHIM_DIR = join(homedir(), '.portos', 'ltx25-encoder-// Generative video upscale (#6511). A spatial-upscale pass fuses the LTX-2.5// Pixel Spatial Upscaler IC-LoRA over a source clip, which is a different// entry point from a text/image render — so it gets its own helper script per-// runtime rather than another mode flag on the generation script. Both scripts-// land with the Python backends (#6512 MLX / #6513 CUDA); until then the-// runtime's venv is absent, which is what gates the feature off.+// runtime rather than another mode flag on the generation script. Both runners+// have landed (#6512 MLX / #6513 CUDA) and share one argv contract+// (`scripts/_upscale_contract.py`); an install with neither runtime's venv+// present still has no generative upscale, which is what gates the feature off.export const LTX25_UPSCALE_HELPER_SCRIPT = join(PATHS.root, 'scripts', 'upscale_ltx25.py');// Wan 2.2 MLX runtime — pinned MLX-Gen checkout provisioned on demand.