Skip to content

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.

Studio diffusion: keep no pinned host copy of a resident Qwen-Image-2.1 text encoder (L4 host RAM -8.1 GiB, peak RSS 25.3 -> 16.6 GiB) (#17359)

Daniel Hanb14e78d7071e
diff --git a/studio/backend/core/inference/diffusion_memory.py b/studio/backend/core/inference/diffusion_memory.py
index bda70345373..065cd90cf5a 100644
--- a/studio/backend/core/inference/diffusion_memory.py
+++ b/studio/backend/core/inference/diffusion_memory.py
@@ -5309,6 +5309,8 @@ def _resident_tensors(group: Any) -> list:
def _release_group(group: Any) -> None:
+ # resident encoder groups with a dropped host copy get it back first
+ rebuild_dropped_host_copy(group)
onload_, offload_ = getattr(group, "_unsloth_streamed_hooks", (None, None))
for name, fn in (("onload_", onload_), ("offload_", offload_)):
if fn is not None:
@@ -5386,12 +5388,37 @@ def release_resident_groups(
return None
modules.sort(key = lambda m: 0 if _is_text_encoder_module(pipe, m) else 1)
left = int(need_mib) * 1024 * 1024
+ # Groups the load kept no host copy of get theirs back in one batch (one slab, one sync) before any streams.
+ pending: list = []
+ budget = left
+ for module in modules:
+ for group in reversed(_offload_groups(module) or []):
+ if budget <= 0:
+ break
+ if not getattr(group, "_unsloth_resident", False):
+ continue
+ for member in [group, *(getattr(group, "_unsloth_tied_groups", None) or [])]:
+ if getattr(member, "_unsloth_resident", False) and member not in pending:
+ pending.append(member)
+ budget -= int(getattr(member, "_unsloth_resident_bytes", 0))
+ try:
+ rebuild_dropped_host_copies(pending)
+ except Exception as exc: # noqa: BLE001 - a group still without a host copy stays resident below
+ if logger is not None:
+ logger.warning(
+ "diffusion.memory: copying resident groups back to the host failed (%s)", exc
+ )
for module in modules:
for group in reversed(_offload_groups(module) or []):
if left <= 0:
break
if not getattr(group, "_unsloth_resident", False):
continue
+ if any(
+ getattr(m, _HOST_DROPPED_ATTR, None)
+ for m in [group, *(getattr(group, "_unsloth_tied_groups", None) or [])]
+ ):
+ continue # no host copy to stream from: it stays resident, later groups may still free room
# Before demoting: a release that fails part way must still wait on the copy stream.
state = getattr(module, "_unsloth_stream_state", None)
if isinstance(state, dict):
@@ -7162,6 +7189,150 @@ def finish_encoder_pins_at_load(pipe: Any, logger: Any = None) -> float:
return waited
+# "0": an image load pins (and keeps) the host copy of every text-encoder offload group, resident ones too.
+RESIDENT_HOST_DROP_ENV = "UNSLOTH_DIFFUSION_DROP_RESIDENT_HOST_COPY"
+_HOST_DROPPED_ATTR = "_unsloth_host_dropped"
+
+
+def _resident_host_drop_enabled() -> bool:
+ return not _env_off(RESIDENT_HOST_DROP_ENV)
+
+
+def drop_resident_host_copies(
+ groups: list,
+ logger: Any = None,
+ label: str = "",
+) -> tuple[list, int]:
+ """Free the pageable host copy of each resident group (its weights live on the card); returns ``(kept, bytes)``:
+ the groups that still need a pin, and the bytes freed. A group whose eviction ever streams it again gets an exact
+ copy back from the card first (``rebuild_dropped_host_copy``). Tied partners drop together or not at all."""
+ import torch
+
+ def droppable(group: Any) -> bool:
+ if not getattr(group, "_unsloth_resident", False) or getattr(
+ group, "offload_to_disk_path", None
+ ):
+ return False
+ cpu = getattr(group, "cpu_param_dict", None)
+ if not isinstance(cpu, dict) or not cpu:
+ return False
+ for t, src in cpu.items():
+ if (
+ type(src) is not torch.Tensor
+ or src.device.type != "cpu"
+ or src.is_pinned()
+ # the weight itself must be on the card, not reading this host copy
+ or getattr(t, "device", None) is None
+ or t.device.type == "cpu"
+ ):
+ return False
+ return True
+
+ kept: list = []
+ dropped: set = set()
+ freed = 0
+ for group in groups:
+ if id(group) in dropped:
+ continue
+ closure = [group, *(getattr(group, "_unsloth_tied_groups", None) or [])]
+ if not all(droppable(g) for g in closure):
+ kept.append(group)
+ continue
+ seen: set = set()
+ for member in closure:
+ cpu = member.cpu_param_dict
+ for src in cpu.values():
+ key = (src.data_ptr(), src.nbytes)
+ if key not in seen:
+ seen.add(key)
+ freed += int(src.nbytes)
+ setattr(member, _HOST_DROPPED_ATTR, list(cpu.keys()))
+ cpu.clear()
+ dropped.add(id(member))
+ if freed and logger is not None:
+ try:
+ logger.info(
+ "diffusion.memory: %s keeps no host copy of its %d resident offload groups (%.1f GiB not pinned); "
+ "an eviction copies them back from the card",
+ label,
+ len(dropped),
+ freed / 2**30,
+ )
+ except Exception: # noqa: BLE001
+ pass
+ return kept, freed
+
+
+def rebuild_dropped_host_copy(group: Any) -> int:
+ """Give ``group`` (and its tied partners) host copies of their device weights again; returns bytes copied."""
+ return rebuild_dropped_host_copies([group])
+
+
+_REBUILD_ALIGN = 512
+
+
+def rebuild_dropped_host_copies(groups: Iterable[Any]) -> int:
+ """Host copies of the device weights of every dropped group in ``groups`` (tied partners included), in one
+ registered slab filled by device-to-host copies; returns bytes copied. Each tensor shared by tied partners is
+ copied once. Without a registered slab (refused, or no CUDA) each tensor gets its own pageable copy."""
+ import torch
+
+ members: list = []
+ seen_groups: set = set()
+ for group in groups:
+ for member in [group, *(getattr(group, "_unsloth_tied_groups", None) or [])]:
+ if id(member) not in seen_groups and getattr(member, _HOST_DROPPED_ATTR, None):
+ seen_groups.add(id(member))
+ members.append(member)
+ if not members:
+ return 0
+ tensors: dict = {}
+ for member in members:
+ for t in getattr(member, _HOST_DROPPED_ATTR, None) or ():
+ tensors.setdefault(id(t), t)
+ lives = {key: (t.data if hasattr(t, "data") else t) for key, t in tensors.items()}
+ offsets: dict = {}
+ total = 0
+ for key, live in lives.items():
+ offsets[key] = total
+ total += -(-int(live.nbytes) // _REBUILD_ALIGN) * _REBUILD_ALIGN
+ device = next((live.device for live in lives.values() if live.device.type == "cuda"), None)
+ slab = None
+ # Pinned only where pinning is allowed now and the copy fits what host RAM can pin now; else pageable copies
+ # (the group streams slower, the release itself never waits on a pin).
+ budget = None if device is None or _pinned_memory_capped() else _pin_budget_mib()
+ if (
+ device is not None
+ and host_pinning_allowed(device)
+ and budget is not None
+ and (total >> 20) <= budget
+ ):
+ try:
+ slab = registered_pinned_empty(total)
+ except Exception: # noqa: BLE001 - per-tensor pageable copies below
+ slab = None
+ hosts: dict = {}
+ with torch.no_grad():
+ if device is not None:
+ torch.cuda.current_stream(device).synchronize()
+ for key, live in lives.items():
+ if slab is not None:
+ off = offsets[key]
+ host = slab[off : off + int(live.nbytes)].view(live.dtype).view(live.shape)
+ host.copy_(live, non_blocking = True)
+ else:
+ host = live.detach().to("cpu", copy = True)
+ hosts[key] = host
+ if slab is not None:
+ torch.cuda.current_stream(device).synchronize()
+ for member in members:
+ cpu = member.cpu_param_dict
+ for t in getattr(member, _HOST_DROPPED_ATTR, None) or ():
+ cpu[t] = hosts[id(t)]
+ setattr(member, _HOST_DROPPED_ATTR, None)
+ return sum(int(live.nbytes) for live in lives.values())
+
+
def _encoder_background_pin_wanted(pipe: Any, device: Any = None) -> bool:
# Needs the registered pin: per-tensor pin_memory() rounds to a power of two, past the weight-byte budget.
return (
@@ -7540,6 +7711,8 @@ class _GroupPinner:
self._lock = threading.Lock()
self.after: list = []
self.late = False
+ # image-load text encoders: groups resident when the pin starts drop their host copy instead of pinning it
+ self.lazy_resident = False
self._thread = threading.Thread(target = self._entry, name = "unsloth-offload-pin", daemon = True)
self._started = False
for group in groups:
@@ -7675,6 +7848,14 @@ class _GroupPinner:
failed = None
pool = None
try:
+ if self.lazy_resident and _resident_host_drop_enabled():
+ # Resident groups are read from the card; pinning their host copy only cost RAM and load time.
+ kept, _freed = drop_resident_host_copies(self.groups, self.logger, self.label)
+ kept_ids = {id(g) for g in kept}
+ for group in self.groups:
+ if id(group) not in kept_ids:
+ self._done[id(group)].set()
+ self.groups = kept
if callable(self.byte_cap):
self.byte_cap = max(0, int(self.byte_cap()))
if self.logger is not None:
@@ -7884,6 +8065,7 @@ def _defer_pinning(
*,
fast: Optional[bool] = None,
byte_cap: Optional[int] = None,
+ lazy_resident: bool = False,
) -> bool:
groups = _offload_groups(module)
if not groups:
@@ -7892,6 +8074,7 @@ def _defer_pinning(
fast = bool(getattr(pipe, _FAST_PIN_REQUEST_ATTR, False))
fast = bool(fast) and _fast_pin_supported(device)
pinner = _GroupPinner(module, groups, device, logger, fast = fast, byte_cap = byte_cap)
+ pinner.lazy_resident = bool(lazy_resident)
pending = getattr(pipe, _PENDING_PINS_ATTR, None)
if pending is None:
pending = []
@@ -8443,7 +8626,9 @@ def _apply_group_offload(
elif _encoder_defers(module) and (whole or encoder_left_mib > 0):
apply_group_offloading(module, **{**ekwargs, "low_cpu_mem_usage": True})
cap = None if whole else int(encoder_left_mib) << 20
- _defer_pinning(pipe, module, onload, logger, fast = True, byte_cap = cap)
+ _defer_pinning(
+ pipe, module, onload, logger, fast = True, byte_cap = cap, lazy_resident = True
+ )
if not whole:
encoder_left_mib = max(0, encoder_left_mib - _module_registered_mib(module))
else:
diff --git a/studio/backend/tests/test_diffusion_measured_placement.py b/studio/backend/tests/test_diffusion_measured_placement.py
index c92dd9ab517..bf03b4c9acb 100644
--- a/studio/backend/tests/test_diffusion_measured_placement.py
+++ b/studio/backend/tests/test_diffusion_measured_placement.py
@@ -235,6 +235,19 @@ def test_never_moves_away_from_residency(q21_pipe):
assert _refine(q21_pipe, model) is model
[email protected]("budget", list(range(3000, 30001, 250)))
+def test_a_held_text_encoder_never_streams_the_transformer(q21_pipe, budget):
+ """Encoder residency shrinks first: while any part of the 8.7 GiB encoder stays resident, the whole transformer
+ does too (it runs every step; the encoder once per prompt)."""
+ total = max(8188, budget + 3000)
+ new = _refine(q21_pipe, _flat_plan(budget, total))
+ te_resident = (
+ not new.stream_text_encoders and new.offload_policy != dm.OFFLOAD_STREAMING
+ ) or int(new.resident_text_encoder_mib or 0) > 0
+ dit_whole = not new.stream_transformer or int(new.resident_transformer_mib or 0) >= 6922
+ assert dit_whole or not te_resident, (budget, new.offload_policy, new.resident_transformer_mib)
+
+
@pytest.mark.parametrize("budget", list(range(3000, 30001, 250)))
def test_every_tier_fits_measured_need(q21_pipe, budget):
"""Whatever the refinement picks, the bytes it keeps on the device plus the measured peak x margin plus the base
diff --git a/studio/backend/tests/test_diffusion_resident_encoder_host_copy.py b/studio/backend/tests/test_diffusion_resident_encoder_host_copy.py
new file mode 100644
index 00000000000..5ea62c0c854
--- /dev/null
+++ b/studio/backend/tests/test_diffusion_resident_encoder_host_copy.py
@@ -0,0 +1,243 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Image load: resident text-encoder groups drop their host copy (saved 8.7 GiB pinned RAM on Qwen-Image-2.1);
+an eviction copies it back from the card."""
+
+from __future__ import annotations
+
+import pathlib
+import types
+
+import pytest
+
+torch = pytest.importorskip("torch")
+
+import core.inference.diffusion_memory as dm
+
+_BACKEND = pathlib.Path(__file__).resolve().parents[1]
+
+
+def test_this_tree_is_imported():
+ assert pathlib.Path(dm.__file__).resolve().is_relative_to(_BACKEND)
+
+
+class _Group:
+ def __init__(
+ self,
+ params,
+ resident,
+ card = "meta",
+ ):
+ self.cpu_param_dict = {}
+ self.offloaded = 0
+ for p in params:
+ host = p.data
+ if resident and card != "cpu":
+ p = torch.nn.Parameter(torch.empty_like(host, device = card), requires_grad = False)
+ self.cpu_param_dict[p] = host
+ self.modules = []
+ self.parameters = list(params)
+ self.buffers = []
+ self._unsloth_resident = resident
+ if resident:
+ self._unsloth_streamed_hooks = (None, None)
+
+ def offload_(self):
+ self.offloaded += 1
+ for p, host in self.cpu_param_dict.items():
+ p.data = host
+
+
+def _param(*values):
+ return torch.nn.Parameter(torch.tensor(values, dtype = torch.float32), requires_grad = False)
+
+
+def pinner(monkeypatch):
+ monkeypatch.delenv(dm.RESIDENT_HOST_DROP_ENV, raising = False)
+ pinned = []
+
+ def pin_memory(self):
+ pinned.append(self)
+ return self.clone()
+
+ monkeypatch.setattr(torch.Tensor, "pin_memory", pin_memory)
+ monkeypatch.setattr(dm, "_bump_placement_epoch", lambda: None)
+ monkeypatch.setattr(dm, "_fast_pin_supported", lambda *_a, **_k: False)
+
+ def run(groups, lazy = True):
+ module = torch.nn.Linear(1, 1)
+ monkeypatch.setattr(dm, "_offload_groups", lambda m: list(groups))
+ pipe = types.SimpleNamespace()
+ assert dm._defer_pinning(
+ pipe, module, torch.device("cpu"), None, fast = False, lazy_resident = lazy
+ )
+ assert dm.start_background_pins(pipe) == 1
+ dm.finish_background_pins(pipe)
+ return pinned
+
+ return run
+
+
+def test_resident_groups_drop_their_host_copy_and_streamed_ones_still_pin(pinner):
+ resident = _Group([_param(1.0, 2.0)], resident = True)
+ streamed = _Group([_param(3.0)], resident = False)
+ pinned = pinner([resident, streamed])
+ assert resident.cpu_param_dict == {}
+ assert getattr(resident, dm._HOST_DROPPED_ATTR)
+ assert len(pinned) == 1 and pinned[0].tolist() == [3.0]
+ assert next(iter(streamed.cpu_param_dict.values())).tolist() == [3.0]
+
+
+def test_the_kill_switch_pins_resident_groups_too(pinner, monkeypatch):
+ monkeypatch.setenv(dm.RESIDENT_HOST_DROP_ENV, "0")
+ resident = _Group([_param(1.0, 2.0)], resident = True)
+ streamed = _Group([_param(3.0)], resident = False)
+ pinned = pinner([resident, streamed])
+ assert len(pinned) == 2
+ assert len(resident.cpu_param_dict) == 1
+
+
+def test_only_image_encoder_pinners_drop(pinner):
+ resident = _Group([_param(1.0, 2.0)], resident = True)
+ pinned = pinner([resident], lazy = False)
+ assert len(pinned) == 1 and len(resident.cpu_param_dict) == 1
+
+
+def test_a_pinned_or_host_reading_group_keeps_its_copy():
+ on_host = _Group([_param(1.0)], resident = True, card = "cpu")
+ kept, freed = dm.drop_resident_host_copies([on_host])
+ assert kept == [on_host] and freed == 0 and len(on_host.cpu_param_dict) == 1
+
+
+def test_tied_partners_drop_together_or_not_at_all():
+ host = torch.tensor([5.0, 6.0])
+ shared = torch.nn.Parameter(torch.empty_like(host, device = "meta"), requires_grad = False)
+ a = _Group([], resident = True)
+ b = _Group([], resident = False)
+ a.cpu_param_dict[shared] = host
+ b.cpu_param_dict[shared] = host
+ a._unsloth_tied_groups, b._unsloth_tied_groups = [b], [a]
+ kept, freed = dm.drop_resident_host_copies([a, b])
+ assert kept == [a, b] and freed == 0
+ b._unsloth_resident = True
+ kept, freed = dm.drop_resident_host_copies([a, b])
+ assert kept == [] and freed == host.nbytes
+
+
+def test_an_eviction_copies_the_device_weights_back_before_streaming(monkeypatch):
+ monkeypatch.setattr(dm, "_bump_placement_epoch", lambda: None)
+ p = _param(7.0, 8.0)
+ group = _Group([p], resident = True, card = "cpu")
+ p.data.copy_(torch.tensor([7.0, 8.0]))
+ group.cpu_param_dict.clear()
+ setattr(group, dm._HOST_DROPPED_ATTR, [p])
+ live = p.data
+ dm._release_group(group)
+ assert group.offloaded == 1 and group._unsloth_resident is False
+ host = group.cpu_param_dict[p]
+ assert host.tolist() == [7.0, 8.0] and host.data_ptr() != live.data_ptr()
+ assert p.data.data_ptr() == host.data_ptr()
+ assert not getattr(group, dm._HOST_DROPPED_ATTR)
+
+
+def test_tied_partners_rebuild_one_shared_copy():
+ shared = _param(1.0, 2.0)
+ a = _Group([], resident = True)
+ b = _Group([], resident = True)
+ a._unsloth_tied_groups, b._unsloth_tied_groups = [b], [a]
+ setattr(a, dm._HOST_DROPPED_ATTR, [shared])
+ setattr(b, dm._HOST_DROPPED_ATTR, [shared])
+ copied = dm.rebuild_dropped_host_copy(a)
+ assert copied == shared.data.nbytes
+ assert a.cpu_param_dict[shared] is b.cpu_param_dict[shared]
+ assert dm.rebuild_dropped_host_copy(b) == 0
+
+
[email protected]("pin_budget", [None, 0])
+def test_cuda_dropped_encoder_streams_bit_identical_after_an_eviction(monkeypatch, pin_budget):
+ """Real diffusers leaf-level group offload on CUDA: the deferred encoder pin drops every resident group's host
+ copy, an oversized release copies them back in one registered slab, the streamed forward and the restored one
+ match the reference bit for bit."""
+ if not torch.cuda.is_available():
+ pytest.skip("CUDA-only: diffusers group offloading with a copy stream")
+ pytest.importorskip("diffusers.hooks")
+ from diffusers.hooks import apply_group_offloading
+
+ monkeypatch.delenv(dm.RESIDENT_HOST_DROP_ENV, raising = False)
+ monkeypatch.delenv("UNSLOTH_DIFFUSION_PARTIAL_RESIDENT", raising = False)
+ if pin_budget is not None:
+ # host RAM cannot pin the copy-back now: pageable copies, same values
+ monkeypatch.setattr(dm, "_pin_budget_mib", lambda: pin_budget)
+ torch.manual_seed(0)
+ net = torch.nn.Sequential(*(torch.nn.Linear(256, 256) for _ in range(6)))
+ x = torch.randn(4, 256)
+ ref = net.to("cuda")(x.cuda()).cpu()
+ net.to("cpu")
+ apply_group_offloading(
+ net,
+ onload_device = torch.device("cuda"),
+ offload_device = torch.device("cpu"),
+ offload_type = "leaf_level",
+ use_stream = True,
+ record_stream = True,
+ non_blocking = True,
+ low_cpu_mem_usage = True,
+ )
+ pipe = types.SimpleNamespace(components = {"text_encoder": net})
+ assert dm._defer_pinning(pipe, net, torch.device("cuda"), None, fast = False, lazy_resident = True)
+ assert dm._keep_groups_resident(net, 1024, "cuda") > 0
+ dm.start_background_pins(pipe)
+ dm.finish_background_pins(pipe)
+ groups = dm._offload_groups(net)
+ dropped = [g for g in groups if getattr(g, dm._HOST_DROPPED_ATTR, None)]
+ assert dropped and all(not g.cpu_param_dict for g in dropped)
+ assert torch.equal(net(x.cuda()).cpu(), ref)
+
+ restore = dm.release_resident_groups(pipe, 1024)
+ assert restore is not None
+ assert not any(getattr(g, dm._HOST_DROPPED_ATTR, None) for g in groups)
+ assert all(next(m.parameters()).device.type == "cpu" for m in net)
+ hosts = [h for g in groups for h in g.cpu_param_dict.values()]
+ assert all(h.is_pinned() for h in hosts) == (pin_budget is None)
+ for _ in range(2):
+ assert torch.equal(net(x.cuda()).cpu(), ref)
+ restore()
+ assert all(next(m.parameters()).device.type == "cuda" for m in net)
+ assert torch.equal(net(x.cuda()).cpu(), ref)
+ again = dm.release_resident_groups(pipe, 1024)
+ assert [h.data_ptr() for g in groups for h in g.cpu_param_dict.values()] == [
+ h.data_ptr() for h in hosts
+ ]
+ assert torch.equal(net(x.cuda()).cpu(), ref)
+ again()
+ assert torch.equal(net(x.cuda()).cpu(), ref)
+
+
+def test_a_group_whose_copy_back_fails_stays_resident_and_the_release_goes_on(monkeypatch):
+ monkeypatch.setattr(dm, "_bump_placement_epoch", lambda: None)
+
+ def refuse(groups):
+ raise MemoryError("host RAM")
+
+ monkeypatch.setattr(dm, "rebuild_dropped_host_copies", refuse)
+ monkeypatch.setattr(
+ dm,
+ "rebuild_dropped_host_copy",
+ lambda g: refuse([g]) if getattr(g, dm._HOST_DROPPED_ATTR, None) else 0,
+ )
+ dropped = _Group([_param(1.0)], resident = True, card = "cpu")
+ dropped.cpu_param_dict.clear()
+ setattr(dropped, dm._HOST_DROPPED_ATTR, list(dropped.parameters))
+ dropped._unsloth_resident_bytes = 4 << 20
+ kept = _Group([_param(2.0)], resident = True, card = "cpu")
+ kept._unsloth_resident_bytes = 4 << 20
+ module = types.SimpleNamespace(_unsloth_resident_room = 8, _unsloth_resident_device = None)
+ monkeypatch.setattr(dm, "_offload_groups", lambda m: [kept, dropped])
+ monkeypatch.setattr(dm, "_is_text_encoder_module", lambda pipe, m: True)
+ pipe = types.SimpleNamespace(components = {"text_encoder": module})
+ restore = dm.release_resident_groups(pipe, 8)
+ assert restore is not None
+ assert dropped._unsloth_resident is True and dropped.offloaded == 0
+ assert kept._unsloth_resident is False and kept.offloaded == 1