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: keep LoRA effects under LTX block streaming by applying adapters per block at inference (#12327)
Adam Eivy12c6d958468f
diff --git a/scripts/ltx_runtime_lora.py b/scripts/ltx_runtime_lora.pyindex 40d836bfac..fc03bc6599 100644--- a/scripts/ltx_runtime_lora.py+++ b/scripts/ltx_runtime_lora.py@@ -22,6 +22,17 @@ miss. Swapping the instance to a cached subclass whose ``__call__`` adds thedelta, with the adapter arrays held outside the parameter tree, keeps everyparameter name and every packed array untouched.+Block streaming (#12327) rebinds ONE shared block per index from the mmap'd+pack and runs it through ``mx.compile(shared, inputs=shared)``, so a delta held+outside that block's parameter tree would be traced as a constant and applied+to every index. Under streaming the model's class is swapped too: its block+provider binds the packed weights exactly as the runtime does (runtime-owned+``_lora_sources`` such as a custom-strength distilled LoRA still merge there),+then points each quantized projection's adapter slots at block ``idx``'s+arrays and fuses float targets into the freshly bound float weight. The block+is recompiled with those slots as declared inputs, so every index sees only+its own delta and the compiled graph stays valid.+The math contract mirrors the runtime's ``apply_loras`` exactly — the samerenamed keys, ``delta = strength * B @ A`` and no alpha rescale — so a q4 renderand a bf16 render at one strength mean the same thing. Validation is stricter:@@ -43,10 +54,6 @@ from typing import Any, Callable, IterableSTRATEGY_RUNTIME = "runtime-delta"STRATEGY_FUSED = "fused-float"STRATEGY_MIXED = "runtime-delta+fused-float"-# Block streaming rebinds one shared, compiled block per index, so an-# activation-space delta has nowhere stable to live; those renders keep the-# runtime's own per-block merge-and-requantize and say so.-STRATEGY_REQUANTIZED = "merged-requantized"_A_SUFFIX = ".lora_A.weight"_B_SUFFIX = ".lora_B.weight"@@ -58,6 +65,16 @@ _ADAPTERS_ATTR = "_portos_runtime_lora"_BASE_CLASS_ATTR = "_portos_runtime_lora_base"_RUNTIME_CLASSES: dict[type, type] = {}+_STREAMING_ATTR = "_portos_streaming_lora"+_STREAMING_BASE_ATTR = "_portos_streaming_lora_base"+_STREAMING_CLASSES: dict[type, type] = {}+# The runtime's renamed adapter keys address blocks under this prefix+# (ltx_core_mlx.loader.sd_ops.LTXV_LORA_BLOCK_PREFIX).+_BLOCK_PREFIX = "transformer_blocks."+# A float projection outside the streamed blocks is fused once; its pre-fusion+# weight is kept so dropping one adapter can re-fuse the rest.+_FUSED_BASE_ATTR = "_portos_fused_base"+def _mlx():import mlx.core as mx@@ -97,6 +114,26 @@ def _module_at(model, target: str):return node+def is_streaming_model(model) -> bool:+ """True for the runtime's StreamingLTXModel: one shared block rebound per index."""+ attrs = getattr(model, "__dict__", {})+ return "_streamer" in attrs and "_shared_block" in attrs+++def _locate(model, target: str):+ """``(module, block)`` for a renamed target; ``block`` is ``(index, path)`` when streamed."""+ if not is_streaming_model(model):+ return _module_at(model, target), None+ attrs = model.__dict__+ if target.startswith(_BLOCK_PREFIX):+ index, _, path = target[len(_BLOCK_PREFIX):].partition(".")+ if index.isdigit() and path:+ if int(index) >= attrs["_streamer"].block_count:+ return None, None+ return _module_at(attrs["_shared_block"], path), (int(index), path)+ return _module_at(model.inner, target), None++def _logical_shape(module, quantized: bool) -> tuple[int, int]:output_dims, stored_input_dims = (int(v) for v in module.weight.shape)if not quantized:@@ -138,7 +175,7 @@ def _plan(model, label: str, tensors: dict, strength: float) -> list[tuple]:if "A" not in pair or "B" not in pair:missing = "lora_B" if "A" in pair else "lora_A"raise ValueError(f"LoRA {label} target {target} has no {missing} tensor")- module = _module_at(model, target)+ module, block = _locate(model, target)if module is None:raise ValueError(f"LoRA {label} targets {target}, which this transformer does not have — "@@ -162,40 +199,57 @@ def _plan(model, label: str, tensors: dict, strength: float) -> list[tuple]:f"LoRA {label} target {target} has lora_A {tuple(down.shape)} / lora_B "f"{tuple(up.shape)}, which do not fit a ({output_dims}, {input_dims}) projection")- planned.append((target, module, quantized, down, up, float(strength)))+ planned.append((target, module, quantized, down, up, float(strength), block))return planned-def _apply(module, quantized: bool, down, up, strength: float) -> None:+def _runtime_pair(down, up, strength: float, dtype) -> tuple:+ """``(A, strength * B)`` in the quantized kernel's activation dtype."""mx, _nn = _mlx()+ return down.astype(dtype), (up.astype(mx.float32) * strength).astype(dtype)+++def _fused_weight(weight, pairs) -> Any:+ """``weight + sum(strength * B @ A)``, accumulated in float32."""+ mx, _nn = _mlx()+ fused = weight.astype(mx.float32)+ for down, up, strength in pairs:+ fused = fused + (up.astype(mx.float32) * strength) @ down.astype(mx.float32)+ return fused.astype(weight.dtype)+++def _apply(module, quantized: bool, down, up, strength: float) -> None:if quantized:# The quantized kernel's scales carry the activation dtype the base# projection computes in; hold the delta in it so nothing promotes.- dtype = module.scales.dtype- entry = (down.astype(dtype), (up.astype(mx.float32) * strength).astype(dtype))+ entry = _runtime_pair(down, up, strength, module.scales.dtype)if _ADAPTERS_ATTR not in module.__dict__:module.__class__ = _runtime_class(type(module))object.__setattr__(module, _ADAPTERS_ATTR, [])module.__dict__[_ADAPTERS_ATTR].append(entry)return- delta = (up.astype(mx.float32) * strength) @ down.astype(mx.float32)- module.weight = (module.weight.astype(mx.float32) + delta).astype(module.weight.dtype)+ module.weight = _fused_weight(module.weight, [(down, up, strength)])-def attach_adapters(model, adapters: Iterable[tuple[str, dict, float]]) -> list[dict]:+def attach_adapters(model, adapters: Iterable[tuple[str, dict, float]], *, tag: str | None = None) -> list[dict]:"""Attach ``(label, renamed_tensors, strength)`` adapters to ``model`` in place.Every adapter is validated before any module changes, so a malformed filelater in the list cannot leave an earlier one half-applied. Returns onesummary per adapter with the strategy its targets actually received.+ ``tag`` lets ``drop_streaming_adapters`` remove these later from a streamed+ model, which the runtime never reloads between stages."""plans = [(label, strength, _plan(model, label, tensors, strength)) for label, tensors, strength in adapters]+ streaming = is_streaming_model(model)summaries = []for label, strength, planned in plans:- quantized_targets = 0- for _target, module, quantized, down, up, scale in planned:- _apply(module, quantized, down, up, scale)- quantized_targets += int(quantized)+ if streaming:+ _attach_streaming(model, planned, tag)+ else:+ for _target, module, quantized, down, up, scale, _block in planned:+ _apply(module, quantized, down, up, scale)+ quantized_targets = sum(int(quantized) for _t, _m, quantized, *_rest in planned)fused_targets = len(planned) - quantized_targetsstrategy = (STRATEGY_MIXED if quantized_targets and fused_targetselse STRATEGY_RUNTIME if quantized_targets else STRATEGY_FUSED)@@ -209,6 +263,198 @@ def attach_adapters(model, adapters: Iterable[tuple[str, dict, float]]) -> list[return summaries+def _streaming_class(base_cls: type) -> type:+ cls = _STREAMING_CLASSES.get(base_cls)+ if cls is not None:+ return cls++ def __call__(self, *args, **kwargs):+ if kwargs.get("block_provider") is None:+ kwargs["block_provider"] = _block_provider(self, use_compiled=kwargs.get("perturbations") is None)+ return base_cls.__call__(self, *args, **kwargs)++ cls = type(f"RuntimeLora{base_cls.__name__}", (base_cls,), {+ "__call__": __call__,+ _STREAMING_BASE_ATTR: base_cls,+ })+ _STREAMING_CLASSES[base_cls] = cls+ return cls+++def _block_provider(model, *, use_compiled: bool):+ """The runtime's per-forward block provider, plus the per-index adapter bind.++ Mirrors ``StreamingLTXModel.__call__`` at the pinned runtimes. ``_streamer``+ and ``_lora_sources`` are read per forward because the two-stage pipelines+ swap the streamer and append a distilled-LoRA source between stages; those+ runtime-owned sources still merge inside ``bind``. Guidance perturbations+ cannot be traced by mx.compile, so they run the eager block, as upstream.+ """+ attrs = model.__dict__+ streamer, shared, state = attrs["_streamer"], attrs["_shared_block"], attrs[_STREAMING_ATTR]+ runtime_sources = attrs.get("_lora_sources") or None+ block = state["compiled"] if use_compiled else shared+ previous: list[int | None] = [None]++ def provider(index: int):+ streamer.bind(shared, index, evict_previous=previous[0], lora_sources=runtime_sources)+ previous[0] = index+ _bind_streamed_block(state, shared, index)+ return block++ return provider+++def _bind_streamed_block(state: dict, shared, index: int) -> None:+ """Point the shared block's adapters at block ``index`` right after its weights bind.++ The casts are built here, per bind, so only the bound block's copies are+ ever alive; a source tensor is whatever the adapter loader returned.+ """+ for path, slots in state["slots"].items():+ for slot, source in zip(slots, state["slot_sources"][path]):+ pair = source["blocks"].get(index)+ slot[0], slot[1] = (source["zero"] if pair is None+ else _runtime_pair(*pair, source["strength"], source["dtype"]))+ for path, sources in state["fused"].items():+ pairs = [(*source["blocks"][index], source["strength"]) for source in sources if index in source["blocks"]]+ if pairs:+ module = _module_at(shared, path)+ module.weight = _fused_weight(module.weight, pairs)+++def _streaming_state(model) -> dict:+ state = model.__dict__.get(_STREAMING_ATTR)+ if state is None:+ # slots: path -> [[down, up], ...], the SAME lists the quantized+ # projection iterates, declared as compile inputs. fused: float block+ # projections, fused into each freshly bound weight. outside: targets+ # beyond the streamed blocks, which stay resident.+ state = {"slots": {}, "slot_sources": {}, "fused": {}, "outside": [], "compiled": None}+ model.__class__ = _streaming_class(type(model))+ object.__setattr__(model, _STREAMING_ATTR, state)+ return state+++def _recompile(model) -> None:+ """Compile the shared block with its adapter slots as declared inputs.++ A fresh compiled function per slot layout: mx.compile retraces when input+ shapes change, but a layout change with equal shapes would reuse a trace+ that reads the wrong slots.+ """+ mx, _nn = _mlx()+ state = model.__dict__[_STREAMING_ATTR]+ shared = model.__dict__["_shared_block"]+ state["compiled"] = mx.compile(shared, inputs=[shared, state["slots"]])+++def _attach_streaming(model, planned: list[tuple], tag: str | None) -> None:+ mx, _nn = _mlx()+ state = _streaming_state(model)+ sources: dict[str, dict] = {}+ for _target, module, quantized, down, up, strength, block in planned:+ if block is None:+ state["outside"].append(_attach_outside_blocks(module, quantized, down, up, strength, tag))+ continue+ index, path = block+ source = sources.get(path)+ if source is None:+ source = sources[path] = {"tag": tag, "strength": strength, "blocks": {}}+ if quantized:+ dtype = module.scales.dtype+ source["dtype"] = dtype+ # A block this adapter does not address keeps the slot layout+ # (and so the compiled trace) and adds nothing.+ source["zero"] = (mx.zeros(down.shape, dtype=dtype), mx.zeros(up.shape, dtype=dtype))+ slots = state["slots"].get(path)+ if slots is None:+ slots = state["slots"][path] = []+ state["slot_sources"][path] = []+ module.__class__ = _runtime_class(type(module))+ object.__setattr__(module, _ADAPTERS_ATTR, slots)+ slots.append(list(source["zero"]))+ state["slot_sources"][path].append(source)+ else:+ state["fused"].setdefault(path, []).append(source)+ source["blocks"][index] = (down, up)+ _recompile(model)+++def _attach_outside_blocks(module, quantized: bool, down, up, strength: float, tag: str | None) -> dict:+ """Apply a non-block target as ``_apply`` does, recording what a drop must undo."""+ if not quantized:+ module.__dict__.setdefault(_FUSED_BASE_ATTR, module.weight)+ _apply(module, quantized, down, up, strength)+ record = {"module": module, "quantized": quantized, "tag": tag, "delta": (down, up, strength)}+ if quantized:+ record["entry"] = module.__dict__[_ADAPTERS_ATTR][-1]+ return record+++def drop_streaming_adapters(model, tag: str | None = None) -> int:+ """Remove adapters attached with ``tag`` (every one when None) from a streamed model.++ Under streaming the runtime's clean stage-2 refine keeps the same model and+ only clears its own ``_lora_sources``, so an IC adapter is dropped here or+ it would condition the refine. Returns the number of projections restored.+ """+ state = model.__dict__.get(_STREAMING_ATTR)+ if state is None:+ return 0+ shared = model.__dict__["_shared_block"]++ def dropped(item: dict) -> bool:+ return tag is None or item["tag"] == tag++ restored = 0+ for path in list(state["slots"]):+ keep = [i for i, source in enumerate(state["slot_sources"][path]) if not dropped(source)]+ slots = state["slots"][path]+ slots[:] = [slots[i] for i in keep]+ state["slot_sources"][path] = [state["slot_sources"][path][i] for i in keep]+ if not slots:+ _restore_class(_module_at(shared, path))+ del state["slots"][path], state["slot_sources"][path]+ restored += 1+ for path in list(state["fused"]):+ state["fused"][path] = [source for source in state["fused"][path] if not dropped(source)]+ if not state["fused"][path]:+ del state["fused"][path]++ removed = [record for record in state["outside"] if dropped(record)]+ state["outside"] = [record for record in state["outside"] if not dropped(record)]+ refuse: dict[int, Any] = {}+ for record in removed:+ module = record["module"]+ if not record["quantized"]:+ refuse[id(module)] = module+ continue+ entries = module.__dict__[_ADAPTERS_ATTR]+ entries[:] = [entry for entry in entries if entry is not record["entry"]]+ if not entries:+ _restore_class(module)+ restored += 1+ for module in refuse.values():+ remaining = [record["delta"] for record in state["outside"] if record["module"] is module]+ module.weight = _fused_weight(module.__dict__[_FUSED_BASE_ATTR], remaining)+ if not remaining:+ del module.__dict__[_FUSED_BASE_ATTR]+ restored += 1++ if tag is None:+ model.__class__ = getattr(type(model), _STREAMING_BASE_ATTR)+ del model.__dict__[_STREAMING_ATTR]+ else:+ _recompile(model)+ return restored+++def _restore_class(module) -> None:+ module.__class__ = getattr(type(module), _BASE_CLASS_ATTR)+ del module.__dict__[_ADAPTERS_ATTR]++def runtime_adapter_targets(model) -> list[str]:"""Names of the projections currently carrying an activation-space delta."""return [name for name, module in model.named_modules() if _ADAPTERS_ATTR in module.__dict__]@@ -216,11 +462,10 @@ def runtime_adapter_targets(model) -> list[str]:def detach_runtime_adapters(model) -> int:"""Restore every swapped projection to its original class. Returns the count."""- count = 0+ count = drop_streaming_adapters(model)for _name, module in model.named_modules():if _ADAPTERS_ATTR in module.__dict__:- module.__class__ = getattr(type(module), _BASE_CLASS_ATTR)- del module.__dict__[_ADAPTERS_ATTR]+ _restore_class(module)count += 1return count@@ -278,33 +523,20 @@ def install_pipeline_adapters(``ic=True`` the pipeline's ``_fuse_loras`` — called once, right beforestage 1 — attaches the IC adapter(s) to the loaded DiT instead; the cleanstage-2 reload goes back through the load hook and so carries the user- adapters but never the IC one.+ adapters but never the IC one. Block streaming takes the same route: the+ load hook returns a StreamingLTXModel and ``attach_adapters`` binds each+ block's delta per index (#12327); its clean refine keeps the model, so the+ reload wrapper drops the IC adapters from it instead.Paths must already be local files: `parse_user_loras` requires that, andthe IC constructor resolves its repo ids before this runs."""- if getattr(pipe, "low_ram_streaming", False):- if user_specs:- pipe._pending_loras = list(user_specs)- merged = [("user", "all", spec) for spec in user_specs]- if ic:- merged += [("ic", "stage-1", spec) for spec in getattr(pipe, "_lora_paths", [])]- for role, stage, (path, strength) in merged:- report.record(role, stage, path, _requantized_summary(path, strength))- if merged:- names = ", ".join(Path(path).name for _role, _stage, (path, _s) in merged)- status(- "Block streaming merges LoRA deltas into the quantized weights per block; a low-bit "- f"pack can lose part of their effect ({names})"- )- return-pipe._pending_loras = Noneload_transformer = pipe._load_transformer_with_optional_streamingdef attach(dit, role: str, stage: str, specs) -> None:loaded = [(path, load_adapter(path), strength) for path, strength in specs]- for (path, _tensors, _strength), summary in zip(loaded, attach_adapters(dit, loaded)):+ for (path, _tensors, _strength), summary in zip(loaded, attach_adapters(dit, loaded, tag=role)):if report.record(role, stage, path, summary):status(f"{role} LoRA {summary['name']}: {summary['strategy']} "@@ -328,6 +560,15 @@ def install_pipeline_adapters(pipe._fuse_loras = attach_ic_adapters+ reload_clean = getattr(pipe, "_reload_clean_transformer", None)+ if callable(reload_clean):+ def reload_clean_without_ic() -> None:+ reload_clean()+ if pipe.dit is not None and is_streaming_model(pipe.dit):+ drop_streaming_adapters(pipe.dit, "ic")++ pipe._reload_clean_transformer = reload_clean_without_ic+def release_pipeline_adapters(pipe) -> None:"""Drop the transformer and every adapter this module attached to it.@@ -342,13 +583,3 @@ def release_pipeline_adapters(pipe) -> None:pipe.dit = Noneif hasattr(pipe, "_loaded"):pipe._loaded = False---def _requantized_summary(path: str, strength: float) -> dict:- return {- "name": Path(path).name,- "strength": float(strength),- "strategy": STRATEGY_REQUANTIZED,- "quantizedTargets": None,- "fusedTargets": None,- }diff --git a/scripts/ltx_runtime_lora_test.py b/scripts/ltx_runtime_lora_test.pyindex 689d9b4c8b..9d90834021 100644--- a/scripts/ltx_runtime_lora_test.py+++ b/scripts/ltx_runtime_lora_test.py@@ -198,8 +198,10 @@ class ValidationTest(unittest.TestCase):class AdapterReportTest(unittest.TestCase):def test_same_basename_or_strength_change_is_a_separate_application(self):report = runtime.AdapterReport()- summary = lambda strength: {"name": "style.safetensors", "strength": strength, "strategy": runtime.STRATEGY_RUNTIME,- "quantizedTargets": 1, "fusedTargets": 0}+ def summary(strength):+ return {"name": "style.safetensors", "strength": strength, "strategy": runtime.STRATEGY_RUNTIME,+ "quantizedTargets": 1, "fusedTargets": 0}+self.assertTrue(report.record("user", "all", "a/style.safetensors", summary(0.5)))self.assertFalse(report.record("user", "all", "a/style.safetensors", summary(0.5)))self.assertTrue(report.record("user", "all", "b/style.safetensors", summary(0.5)))@@ -302,14 +304,364 @@ class TwoStageContractTest(unittest.TestCase):self.assertEqual(runtime.runtime_adapter_targets(held), [])self.assertIs(type(held.transformer_blocks[0].attn1.to_q), nn.QuantizedLinear)- def test_block_streaming_keeps_the_runtime_merge_and_says_so(self):- pipe = FakeICLoraPipeline([("ingredients.safetensors", 1.0)], low_ram_streaming=True)- original_fuse = pipe._fuse_loras- self.install(pipe)- self.assertEqual(pipe._pending_loras, [("character.safetensors", 0.8)])- self.assertEqual(pipe._fuse_loras, original_fuse)- self.assertEqual({e["strategy"] for e in self.report.entries}, {runtime.STRATEGY_REQUANTIZED})- self.assertTrue(any("Block streaming" in s for s in self.statuses))++# --------------------------------------------------------------------------+# Block streaming (#12327). The fixtures mirror the pinned runtimes'+# ltx_core_mlx.loader.block_streaming: one shared block, rebound per index with+# load_weights(strict=True), pre-compiled with mx.compile(shared, inputs=shared),+# and a provider that falls back to the eager block under perturbations.+# --------------------------------------------------------------------------++DIM, BLOCKS = 256, 2+++class StreamAttention(nn.Module):+ def __init__(self, dim):+ super().__init__()+ self.to_q = nn.Linear(dim, dim, bias=True)+++class StreamBlock(nn.Module):+ """A quantized attention projection beside a float one, chainable block to block."""++ def __init__(self, dim=DIM):+ super().__init__()+ self.attn1 = StreamAttention(dim)+ self.ff = nn.Linear(dim, dim, bias=False)++ def __call__(self, x, perturbations=None):+ return self.attn1.to_q(x) + self.ff(x)+++def quantize_block(block):+ nn.quantize(block, group_size=GROUP, bits=BITS, class_predicate=lambda p, m: p.endswith(("to_q", "proj_in")))+ return block+++class Outer(nn.Module):+ """Non-block projections: the runtime keeps these resident beside the streamed blocks."""++ def __init__(self, dim=DIM):+ super().__init__()+ self.proj_in = nn.Linear(dim, dim, bias=False)+ self.proj_out = nn.Linear(dim, dim, bias=False)+++def outer_weights(dim):+ mx.random.seed(19)+ outer = Outer(dim)+ outer.update(mlx.utils.tree_map(lambda v: mx.random.normal(v.shape) * 0.02, outer.parameters()))+ quantize_block(outer)+ mx.eval(outer.parameters())+ return mlx.utils.tree_flatten(outer.parameters())+++def with_outer(model, dim, weights):+ outer = quantize_block(Outer(dim))+ outer.load_weights(weights, strict=True)+ model.proj_in, model.proj_out = outer.proj_in, outer.proj_out+ return model+++def block_weights(dim, seed):+ mx.random.seed(seed)+ block = StreamBlock(dim)+ block.update(mlx.utils.tree_map(lambda v: mx.random.normal(v.shape) * 0.02, block.parameters()))+ quantize_block(block)+ mx.eval(block.parameters())+ return mlx.utils.tree_flatten(block.parameters())+++def merge_requantize(weights, index, sources):+ """The runtime's per-block merge: dequantize, add the delta, quantize again."""+ merged = dict(weights)+ for source in sources:+ tensors = source.get_block_lora_dict(index)+ for key in [k for k in tensors if k.endswith(".lora_A.weight")]:+ path = key[: -len(".lora_A.weight")]+ delta = (tensors[f"{path}.lora_B.weight"] * source.strength) @ tensors[key]+ if f"{path}.scales" in merged:+ dense = mx.dequantize(merged[f"{path}.weight"], merged[f"{path}.scales"], merged[f"{path}.biases"],+ group_size=GROUP, bits=BITS)+ packed = mx.quantize(dense + delta, group_size=GROUP, bits=BITS)+ merged[f"{path}.weight"], merged[f"{path}.scales"], merged[f"{path}.biases"] = packed+ else:+ merged[f"{path}.weight"] = merged[f"{path}.weight"] + delta+ return list(merged.items())+++class FakeBlockLoraSource:+ """``BlockLoraSource``'s surface over an already renamed adapter dict."""++ def __init__(self, tensors, strength):+ self.tensors, self.strength = tensors, strength++ def get_block_lora_dict(self, index):+ prefix = f"transformer_blocks.{index}."+ return {k[len(prefix):]: v for k, v in self.tensors.items() if k.startswith(prefix)}++ def close(self):+ pass+++class FakeStreamer:+ def __init__(self, blocks):+ self.blocks = blocks+ self.bound = []++ @property+ def block_count(self):+ return len(self.blocks)++ def bind(self, block, idx, evict_previous=None, lora_sources=None):+ weights = self.blocks[idx]+ if lora_sources:+ weights = merge_requantize(weights, idx, lora_sources)+ block.load_weights(weights, strict=True)+ self.bound.append(idx)+++class FakeInner(nn.Module):+ def __init__(self, shared, blocks=BLOCKS):+ super().__init__()+ self.transformer_blocks = [shared]+ self.num_layers = blocks++ def __call__(self, x, block_provider=None, perturbations=None):+ x = self.proj_in(x)+ for index in range(self.num_layers):+ block = block_provider(index)+ x = block(x) if perturbations is None else block(x, perturbations=perturbations)+ return self.proj_out(x)+++class FakeStreamingLTXModel(nn.Module):+ """StreamingLTXModel at the pinned runtimes, reduced to what the adapters touch."""++ def __init__(self, model, streamer, lora_sources=None):+ super().__init__()+ self.inner = model+ shared = model.transformer_blocks[0]+ object.__setattr__(self, "_streamer", streamer)+ object.__setattr__(self, "_shared_block", shared)+ object.__setattr__(self, "_compiled_block", mx.compile(shared, inputs=shared))+ object.__setattr__(self, "_lora_sources", lora_sources or [])++ def __call__(self, *args, **kwargs):+ if kwargs.get("block_provider") is None:+ streamer = object.__getattribute__(self, "_streamer")+ shared = object.__getattribute__(self, "_shared_block")+ compiled = object.__getattribute__(self, "_compiled_block")+ lora_sources = object.__getattribute__(self, "_lora_sources")+ prev_idx = [None]+ use_compiled = kwargs.get("perturbations") is None++ def provider(idx):+ streamer.bind(shared, idx, evict_previous=prev_idx[0], lora_sources=lora_sources or None)+ prev_idx[0] = idx+ return compiled if use_compiled else shared++ kwargs["block_provider"] = provider+ return self.inner(*args, **kwargs)++ def __getattr__(self, name):+ try:+ return super().__getattr__(name)+ except AttributeError:+ return getattr(super().__getattr__("inner"), name)+++class ResidentChain(nn.Module):+ """The same blocks held resident, for the resident runtime path as the reference."""++ def __init__(self, blocks, dim=DIM):+ super().__init__()+ with_outer(self, dim, outer_weights(dim))+ self.transformer_blocks = []+ for weights in blocks:+ block = quantize_block(StreamBlock(dim))+ block.load_weights(weights, strict=True)+ self.transformer_blocks.append(block)++ def __call__(self, x):+ x = self.proj_in(x)+ for block in self.transformer_blocks:+ x = block(x)+ return self.proj_out(x)+++def streaming_fixture(dim=DIM, blocks=BLOCKS):+ weights = [block_weights(dim, seed=20 + i) for i in range(blocks)]+ inner = with_outer(FakeInner(quantize_block(StreamBlock(dim)), blocks), dim, outer_weights(dim))+ return FakeStreamingLTXModel(inner, FakeStreamer(weights)), weights+++def block_adapter(index, path, seed, scale=1e-3, dim=DIM, rank=RANK):+ return outer_adapter(f"transformer_blocks.{index}.{path}", seed, scale, dim, rank)+++def outer_adapter(target, seed, scale=1e-3, dim=DIM, rank=RANK):+ mx.random.seed(seed)+ return {+ f"{target}.lora_A.weight": mx.random.normal((rank, dim)) * scale ** 0.5,+ f"{target}.lora_B.weight": mx.random.normal((dim, rank)) * scale ** 0.5,+ }+++def user_adapter():+ """Different deltas per block, on a quantized and a float projection."""+ return {**block_adapter(0, "attn1.to_q", 31), **block_adapter(1, "attn1.to_q", 32), **block_adapter(0, "ff", 33)}+++def ic_adapter():+ """Only block 1 inside the stream (block 0 binds an empty slot), plus both outer kinds."""+ return {**block_adapter(1, "attn1.to_q", 41), **outer_adapter("proj_in", 42), **outer_adapter("proj_out", 43)}+++def allclose(a, b):+ mx.eval(a, b)+ return float(mx.abs(a - b).max()) < 1e-4+++class StreamingTest(unittest.TestCase):+ def setUp(self):+ mx.random.seed(5)+ self.x = mx.random.normal((4, DIM))++ def test_each_block_receives_only_its_own_delta_and_packed_weights_stay_put(self):+ model, weights = streaming_fixture()+ packed = [dict(block) for block in weights]+ adapters = [("user.safetensors", user_adapter(), 0.8), ("ic.safetensors", ic_adapter(), 1.0)]+ summaries = runtime.attach_adapters(model, adapters, tag="user")++ resident = ResidentChain(weights)+ runtime.attach_adapters(resident, adapters)+ plain = ResidentChain(weights)(self.x)+ expected = resident(self.x)++ # Equal to the resident path, so each block saw its own delta; the+ # runtime's compiled block would have frozen one block's arrays.+ self.assertTrue(allclose(model(self.x), expected))+ # The eager block (guidance perturbations) takes the same adapters.+ self.assertTrue(allclose(model(self.x, perturbations=object()), expected))+ self.assertFalse(allclose(expected, plain))++ self.assertEqual([s["strategy"] for s in summaries], [runtime.STRATEGY_MIXED, runtime.STRATEGY_MIXED])+ self.assertEqual([(s["quantizedTargets"], s["fusedTargets"]) for s in summaries], [(2, 1), (2, 1)])+ for before, after in zip(packed, weights):+ for key, array in before.items():+ self.assertIs(dict(after)[key], array)+ shared = model.__dict__["_shared_block"]+ self.assertIs(shared.attn1.to_q.weight, dict(weights[BLOCKS - 1])["attn1.to_q.weight"])++ def test_runtime_owned_sources_still_merge_and_the_streamer_can_be_swapped(self):+ model, weights = streaming_fixture()+ runtime.attach_adapters(model, [("user.safetensors", user_adapter(), 0.8)], tag="user")+ distilled = FakeBlockLoraSource(block_adapter(0, "attn1.to_q", 51, scale=1e-2), 0.5)+ object.__setattr__(model, "_lora_sources", [distilled])+ replacement = FakeStreamer(weights)+ object.__setattr__(model, "_streamer", replacement)+ observed = model(self.x)++ # The runtime's own merge of its distilled source, then the user delta on top.+ merged = ResidentChain([merge_requantize(w, i, [distilled]) for i, w in enumerate(weights)])+ runtime.attach_adapters(merged, [("user.safetensors", user_adapter(), 0.8)])+ self.assertEqual(replacement.bound, list(range(BLOCKS)))+ self.assertTrue(allclose(observed, merged(self.x)))++ def test_a_streaming_ic_render_drops_the_ic_adapter_for_the_clean_refine(self):+ model, weights = streaming_fixture()+ files = {"ic.safetensors": ic_adapter(), "user.safetensors": user_adapter()}+ report, statuses = runtime.AdapterReport(), []+ pipe = FakeStreamingICPipeline(model, [("ic.safetensors", 1.0)])+ runtime.install_pipeline_adapters(pipe, [("user.safetensors", 0.8)], report=report,+ status=statuses.append, ic=True, load_adapter=files.__getitem__)+ stage_1, stage_2 = pipe.generate(self.x)++ both = ResidentChain(weights)+ runtime.attach_adapters(both, [("u", user_adapter(), 0.8), ("i", ic_adapter(), 1.0)])+ user_only = ResidentChain(weights)+ runtime.attach_adapters(user_only, [("u", user_adapter(), 0.8)])+ self.assertTrue(allclose(stage_1, both(self.x)))+ self.assertTrue(allclose(stage_2, user_only(self.x)))+ self.assertEqual({e["role"]: e["strategy"] for e in report.entries},+ {"user": runtime.STRATEGY_MIXED, "ic": runtime.STRATEGY_MIXED})+ self.assertEqual({e["role"]: e["stages"] for e in report.entries}, {"user": ["all"], "ic": ["stage-1"]})++ held = pipe.dit+ runtime.release_pipeline_adapters(pipe)+ self.assertIs(type(held), FakeStreamingLTXModel)+ self.assertIs(type(held.__dict__["_shared_block"].attn1.to_q), nn.QuantizedLinear)+ self.assertIs(type(held.inner.proj_in), nn.QuantizedLinear)+ self.assertEqual(runtime.runtime_adapter_targets(held), [])++ def test_streaming_validation_refuses_before_mutating(self):+ model, _weights = streaming_fixture()+ good = ("first.safetensors", user_adapter(), 1.0)+ for tensors, pattern in (+ (block_adapter(BLOCKS, "attn1.to_q", 61), "does not have"),+ (block_adapter(0, "attn1.to_q", 62, dim=DIM // 2), "do not fit"),+ (block_adapter(0, "attn1.to_k", 63), "does not have"),+ ):+ with self.assertRaisesRegex(ValueError, pattern):+ runtime.attach_adapters(model, [good, ("bad.safetensors", tensors, 1.0)])+ self.assertIs(type(model), FakeStreamingLTXModel)+ self.assertEqual(runtime.runtime_adapter_targets(model), [])++ def test_peak_memory_stays_within_the_merge_path(self):+ dim = 1024+ mx.random.seed(9)+ x = mx.random.normal((16, dim))+ tensors = {**block_adapter(0, "attn1.to_q", 71, dim=dim), **block_adapter(1, "attn1.to_q", 72, dim=dim)}++ def peak(attach):+ model, _weights = streaming_fixture(dim=dim)+ attach(model)+ mx.eval(x, *[v for v in tensors.values()])+ mx.clear_cache()+ mx.reset_peak_memory()+ baseline = mx.get_active_memory()+ mx.eval(model(x))+ return mx.get_peak_memory() - baseline++ merged = peak(lambda m: object.__setattr__(m, "_lora_sources", [FakeBlockLoraSource(tensors, 1.0)]))+ runtime_delta = peak(lambda m: runtime.attach_adapters(m, [("user.safetensors", tensors, 1.0)]))+ self.assertLessEqual(runtime_delta, merged * 1.10)+++class FakeStreamingICPipeline:+ """ICLoraPipeline's streaming surface: _fuse_loras before stage 1, and a clean+ stage-2 refine that keeps the model and clears only its own _lora_sources."""++ def __init__(self, model, lora_paths):+ self.model = model+ self._lora_paths = list(lora_paths)+ self.low_ram_streaming = True+ self.dit = None+ self._loaded = False++ def _load_transformer_with_optional_streaming(self, _path):+ if getattr(self, "_pending_loras", None):+ raise AssertionError("runtime path must not hand LoRAs to the merge-and-requantize loader")+ return self.model++ def _fuse_loras(self):+ raise AssertionError("upstream bind-time merge _fuse_loras must not run")++ def _reload_clean_transformer(self):+ for source in object.__getattribute__(self.dit, "_lora_sources"):+ source.close()+ object.__setattr__(self.dit, "_lora_sources", [])++ def generate(self, x):+ self.dit = self._load_transformer_with_optional_streaming("transformer.safetensors")+ self._loaded = True+ self._fuse_loras()+ stage_1 = self.dit(x)+ self._reload_clean_transformer()+ stage_2 = self.dit(x)+ mx.eval(stage_1, stage_2)+ return stage_1, stage_2if __name__ == "__main__":diff --git a/server/services/videoGen/generateVideoHelpers.js b/server/services/videoGen/generateVideoHelpers.jsindex a3e424ca40..54dc2e417d 100644--- a/server/services/videoGen/generateVideoHelpers.js+++ b/server/services/videoGen/generateVideoHelpers.js@@ -886,8 +886,8 @@ export async function finalizeGeneratedVideo({ job, jobId, outputPath, filename,// a resident-by-default render and on runners that don't report one....(job.streamingPolicy ? { streamingPolicyApplied: job.streamingPolicy } : {}),// How each LoRA adapter was actually applied (#12262) — at inference- // beside the packed weights, fused into float ones, or merged and- // re-quantized under block streaming. Absent on adapter-free renders.+ // beside the packed weights or fused into float ones, resident or+ // block-streamed (#12327). Absent on adapter-free renders....(job.loraStrategy ? { loraStrategyApplied: job.loraStrategy } : {}),});return history;