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: stream the text connectors under streaming offload so the denoise keeps more transformer groups resident (A100 16 GiB -16% per clip) (#17386)
Daniel Hanbd8ddd75c125
diff --git a/studio/backend/core/inference/diffusion_memory.py b/studio/backend/core/inference/diffusion_memory.pyindex c76bab20637..fc2f5e37041 100644--- a/studio/backend/core/inference/diffusion_memory.py+++ b/studio/backend/core/inference/diffusion_memory.py@@ -3255,6 +3255,38 @@ def _streamable_components(pipe: Any, torch: Any) -> dict[str, tuple[Any, str]]:return streamed+# "0" keeps run-once companions resident under streaming offload.+STREAM_RUN_ONCE_COMPANIONS_ENV = "UNSLOTH_VIDEO_STREAM_RUN_ONCE_COMPANIONS"+# Run once per request before step 0 (LTX-2 text connectors).+_RUN_ONCE_COMPANION_CLASSES = ("LTX2TextConnectors",)+++def run_once_companions(pipe: Any) -> dict[str, Any]:+ """Run-once companions to stream leaf by leaf with the encoders, keeping them off the card for the denoise."""+ if _env_off(STREAM_RUN_ONCE_COMPANIONS_ENV):+ return {}+ components = getattr(pipe, "components", None)+ if not isinstance(components, dict):+ return {}+ return {+ str(name): module+ for name, module in components.items()+ if type(module).__name__ in _RUN_ONCE_COMPANION_CLASSES+ and callable(getattr(module, "parameters", None))+ }+++def _run_once_companions_pin(dit_mib: int, leaf_mib: int, companion_mib: int, device: Any) -> bool:+ """Pin budget fits the companions too; unpinned streaming is slower than resident."""+ forced = str(os.environ.get(GROUP_OFFLOAD_PIN_ENV, "")).strip().lower()+ if forced in ("0", "off", "false", "no") or not host_pinning_allowed(device):+ return False+ if forced in ("1", "on", "true", "yes"):+ return True+ budget = None if _pinned_memory_capped() else _pin_budget_mib()+ return budget is not None and budget > 0 and dit_mib + leaf_mib + companion_mib <= budget++def _module_storage_bytes(module: Any, seen: set[int]) -> int:storage_bytes = 0for tensor in list(module.parameters(recurse = True)) + list(module.buffers(recurse = True)):@@ -9469,9 +9501,10 @@ def _apply_streaming_offload(onload.type == "cuda" and "low_cpu_mem_usage" in params and host_pinning_allowed(onload))+ companions = run_once_companions(pipe)# Small companions (tiled VAE) stay resident; transformers and encoders stay on CPU behind hooks.for name, component in components.items():- if str(name) in streamed:+ if str(name) in streamed or str(name) in companions:continueif isinstance(component, torch.nn.Module):component.to(onload)@@ -9517,6 +9550,24 @@ def _apply_streaming_offload(leaf_mib = sum(leaf_pin_mib(n, m, t) for n, (m, t) in streamed.items() if t != "block_level")+ companion_mib = sum(pin_mib(m) for m in companions.values())+ if companions and _run_once_companions_pin(+ dit_pin_mib, leaf_mib, companion_mib, onload+ ):+ for comp_name, module in companions.items():+ streamed[comp_name] = (module, "leaf_level")+ leaf_mib += companion_mib+ if logger is not None:+ logger.info(+ "diffusion.memory: streaming %s (%d MiB) leaf by leaf: run once before step 0, off the "+ "card for the denoise",+ ", ".join(type(m).__name__ for m in companions.values()),+ companion_mib,+ )+ for comp_name, module in companions.items():+ if comp_name not in streamed:+ module.to(onload)+ if prefetch:pin_dits, pin_encoders = _streamed_pin_plan(dit_pin_mib, leaf_mib, logger, device = onload)diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.pyindex 44fbd5786c8..83c601ffc9f 100644--- a/studio/backend/core/inference/video.py+++ b/studio/backend/core/inference/video.py@@ -4964,6 +4964,8 @@ def _video_offload_vram_floor_mib(if bool(getattr(plan, "stream_text_encoders", False)):streamed |= encoderselif policy == OFFLOAD_STREAMING:+ from .diffusion_memory import run_once_companions+ encoders |= {n for n in run_once_companions(pipe) if n in sizes}streamed = denoisers | encoderselse:return Nonediff --git a/studio/backend/tests/test_video_run_once_companions.py b/studio/backend/tests/test_video_run_once_companions.pynew file mode 100644index 00000000000..d9e6c4a3210--- /dev/null+++ b/studio/backend/tests/test_video_run_once_companions.py@@ -0,0 +1,165 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""Streaming offload streams LTX-2's run-once text connectors with the encoders, off the denoise floor."""++import sys+import types++import pytest++torch = pytest.importorskip("torch")++import core.inference.diffusion_memory as dm++_ENV = "UNSLOTH_VIDEO_STREAM_RUN_ONCE_COMPANIONS"+++class LTX2TextConnectors(torch.nn.Module):+ def __init__(self, mib):+ super().__init__()+ self.layers = torch.nn.ModuleList([_linear(2) for _ in range(mib // 2)])+ self.moved_to = []++ def to(self, *args, **kwargs):+ self.moved_to.append(args)+ return self+++class _Recorded(torch.nn.Module):+ def __init__(self, module):+ super().__init__()+ self.inner = module+ self.moved_to = []++ def to(self, *args, **kwargs):+ self.moved_to.append(args)+ return self+++def _linear(mib):+ return torch.nn.Linear(1024, mib * 512, bias = False).to(torch.bfloat16)+++def _pipe(connector_mib = 6):+ dit = torch.nn.Module()+ dit.blocks = torch.nn.ModuleList([_linear(2) for _ in range(4)])+ pipe = types.SimpleNamespace()+ pipe.transformer = dit+ pipe.connectors = LTX2TextConnectors(connector_mib)+ pipe.vae = _Recorded(_linear(3))+ pipe.components = {+ "transformer": dit,+ "connectors": pipe.connectors,+ "vae": pipe.vae,+ "scheduler": object(),+ }+ return pipe+++def _plan(policy, te = False):+ return types.SimpleNamespace(+ offload_policy = policy,+ stream_text_encoders = te,+ stream_transformer = True,+ device_memory = types.SimpleNamespace(backend = "cuda"),+ )+++def test_streaming_floor_leaves_the_connectors_off_the_card(monkeypatch):+ from core.inference.video import _video_offload_vram_floor_mib++ monkeypatch.delenv(_ENV, raising = False)+ pipe = _pipe()+ # vae 3 + DiT window (2x2 MiB); 6 MiB connectors excluded+ assert _video_offload_vram_floor_mib(pipe, _plan("streaming")) == 3 + 4+ assert _video_offload_vram_floor_mib(pipe, _plan("streaming"), phase = "decode") == 3+++def test_kill_switch_and_other_tiers_keep_the_connectors_resident(monkeypatch):+ from core.inference.video import _video_offload_vram_floor_mib++ pipe = _pipe()+ monkeypatch.delenv(_ENV, raising = False)+ assert _video_offload_vram_floor_mib(pipe, _plan("group")) == 3 + 6 + 4+ assert _video_offload_vram_floor_mib(pipe, _plan("group", te = True)) == 3 + 6 + 4+ monkeypatch.setenv(_ENV, "0")+ assert _video_offload_vram_floor_mib(pipe, _plan("streaming")) == 3 + 6 + 4+++def _stub_streaming(monkeypatch, budget_mib):+ pytest.importorskip("diffusers.hooks")+ calls = []++ def apply_group_offloading(+ module,+ onload_device = None,+ offload_device = None,+ offload_type = None,+ num_blocks_per_group = None,+ use_stream = False,+ non_blocking = False,+ record_stream = False,+ low_cpu_mem_usage = False,+ ):+ calls.append((module, offload_type, low_cpu_mem_usage))++ monkeypatch.setattr(+ sys.modules["diffusers.hooks"], "apply_group_offloading", apply_group_offloading+ )+ for name in (+ dm.GROUP_OFFLOAD_PIN_ENV,+ dm.BACKGROUND_PIN_ENV,+ "UNSLOTH_DIFFUSION_STREAMING_PREFETCH",+ ):+ monkeypatch.delenv(name, raising = False)+ for name, value in (+ ("host_pinning_allowed", True),+ ("_streaming_prefetch_enabled", True),+ ("_pinned_memory_capped", False),+ ("_pin_top_level_group", True),+ ):+ monkeypatch.setattr(dm, name, lambda *a, _v = value, **k: _v)+ for name in (+ "install_group_offload_buffer_restore",+ "install_group_offload_hooks_eager",+ "install_group_pin_wait",+ "install_group_prefetch",+ "_skip_top_level_copy_back",+ "_pin_vision_embedding_device",+ ):+ monkeypatch.setattr(dm, name, lambda *a, **k: None)+ monkeypatch.setattr(+ dm,+ "_apply_group_offloading_packed",+ lambda apply, module, kwargs, logger: apply(module, **kwargs),+ )+ monkeypatch.setattr(dm, "_pin_budget_mib", lambda: budget_mib)+ return calls+++def test_streaming_offload_streams_the_connectors_when_they_pin(monkeypatch):+ monkeypatch.delenv(_ENV, raising = False)+ calls = _stub_streaming(monkeypatch, 1 << 20)+ pipe = _pipe()+ dm._apply_streaming_offload(pipe, "cuda", None)+ hooked = {id(m): (t, low) for m, t, low in calls}+ assert hooked[id(pipe.connectors)] == ("leaf_level", False)+ assert pipe.connectors.moved_to == []+ assert pipe.vae.moved_to++[email protected]("why", ["budget", "kill_switch"])+def test_connectors_stay_resident_unless_pinned_or_when_switched_off(monkeypatch, why):+ if why == "kill_switch":+ monkeypatch.setenv(_ENV, "0")+ calls = _stub_streaming(monkeypatch, 1 << 20)+ else:+ monkeypatch.delenv(_ENV, raising = False)+ calls = _stub_streaming(+ monkeypatch, 9+ ) # the 8 MiB DiT pins, the 6 MiB connectors would not+ pipe = _pipe()+ dm._apply_streaming_offload(pipe, "cuda", None)+ assert all(m is not pipe.connectors for m, _t, _low in calls)+ assert pipe.connectors.moved_to