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 LTX-2.5: keep a streamed denoiser partly resident per request (#16845)
Daniel Hanfdd45f454eaf
diff --git a/studio/backend/core/inference/video_ltx25.py b/studio/backend/core/inference/video_ltx25.pyindex 4cdb72636cf..9fcb72dcb39 100644--- a/studio/backend/core/inference/video_ltx25.py+++ b/studio/backend/core/inference/video_ltx25.py@@ -816,6 +816,59 @@ def _server_reserved_mib(device: Optional[str]) -> Optional[int]:return None+def _encode_room_mib(client: Any) -> Optional[int]:+ """The room the worker's encode plan sees now (``video_ltx25_te_worker._encode_room_mib``); None when unreadable."""+ from .video_ltx25_te_worker import _encode_room_mib as worker_room++ device = client.config.get("device")+ return worker_room(client.config, _server_reserved_mib(device))+++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."""+ config = getattr(client, "config", None) or {}+ if (+ not config+ or config.get("resident")+ or not str(config.get("device") or "").startswith("cuda")+ ):+ return None+ try:+ import torch++ from .diffusion_memory import release_resident_groups+ from .video_ltx25_te_worker import ENCODE_MARGIN_MIB+ from .video_stream_residency import resident_mib++ held = resident_mib(getattr(pipe, "transformer", None))+ if held <= 0:+ return None+ torch.cuda.empty_cache()+ room = _encode_room_mib(client)+ if room is None:+ return None+ info = getattr(client, "info", None) or {}+ weights = int(info.get("weights_mib") or 0)+ whole = weights + ENCODE_MARGIN_MIB if weights > 0 else None+ streamed = info.get("stream_need_mib")+ if whole is not None and room < whole <= room + held:+ target = whole+ elif streamed is not None and room < int(streamed):+ target = int(streamed)+ else:+ 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+ except Exception as exc: # noqa: BLE001 -- the encode still runs, maybe on the CPU+ logger.warning("video.ltx25_te: lending resident blocks skipped (%s)", exc)+ return None++class TextEncoderWorkerError(RuntimeError):def __init__(self,@@ -883,6 +936,8 @@ class Ltx25TextEncoderClient:self._resp: Any = Noneself._ready = Falseself._seq = 0+ # Request the worker is still computing (a cancel abandons it).+ self._inflight: Optional[int] = Noneself._lock = threading.Lock()self._cache: list[tuple[tuple, Any]] = []self.info: dict[str, Any] = {}@@ -1008,6 +1063,7 @@ class Ltx25TextEncoderClient:def close(self) -> None:proc, self._proc = self._proc, Noneself._ready = False+ self._inflight = Noneself._cache.clear()if proc is None:return@@ -1024,6 +1080,19 @@ class Ltx25TextEncoderClient:logger.info("video.ltx25_te: encoder worker stopped")# encoding+ def stop_if_busy(self) -> bool:+ """Stop a worker still running an abandoned encode, freeing its card memory; the next encode restarts it."""+ if self._inflight is None or not self.alive():+ return False+ logger.info("video.ltx25_te: stopping the encoder worker mid-encode (request cancelled)")+ self.close()+ return True++ def cached(self, prompts: list[str], max_sequence_length: int) -> bool:+ key = (tuple(prompts), int(max_sequence_length))+ with self._lock:+ return any(cached_key == key for cached_key, _ in self._cache)+def encode(self,prompts: list[str],@@ -1058,11 +1127,17 @@ class Ltx25TextEncoderClient:"server_reserved_mib": _server_reserved_mib(self.config.get("device")),})+ self._inflight = seqwhile True:- msg = self._get(cancel, "encoding the prompt", request_id = seq)+ try:+ msg = self._get(cancel, "encoding the prompt", request_id = seq)+ except TextEncoderWorkerError:+ self._inflight = None+ raise# A reply to a request a cancel abandoned arrives first; skip it.if msg.get("type") == "embeds" and msg.get("id") == seq:break+ self._inflight = Noneembeds, mask = msg["embeds"], msg["mask"]self.last_encode = {k: v for k, v in msg.items() if k not in ("type", "id", "embeds", "mask")@@ -1098,8 +1173,25 @@ def install_remote_encode_prompt(pipe: Any, client: Ltx25TextEncoderClient) -> Ndtype = dtype or getattr(getattr(pipe, "transformer", None), "dtype", None)def _one(texts: list[str]) -> tuple[Any, Any]:- # The client's own cached tensors (read only): every op below returns a new tensor.- cached, mask = client.encode(texts, max_sequence_length, copy = False)+ # Cache miss: lend resident DiT blocks to the worker for the encode.+ is_cached = getattr(client, "cached", None)+ restore = (+ lend_resident_dit_for_encode(pipe, client)+ if callable(is_cached) and not is_cached(texts, max_sequence_length)+ else None+ )+ try:+ # The client's own cached tensors (read only): every op below returns a new tensor.+ cached, mask = client.encode(texts, max_sequence_length, copy = False)+ except BaseException:+ # A cancelled encode may still use the lent memory: stop it before pinning back.+ stop = getattr(client, "stop_if_busy", None)+ if restore is not None and callable(stop):+ stop()+ raise+ finally:+ if restore is not None:+ restore()batch = cached.shape[0]embeds = cached.to(device = device, dtype = dtype)mask = mask.to(device = device)diff --git a/studio/backend/core/inference/video_ltx25_te_worker.py b/studio/backend/core/inference/video_ltx25_te_worker.pyindex bb2c6c37c3d..33307efa980 100644--- a/studio/backend/core/inference/video_ltx25_te_worker.py+++ b/studio/backend/core/inference/video_ltx25_te_worker.py@@ -659,6 +659,19 @@ def _encode_plan(return configured, parts+def _stream_need_mib_or_none(config: dict, model: Any) -> Optional[int]:+ """``_encode_plan``'s streamed need, or None when this encoder never streams."""+ if config.get("resident") or (os.environ.get(STREAM_ENCODE_ENV) or "").strip() == "0":+ return None+ if str(config.get("device") or "").split(":", 1)[0] not in ("cuda", "xpu"):+ return None+ try:+ parts = _stream_parts(model)+ return None if parts is None else _stream_need_mib(parts)+ except Exception: # noqa: BLE001 -- reporting only+ return None++# "0" turns the layer-streamed encode off (a card too small for the whole encoder then encodes on the CPU again).STREAM_ENCODE_ENV = "UNSLOTH_LTX25_TE_STREAM"@@ -888,6 +901,8 @@ def run_text_encoder_worker(*, cmd_queue: Any, resp_queue: Any, config: dict) -># "hosted" (the unsloth file), "quantized_at_load" (built from the dense encoder) or None (bf16)."te_source": config.get("_te_source"),"weights_mib": _weights_mib_or_none(model),+ # video_ltx25.lend_resident_dit_for_encode lends resident denoiser blocks up to this.+ "stream_need_mib": _stream_need_mib_or_none(config, model),**_memory_stats(config.get("device") or ""),})diff --git a/studio/backend/core/inference/video_stream_residency.py b/studio/backend/core/inference/video_stream_residency.pyindex ea549e8fdd2..1f613bae725 100644--- a/studio/backend/core/inference/video_stream_residency.py+++ b/studio/backend/core/inference/video_stream_residency.py@@ -1,7 +1,7 @@# SPDX-License-Identifier: AGPL-3.0-only# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0-"""Keeps top group and block prefix of a Wan, HunyuanVideo-1.5 or LTX-2 denoiser resident, re-fitted per+"""Keeps top group and block prefix of a Wan, HunyuanVideo-1.5, LTX-2 or LTX-2.5 denoiser resident, re-fitted perrequest; need estimate stays the lower bound; kill switches UNSLOTH_VIDEO_DIT_RESIDENT=0,UNSLOTH_VIDEO_DIT_RESIDENT_BLOCKS=0 (top group only), UNSLOTH_VIDEO_DIT_RESIDENT_MEASURED=0(estimate only)."""@@ -17,8 +17,8 @@ VIDEO_DIT_RESIDENT_MEASURED_ENV = "UNSLOTH_VIDEO_DIT_RESIDENT_MEASURED"RESIDENT_POLICIES = ("group", "streaming")# Single-DiT families measured under the fit (MiniMax-H3 has its own controller, video_minimax_h3_residency).RESIDENT_FAMILY_PREFIXES = ("wan", "hunyuanvideo-1.5")-# Matched by name only: "ltx-2" covers LTX-2.0 to 2.3; "ltx-2.5" (another decoder stack) is not measured.-RESIDENT_FAMILIES = ("ltx-2",)+# Exact names: "ltx-2" covers LTX-2.0 to 2.3; LTX-2.5 lends blocks to its encoder worker (video_ltx25).+RESIDENT_FAMILIES = ("ltx-2", "ltx-2.5")# A measured peak is scaled by this and a fixed slack is kept on top (allocator fragmentation, cuDNN workspaces).MEASURED_PEAK_MARGIN = 1.15MEASURED_SLACK_MIB = 1024diff --git a/studio/backend/tests/test_video_ltx25.py b/studio/backend/tests/test_video_ltx25.pyindex 0f73fea1033..2e9767b8c1f 100644--- a/studio/backend/tests/test_video_ltx25.py+++ b/studio/backend/tests/test_video_ltx25.py@@ -2647,6 +2647,23 @@ def test_an_encoder_too_big_to_onload_whole_streams_before_it_falls_back_to_the_assert worker._encode_plan(offloaded, _FakeEncoderModel()) == ("cpu", None)+def test_the_worker_reports_its_streamed_need_only_when_it_can_stream(monkeypatch):+ from core.inference import video_ltx25_te_worker as worker++ model = _stack_model(width = 512)+ monkeypatch.delenv(worker.STREAM_ENCODE_ENV, raising = False)+ offloaded = {"device": "cuda:0", "resident": False}+ need = worker._stream_need_mib(worker._stream_parts(model))+ assert worker._stream_need_mib_or_none(offloaded, model) == need+ assert worker._stream_need_mib_or_none({"device": "xpu:0", "resident": False}, model) == need+ assert worker._stream_need_mib_or_none({"device": "cuda:0", "resident": True}, model) is None+ assert worker._stream_need_mib_or_none({"device": "cpu", "resident": False}, model) is None+ assert worker._stream_need_mib_or_none({"device": "mps", "resident": False}, model) is None+ assert worker._stream_need_mib_or_none(offloaded, _FakeEncoderModel()) is None+ monkeypatch.setenv(worker.STREAM_ENCODE_ENV, "0")+ assert worker._stream_need_mib_or_none(offloaded, model) is None++def test_a_streamed_encode_never_moves_the_whole_encoder(monkeypatch):import torch@@ -2726,3 +2743,205 @@ def test_one_video_per_prompt_skips_the_repeat_copy_unless_it_would_alias_the_carepeats.clear()pe = encode(_CachedClient(torch.float32), 2)assert pe.shape == (2, 4, 6) and [r for r in repeats if len(r) == 3] == [(1, 4, 6)]+++class _LendClient(_FakeClient):+ def __init__(+ self,+ *,+ resident = False,+ weights_mib = 22811,+ stream_need_mib = 6900,+ budget_mib = None,+ hit = False,+ ):+ super().__init__()+ self.config = {"device": "cuda:0", "resident": resident, "budget_mib": budget_mib}+ self.info = {"weights_mib": weights_mib, "stream_need_mib": stream_need_mib}+ self.hit = hit+ self.events = []++ def cached(self, texts, max_len):+ return self.hit++ def encode(+ self,+ texts,+ max_len,+ cancel = None,+ copy = True,+ ):+ self.events.append("encode")+ return super().encode(texts, max_len, cancel = cancel, copy = copy)+++def _lend_env(+ monkeypatch,+ *,+ free_mib,+ held_mib,+ reserved_mib = 0,+ total_mib = 23034,+):+ import torch++ from core.inference import diffusion_memory as dm+ from core.inference import video_stream_residency as vr++ released = []+ monkeypatch.setattr(torch.cuda, "mem_get_info", lambda dev: (free_mib << 20, total_mib << 20))+ monkeypatch.setattr(torch.cuda, "memory_reserved", lambda dev: reserved_mib << 20)+ monkeypatch.setattr(torch.cuda, "empty_cache", lambda: None)+ monkeypatch.setattr(vr, "resident_mib", lambda module: held_mib)++ def release(+ pipe,+ need_mib,+ logger = None,+ denoisers_only = False,+ reason = "",+ device = None,+ ):+ assert denoisers_only and reason == "the prompt encode"+ released.append(need_mib)++ def restore(strict = False):+ released.append("restored")++ return restore++ monkeypatch.setattr(dm, "release_resident_groups", release)+ return released+++def test_lend_streams_resident_blocks_only_when_the_encoder_then_fits_or_room_is_below_the_floor(+ monkeypatch,+):+ from core.inference.video_ltx25_te_worker import ENCODE_MARGIN_MIB++ pipe = SimpleNamespace(transformer = object())+ whole = 22811 + ENCODE_MARGIN_MIB+ # lending 6 GiB of the 20 GiB resident makes the whole encoder fit: stream exactly the shortfall+ released = _lend_env(monkeypatch, free_mib = whole - 6000, held_mib = 20000)+ restore = v25.lend_resident_dit_for_encode(pipe, _LendClient())+ assert released == [6000] and callable(restore)+ restore()+ assert released == [6000, "restored"]+ released = _lend_env(monkeypatch, free_mib = whole + 1, held_mib = 20000)+ assert v25.lend_resident_dit_for_encode(pipe, _LendClient()) is None and released == []+ # room already clears the worker's streamed need: nothing lent+ released = _lend_env(monkeypatch, free_mib = 6900, held_mib = 4000)+ assert v25.lend_resident_dit_for_encode(pipe, _LendClient()) is None and released == []+ # below the worker's streamed need: lend up to it+ released = _lend_env(monkeypatch, free_mib = 5000, held_mib = 4000)+ assert v25.lend_resident_dit_for_encode(pipe, _LendClient()) is not None+ assert released == [6900 - 5000]+ # an encoder that never streams: no streamed target+ released = _lend_env(monkeypatch, free_mib = 5000, held_mib = 4000)+ assert v25.lend_resident_dit_for_encode(pipe, _LendClient(stream_need_mib = None)) is None+ assert released == []+ # the load budget minus what this process reserves caps the room, as in the worker+ released = _lend_env(monkeypatch, free_mib = whole + 5000, held_mib = 20000, reserved_mib = 10000)+ client = _LendClient(budget_mib = whole + 10000)+ from core.inference.video_ltx25_te_worker import WORKER_CONTEXT_MIB++ assert v25.lend_resident_dit_for_encode(pipe, client) is not None+ assert released == [WORKER_CONTEXT_MIB]+ released = _lend_env(monkeypatch, free_mib = 100, held_mib = 0)+ assert v25.lend_resident_dit_for_encode(pipe, _LendClient()) is None+ released = _lend_env(monkeypatch, free_mib = 100, held_mib = 20000)+ assert v25.lend_resident_dit_for_encode(pipe, _LendClient(resident = True)) is None+ cpu = _LendClient()+ cpu.config["device"] = "cpu"+ assert v25.lend_resident_dit_for_encode(pipe, cpu) is None and released == []+++def test_remote_encode_prompt_pins_lent_blocks_back_after_the_encode_and_skips_cache_hits(+ monkeypatch,+):+ import torch++ events = []++ def lend(pipe, client):+ events.append("lend")+ return lambda strict = False: events.append("restore")++ monkeypatch.setattr(v25, "lend_resident_dit_for_encode", lend)+ pipe = SimpleNamespace(+ _execution_device = torch.device("cpu"), transformer = SimpleNamespace(dtype = torch.bfloat16)+ )+ client = _LendClient()+ client.events = events+ v25.install_remote_encode_prompt(pipe, client)+ pipe.encode_prompt(prompt = "a fox", do_classifier_free_guidance = False, max_sequence_length = 4)+ assert events == ["lend", "encode", "restore"]+ events.clear()+ client.hit = True+ pipe.encode_prompt(prompt = "a fox", do_classifier_free_guidance = False, max_sequence_length = 4)+ assert events == ["encode"]++ # a failed encode still pins the lent blocks back+ def boom(*a, **k):+ events.append("encode")+ raise RuntimeError("worker died")++ events.clear()+ client.hit = False+ client.encode = boom+ client.stop_if_busy = lambda: events.append("stop_if_busy")+ with pytest.raises(RuntimeError):+ pipe.encode_prompt(prompt = "a fox", do_classifier_free_guidance = False, max_sequence_length = 4)+ assert events == ["lend", "encode", "stop_if_busy", "restore"]+++def test_a_cancelled_encode_stops_the_busy_worker_and_a_finished_one_does_not(monkeypatch):+ """Only a worker still computing an abandoned encode is stopped; one that answered (embeds or error) is kept."""+ import threading++ import torch++ 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+ closed = []+ monkeypatch.setattr(+ client, "close", lambda: closed.append(True) or setattr(client, "_inflight", None)+ )+ cancel = threading.Event()+ cancel.set()+ client._cmd.put = lambda msg: None # no reply: still encoding+ with pytest.raises(RuntimeError):+ client.encode(["p"], 2, cancel = cancel)+ assert client.stop_if_busy() is True and closed == [True]+ assert client.stop_if_busy() is False++ def reply(msg):+ client._resp.put(+ {+ "type": "embeds",+ "id": msg["id"],+ "embeds": torch.zeros(1, 2, 3),+ "mask": torch.ones(1, 2),+ }+ )++ client._cmd.put = reply+ client.encode(["q"], 2)+ assert client.stop_if_busy() is False+ client._cmd.put = lambda msg: client._resp.put(+ {"type": "error", "id": msg["id"], "error": "boom"}+ )+ with pytest.raises(v25.TextEncoderWorkerError):+ client.encode(["r"], 2)+ assert client.stop_if_busy() is False and closed == [True]diff --git a/studio/backend/tests/test_video_stream_residency.py b/studio/backend/tests/test_video_stream_residency.pyindex 3d2b105b351..8e78b9c207b 100644--- a/studio/backend/tests/test_video_stream_residency.py+++ b/studio/backend/tests/test_video_stream_residency.py@@ -30,16 +30,19 @@ def _applies(**kw):return vr.applies(family, **args)-def test_applies_only_to_block_streamed_single_dit_wan_hunyuanvideo_and_ltx2_on_cuda(monkeypatch):+def test_applies_only_to_block_streamed_single_dit_wan_hunyuanvideo_and_ltx_on_cuda(monkeypatch):assert _applies()assert _applies(offload_policy = "streaming")assert _applies(device = "cuda")assert not _applies(family = "wan2.2-t2v-a14b", is_moe = True)assert _applies(family = "ltx-2")assert _applies(family = "ltx-2", offload_policy = "streaming")- assert not _applies(family = "ltx-2.5")assert not _applies(family = "ltx-2-custom")assert not _applies(family = "ltx-2", is_moe = True)+ assert _applies(family = "ltx-2.5")+ assert _applies(family = "ltx-2.5", offload_policy = "streaming")+ assert not _applies(family = "ltx-2.5", offload_policy = "model")+ assert not _applies(family = "ltx-2.5-custom")assert _applies(family = "hunyuanvideo-1.5")assert _applies(family = "hunyuanvideo-1.5-720p", offload_policy = "streaming")assert not _applies(family = "minimax-h3")