Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: stream the LTX-2.5 text encode on the card under a VRAM budget, no per-prompt encoder copy back (#17000)
Daniel Han92707557e6ac
diff --git a/studio/backend/core/inference/video_ltx25.py b/studio/backend/core/inference/video_ltx25.pyindex 9fcb72dcb39..08a9aa1feae 100644--- a/studio/backend/core/inference/video_ltx25.py+++ b/studio/backend/core/inference/video_ltx25.py@@ -824,9 +824,172 @@ def _encode_room_mib(client: Any) -> Optional[int]:return worker_room(client.config, _server_reserved_mib(device))+# Never parked: the denoisers lend blocks instead; an in-process text encoder is the encode itself.+_NEVER_PARKED = ("transformer", "transformer_2", "unconditional_transformer")+# Host copy kept on a parked module between requests, refreshed from the card at every park.+_PARK_HOST_ATTR = "_unsloth_ltx25_park_host"+# "0" lends only resident denoiser blocks (a short card then encodes on the CPU, as before).+PARK_COMPANIONS_ENV = "UNSLOTH_LTX25_PARK_FOR_ENCODE"+++def _module_tensors(module: Any) -> list:+ """``(table, key, tensor)`` per distinct parameter / buffer (tied weights listed once)."""+ seen: set = set()+ out = []+ for sub in module.modules():+ for table in (sub._parameters, sub._buffers):+ for key, tensor in table.items():+ if tensor is None or id(tensor) in seen:+ continue+ seen.add(id(tensor))+ out.append((table, key, tensor))+ return out+++def _hooked(module: Any) -> bool:+ """An accelerate hook, or a diffusers registry holding any hook (an empty registry moves nothing)."""+ if getattr(module, "_hf_hook", None) is not None:+ return True+ registry = getattr(module, "_diffusers_hook", None)+ return registry is not None and bool(getattr(registry, "hooks", True))+++def _parkable_components(pipe: Any, device: Any) -> list:+ """``[(name, module, MiB)]``, largest first: hook-free modules wholly on the card that the encode never runs."""+ import torch++ dev = torch.device(str(device))+ out = []+ for name, module in (getattr(pipe, "components", {}) or {}).items():+ if (+ not isinstance(module, torch.nn.Module)+ or str(name) in _NEVER_PARKED+ or str(name).startswith("text_encoder")+ # The VAE decode is compiled and keeps fused weight copies, so its storage must not move under it.+ or "vae" in str(name).lower()+ or any(_hooked(sub) for sub in module.modules())+ ):+ continue+ tensors = _module_tensors(module)+ if not tensors:+ continue+ on_card = True+ for _table, _key, tensor in tensors:+ data = tensor.data if isinstance(tensor, torch.nn.Parameter) else tensor+ if (+ type(data) is not torch.Tensor+ or data.device.type != dev.type+ or (dev.index is not None and data.device.index != dev.index)+ ):+ on_card = False+ break+ if on_card:+ nbytes = sum(t.numel() * t.element_size() for _tb, _k, t in tensors)+ out.append((str(name), module, -(-nbytes // (1 << 20))))+ out.sort(key = lambda item: -item[2])+ return out+++def _park_host_copy(module: Any, tensors: list) -> Optional[list]:+ """Kept host copy per tensor, pinned where the host-RAM reserve allows, else pageable; None if it cannot fit."""+ import torch++ shapes = [(tuple(t.shape), t.dtype) for _tb, _k, t in tensors]+ kept = module.__dict__.get(_PARK_HOST_ATTR)+ if kept is not None and kept[0] == shapes:+ return kept[1]+ from .diffusion_memory import (+ _PIN_RESERVE_FRACTION,+ _PIN_RESERVE_MIN_BYTES,+ _available_system_memory_mib,+ _host_ram_capacity_mib,+ _windows_commit_headroom_mib,+ registered_pinned_empty,+ )++ sizes = [t.numel() * t.element_size() for _tb, _k, t in tensors]+ need = sum(sizes)+ available, total = _available_system_memory_mib(), _host_ram_capacity_mib()+ if available is None or total is None:+ return None+ commit = _windows_commit_headroom_mib()+ if commit is not None:+ available = min(int(available), int(commit))+ reserve = max(_PIN_RESERVE_MIN_BYTES, int((int(total) << 20) * _PIN_RESERVE_FRACTION))+ if (int(available) << 20) - need < reserve:+ return None+ slab = registered_pinned_empty(need)+ views = []+ offset = 0+ for (_tb, _k, tensor), size in zip(tensors, sizes):+ if slab is not None:+ view = slab[offset : offset + size].view(tensor.dtype).view(tensor.shape)+ offset += size+ else:+ view = torch.empty(tensor.shape, dtype = tensor.dtype, device = "cpu")+ views.append(view)+ module.__dict__[_PARK_HOST_ATTR] = (shapes, views)+ return views+++def _park_for_encode(pipe: Any, device: Any, need_mib: int) -> Optional[Callable[[], None]]:+ """Park companions on their host copy, largest first, until ``need_mib`` is freed; returns the restore or None."""+ if (os.environ.get(PARK_COMPANIONS_ENV) or "").strip() == "0" or need_mib <= 0:+ return None+ import torch++ parked: list = []++ def restore() -> None:+ while parked:+ for table, key, param, home, host in parked.pop():+ moved = host.to(home, copy = True, non_blocking = host.is_pinned())+ if param is not None:+ param.data = moved+ else:+ table[key] = moved++ left = int(need_mib)+ try:+ for name, module, mib in _parkable_components(pipe, device):+ if left <= 0:+ break+ tensors = _module_tensors(module)+ hosts = _park_host_copy(module, tensors)+ if hosts is None:+ continue+ for (_table, _key, tensor), host in zip(tensors, hosts):+ host.copy_(tensor.data if isinstance(tensor, torch.nn.Parameter) else tensor)+ # Copies must land before the card's tensors are dropped.+ if torch.device(str(device)).type == "cuda":+ torch.cuda.synchronize(torch.device(str(device)))+ entries = []+ for (table, key, tensor), host in zip(tensors, hosts):+ is_param = isinstance(tensor, torch.nn.Parameter)+ entries.append((table, key, tensor if is_param else None, tensor.device, host))+ if is_param:+ tensor.data = host+ else:+ table[key] = host+ parked.append(entries)+ del tensors+ left -= mib+ logger.info(+ "video.ltx25_te: %s (%d MiB) steps off the card for the prompt encode", name, mib+ )+ except Exception as exc: # noqa: BLE001 -- whatever moved goes back; the encode still runs, maybe on the CPU+ logger.warning("video.ltx25_te: parking companions for the encode failed (%s)", exc)+ restore()+ return None+ if not parked:+ return None+ if torch.device(str(device)).type == "cuda":+ torch.cuda.empty_cache()+ return restore++def lend_resident_dit_for_encode(pipe: Any, client: Any) -> Optional[Callable[..., None]]:- """Stream resident denoiser blocks again so the encoder fits on the card (whole if lending makes it fit, else the- worker's ``stream_need_mib``); returns the restore that pins them back, or None when nothing was lent."""+ """Free card room for a non-resident encode: lend denoiser blocks, then park companions; returns the restore."""config = getattr(client, "config", None) or {}if (not config@@ -842,7 +1005,15 @@ def lend_resident_dit_for_encode(pipe: Any, client: Any) -> Optional[Callable[..from .video_stream_residency import resident_mibheld = resident_mib(getattr(pipe, "transformer", None))- if held <= 0:+ from .host_pinning import host_pinning_allowed++ parkable = 0+ # On unified memory the host copy and the card are the same RAM: parking frees nothing.+ if (os.environ.get(PARK_COMPANIONS_ENV) or "").strip() != "0" and host_pinning_allowed(+ config["device"]+ ):+ parkable = sum(mib for _n, _m, mib in _parkable_components(pipe, config["device"]))+ if held + parkable <= 0:return Nonetorch.cuda.empty_cache()room = _encode_room_mib(client)@@ -852,18 +1023,37 @@ def lend_resident_dit_for_encode(pipe: Any, client: Any) -> Optional[Callable[..weights = int(info.get("weights_mib") or 0)whole = weights + ENCODE_MARGIN_MIB if weights > 0 else Nonestreamed = info.get("stream_need_mib")+ # Companions are parked only to reach the streamed need: a whole onload is worth only the blocks it frees.if whole is not None and room < whole <= room + held:- target = whole- elif streamed is not None and room < int(streamed):+ target, parkable = whole, 0+ elif streamed is not None and room < int(streamed) <= room + held + parkable:target = int(streamed)+ elif streamed is not None and room < int(streamed) and held > 0:+ target, parkable = int(streamed), 0else:return None- restore = release_resident_groups(- pipe, target - room, logger, denoisers_only = True, reason = "the prompt encode"- )- if restore is not None:- torch.cuda.empty_cache()- return restore+ restores: list = []+ if held > 0:+ restore = release_resident_groups(+ pipe, target - room, logger, denoisers_only = True, reason = "the prompt encode"+ )+ if restore is not None:+ restores.append(restore)+ torch.cuda.empty_cache()+ room = _encode_room_mib(client)+ if parkable and room is not None and room < target:+ restore = _park_for_encode(pipe, config["device"], target - room)+ if restore is not None:+ restores.append(restore)+ if not restores:+ return None++ def restore_all() -> None:+ # Companions back first (the connectors run next), then the denoiser's blocks.+ for undo in reversed(restores):+ undo()++ return restore_allexcept Exception as exc: # noqa: BLE001 -- the encode still runs, maybe on the CPUlogger.warning("video.ltx25_te: lending resident blocks skipped (%s)", exc)return None@@ -942,6 +1132,8 @@ class Ltx25TextEncoderClient:self._cache: list[tuple[tuple, Any]] = []self.info: dict[str, Any] = {}self.last_encode: dict[str, Any] = {}+ # encode_prompt calls, one per render: the second means a render (and the server's pins) has finished.+ self.renders = 0# process managementdef start(self) -> None:@@ -1125,6 +1317,9 @@ class Ltx25TextEncoderClient:"prompts": list(prompts),"max_sequence_length": int(max_sequence_length),"server_reserved_mib": _server_reserved_mib(self.config.get("device")),+ # The server pins its own host weights during the first render; the encoder's pin waits for that+ # so it never takes the host RAM those pins need.+ "pin_host": self.renders > 1,})self._inflight = seq@@ -1169,6 +1364,7 @@ def install_remote_encode_prompt(pipe: Any, client: Ltx25TextEncoderClient) -> Ndevice: Any = None,dtype: Any = None,) -> tuple[Any, Any, Any, Any]:+ client.renders = int(getattr(client, "renders", 0) or 0) + 1device = device or pipe._execution_devicedtype = dtype or getattr(getattr(pipe, "transformer", None), "dtype", None)diff --git a/studio/backend/core/inference/video_ltx25_te_worker.py b/studio/backend/core/inference/video_ltx25_te_worker.pyindex 3d36ac610de..0e8b08b2d6f 100644--- a/studio/backend/core/inference/video_ltx25_te_worker.py+++ b/studio/backend/core/inference/video_ltx25_te_worker.py@@ -676,6 +676,126 @@ def _stream_need_mib_or_none(config: dict, model: Any) -> Optional[int]:STREAM_ENCODE_ENV = "UNSLOTH_LTX25_TE_STREAM"+def _to_device(tensor: Any, device: Any) -> Any:+ """Device copy; non-blocking from pinned memory (same-stream reader, host copy never written)."""+ try:+ pinned = tensor.device.type == "cpu" and tensor.is_pinned()+ except Exception: # noqa: BLE001 -- unknown: the blocking copy+ pinned = False+ return tensor.to(device, copy = True, non_blocking = pinned)+++def _onloads_whole(model: Any) -> bool:+ """Whether ``_Onload`` reaches every tensor ``model.to`` would move: no module overrides ``_apply``."""+ import torch+ try:+ return all(type(m)._apply is torch.nn.Module._apply for m in model.modules())+ except Exception: # noqa: BLE001 -- unknown: keep ``model.to``+ return False+++def _discrete_card(device: Any) -> bool:+ """A CUDA card with its own memory. On unified memory (Apple, Jetson / GB10, Strix Halo) a kept host copy would+ hold the encoder twice in the same RAM during the encode, so those keep ``model.to``."""+ if str(device).split(":", 1)[0] != "cuda":+ return False+ try:+ from core.inference.host_pinning import host_pinning_allowed+ return bool(host_pinning_allowed(device))+ except Exception: # noqa: BLE001 -- unclassifiable: keep ``model.to``+ return False+++# "0" keeps the non-resident encoder's host copy pageable.+PIN_HOST_ENV = "UNSLOTH_LTX25_TE_PIN"+++def _pin_host_copy(model: Any, config: dict) -> int:+ """Copy a non-resident encoder's host weights into registered (pinned) chunks once, Linux CUDA only and only with+ room for the transient second copy, so uploads run at DMA speed; returns bytes pinned, 0 when skipped."""+ if config.get("resident") or (os.environ.get(PIN_HOST_ENV) or "").strip() == "0":+ return 0+ device = str(config.get("device") or "")+ if not device.startswith("cuda"):+ return 0+ try:+ from core.inference.diffusion_memory import (+ _exact_pin_supported,+ _named_buffers,+ _pin_host_weights,+ )++ if not _exact_pin_supported(device):+ return 0+ host = {name: p.data for name, p in model.named_parameters() if p.device.type == "cpu"}+ buffers = {name: b for name, b in _named_buffers(model) if b.device.type == "cpu"}+ if not _pin_fits_twice(list(host.values()) + list(buffers.values())):+ return 0+ return int(+ _pin_host_weights(model, host, None, buffer_host = buffers, exact = True, device = device)+ or 0+ )+ except Exception as exc: # noqa: BLE001 -- an optimisation: the encode reads the pageable copy+ print(f"video.ltx25_te: host copy left pageable ({exc})", file = sys.stderr, flush = True)+ return 0+++def _own_host_copy(model: Any) -> bool:+ """Copy the host weights out of the checkpoint's file mapping into process memory, once, before the first card+ encode. Base did this implicitly (``model.to("cpu")`` after each encode); kept mapped, the pages are page cache the+ server's pins evict, and each onload then re-reads 23 GB from disk (70-80 s per encode on an A100 host)."""+ import torch++ if not _host_fits(list(model.parameters()) + list(model.buffers()), copies = 1):+ # Base's streamed and CPU encodes kept the mapping too; a short host keeps it rather than risk the OOM killer.+ return False+ try:+ # Keyed by identity: a tied tensor is copied once and stays shared.+ done: dict = {}+ with torch.no_grad():+ for module in model.modules():+ for table in (module._parameters, module._buffers):+ for key, tensor in list(table.items()):+ if tensor is None or tensor.device.type != "cpu":+ continue+ if isinstance(tensor, torch.nn.Parameter):+ if id(tensor) not in done:+ done[id(tensor)] = tensor+ tensor.data = tensor.data.clone()+ continue+ if id(tensor) not in done:+ done[id(tensor)] = tensor.clone()+ table[key] = done[id(tensor)]+ return True+ except Exception as exc: # noqa: BLE001 -- the mapped copy still encodes, only slower when evicted+ print(f"video.ltx25_te: host copy left mapped ({exc})", file = sys.stderr, flush = True)+ return False+++def _pin_fits_twice(tensors: list) -> bool:+ """Whether host RAM holds a second copy of ``tensors`` above the pin reserve. The loaded encoder's tensors share+ storages, so the pinned chunks fill before the pageable copy is freed (24.9 -> 42.7 GB on an A100 host); on a host+ without that room the pin pushed the box into reclaim and encodes took 70-80 s instead of 22 s."""+ return _host_fits(tensors, copies = 2)+++def _host_fits(tensors: list, copies: int) -> bool:+ """Whether host RAM holds ``copies`` more copies of ``tensors`` above the pin reserve."""+ from core.inference.diffusion_memory import (+ _PIN_RESERVE_FRACTION,+ _PIN_RESERVE_MIN_BYTES,+ _available_system_memory_mib,+ _host_ram_capacity_mib,+ )++ available, total = _available_system_memory_mib(), _host_ram_capacity_mib()+ if available is None or total is None:+ return False+ need = sum(int(t.numel()) * int(t.element_size()) for t in tensors)+ reserve = max(_PIN_RESERVE_MIN_BYTES, int((int(total) << 20) * _PIN_RESERVE_FRACTION))+ return (int(available) << 20) - int(copies) * need >= reserve++class _Onload:"""Moves the tensors of some modules to a device and back. Parameters keep their identity (``.data`` swaps, so atied weight moves once); the host tensors are kept and restored, so returning costs no copy."""@@ -701,11 +821,11 @@ class _Onload:if id(tensor) not in self.moved:self.moved[id(tensor)] = tensorself.saved.append((tensor, None, None, tensor.data))- tensor.data = tensor.data.to(self.device, copy = True)+ tensor.data = _to_device(tensor.data, self.device)continuemoved = self.moved.get(id(tensor))if moved is None:- moved = tensor.to(self.device, copy = True)+ moved = _to_device(tensor, self.device)self.moved[id(tensor)] = movedself.saved.append((None, table, key, tensor))table[key] = moved@@ -848,8 +968,6 @@ def _encode_on(max_len: int,server_reserved_mib: Optional[int] = None,) -> tuple[Any, Any, str]:- import torch-resident = bool(config.get("resident"))device, stream = _encode_plan(config, model, server_reserved_mib)tokenizer.padding_side = "left"@@ -864,10 +982,68 @@ def _encode_on(return_tensors = "pt",)config["_streamed"] = stream is not None+ oom: Optional[str] = None+ try:+ embeds_host, mask_host = _run_encode(model, config, inputs, device, stream)+ except Exception as exc:+ if resident or device == "cpu" or not _is_out_of_memory(exc):+ raise+ oom = str(exc)+ if oom is not None:+ # Outside the handler, so the failed attempt's card tensors are gone before the CPU encode; then hand the+ # card back, since the server plans the denoise against it.+ _empty_accelerator_cache(device)+ print(+ f"video.ltx25_te: out of memory encoding on {device} ({oom}); encoding on the CPU",+ file = sys.stderr,+ flush = True,+ )+ device, config["_streamed"] = "cpu", False+ embeds_host, mask_host = _run_encode(model, config, inputs, device, None)+ return embeds_host, mask_host, device+++def _empty_accelerator_cache(device: Any) -> None:+ import torch++ kind = str(device).split(":", 1)[0]+ accel = getattr(torch, kind, None) if kind in ("cuda", "xpu") else None+ if accel is not None and accel.is_available():+ accel.empty_cache()+++def _is_out_of_memory(exc: BaseException) -> bool:+ import torch+ kinds = tuple(+ k+ for k in (+ getattr(torch, "OutOfMemoryError", None),+ getattr(torch.cuda, "OutOfMemoryError", None),+ )+ if isinstance(k, type)+ )+ return (bool(kinds) and isinstance(exc, kinds)) or "out of memory" in str(exc).lower()+++def _run_encode(model: Any, config: dict, inputs: Any, device: str, stream: Any) -> tuple[Any, Any]:+ import torch++ resident = bool(config.get("resident"))onloaded = not resident and device != "cpu" and stream is None- if onloaded:+ if not resident and device != "cpu" and _discrete_card(device):+ if config.get("_pin_host") and "_pinned_bytes" not in config:+ config["_pinned_bytes"] = _pin_host_copy(model, config)+ if not config.get("_pinned_bytes") and not config.get("_owned_host"):+ config["_owned_host"] = _own_host_copy(model)+ # Onload copies host tensors up and restores by repointing: no 23 GB device-to-host copy per prompt.+ whole = (+ _Onload(device) if onloaded and _discrete_card(device) and _onloads_whole(model) else None+ )+ if whole is None and onloaded:model.to(device)try:+ if whole is not None:+ whole.add([model])with (_streamed(stream, device) if stream is not None else _no_context(),torch.inference_mode(),@@ -879,15 +1055,14 @@ def _encode_on(mask_host = mask.to("cpu")del embedsfinally:- if onloaded:+ if whole is not None:+ whole.restore()+ elif onloaded:model.to("cpu")# Return the encode's activations (and, onloaded, the weights) to the card: a resident worker otherwise keeps# ~1.7 GB cached through the denoise, an onloaded one the whole encoder.- kind = str(device).split(":", 1)[0]- accel = getattr(torch, kind, None) if kind in ("cuda", "xpu") else None- if accel is not None and accel.is_available():- accel.empty_cache()- return embeds_host, mask_host, device+ _empty_accelerator_cache(device)+ return embeds_host, mask_hostdef _no_context() -> Any:@@ -939,6 +1114,7 @@ def run_text_encoder_worker(*, cmd_queue: Any, resp_queue: Any, config: dict) ->if kind != "encode":continuetry:+ config["_pin_host"] = bool(msg.get("pin_host"))embeds, mask, device = _encode_on(tokenizer,model,@@ -955,6 +1131,7 @@ def run_text_encoder_worker(*, cmd_queue: Any, resp_queue: Any, config: dict) ->"mask": mask,"device": device,"streamed": bool(config.get("_streamed")),+ "pinned_mib": int(config.get("_pinned_bytes") or 0) >> 20,**_memory_stats(config.get("device") or ""),})diff --git a/studio/backend/tests/test_video_ltx25.py b/studio/backend/tests/test_video_ltx25.pyindex cf0cf638ac4..7547b5c9d19 100644--- a/studio/backend/tests/test_video_ltx25.py+++ b/studio/backend/tests/test_video_ltx25.py@@ -2388,6 +2388,47 @@ def test_client_sends_the_budget_and_the_servers_share():assert v25._server_reserved_mib("cpu") is None+def test_the_client_lets_the_worker_pin_only_after_a_render(monkeypatch):+ """The first render pins the server's own host weights; the encoder's pin must not take that RAM first."""+ import torch++ monkeypatch.setattr(torch.cuda, "is_available", lambda: False)+ client = v25.Ltx25TextEncoderClient(+ repo = "r",+ hf_token = None,+ cache_dir = None,+ local_files_only = True,+ device = "cpu",+ dtype = "bfloat16",+ resident = False,+ venv_dir = "/x",+ )+ client._cmd, client._resp = queue.Queue(), queue.Queue()+ client._proc = SimpleNamespace(is_alive = lambda: True, exitcode = None)+ client._ready = True+ sent = []++ def fake_put(msg):+ sent.append(msg)+ client._resp.put(+ {+ "type": "embeds",+ "id": msg["id"],+ "embeds": torch.zeros(1, 2, 3),+ "mask": torch.ones(1, 2),+ }+ )++ client._cmd.put = fake_put+ pipe = SimpleNamespace(+ _execution_device = torch.device("cpu"), transformer = SimpleNamespace(dtype = torch.float32)+ )+ v25.install_remote_encode_prompt(pipe, client)+ for text in ("a fox", "a hen"):+ pipe.encode_prompt(prompt = text, do_classifier_free_guidance = False, max_sequence_length = 2)+ assert [m["pin_host"] for m in sent] == [False, True]++@pytest.mark.parametrize("resident", [False, True])def test_client_frees_the_servers_cached_blocks_before_a_non_resident_encode(monkeypatch, resident):"""Only a non-resident cache miss releases the server's cached blocks, before its reservation is sent."""@@ -2654,6 +2695,265 @@ def test_a_streamed_encode_runs_each_layer_onloaded_alone_and_matches(monkeypatcassert all(not layer._forward_pre_hooks and not layer._forward_hooks for layer in layers)+def test_a_whole_onload_keeps_the_host_copy_and_restores_it_without_a_copy(monkeypatch):+ """Onload restores the same host tensors (no ``model.to``) and matches a host encode."""+ import torch++ from core.inference import video_ltx25_te_worker as worker++ model = _stack_model()+ moves = []+ monkeypatch.setattr(model, "to", lambda *a, **k: moves.append(a) or model)+ # A distinct device string the onload path takes, while the compute stays on the host.+ monkeypatch.setattr(worker, "_encode_plan", lambda config, m, reserved = None: ("cpu:0", None))+ monkeypatch.setattr(worker, "_discrete_card", lambda device: True)+ host = {id(t): t.data_ptr() for t in list(model.parameters()) + list(model.buffers())}+ seen = []+ handle = model.model.language_model.layers[0].register_forward_pre_hook(+ lambda module, _args: seen.append(module.weight.data_ptr() != host[id(module.weight)])+ )+ # The host copy is already the process's own (see the next test): every encode restores it as is.+ config = {"device": "cuda:0", "resident": False, "_owned_host": True}+ try:+ for _ in range(2):+ embeds, _mask, device = worker._encode_on(_FakeTokenizer(), model, config, ["a fox"], 6)+ assert device == "cpu:0" and config["_streamed"] is False+ finally:+ handle.remove()+ assert moves == [] and seen == [True, True]+ assert all(+ t.data_ptr() == host[id(t)] for t in list(model.parameters()) + list(model.buffers())+ )+ assert model.lm_head.weight is model.model.language_model.embed_tokens.weight+ with torch.inference_mode():+ plain = worker._pack_hidden_states(+ model, torch.ones(1, 6, dtype = torch.long), torch.ones(1, 6, dtype = torch.long)+ )+ assert torch.equal(embeds, plain)+++def test_the_first_card_encode_owns_the_host_copy_once_when_it_is_not_pinned(monkeypatch):+ """A checkpoint-mapped host copy is page cache the server's pins can evict; it is copied into process memory once+ (as base's copy back did), ties kept, values unchanged; a pinned copy skips it."""+ import torch++ from core.inference import video_ltx25_te_worker as worker++ model = _stack_model()+ language = model.model.language_model+ language.extra = torch.nn.Module()+ language.extra.register_buffer("scale", language.scale) # a tied buffer+ before = {n: t.detach().clone() for n, t in model.state_dict().items()}+ ptrs = {id(t): t.data_ptr() for t in list(model.parameters()) + list(model.buffers())}+ params = list(model.parameters())+ monkeypatch.setattr(worker, "_encode_plan", lambda config, m, reserved = None: ("cpu:0", None))+ monkeypatch.setattr(worker, "_discrete_card", lambda device: True)+ from core.inference import diffusion_memory++ monkeypatch.setattr(diffusion_memory, "_available_system_memory_mib", lambda: 64 << 10)+ monkeypatch.setattr(diffusion_memory, "_host_ram_capacity_mib", lambda: 128 << 10)+ owned = []+ real = worker._own_host_copy+ monkeypatch.setattr(worker, "_own_host_copy", lambda m: owned.append(1) or real(m))+ config = {"device": "cuda:0", "resident": False}+ for _ in range(2):+ worker._encode_on(_FakeTokenizer(), model, config, ["a fox"], 6)+ assert owned == [1] and config["_owned_host"] is True+ assert all(t.data_ptr() != ptrs[id(t)] for t in params)+ assert list(model.parameters()) == params+ assert model.lm_head.weight is language.embed_tokens.weight+ assert language.extra.scale is language.scale+ after = model.state_dict()+ assert all(torch.equal(before[n], after[n]) for n in before)+ pinned = _stack_model()+ worker._encode_on(+ _FakeTokenizer(),+ pinned,+ {"device": "cuda:0", "resident": False, "_pinned_bytes": 1},+ ["a"],+ 6,+ )+ assert owned == [1]+ # unified memory keeps model.to, which copies anyway: no extra host copy there+ monkeypatch.setattr(worker, "_discrete_card", lambda device: False)+ worker._encode_on(+ _FakeTokenizer(), _stack_model(), {"device": "cuda:0", "resident": False}, ["a"], 6+ )+ assert owned == [1]+ # a host without room above the reserve keeps the mapping (as base's streamed encode did)+ monkeypatch.setattr(diffusion_memory, "_available_system_memory_mib", lambda: 1)+ short = _stack_model()+ ptrs = [t.data_ptr() for t in short.parameters()]+ assert real(short) is False and [t.data_ptr() for t in short.parameters()] == ptrs+ # a CPU encode never copies+ monkeypatch.setattr(worker, "_encode_plan", lambda config, m, reserved = None: ("cpu", None))+ worker._encode_on(+ _FakeTokenizer(), _stack_model(), {"device": "cuda:0", "resident": False}, ["a"], 6+ )+ assert owned == [1]+++def test_unified_memory_keeps_moving_the_encoder_with_model_to(monkeypatch):+ """No kept host copy where the card is host RAM (integrated GPU, any non-CUDA device): one copy, as before."""+ from core.inference import host_pinning+ from core.inference import video_ltx25_te_worker as worker++ monkeypatch.setattr(host_pinning, "host_pinning_allowed", lambda device = None: False)+ assert not worker._discrete_card("cuda:0")+ assert not worker._discrete_card("mps") and not worker._discrete_card("xpu:0")+ monkeypatch.setattr(host_pinning, "host_pinning_allowed", lambda device = None: True)+ assert worker._discrete_card("cuda:0")+ model = _stack_model()+ moves = []+ monkeypatch.setattr(model, "to", lambda *a, **k: moves.append(a) or model)+ monkeypatch.setattr(worker, "_encode_plan", lambda config, m, reserved = None: ("mps", None))+ config = {"device": "mps", "resident": False}+ try:+ worker._encode_on(_FakeTokenizer(), model, config, ["a fox"], 6)+ except Exception: # noqa: BLE001 -- no MPS here; the move order is what matters+ pass+ assert moves and moves[0] == ("mps",)+++def test_lend_never_parks_on_unified_memory(monkeypatch):+ from core.inference import host_pinning++ pipe = SimpleNamespace(transformer = object(), components = {})+ monkeypatch.setattr(+ v25, "_parkable_components", lambda pipe, device: [("connectors", None, 6050)]+ )+ monkeypatch.setattr(v25, "_park_for_encode", lambda *a: pytest.fail("parked on unified memory"))+ monkeypatch.setattr(host_pinning, "host_pinning_allowed", lambda device = None: False)+ _lend_env(monkeypatch, free_mib = 4914, held_mib = 0)+ assert v25.lend_resident_dit_for_encode(pipe, _LendClient()) is None+++def test_a_module_with_its_own_apply_onloads_through_model_to(monkeypatch):+ import torch++ from core.inference import video_ltx25_te_worker as worker++ class Odd(torch.nn.Linear):+ def _apply(+ self,+ fn,+ recurse = True,+ ):+ return super()._apply(fn, recurse)++ model = _stack_model()+ assert worker._onloads_whole(model)+ model.model.language_model.norm = Odd(8, 8)+ assert not worker._onloads_whole(model)+ assert not worker._onloads_whole(object())+++def test_the_host_copy_is_pinned_once_before_the_first_card_encode(monkeypatch):+ from core.inference import diffusion_memory+ from core.inference import video_ltx25_te_worker as worker++ calls = []++ def _pin(+ module,+ host,+ logger,+ buffer_host = None,+ layout = None,+ exact = False,+ device = None,+ ):+ calls.append((sorted(host), sorted(buffer_host or {}), exact, device))+ return 3 << 20++ monkeypatch.setattr(diffusion_memory, "_pin_host_weights", _pin)+ monkeypatch.setattr(diffusion_memory, "_exact_pin_supported", lambda device = None: True)+ monkeypatch.setattr(diffusion_memory, "_available_system_memory_mib", lambda: 64 << 10)+ monkeypatch.setattr(diffusion_memory, "_host_ram_capacity_mib", lambda: 128 << 10)+ monkeypatch.setattr(worker, "_discrete_card", lambda device: True)+ model = _stack_model()+ monkeypatch.setattr(worker, "_encode_plan", lambda config, m, reserved = None: ("cpu:0", None))+ config = {"device": "cuda:0", "resident": False}+ # Not before the server says its own pins are done.+ worker._encode_on(_FakeTokenizer(), model, config, ["a fox"], 6)+ assert calls == [] and "_pinned_bytes" not in config+ config["_pin_host"] = True+ for _ in range(2):+ worker._encode_on(_FakeTokenizer(), model, config, ["a fox"], 6)+ assert len(calls) == 1 and calls[0][2] is True and calls[0][3] == "cuda:0"+ assert "model.language_model.layers.0.weight" in calls[0][0]+ assert calls[0][1] == ["model.language_model.scale"]+ assert config["_pinned_bytes"] == 3 << 20+ # A CPU encode, a resident encoder, the kill switch and a platform without registered pins never pin.+ calls.clear()+ monkeypatch.setattr(worker, "_encode_plan", lambda config, m, reserved = None: ("cpu", None))+ worker._encode_on(+ _FakeTokenizer(), model, {"device": "cuda:0", "resident": False}, ["a fox"], 6+ )+ assert worker._pin_host_copy(model, {"device": "cuda:0", "resident": True}) == 0+ assert worker._pin_host_copy(model, {"device": "xpu:0", "resident": False}) == 0+ monkeypatch.setenv(worker.PIN_HOST_ENV, "0")+ assert worker._pin_host_copy(model, {"device": "cuda:0", "resident": False}) == 0+ monkeypatch.delenv(worker.PIN_HOST_ENV)+ monkeypatch.setattr(diffusion_memory, "_exact_pin_supported", lambda device = None: False)+ assert worker._pin_host_copy(model, {"device": "cuda:0", "resident": False}) == 0+ assert calls == []+ # Room for one copy but not the transient second one above the reserve: stay pageable.+ monkeypatch.setattr(diffusion_memory, "_exact_pin_supported", lambda device = None: True)+ nbytes = sum(+ t.numel() * t.element_size() for t in list(model.parameters()) + list(model.buffers())+ )+ reserve = max(+ diffusion_memory._PIN_RESERVE_MIN_BYTES,+ int((128 << 30) * diffusion_memory._PIN_RESERVE_FRACTION),+ )+ monkeypatch.setattr(+ diffusion_memory, "_available_system_memory_mib", lambda: (reserve + nbytes) >> 20+ )+ assert not worker._pin_fits_twice(list(model.parameters()) + list(model.buffers()))+ assert (+ worker._pin_host_copy(model, {"device": "cuda:0", "resident": False}) == 0 and calls == []+ )+ monkeypatch.setattr(+ diffusion_memory, "_available_system_memory_mib", lambda: ((reserve + 2 * nbytes) >> 20) + 1+ )+ assert worker._pin_fits_twice(list(model.parameters()) + list(model.buffers()))+++def test_an_encode_out_of_memory_on_the_card_retries_on_the_cpu(monkeypatch):+ import torch++ from core.inference import video_ltx25_te_worker as worker++ model = _stack_model()+ monkeypatch.setattr(worker, "_encode_plan", lambda config, m, reserved = None: ("cuda:0", None))+ real = worker._run_encode+ tried = []++ def _run(model, config, inputs, device, stream):+ tried.append(device)+ if device != "cpu":+ raise torch.OutOfMemoryError("CUDA out of memory. Tried to allocate 2.00 GiB")+ return real(model, config, inputs, device, stream)++ monkeypatch.setattr(worker, "_run_encode", _run)+ config = {"device": "cuda:0", "resident": False}+ embeds, _mask, device = worker._encode_on(_FakeTokenizer(), model, config, ["a fox"], 6)+ assert tried == ["cuda:0", "cpu"] and device == "cpu" and config["_streamed"] is False+ with torch.inference_mode():+ plain = worker._pack_hidden_states(+ model, torch.ones(1, 6, dtype = torch.long), torch.ones(1, 6, dtype = torch.long)+ )+ assert torch.equal(embeds, plain)++ def _broken(model, config, inputs, device, stream):+ raise ValueError("not a memory error")++ monkeypatch.setattr(worker, "_run_encode", _broken)+ with pytest.raises(ValueError):+ worker._encode_on(_FakeTokenizer(), model, config, ["a fox"], 6)++def test_an_encoder_too_big_to_onload_whole_streams_before_it_falls_back_to_the_cpu(monkeypatch):from core.inference import video_ltx25_te_worker as worker@@ -2895,6 +3195,128 @@ def test_lend_streams_resident_blocks_only_when_the_encoder_then_fits_or_room_isassert v25.lend_resident_dit_for_encode(pipe, cpu) is None and released == []+def _park_pipe():+ import torch++ torch.manual_seed(0)+ connectors = torch.nn.Sequential(torch.nn.Linear(8, 8), torch.nn.LayerNorm(8))+ connectors.register_buffer("table", torch.arange(4.0))+ vocoder = torch.nn.Linear(4, 4)+ hooked = torch.nn.Linear(4, 4)+ hooked._hf_hook = object()+ nested = torch.nn.Sequential(torch.nn.Linear(4, 4))+ nested[0]._diffusers_hook = SimpleNamespace(hooks = {"group_offloading": object()})+ # an empty diffusers registry holds no hook: still parkable+ connectors[0]._diffusers_hook = SimpleNamespace(hooks = {})+ return SimpleNamespace(+ components = {+ "connectors": connectors,+ "vocoder": vocoder,+ "vae": torch.nn.Linear(4, 4),+ "audio_vae": torch.nn.Linear(4, 4),+ "hooked": hooked,+ "nested": nested,+ "transformer": torch.nn.Linear(16, 16),+ "scheduler": object(),+ }+ )+++def test_parking_moves_only_plain_companions_and_restores_the_same_tensors(monkeypatch):+ import torch++ from core.inference import diffusion_memory as dm++ monkeypatch.setattr(dm, "_available_system_memory_mib", lambda: 64 << 10)+ monkeypatch.setattr(dm, "_host_ram_capacity_mib", lambda: 128 << 10)+ monkeypatch.setattr(dm, "_windows_commit_headroom_mib", lambda: None)+ monkeypatch.setattr(dm, "registered_pinned_empty", lambda nbytes, fill = None: None)+ pipe = _park_pipe()+ names = [name for name, _m, _mib in v25._parkable_components(pipe, "cpu")]+ # no transformer (it lends blocks), no VAE (compiled decode), no hook on the module or a child, no non-module+ assert names == ["connectors", "vocoder"]+ connectors = pipe.components["connectors"]+ params = list(connectors.parameters())+ before = [t.detach().clone() for t in params] + [connectors.table.clone()]+ ptrs = [t.data_ptr() for t in params]+ for _ in range(2):+ restore = v25._park_for_encode(pipe, "cpu", 1)+ assert callable(restore)+ # largest first, and only as much as asked: the connectors went, the vocoder stayed+ kept = connectors.__dict__[v25._PARK_HOST_ATTR][1]+ host = {k.data_ptr() for k in kept}+ assert {t.data_ptr() for t in params} | {connectors.table.data_ptr()} == host+ assert v25._PARK_HOST_ATTR not in pipe.components["vocoder"].__dict__+ restore()+ assert all(t is p for t, p in zip(connectors.parameters(), params))+ assert all(+ torch.equal(a, b)+ for a, b in zip(list(connectors.parameters()) + [connectors.table], before)+ )+ assert not ({t.data_ptr() for t in connectors.parameters()} & host)+ assert ptrs # the module still runs+ connectors(torch.ones(1, 8))+ # The kill switch, nothing asked, or a host that cannot hold the copy: nothing moves.+ monkeypatch.setenv(v25.PARK_COMPANIONS_ENV, "0")+ assert v25._park_for_encode(pipe, "cpu", 10) is None+ monkeypatch.delenv(v25.PARK_COMPANIONS_ENV)+ assert v25._park_for_encode(pipe, "cpu", 0) is None+ fresh = _park_pipe()+ # Windows: free RAM is not enough when the commit limit has no room for the copy.+ monkeypatch.setattr(dm, "_windows_commit_headroom_mib", lambda: 1)+ assert v25._park_for_encode(fresh, "cpu", 10) is None+ monkeypatch.setattr(dm, "_windows_commit_headroom_mib", lambda: None)+ monkeypatch.setattr(dm, "_available_system_memory_mib", lambda: 1)+ assert v25._park_for_encode(fresh, "cpu", 10) is None+ assert v25._PARK_HOST_ATTR not in fresh.components["connectors"].__dict__+++def test_lend_parks_companions_only_when_blocks_alone_leave_the_stream_short(monkeypatch):+ """16 GiB A100: lent blocks still leave the stream short, so the connectors park."""+ pipe = SimpleNamespace(transformer = object(), components = {})+ events = []+ monkeypatch.setattr(+ v25, "_parkable_components", lambda pipe, device: [("connectors", None, 6050)]+ )++ def park(pipe, device, need):+ events.append(("park", need))+ return lambda: events.append("unpark")++ monkeypatch.setattr(v25, "_park_for_encode", park)+ released = _lend_env(monkeypatch, free_mib = 2566, held_mib = 2264)+ rooms = iter([2566, 4894])+ monkeypatch.setattr(v25, "_encode_room_mib", lambda client: next(rooms))+ restore = v25.lend_resident_dit_for_encode(pipe, _LendClient())+ assert released == [6900 - 2566] and events == [("park", 6900 - 4894)]+ restore()+ # companions back before the blocks are pinned again+ assert events[-1] == "unpark" and released[-1] == "restored"+ # nothing resident in the denoiser (the first encode): the connectors alone make the room+ events.clear()+ released = _lend_env(monkeypatch, free_mib = 4914, held_mib = 0)+ monkeypatch.setattr(v25, "_encode_room_mib", lambda client: 4914)+ assert v25.lend_resident_dit_for_encode(pipe, _LendClient()) is not None+ assert released == [] and events == [("park", 6900 - 4914)]+ # blocks alone are enough: nothing parks+ events.clear()+ released = _lend_env(monkeypatch, free_mib = 5000, held_mib = 4000)+ rooms = iter([5000, 6900])+ monkeypatch.setattr(v25, "_encode_room_mib", lambda client: next(rooms))+ assert v25.lend_resident_dit_for_encode(pipe, _LendClient()) is not None+ assert released == [1900] and events == []+ # even everything lent is short: blocks go as before, the companions stay+ monkeypatch.setattr(v25, "_parkable_components", lambda pipe, device: [("vae", None, 1000)])+ released = _lend_env(monkeypatch, free_mib = 100, held_mib = 2000)+ monkeypatch.setattr(v25, "_encode_room_mib", lambda client: 100)+ assert v25.lend_resident_dit_for_encode(pipe, _LendClient()) is not None+ assert released == [6800] and events == []+ # the kill switch keeps the companions+ monkeypatch.setenv(v25.PARK_COMPANIONS_ENV, "0")+ released = _lend_env(monkeypatch, free_mib = 4914, held_mib = 0)+ assert v25.lend_resident_dit_for_encode(pipe, _LendClient()) is None and events == []++def test_remote_encode_prompt_pins_lent_blocks_back_after_the_encode_and_skips_cache_hits(monkeypatch,):