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
fix: run the LTX-2.5 generative upscale as a single conditioned stage at the output size (#6512)
[._.]/ Adam Eivy09441c46ae68
diff --git a/docs/features/video-upscale.md b/docs/features/video-upscale.mdindex 0716409867..a92faf6737 100644--- a/docs/features/video-upscale.md+++ b/docs/features/video-upscale.md@@ -102,11 +102,40 @@ the script path differ. What stays per-runner is what genuinely differs: theruntime it imports, the host it gates on, the pack layout it validates, and therename maps its loader fuses through.+## The recipe++The generative method is Lightricks' standard IC-LoRA video-to-video pass, as+their IC-LoRA guide and ComfyUI reference workflow run the Pixel Spatial+Upscaler: the distilled model with the adapter fused at strength 1.0, a single+denoising stage **at the output resolution**, and the low-resolution clip as+the in-context reference at half of it (the adapter's+`reference_downscale_factor` is 2). No text steering is added — the source clip+is the whole conditioning signal — and the distilled 8-sigma schedule is used+as-is.++Both runtimes' `ICLoraPipeline` interpret the size they are handed as the dims+of an optional latent-upsample second stage, rendering the conditioned stage+at half of it. The runners therefore request **twice** the output and skip+that second stage, so the conditioned stage renders at the output size with+the source as a native-resolution reference. Requesting the output size itself+would condition on the source downscaled by another 2× and hand the second+doubling to the latent upsampler — a pixel-faithful refinement the adapter is+not.++On macOS the MLX q8 pack may hold the distilled model either pre-fused+(`transformer-distilled.safetensors`) or as the dev transformer plus the+450-step distilled LoRA; the runner takes the pre-fused file when present and+otherwise fuses the distilled LoRA beside the adapter, which the pack documents+as the equivalent layout. A dev transformer without that LoRA is refused, since+the distilled schedule is only valid on the distilled model.+## The model grid, and why nothing is silently lost-LTX-2.5 renders on a two-stage grid: output dimensions must divide by **64**,-and the frame count must satisfy `frames % 8 == 1` with a floor of **9**. Since-the scale is 2×, a *source* axis conforms exactly when it divides by 32.+LTX-2.5 renders on a fixed grid: output dimensions must divide by **64**, and+the frame count must satisfy `frames % 8 == 1` with a floor of **9**. Since the+scale is 2×, a *source* axis conforms exactly when it divides by 32 — which is+also what keeps the reference at the (padded) source's own size on the VAE's+32-pixel grid rather than resampling it before it conditions anything.A source that does not conform is **padded, never trimmed** — extra pixels onthe right/bottom and extra frames on the tail, cropped back off the outputdiff --git a/scripts/_upscale_contract.py b/scripts/_upscale_contract.pyindex ae71e4f43d..1fc3425eac 100644--- a/scripts/_upscale_contract.py+++ b/scripts/_upscale_contract.py@@ -24,21 +24,38 @@ import jsonimport structfrom 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.+# The LTX-2.5 grid, mirrored from `LTX_GRID` in+# `server/services/videoGen/upscalePlan.js` and confirmed against both runtimes.+# The video VAE compresses spatially by 32, and the upscaler's reference has to+# land on that grid at HALF the output (see `assert_reference_scale_fits`), so+# the OUTPUT axis must be divisible by 64 — which is also what upstream's own+# `assert_resolution(..., is_two_stage=True)` demands of the request both+# runners make (`conditioned_stage_request` below). 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 = 64FRAME_MODULUS = 8FRAME_REMAINDER = 1MIN_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 VAE's spatial compression: the reference clip is resized onto this grid+# before it is encoded, so a reference that is not a multiple of it gets+# resampled — which for an upscaler means conditioning on a blurred source.+VAE_SPATIAL_COMPRESSION = 32++# How both `ICLoraPipeline`s interpret the `height`/`width` they are handed:+# as the dims of the OPTIONAL latent-upsample stage 2, with the IC-conditioned+# stage 1 rendering at exactly half of that. The Pixel Spatial Upscaler is the+# standard single-stage IC-LoRA video-to-video recipe (Lightricks' IC-LoRA+# guide and their ComfyUI reference workflow run it "single-stage distilled at+# your set resolution", reference at half), so a runner asks for TWICE the+# output and skips stage 2: stage 1 then renders AT the output size with the+# source as a native-resolution reference, and the decoded clip is the output.+# Requesting the output itself would render stage 1 at half the output —+# conditioning on the source downscaled by another 2x — and hand the second+# doubling to the latent upsampler, which is exactly the pixel-faithful+# refinement the adapter is not.+PIPELINE_REQUEST_MULTIPLIER = 2# The upscale contract carries no prompt (#6511): the source clip is the whole# conditioning signal, and inventing text steering would push synthesized detail@@ -183,20 +200,32 @@ def reference_downscale_factor(header: "dict | None") -> int:return scale if scale >= 1 else 1+def conditioned_stage_request(width: int, height: int) -> "tuple[int, int]":+ """The `(width, height)` a runner hands the pipeline so stage 1 renders at the output.++ Paired with `skip_stage_2=True` on both runtimes — see+ `PIPELINE_REQUEST_MULTIPLIER`. Kept as one helper so the two runners cannot+ disagree about which stage the output comes from.+ """+ return width * PIPELINE_REQUEST_MULTIPLIER, height * PIPELINE_REQUEST_MULTIPLIER++def assert_reference_scale_fits(scale: int, width: int, height: int) -> None:- """Enforce the adapter's own resolution rule on the STAGE-1 dimensions.+ """Enforce the adapter's own resolution rule on the conditioned stage's dims.`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.+ by the factor and snaps the result onto the VAE grid. With+ `conditioned_stage_request` those dims ARE the output, so the reference is+ `output / scale` — and for the upscaler that must be the (padded) source's+ own size, or the source is resampled before it conditions anything. Hence+ the output must divide by `scale * 32`. Stating the rule in OUTPUT terms is+ what makes the message actionable — the user picked an output 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:+ required = scale * VAE_SPATIAL_COMPRESSION+ if height % required == 0 and width % required == 0:return- required = scale * STAGE1_DIVISORraise SystemExit(f"This adapter downscales its reference by {scale}, so the output dimensions must be "f"divisible by {required}; got {width}x{height}."diff --git a/scripts/upscale_ltx25.py b/scripts/upscale_ltx25.pyindex e205d81d79..ade65c0299 100755--- a/scripts/upscale_ltx25.py+++ b/scripts/upscale_ltx25.py@@ -22,9 +22,18 @@ gated model card:it and otherwise falls back to the remote 2.3 Gemma 3 id — a wrong encoderAND an unannounced multi-GB download — so `validate_model_dir` refuses apack that lacks it instead of letting that fallback happen.- - The schedule is the fixed distilled one: `DISTILLED_SIGMAS` is 8 steps and- `STAGE_2_SIGMAS` is 3. Passing no step counts selects exactly those, which- is why this runner exposes no steps flag.+ - The recipe is the standard single-stage IC-LoRA video-to-video pass+ (Lightricks' IC-LoRA guide and their ComfyUI reference workflow: distilled+ schedule at the set resolution, the low-resolution clip as the reference at+ half of it). `ICLoraPipeline.generate` renders its IC-conditioned stage 1+ at HALF the dims it is handed and offers a latent-upsample stage 2 for the+ other half, so this runner requests twice the output and skips stage 2 —+ stage 1 then renders at the output size, conditioned on the source at its+ native resolution, and its decode is the deliverable+ (`_upscale_contract.conditioned_stage_request`).+ - The schedule is the fixed distilled one: `DISTILLED_SIGMAS` is 8 steps.+ Passing no step count selects exactly that, which is why this runner+ exposes no steps flag.- Quantization-safe fusion is the runtime's own contract: `apply_loras()`dequantizes an int4/int8 weight, adds the delta, and re-quantizes. What itdoes NOT do is complain when an adapter addresses keys the transformer does@@ -56,6 +65,7 @@ from _upscale_contract import ( # noqa: E402REFERENCE_STRENGTH,add_upscale_arguments,assert_reference_scale_fits,+ conditioned_stage_request,lora_target_keys,read_safetensors_header,reference_downscale_factor,@@ -66,6 +76,20 @@ from _upscale_contract import ( # noqa: E402# than a fallback — see the module docstring.TEXT_ENCODER_DIRNAME = "text_encoder"+# The two layouts the pinned q8 pack documents for the distilled model. The+# pre-fused `transformer-distilled.safetensors` is what `ICLoraPipeline.load()`+# resolves on its own; a pack that carries only the dev transformer holds the+# SAME model as dev weights plus the 450-step distilled LoRA, which the pack+# README names as the equivalent non-streaming arrangement and the runtime's+# own two-stage pipelines fuse for their distilled stage. The distilled+# schedule this runner drives is only valid on the distilled model, so dev+# WITHOUT that LoRA is a refusal, never a fallback.+DEV_TRANSFORMER_FILENAME = "transformer-dev.safetensors"+DISTILLED_LORA_FILENAME = "ltx-2.5-22b-distilled-lora-450.safetensors"+# Full strength turns the dev weights INTO the distilled model — the pack's+# README states the pre-fused file is this LoRA at the default strength of 1.0.+DISTILLED_LORA_STRENGTH = 1.0+FINGERPRINT_PACKAGES = ["ltx_pipelines_mlx", "ltx_core_mlx", "mlx", "mlx_metal"]@@ -137,6 +161,46 @@ def resolve_transformer_path(model_dir: Path) -> "Path | None":return fallback if fallback.is_file() else None+def resolve_transformer_layout(model_dir: Path) -> "tuple[Path | None, Path | None]":+ """`(transformer, distilled_lora)` for the pack — see the layout constants.++ The pre-fused distilled transformer wins whenever present (`distilled_lora`+ is then None). Otherwise the dev transformer is returned WITH the distilled+ LoRA that turns it into the distilled model, and `(None, None)` when the+ pack has neither the distilled file nor a dev file. A dev file whose LoRA is+ missing is reported as `(dev, None)` so the caller can refuse it by name.+ """+ distilled = resolve_transformer_path(model_dir)+ if distilled is not None:+ return distilled, None+ dev = model_dir / DEV_TRANSFORMER_FILENAME+ if not dev.is_file():+ return None, None+ lora = model_dir / DISTILLED_LORA_FILENAME+ return dev, (lora if lora.is_file() else None)+++def make_pipeline(pipeline_cls, model_dir: Path, transformer_path: Path, lora_paths):+ """An `ICLoraPipeline` whose DiT is the resolved transformer, whichever layout.++ `ICLoraPipeline.load()` resolves the transformer itself and knows only the+ distilled-file layout, so a dev-layout pack has to be steered: the subclass+ loads the resolved file first and lets `load()` skip its own resolution+ (it only resolves when `dit` is still None). The load still happens inside+ `generate()`, AFTER the text encoder has been freed, so nothing here holds+ the DiT resident through prompt encoding. `lora_paths` is every adapter+ `_fuse_loras` will add to the DiT in ONE pass — the IC adapter, and on a dev+ layout the distilled LoRA beside it.+ """+ class PackLayoutPipeline(pipeline_cls):+ def load(self):+ if self.dit is None and not self._loaded:+ self.dit = self._load_transformer_with_optional_streaming(transformer_path)+ super().load()++ return PackLayoutPipeline(model_dir=str(model_dir), lora_paths=list(lora_paths))++def transformer_weight_keys(transformer_path: Path) -> "set[str]":"""The transformer's fusable parameter names, read from its header alone.@@ -218,11 +282,19 @@ def main() -> None:# move this behind a `pipe.load()`: `generate()` deliberately loads the text# encoder, encodes, frees it, and only THEN loads the transformer, so# pre-loading would hold a multi-GB DiT resident through prompt encoding.- transformer_path = resolve_transformer_path(model_dir)+ transformer_path, distilled_lora = resolve_transformer_layout(model_dir)if transformer_path is None:raise SystemExit(f"The LTX-2.5 pack at {model_dir} has no transformer weight file. Repair the model in Video Gen.")+ if transformer_path.name == DEV_TRANSFORMER_FILENAME and distilled_lora is None:+ raise SystemExit(+ f"The LTX-2.5 pack at {model_dir} carries only {DEV_TRANSFORMER_FILENAME} and not the "+ f"{DISTILLED_LORA_FILENAME} that makes it the distilled model the upscale schedule needs. "+ "Repair the model in Video Gen."+ )+ layout = transformer_path.name + (f" + {distilled_lora.name}" if distilled_lora else "")+ log(f"STATUS:Transformer layout: {layout}")fused = assert_adapter_fuses(args.ic_lora_path,transformer_weight_keys(transformer_path),@@ -232,23 +304,31 @@ def main() -> None:log("STAGE:load-pipeline")log(f"STATUS:Loading LTX-2.5 MLX upscale pipeline ({args.width}x{args.height}, {args.num_frames} frames)")- pipe = ICLoraPipeline(model_dir=str(model_dir), lora_paths=[(args.ic_lora_path, 1.0)])+ lora_paths = [(args.ic_lora_path, 1.0)]+ if distilled_lora is not None:+ lora_paths.append((str(distilled_lora), DISTILLED_LORA_STRENGTH))+ pipe = make_pipeline(ICLoraPipeline, model_dir, transformer_path, lora_paths)output = Path(args.output)output.parent.mkdir(parents=True, exist_ok=True)+ request_width, request_height = conditioned_stage_request(args.width, args.height)log("STAGE:inference")with heartbeat("ltx25-upscale-inference"):- # No stage step counts: `DISTILLED_SIGMAS` / `STAGE_2_SIGMAS` ARE the- # distilled schedule (8 + 3), and passing a count would truncate them.+ # Stage 1 renders at half the requested dims — i.e. AT the output — with+ # the source as its native-resolution reference, and `skip_stage_2`+ # makes that stage's decode the deliverable (see the module docstring).+ # No stage-1 step count: `DISTILLED_SIGMAS` IS the distilled schedule+ # (8 steps), and passing a count would truncate it.pipe.generate_and_save(prompt=args.prompt,output_path=str(output),video_conditioning=[(reference, REFERENCE_STRENGTH) for reference in args.ic_reference],- height=args.height,- width=args.width,+ height=request_height,+ width=request_width,num_frames=args.num_frames,frame_rate=args.fps,seed=args.seed,+ skip_stage_2=True,)if not output.is_file():raise SystemExit(f"The LTX-2.5 upscale completed but did not write {output}.")diff --git a/scripts/upscale_ltx25.test.js b/scripts/upscale_ltx25.test.jsindex dfa1a18aeb..23e6ce766a 100644--- a/scripts/upscale_ltx25.test.js+++ b/scripts/upscale_ltx25.test.js@@ -194,14 +194,27 @@ describe.skipIf(!pyBin)('upscale_ltx25.py — adapter metadata (#6512)', () => {expect(call(`repr(runner.read_safetensors_header(${JSON.stringify(join(scratch, 'nope.safetensors'))}))`)).toBe('None');}, PY_TEST_TIMEOUT_MS);- // The rule the pipeline enforces applies to the STAGE-1 dims, which are half- // the output — so a factor of 2 really demands an output divisible by 4. The- // message has to speak in output terms because that is what the user chose.- it('enforces the adapter factor against the half-resolution stage dims', () => {+ // The conditioned stage renders AT the output, so the reference is+ // `output / factor` — and it has to land on the VAE's 32-pixel grid at the+ // source's own size, or the source is resampled before it conditions+ // anything. A factor of 2 therefore demands an output divisible by 64, and a+ // factor of 4 by 128. The message speaks in output terms because that is+ // what the user chose.+ it('enforces the adapter factor against the output the conditioned stage renders at', () => {expect(call('runner.assert_reference_scale_fits(2, 1728, 1024) or "OK"')).toBe('OK');expect(call('runner.assert_reference_scale_fits(1, 100, 100) or "OK"')).toBe('OK');- expect(call('runner.assert_reference_scale_fits(4, 1028, 1024) or "OK"'))- .toMatch(/^REJECTED:.*divisible by 8/);+ expect(call('runner.assert_reference_scale_fits(2, 1056, 1024) or "OK"'))+ .toMatch(/^REJECTED:.*divisible by 64/);+ expect(call('runner.assert_reference_scale_fits(4, 1088, 1024) or "OK"'))+ .toMatch(/^REJECTED:.*divisible by 128/);+ }, PY_TEST_TIMEOUT_MS);++ // Both pipelines render their IC-conditioned stage at HALF the dims they are+ // handed. The recipe is single-stage at the output with the source at half,+ // so the runner asks for twice the output and skips stage 2 — a runner that+ // passed the output through would condition on a further-downscaled source.+ it('requests twice the output so the conditioned stage renders at the output size', () => {+ expect(call('runner.conditioned_stage_request(1024, 576)')).toBe('(2048, 1152)');}, PY_TEST_TIMEOUT_MS);// `apply_loras` pairs lora_A with lora_B per weight and skips a prefix missing@@ -290,4 +303,46 @@ describe.skipIf(!pyBin)('upscale_ltx25.py — transformer header (#6512)', () =>writeFileSync(join(pack, 'transformer.safetensors'), '');expect(resolve(pack)).toBe("'transformer.safetensors'");}, PY_TEST_TIMEOUT_MS);++ // The pinned q8 pack documents two layouts for the distilled model: the+ // pre-fused file, or the dev transformer plus the 450-step distilled LoRA.+ // The pipeline's own loader knows only the first, so the runner resolves the+ // layout itself — and refuses dev WITHOUT the LoRA, because the distilled+ // schedule on an un-distilled model is not a fallback, it is a wrong render.+ it('resolves the dev + distilled-LoRA layout, preferring a pre-fused distilled file', () => {+ const pack = mkdtempSync(join(tmpdir(), 'portos-ltx25-layout-'));+ const layout = (dir) => call(`[p and p.name for p in runner.resolve_transformer_layout(__import__("pathlib").Path(${JSON.stringify(dir)}))]`);+ expect(layout(pack)).toBe('[None, None]');++ writeFileSync(join(pack, 'transformer-dev.safetensors'), '');+ expect(layout(pack)).toBe("['transformer-dev.safetensors', None]");++ writeFileSync(join(pack, 'ltx-2.5-22b-distilled-lora-450.safetensors'), '');+ expect(layout(pack)).toBe("['transformer-dev.safetensors', 'ltx-2.5-22b-distilled-lora-450.safetensors']");++ writeFileSync(join(pack, 'transformer-distilled.safetensors'), '');+ expect(layout(pack)).toBe("['transformer-distilled.safetensors', None]");+ }, PY_TEST_TIMEOUT_MS);++ // `ICLoraPipeline.load()` resolves the transformer only while `dit` is None,+ // so steering a dev-layout pack means loading the resolved file first and+ // letting the base `load()` skip its own resolution. Exercised against a+ // stand-in base class so the contract is pinned without the MLX wheel.+ it('loads the resolved transformer before the base pipeline resolves its own', () => {+ const source = [+ 'class FakeBase:',+ ' def __init__(self, model_dir, lora_paths=None):',+ ' self.model_dir = model_dir; self.lora_paths = lora_paths; self.dit = None; self._loaded = False; self.calls = []',+ ' def _load_transformer_with_optional_streaming(self, path):',+ ' self.calls.append(path.name); return "dit"',+ ' def load(self):',+ ' self.calls.append("base-load:" + str(self.dit)); self._loaded = True',+ 'from pathlib import Path',+ 'pipe = runner.make_pipeline(FakeBase, Path("/pack"), Path("/pack/transformer-dev.safetensors"), [("adapter", 1.0), ("distilled", 1.0)])',+ 'pipe.load(); pipe.load()',+ 'print(pipe.calls, pipe.lora_paths, pipe.model_dir)',+ ].join('\n');+ expect(trimmed(runPython(`${importRunner}\n${source}`)))+ .toBe("['transformer-dev.safetensors', 'base-load:dit', 'base-load:dit'] [('adapter', 1.0), ('distilled', 1.0)] /pack");+ }, PY_TEST_TIMEOUT_MS);});diff --git a/scripts/upscale_ltx25_cuda.py b/scripts/upscale_ltx25_cuda.pyindex f798ed3bb3..07f7381bfb 100644--- a/scripts/upscale_ltx25_cuda.py+++ b/scripts/upscale_ltx25_cuda.py@@ -18,8 +18,14 @@ installs), not inferred from the gated model card:that `generate_ltx25_cuda.py` already drives `DistilledPipeline` with, sothe FP8 cast policy and disk streaming that make a 22B model fit a consumercard 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.+ (`stage_2` is built with `loras=()`), and stage 1 renders at HALF the+ `height`/`width` it is handed — so, exactly like the MLX runner, this one+ requests twice the output and passes `skip_stage_2=True`: the conditioned+ stage renders at the output size with the source as a native-resolution+ reference and its decode is the deliverable+ (`_upscale_contract.conditioned_stage_request`). That is the standard+ single-stage IC-LoRA video-to-video recipe Lightricks documents for the+ upscaler; the latent-upsample stage 2 never runs.- The LoRA is a `LoraPathStrengthAndSDOps(path, strength, sd_ops)` and the`sd_ops` is the runtime's own `LTXV_LORA_COMFY_RENAMING_MAP`. Both comefrom `ltx_core.loader`; naming the map here rather than reimplementing it@@ -39,12 +45,12 @@ installs), not inferred from the gated model card:requires the raw `model.diffusion_model.` prefix and strips it; the LoRAmap 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.+ - The schedule is the fixed distilled one — `DISTILLED_SIGMAS` (8) is the+ `__call__` default for stage 1 — which is why this runner, like the MLX+ one, exposes no steps flag.+ - `assert_resolution(..., is_two_stage=True)` demands `% 64` of the REQUEST,+ which the shared contract's `% 64` rule on the output satisfies twice over,+ 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@@ -73,6 +79,7 @@ from _upscale_contract import ( # noqa: E402REFERENCE_STRENGTH,add_upscale_arguments,assert_reference_scale_fits,+ conditioned_stage_request,entry_shape,lora_delta_shapes,read_safetensors_header,@@ -310,21 +317,25 @@ def main() -> None:offload_mode=OffloadMode.DISK,)+ request_width, request_height = conditioned_stage_request(args.width, args.height)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.+ # Stage 1 renders at half the requested dims — i.e. AT the output — and+ # `skip_stage_2` makes its decode the deliverable (module docstring).+ # No sigma override: `DISTILLED_SIGMAS` IS the distilled schedule (8)+ # and is this call's stage-1 default. `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,+ height=request_height,+ width=request_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,+ skip_stage_2=True,)output = Path(args.output)diff --git a/scripts/upscale_ltx25_cuda.test.js b/scripts/upscale_ltx25_cuda.test.jsindex fac704c73a..9811432781 100644--- a/scripts/upscale_ltx25_cuda.test.js+++ b/scripts/upscale_ltx25_cuda.test.js@@ -321,11 +321,18 @@ describe.skipIf(!pyBin)('upscale_ltx25_cuda.py — adapter fusion guard (#6513)'// 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', () => {+ it('reads the factor off the weight and enforces it against the output the conditioned stage renders at', () => {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/);+ expect(call('runner.assert_reference_scale_fits(4, 1088, 1024) or "OK"'))+ .toMatch(/^REJECTED:.*divisible by 128/);+ }, PY_TEST_TIMEOUT_MS);++ // Same recipe as MLX: upstream's `ICLoraPipeline` renders stage 1 at half+ // the dims it is handed, so the runner requests twice the output and skips+ // stage 2. Shared through the contract module so the two cannot drift.+ it('requests twice the output through the shared contract', () => {+ expect(call('runner.conditioned_stage_request(1024, 576)')).toBe('(2048, 1152)');}, PY_TEST_TIMEOUT_MS);});diff --git a/server/lib/icLoraWeights.js b/server/lib/icLoraWeights.jsindex c85654cab7..2b61fcdc90 100644--- a/server/lib/icLoraWeights.js+++ b/server/lib/icLoraWeights.js@@ -170,20 +170,16 @@ export const IC_LORA_MODES = Object.freeze({revision: '5863fdef3eaa8b2d69fa22e259a1d75fede215dd',// Exact, from the repo's blob listing — not an estimate. Do not round it.sizeBytes: 327_322_640,- // UNKNOWN, deliberately, and it STAYS unknown here. Every other entry's- // factor was read from the weight's safetensors `__metadata__`; this- // weight's file is gated, so there is nothing for the repo to read. `null`- // means "no constraint asserted", which icResolutionIssue treats as "impose- // no rule" rather than guessing a factor and either rejecting valid- // resolutions or green-lighting bad ones.- //- // #6512 resolved this by MEASURING instead of transcribing: an install that- // has accepted the terms and downloaded the weight reads the real value out- // of the file it holds (`readIcLoraReferenceDownscaleFactor` below, and- // `reference_downscale_factor` in `scripts/upscale_ltx25.py`, which enforces- // it). Hardcoding a number here would put a value nobody in this repo can- // verify ahead of the one every user can — so leave it null.- referenceDownscaleFactor: null,+ // Read from the weight's safetensors `__metadata__.reference_downscale_factor`+ // — "2" — on 2026-09-07, off the file at the pinned revision above+ // (sha256 984851b769ea2bcb4c9e0a239a7676239e42c6a6001ddc69943b41ff0b283c1d),+ // on an install that had accepted the license (#6512). The model card+ // states the same value. The entry was `null` until then precisely because+ // the file is gated and nothing in this repo could open it; the value here+ // is the DECLARED one, and `readIcLoraReferenceDownscaleFactor` below still+ // reads the real file whenever an install holds it, so a re-pinned weight+ // that changes its factor is measured rather than trusted.+ referenceDownscaleFactor: 2,// The clip being upscaled is the single reference.minReferences: 1,maxReferences: 1,diff --git a/server/lib/icLoraWeights.test.js b/server/lib/icLoraWeights.test.jsindex b9a64f491c..e6da0dfb25 100644--- a/server/lib/icLoraWeights.test.js+++ b/server/lib/icLoraWeights.test.js@@ -120,13 +120,15 @@ describe('IC-LoRA registry', () => {expect(icResolutionIssue(IC_LORA_MODES.control, 704, 448)).toBeNull();});- it('asserts no resolution rule for a weight whose factor has not been read', () => {- // The upscaler's file is gated, so its `reference_downscale_factor` is- // unknown rather than known-to-be-1. Guessing either way is the bug: a- // guessed 2 rejects valid resolutions, and treating a non-number as a- // divisor produces a nonsense message. Both must yield "no rule".- expect(IC_LORA_MODES['pixel-upscale'].referenceDownscaleFactor).toBeNull();- expect(icResolutionIssue(IC_LORA_MODES['pixel-upscale'], 705, 449)).toBeNull();+ it('applies the upscaler factor now that it has been measured, and no rule for an unread one', () => {+ // The upscaler's factor was read off the gated weight (#6512), so the+ // plan can state its rule before a download. A weight whose factor is+ // genuinely unknown must still yield "no rule": guessing rejects valid+ // resolutions, and treating a non-number as a divisor produces a nonsense+ // message.+ expect(icResolutionIssue(IC_LORA_MODES['pixel-upscale'], 705, 449)).toMatch(/divisible by 2/);+ expect(icResolutionIssue(IC_LORA_MODES['pixel-upscale'], 704, 448)).toBeNull();+ expect(icResolutionIssue({ referenceDownscaleFactor: null }, 705, 449)).toBeNull();expect(icResolutionIssue({ referenceDownscaleFactor: undefined }, 705, 449)).toBeNull();expect(icResolutionIssue({ referenceDownscaleFactor: '2' }, 705, 449)).toBeNull();});@@ -411,18 +413,22 @@ describe('the LTX-2.5 Pixel Spatial Upscaler weight (#6502)', () => {});});-// #6512. The Pixel Spatial Upscaler entry holds `referenceDownscaleFactor: null`-// because its file is gated and nobody in this repo can read it — so the value-// is MEASURED off the weight an install downloaded rather than transcribed from-// a card. `measured` is what keeps "the weight declares 1" apart from "nobody-// has read it yet": both impose no rule, but only one is a fact.+// #6512. The Pixel Spatial Upscaler's factor was MEASURED off the gated weight+// once an install could open it, and the registry now declares that value — but+// the file is still read whenever it is present, so `measured` keeps "the+// registry says 2" apart from "this file says 2": a re-pinned weight that+// changes its factor is measured rather than trusted.describe('readIcLoraReferenceDownscaleFactor', () => {const upscaler = () => icLoraSpecByKey('pixel-upscale');+ it('declares the measured factor so the plan can state the rule before the weight is downloaded', () => {+ expect(upscaler().referenceDownscaleFactor).toBe(2);+ });+it('falls back to the registry value when nothing is cached, without reading a file', async () => {mockFindCachedRepoFile.mockResolvedValue(null);expect(await readIcLoraReferenceDownscaleFactor(upscaler()))- .toEqual({ factor: null, measured: false });+ .toEqual({ factor: 2, measured: false });expect(mockReadSafetensorsHeader).not.toHaveBeenCalled();});@@ -444,12 +450,13 @@ describe('readIcLoraReferenceDownscaleFactor', () => {});// An UNREADABLE header is not a measurement of anything. Collapsing it into a- // measured 1 would assert a rule off a file we failed to open.+ // measured 1 would assert a rule off a file we failed to open; the declared+ // registry value stands, unmeasured.it('does not claim a measurement when the header cannot be read', async () => {mockFindCachedRepoFile.mockResolvedValue('/cache/truncated.safetensors');mockReadSafetensorsHeader.mockResolvedValue(null);expect(await readIcLoraReferenceDownscaleFactor(upscaler()))- .toEqual({ factor: null, measured: false });+ .toEqual({ factor: 2, measured: false });});// A 2.3 weight already carries a verified number, so a cached read must agreediff --git a/server/services/videoGen/upscaleJob.js b/server/services/videoGen/upscaleJob.jsindex 5d0087eb12..d1f864e0de 100644--- a/server/services/videoGen/upscaleJob.js+++ b/server/services/videoGen/upscaleJob.js@@ -50,6 +50,14 @@ import {const MAX_SEED = 2 ** 32 - 1;const STAGE_RE = /^STAGE:\s*(\S+)\s*(.*)$/;+// Both runners emit these once, before the pipeline loads: the runtime+// fingerprint (`scripts/_runner_common.py emit_runtime_fingerprint`) and the+// adapter's `reference_downscale_factor` read off the weight. They are+// provenance, so they are captured here and written onto the history row —+// a render can then be tied to the exact ltx/mlx/torch + chip stack and the+// factor it enforced, the way a plain render's row carries `runtime`.+const RUNTIME_PREFIX = 'RUNTIME:';+const REFERENCE_DOWNSCALE_RE = /^UPSCALE_REFERENCE_DOWNSCALE:\s*(\d+)\s*$/;const STDERR_TAIL_LINES = 20;// jobId → the in-flight run's cancel handles. Module-local rather than the@@ -212,6 +220,7 @@ const runUpscaleChild = async ({ jobId, bin, args, runtime, entry }) => {// so signal it immediately instead of waiting for a render nobody wants.if (entry.canceled) cancel(jobId);const stderrTail = [];+ const provenance = { runtime: null, referenceDownscale: null };const onLine = (line, isStderr) => {const text = String(line).trim();if (!text || PYTHON_NOISE_RE.test(text)) return;@@ -220,6 +229,17 @@ const runUpscaleChild = async ({ jobId, bin, args, runtime, entry }) => {if (stderrTail.length > STDERR_TAIL_LINES) stderrTail.shift();}videoGenEvents.emit('activity', { generationId: jobId });+ if (text.startsWith(RUNTIME_PREFIX)) {+ // A malformed payload stays in the stderr tail rather than becoming a+ // half-parsed fingerprint on the row.+ try { provenance.runtime = JSON.parse(text.slice(RUNTIME_PREFIX.length)); } catch { /* keep null */ }+ return;+ }+ const downscale = REFERENCE_DOWNSCALE_RE.exec(text);+ if (downscale) {+ provenance.referenceDownscale = Number(downscale[1]);+ return;+ }const stage = STAGE_RE.exec(text);if (stage) {videoGenEvents.emit('status', { generationId: jobId, phase: stage[1], message: stage[2] || stage[1] });@@ -240,7 +260,7 @@ const runUpscaleChild = async ({ jobId, bin, args, runtime, entry }) => {};proc.on('error', (err) => settle({ ok: false, reason: `spawn failed: ${err.message}` }));proc.on('close', (code, signal) => {- if (code === 0) { settle({ ok: true }); return; }+ if (code === 0) { settle({ ok: true, ...provenance }); return; }const tail = stderrTail.slice(-4).join(' | ');const how = signal ? `killed (${signal})` : `exit ${code}`;settle({ ok: false, reason: tail ? `upscale runner ${how}: ${tail}` : `upscale runner ${how}` });@@ -394,6 +414,12 @@ export async function runVideoUpscale({upscaleMethod: 'ltx',upscaleRuntime: runtime,upscaleAdapter: adapterKey,+ // Measured by the runner off the weight it fused, and the rule it+ // enforced — null when the runner did not report one.+ upscaleReferenceDownscale: rendered.referenceDownscale ?? null,+ // Same shape a plain render's row carries: the exact ltx/mlx/torch ++ // chip + OS stack this clip rendered on. Absent when not reported.+ ...(rendered.runtime ? { runtime: rendered.runtime } : {}),// What the grid actually required of this source, kept beside the result// so a reader can tell a padded render from a conforming one.upscaleAlignment: {diff --git a/server/services/videoGen/upscaleJob.test.js b/server/services/videoGen/upscaleJob.test.jsindex df0b576e87..1c114077f3 100644--- a/server/services/videoGen/upscaleJob.test.js+++ b/server/services/videoGen/upscaleJob.test.js@@ -299,6 +299,30 @@ describe('local-only (#6511 item 7)', () => {});describe('runVideoUpscale — success', () => {+ // Both runners announce the fingerprint of the stack they run on and the+ // factor they read off the adapter before the pipeline loads. Those are+ // provenance: a clip must be traceable to the exact runtime and the rule it+ // enforced, the way a plain render's row carries `runtime` (#6512).+ it('records the runtime fingerprint and measured reference factor the runner reports', async () => {+ const fingerprint = { runtime: 'ltx25', versions: { mlx: '0.32.0' }, chip: 'Apple Mx' };+ const entry = await runWith(() => {+ state.child.stderr.emit('data', 'UPSCALE_REFERENCE_DOWNSCALE:2\n');+ state.child.stderr.emit('data', `RUNTIME:${JSON.stringify(fingerprint)}\n`);+ state.child.stderr.emit('data', 'STAGE:inference\n');+ finishChild(0);+ });+ expect(entry.upscaleReferenceDownscale).toBe(2);+ expect(entry.runtime).toEqual(fingerprint);+ });++ it('keeps a malformed fingerprint line off the row instead of half-parsing it', async () => {+ const entry = await runWith(() => {+ state.child.stderr.emit('data', 'RUNTIME:{not json\n');+ finishChild(0);+ });+ expect(entry.runtime).toBeUndefined();+ });+it('writes a new history row carrying the full provenance contract', async () => {const completed = [];videoGenEvents.on('completed', (e) => completed.push(e));@@ -322,6 +346,10 @@ describe('runVideoUpscale — success', () => {hidden: false,});expect(entry.renderMs).toBeGreaterThanOrEqual(0);+ // Nothing reported by the runner → explicit absent sentinels, never a+ // guessed factor or a half-parsed fingerprint.+ expect(entry.upscaleReferenceDownscale).toBeNull();+ expect(entry.runtime).toBeUndefined();// The source render's timing must not ride along on a row that only paid// for the upscale.expect(entry.renderStartedAt).not.toBe('2026-01-01T00:00:00.000Z');diff --git a/server/services/videoGen/upscalePlan.js b/server/services/videoGen/upscalePlan.jsindex 6f3db359ac..ad84fdd93f 100644--- a/server/services/videoGen/upscalePlan.js+++ b/server/services/videoGen/upscalePlan.js@@ -53,18 +53,18 @@ export const ltxUpscaleBaseModelId = (runtime) => (LTX_UPSCALE_BASE_MODEL_BY_RUNTIME[runtime] || null);-// The LTX-2.5 two-stage grid, mirrored from `validate_args` in-// `scripts/generate_ltx25_cuda.py`: output dimensions must be divisible by 64-// and the frame count must satisfy `frames % 8 == 1` with a floor of 9.+// The LTX-2.5 grid, mirrored from `scripts/_upscale_contract.py`: output+// dimensions must be divisible by 64 and the frame count must satisfy+// `frames % 8 == 1` with a floor of 9.//-// #6512 confirmed the MLX backend imposes the SAME rule, and read it off the-// pinned runtime rather than the gated model card: `ICLoraPipeline.generate`-// renders Stage 1 at `height // 2` / `width // 2`, and-// `compute_video_latent_shape` compresses spatially by 32 — so the OUTPUT axis-// must divide by 64. Temporal compression is 8 and the IC reference encoder-// needs a (1 + 8k)-frame input, which is the frame rule. Both runners now read-// the rule from here; `scripts/upscale_ltx25.py` mirrors the numbers with a-// comment pointing back, the way the CUDA runner already does.+// #6512 established the rule on both backends from the runtimes and Lightricks'+// own IC-LoRA recipe rather than the gated card. The upscaler is the standard+// single-stage IC-LoRA pass at the OUTPUT size with the source as a reference+// at half of it; the video VAE compresses spatially by 32, so for the reference+// to land on that grid at exactly the (padded) source's own size — rather than+// being resampled before it conditions anything — the output must divide by+// 2 × 32. Temporal compression is 8 and the IC reference encoder needs a+// (1 + 8k)-frame input, which is the frame rule.export const LTX_GRID = Object.freeze({spatialMultiple: 64,frameModulus: 8,