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 oversized diffusion components on low-VRAM GPUs (#8141)
oobaboogaa08234d61a39
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.pyindex 1bf8e83f144..3f2fdb4cc9f 100644--- a/studio/backend/core/inference/diffusion.py+++ b/studio/backend/core/inference/diffusion.py@@ -64,6 +64,7 @@ from .diffusion_memory import (MEMORY_MODE_BALANCED,MEMORY_MODE_LOW_VRAM,OFFLOAD_NONE,+ OFFLOAD_STREAMING,apply_memory_plan,estimate_gguf_resident_mib,estimate_image_runtime_mib,@@ -72,6 +73,7 @@ from .diffusion_memory import (normalize_memory_mode,plan_diffusion_memory,plan_fits_total_capacity,+ refine_memory_plan_for_components,settled_snapshot_device_memory,)from .diffusion_speed import (@@ -2915,6 +2917,19 @@ class DiffusionBackend:))+ # Whole-module offload still onloads one complete component for its forward.+ # Refine it from the loaded, possibly quantized weights so an oversized text+ # encoder uses leaf streaming instead of failing during prompt encoding.+ refined_plan = refine_memory_plan_for_components(pipe, plan)+ if refined_plan.offload_policy != plan.offload_policy:+ logger.info(+ "diffusion.memory: refined policy %s -> %s (%s)",+ plan.offload_policy,+ refined_plan.offload_policy,+ "; ".join(refined_plan.reasons),+ )+ plan = refined_plan+# Persistent conditioning cache (UNSLOTH_DIFFUSION_COND_CACHE_DIR): repeated prompts skip the text-encoder# forward. After the TE quant so the key reflects the encoders that run; ``base`` keys the companion repo.cond_cache.install(@@ -2999,6 +3014,9 @@ class DiffusionBackend:effective_policy,"everything fits on the GPU, no offload needed"if effective_policy == OFFLOAD_NONE+ else "a loaded component exceeds the device budget; "+ "streaming transformer blocks and text-encoder layers"+ if effective_policy == OFFLOAD_STREAMINGelse "planned from measured free VRAM vs estimated footprint",),"transformer_cache": (diff --git a/studio/backend/core/inference/diffusion_memory.py b/studio/backend/core/inference/diffusion_memory.pyindex c78d24cb16e..e034c93210c 100644--- a/studio/backend/core/inference/diffusion_memory.py+++ b/studio/backend/core/inference/diffusion_memory.py@@ -17,7 +17,7 @@ imported lazily.from __future__ import annotationsimport os-from dataclasses import dataclass+from dataclasses import dataclass, replacefrom typing import Any, Optional@@ -36,10 +36,12 @@ MEMORY_MODES = (# none -- all weights resident (fastest; fits only with room).# model -- enable_model_cpu_offload(): one top-level module on the GPU at a time.# group -- apply_group_offloading() on the transformer: stream a few blocks at a time with a prefetch stream.-# sequential -- enable_sequential_cpu_offload(): submodule-level (broken for GGUF on diffusers 0.38, kept as an escape hatch).+# streaming -- group-offload the transformer and leaf-offload text encoders that cannot fit whole.+# sequential -- enable_sequential_cpu_offload(): submodule-level (broken for GGUF through diffusers 0.39, kept as an escape hatch).OFFLOAD_NONE = "none"OFFLOAD_MODEL = "model"OFFLOAD_GROUP = "group"+OFFLOAD_STREAMING = "streaming"OFFLOAD_SEQUENTIAL = "sequential"# Transformer blocks resident per group under group offloading: fewer = lower VRAM, more host-to-device traffic.@@ -106,7 +108,7 @@ class MemoryPlan:@propertydef engages_offload(self) -> bool:- return self.offload_policy in (OFFLOAD_MODEL, OFFLOAD_SEQUENTIAL)+ return self.offload_policy != OFFLOAD_NONEdef as_public_dict(self) -> dict[str, Any]:return {@@ -379,6 +381,7 @@ def plan_diffusion_memory(none - everything resident: fastest, highest VRAM.group - stream the transformer, companions resident: near-resident speed, moderate cut.model - offload every component: lowest VRAM, slow.+ streaming - stream transformer blocks and text-encoder leaves when one component cannot fit."""mode = normalize_memory_mode(requested_mode) or MEMORY_MODE_AUTOcan_offload = bool(getattr(target, "supports_model_cpu_offload", False))@@ -464,6 +467,96 @@ def plan_diffusion_memory(# ── apply to a built pipeline ─────────────────────────────────────────────────+def _streamable_components(pipe: Any, torch: Any) -> dict[str, tuple[Any, str]]:+ """Component name -> (module, group-offload type) for what streaming keeps off the device.++ Every denoiser streams block by block; every text encoder streams leaf by leaf. Anything else+ (the VAE, an image encoder) has no granular hook here and stays resident, so this is also the+ set ``refine_memory_plan_for_components`` is allowed to size the policy against."""+ streamed: dict[str, tuple[Any, str]] = {}+ for name in ("transformer", "transformer_2", "unconditional_transformer"):+ module = getattr(pipe, name, None)+ if isinstance(module, torch.nn.Module):+ streamed[name] = (module, "block_level")+ for name, module in getattr(pipe, "components", {}).items():+ if str(name).startswith("text_encoder") and isinstance(module, torch.nn.Module):+ streamed[str(name)] = (module, "leaf_level")+ return streamed+++def refine_memory_plan_for_components(pipe: Any, plan: MemoryPlan) -> MemoryPlan:+ """Replace whole-module offload when a loaded component cannot fit on the device.++ The coarse planner runs before the pipeline exists. At this point the weights are still on+ CPU, so their actual packed storage is a better signal than family or cache estimates. Keep+ whole-module offload when every component can fit, preserving its faster execution. When one+ cannot, use granular streaming so no forward needs to materialise that component in full.++ Only a STREAMABLE component justifies the switch, and only if the components streaming cannot+ hook still fit resident TOGETHER: whole-module offload onloads one at a time, streaming holds+ all of them at once, so refining past either bound would trade one OOM for another.+ """+ if plan.offload_policy != OFFLOAD_MODEL:+ return plan+ budget = plan.estimates.get("safe_device_budget_mib")+ if budget is None or int(budget) <= 0:+ return plan++ try:+ import torch++ components = getattr(pipe, "components", {})+ transformer = getattr(pipe, "transformer", None)+ if not isinstance(components, dict) or not isinstance(transformer, torch.nn.Module):+ return plan+ streamable = _streamable_components(pipe, torch)++ sizes: dict[str, int] = {}+ mib = 1024 * 1024+ for name, component in components.items():+ if not isinstance(component, torch.nn.Module):+ continue+ seen: set[int] = set()+ storage_bytes = 0+ tensors = list(component.parameters(recurse = True)) + list(+ component.buffers(recurse = True)+ )+ for tensor in tensors:+ marker = id(tensor)+ if marker in seen:+ continue+ seen.add(marker)+ storage_bytes += int(tensor.numel()) * int(tensor.element_size())+ sizes[str(name)] = (storage_bytes + mib - 1) // mib+ except Exception: # noqa: BLE001 - runtime measurement is an optional refinement+ return plan++ streamed_sizes = {n: m for n, m in sizes.items() if n in streamable}+ if not streamed_sizes:+ return plan+ largest_name, largest_mib = max(streamed_sizes.items(), key = lambda item: item[1])+ if largest_mib <= int(budget):+ return plan+ # What streaming leaves resident, all at once. Over budget here means streaming OOMs too.+ resident_mib = sum(m for n, m in sizes.items() if n not in streamable)+ if resident_mib > int(budget):+ return plan++ estimates = dict(plan.estimates)+ estimates["largest_component_mib"] = largest_mib+ estimates["streaming_resident_mib"] = resident_mib+ return replace(+ plan,+ offload_policy = OFFLOAD_STREAMING,+ estimates = estimates,+ reasons = plan.reasons+ + (+ f"loaded {largest_name} is {largest_mib} MiB, above the {int(budget)} MiB "+ "device budget; streaming transformer blocks and text-encoder layers",+ ),+ )++def apply_memory_plan(pipe: Any,plan: MemoryPlan,@@ -476,7 +569,7 @@ def apply_memory_plan(Returns the ``(offload_policy, vae_tiling)`` ACTUALLY engaged, which can differ from the plan:tiling is a no-op where there's no tiling control, and group / sequential offload fall back to- whole-module offload if unsupported (e.g. sequential is broken for GGUF on diffusers 0.38)."""+ whole-module offload if unsupported (e.g. sequential is broken for GGUF through diffusers 0.39)."""tiling_engaged = Falseif plan.vae_tiling:tiling_engaged = _enable_vae_saver(pipe, "enable_vae_tiling", "enable_tiling", logger)@@ -497,6 +590,8 @@ def apply_memory_plan(if not _apply_group_offload(pipe, device, logger):_fallback_to_model_offload()policy = OFFLOAD_MODEL+ elif policy == OFFLOAD_STREAMING:+ _apply_streaming_offload(pipe, device, logger)elif policy == OFFLOAD_SEQUENTIAL:try:pipe.enable_sequential_cpu_offload(device = device)@@ -594,3 +689,71 @@ def _apply_group_offload(pipe: Any, device: str, logger: Any) -> bool:exc,)return False+++def _apply_streaming_offload(pipe: Any, device: str, logger: Any) -> None:+ """Stream transformer blocks and text-encoder leaves without whole-component onloads.++ This is selected only after measuring a component larger than the safe device budget, so a+ model-offload fallback would deterministically OOM. Any setup failure is therefore fatal and+ reports the granular-offload failure directly.+ """+ installed = 0+ try:+ import inspect++ import torch+ from diffusers.hooks import apply_group_offloading++ components = getattr(pipe, "components", {})+ if not isinstance(components, dict):+ raise RuntimeError("pipeline does not expose its components")++ # Same selection the planner sized against, so what it promised to stream is what streams.+ streamed = _streamable_components(pipe, torch)+ if "transformer" not in streamed:+ raise RuntimeError("pipeline has no transformer to stream")++ onload = torch.device(device)+ offload = torch.device("cpu")+ params = inspect.signature(apply_group_offloading).parameters+ use_stream = onload.type == "cuda" and "low_cpu_mem_usage" in params++ # Keep small companions such as the tiled VAE resident. Every transformer and text+ # encoder remains on CPU behind a granular hook.+ for name, component in components.items():+ if str(name) in streamed:+ continue+ if isinstance(component, torch.nn.Module):+ component.to(onload)++ for module, offload_type in streamed.values():+ kwargs: dict[str, Any] = {+ "onload_device": onload,+ "offload_device": offload,+ "offload_type": offload_type,+ }+ if offload_type == "block_level":+ kwargs["num_blocks_per_group"] = DEFAULT_GROUP_BLOCKS+ if "use_stream" in params:+ kwargs["use_stream"] = use_stream+ if use_stream and "non_blocking" in params:+ kwargs["non_blocking"] = True+ if use_stream and "record_stream" in params:+ kwargs["record_stream"] = False+ if use_stream and "low_cpu_mem_usage" in params:+ kwargs["low_cpu_mem_usage"] = True+ apply_group_offloading(module, **kwargs)+ installed += 1+ except Exception as exc:+ if logger is not None:+ logger.warning(+ "diffusion.memory: granular streaming offload failed after installing hooks "+ "on %d module(s): %s",+ installed,+ exc,+ )+ raise RuntimeError(+ "A diffusion component is larger than the available GPU memory, and granular "+ f"streaming offload could not be enabled: {exc}"+ ) from excdiff --git a/studio/backend/models/inference.py b/studio/backend/models/inference.pyindex 93effb2ea82..924f8340c0c 100644--- a/studio/backend/models/inference.py+++ b/studio/backend/models/inference.py@@ -2971,7 +2971,7 @@ class DiffusionStatusResponse(BaseModel):)cpu_offload: bool = Field(False, description = "Whether CPU offload is engaged")offload_policy: Optional[str] = Field(- None, description = "Resolved offload policy: none | group | model | sequential"+ None, description = "Resolved offload policy: none | group | model | streaming | sequential")vae_tiling: bool = Field(False, description = "Whether VAE tiling/slicing is enabled")memory_mode: Optional[str] = Field(None, description = "Requested memory mode")diff --git a/studio/backend/tests/test_diffusion_backend.py b/studio/backend/tests/test_diffusion_backend.pyindex ff126ece898..9cf4dd21701 100644--- a/studio/backend/tests/test_diffusion_backend.py+++ b/studio/backend/tests/test_diffusion_backend.py@@ -2721,6 +2721,37 @@ def test_load_memory_mode_low_vram_engages_model_offload(fake_runtime, tmp_path,assert pipe.offloaded is True and pipe.moved_to is None # offload owns placement+def test_load_refines_component_placement_after_text_encoder_quantization(+ fake_runtime, tmp_path, monkeypatch+):+ from core.inference import diffusion as dmod++ (tmp_path / "m.gguf").write_bytes(b"x")+ backend = DiffusionBackend()+ _force_cuda_target(backend, monkeypatch)+ seen = {"quantized": False, "refined": False}++ def _quantize(*args, **kwargs):+ seen["quantized"] = True+ return None++ def _refine(pipe, plan):+ assert seen["quantized"] is True+ assert pipe is not None and plan.offload_policy == "model"+ seen["refined"] = True+ return plan++ monkeypatch.setattr(dmod, "quantize_text_encoders", _quantize)+ monkeypatch.setattr(dmod, "refine_memory_plan_for_components", _refine)+ backend.load_pipeline(+ str(tmp_path),+ gguf_filename = "m.gguf",+ family_override = "z-image",+ memory_mode = "low_vram",+ )+ assert seen == {"quantized": True, "refined": True}++def test_load_explicit_cpu_offload_engages_model_offload_on_cuda(fake_runtime, tmp_path, monkeypatch):diff --git a/studio/backend/tests/test_diffusion_memory.py b/studio/backend/tests/test_diffusion_memory.pyindex 7ad2bb67a94..263771f9820 100644--- a/studio/backend/tests/test_diffusion_memory.py+++ b/studio/backend/tests/test_diffusion_memory.py@@ -15,6 +15,7 @@ import typesimport pytestfrom core.inference.diffusion_memory import (+ DEFAULT_GROUP_BLOCKS,DEFAULT_IMAGE_HEIGHT,DEFAULT_IMAGE_WIDTH,MEMORY_MODE_BALANCED,@@ -24,6 +25,7 @@ from core.inference.diffusion_memory import (OFFLOAD_MODEL,OFFLOAD_NONE,OFFLOAD_SEQUENTIAL,+ OFFLOAD_STREAMING,DeviceMemory,MemoryPlan,apply_memory_plan,@@ -31,6 +33,7 @@ from core.inference.diffusion_memory import (estimate_image_runtime_mib,normalize_memory_mode,plan_diffusion_memory,+ refine_memory_plan_for_components,snapshot_device_memory,)@@ -506,6 +509,196 @@ def test_apply_group_fallback_enables_vae_tiling():assert tiled is True and "vae_tiling" in pipe.calls+def _install_sized_torch(monkeypatch):+ import sys++ class Tensor:+ def __init__(self, size_mib):+ self.size_mib = size_mib++ def numel(self):+ return self.size_mib * 1024 * 1024++ def element_size(self):+ return 1++ class Module:+ def __init__(self, size_mib = 0):+ self.tensor = Tensor(size_mib)+ self.moved_to = None++ def parameters(self, recurse = True):+ return [self.tensor]++ def buffers(self, recurse = True):+ return []++ def to(self, device):+ self.moved_to = device+ return self++ fake_torch = types.ModuleType("torch")+ fake_torch.nn = types.SimpleNamespace(Module = Module)+ fake_torch.device = lambda value: types.SimpleNamespace(type = str(value).split(":")[0])+ monkeypatch.setitem(sys.modules, "torch", fake_torch)+ return Module+++def test_refine_model_offload_streams_only_when_a_component_exceeds_budget(monkeypatch):+ Module = _install_sized_torch(monkeypatch)+ plan = MemoryPlan(+ requested_mode = "low_vram",+ offload_policy = OFFLOAD_MODEL,+ vae_tiling = True,+ vae_slicing = True,+ device_memory = _discrete(8000),+ estimates = {"safe_device_budget_mib": 6000},+ )++ fitting_transformer = Module(4000)+ fits = types.SimpleNamespace(+ transformer = fitting_transformer,+ components = {"transformer": fitting_transformer, "text_encoder": Module(5500)},+ )+ assert refine_memory_plan_for_components(fits, plan) is plan++ transformer = Module(2500)+ oversized = types.SimpleNamespace(+ transformer = transformer,+ components = {"transformer": transformer, "text_encoder": Module(7500)},+ )+ refined = refine_memory_plan_for_components(oversized, plan)+ assert refined.offload_policy == OFFLOAD_STREAMING+ assert refined.estimates["largest_component_mib"] == 7500+ assert any("text_encoder" in reason for reason in refined.reasons)+++def test_refine_keeps_model_offload_when_streaming_cannot_help(monkeypatch):+ """Only a component streaming can actually hook justifies leaving whole-module offload."""+ Module = _install_sized_torch(monkeypatch)+ plan = MemoryPlan(+ requested_mode = "low_vram",+ offload_policy = OFFLOAD_MODEL,+ vae_tiling = True,+ vae_slicing = True,+ device_memory = _discrete(8000),+ estimates = {"safe_device_budget_mib": 6000},+ )++ # The oversized component has no granular hook, so streaming would onload it whole anyway.+ transformer = Module(2500)+ fat_vae = types.SimpleNamespace(+ transformer = transformer,+ components = {+ "transformer": transformer,+ "text_encoder": Module(1200),+ "vae": Module(7500),+ },+ )+ assert refine_memory_plan_for_components(fat_vae, plan) is plan++ # Each component fits, but streaming holds every unstreamed one at once: 3000 + 3500 > 6000.+ transformer = Module(2000)+ fat_resident = types.SimpleNamespace(+ transformer = transformer,+ components = {+ "transformer": transformer,+ "text_encoder": Module(6500),+ "vae": Module(3000),+ "image_encoder": Module(3500),+ },+ )+ assert refine_memory_plan_for_components(fat_resident, plan) is plan++ # Same shape with a resident set that fits still streams, and reports what stays behind.+ transformer = Module(2000)+ slim_resident = types.SimpleNamespace(+ transformer = transformer,+ components = {+ "transformer": transformer,+ "text_encoder": Module(6500),+ "vae": Module(300),+ "image_encoder": Module(500),+ },+ )+ refined = refine_memory_plan_for_components(slim_resident, plan)+ assert refined.offload_policy == OFFLOAD_STREAMING+ assert refined.estimates["streaming_resident_mib"] == 800+++def test_apply_streaming_uses_block_and_leaf_hooks_with_bounded_cpu_memory(monkeypatch):+ Module = _install_sized_torch(monkeypatch)+ calls = []++ def _apply(+ module,+ *,+ onload_device,+ offload_device,+ offload_type,+ num_blocks_per_group = None,+ use_stream = False,+ non_blocking = False,+ record_stream = True,+ low_cpu_mem_usage = False,+ ):+ calls.append(+ (+ module,+ offload_type,+ num_blocks_per_group,+ use_stream,+ non_blocking,+ record_stream,+ low_cpu_mem_usage,+ )+ )++ import sys++ if "diffusers" not in sys.modules:+ monkeypatch.setitem(sys.modules, "diffusers", types.ModuleType("diffusers"))+ hooks = types.ModuleType("diffusers.hooks")+ hooks.apply_group_offloading = _apply+ monkeypatch.setitem(sys.modules, "diffusers.hooks", hooks)++ transformer = Module(2500)+ text_encoder = Module(7500)+ vae = Module(200)+ pipe = types.SimpleNamespace(+ transformer = transformer,+ components = {+ "transformer": transformer,+ "text_encoder": text_encoder,+ "vae": vae,+ },+ )+ effective, _ = apply_memory_plan(+ pipe, _manual_plan(OFFLOAD_STREAMING, tiling = True), device = "cuda"+ )++ assert effective == OFFLOAD_STREAMING+ assert vae.moved_to.type == "cuda"+ assert [(call[1], call[2]) for call in calls] == [+ ("block_level", DEFAULT_GROUP_BLOCKS),+ ("leaf_level", None),+ ]+ assert all(call[3:] == (True, True, False, True) for call in calls)+++def test_apply_streaming_does_not_fall_back_to_known_oom_path(monkeypatch):+ import core.inference.diffusion_memory as mem++ def _fail(*args, **kwargs):+ raise RuntimeError("granular streaming offload could not be enabled")++ monkeypatch.setattr(mem, "_apply_streaming_offload", _fail)+ pipe = _RecordingPipe()+ with pytest.raises(RuntimeError, match = "granular streaming offload could not be enabled"):+ apply_memory_plan(pipe, _manual_plan(OFFLOAD_STREAMING, tiling = True), device = "cuda")+ assert "model_offload" not in pipe.calls++def test_apply_sequential_offload():pipe = _RecordingPipe()effective, _ = apply_memory_plan(