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: pin streamed image text encoders with the background pinner, and the prefix that fits (#15206)

Daniel Han43798e2730e9
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.py
index 62e6045777d..d3023f7b823 100644
--- a/studio/backend/core/inference/diffusion.py
+++ b/studio/backend/core/inference/diffusion.py
@@ -218,6 +218,10 @@ from .diffusion_memory import (
reclaim_host_memory,
reclaim_offload_host_memory,
release_pinned_host_memory,
+ request_background_encoder_pins,
+ finish_encoder_pins_at_load,
+ start_background_pins,
+ stop_background_pins,
refine_balanced_plan_for_components,
refine_memory_plan_for_components,
refine_plan_from_loaded_weights,
@@ -10767,6 +10771,8 @@ class DiffusionBackend:
# a refinement may have re-tiered the plan; routed encoders need group offload
plan = self._small_host_plan(pipe, plan, fam, logger)
plan = refine_plan_for_multigpu(pipe, plan, logger)
+ # streamed text encoders pin after the load returns, before or during the first encode
+ request_background_encoder_pins(pipe)
effective_policy, effective_tiling = apply_memory_plan(
pipe,
plan,
@@ -10777,6 +10783,7 @@ class DiffusionBackend:
placement_device = target.torch_device,
logger = logger,
)
+ start_background_pins(pipe)
# a transient OOM during setup may have re-planned to lower residency
plan = applied_plan(pipe, plan)
_drop_measured_reserve_for_layer_split(pipe, plan)
@@ -11085,6 +11092,8 @@ class DiffusionBackend:
self._stop_load_prefetch()
# Pre-commit failure: roll back the process-wide mutations (symmetric with _unload_locked).
if not state_committed:
+ # Never published, so _unload_locked cannot reach them: the pinners would keep the encoders.
+ stop_background_pins(pipe)
# First: its gate sits in front of the CUDA-graph layer uninstalled by identity below.
if load_bg_compile is not None:
load_bg_compile.close()
@@ -11122,6 +11131,7 @@ class DiffusionBackend:
"; ".join(plan.reasons),
plan.estimates,
)
+ finish_encoder_pins_at_load(getattr(state, "pipe", None), logger)
return self.status()
@staticmethod
@@ -14958,6 +14968,8 @@ class DiffusionBackend:
state = self._state
if state is None:
return
+ # A pinner still copying would hold its host copies past release_pinned_host_memory().
+ stop_background_pins(getattr(state, "pipe", None))
# An in-flight background compile still runs the denoiser the teardown below frees.
if state.bg_compile is not None:
try:
diff --git a/studio/backend/core/inference/diffusion_memory.py b/studio/backend/core/inference/diffusion_memory.py
index e481c58bbf7..0bc68d08773 100644
--- a/studio/backend/core/inference/diffusion_memory.py
+++ b/studio/backend/core/inference/diffusion_memory.py
@@ -5985,6 +5985,27 @@ def _module_host_mib(module: Any) -> int:
return 0
+_HOST_PAGE = 4096
+
+
+def _page_bytes(nbytes: int) -> int:
+ return -(-int(nbytes) // _HOST_PAGE) * _HOST_PAGE
+
+
+def _module_registered_mib(module: Any) -> int:
+ """Pinned host MiB of ``module`` in registered host memory (``registered_host_copy``): each tensor page-rounded."""
+ try:
+ total = sum(
+ _page_bytes(nbytes)
+ for tensor in _unique_tensors(module)
+ for nbytes in _storage_nbytes(tensor)
+ if nbytes > 0
+ )
+ return -(-total // (1024 * 1024))
+ except Exception: # noqa: BLE001 - priced as the per-tensor pin
+ return _module_host_mib(module)
+
+
def _unique_tensors(module: Any) -> list:
seen: set[int] = set()
out = []
@@ -6188,6 +6209,57 @@ def _background_pin_enabled() -> bool:
) and host_pinning_allowed()
+# "0": image-load streamed encoders pin into slabs up front instead of on a background worker.
+ENCODER_BACKGROUND_PIN_ENV = "UNSLOTH_DIFFUSION_ENCODER_BACKGROUND_PIN"
+# "0": an encoder that does not fit the pin budget whole pins nothing instead of a fitting prefix.
+PARTIAL_ENCODER_PIN_ENV = "UNSLOTH_DIFFUSION_PARTIAL_ENCODER_PIN"
+_ENCODER_PIN_REQUEST_ATTR = "_unsloth_background_encoder_pin_requested"
+_PARTIAL_PIN_MIN_MIB = 256
+
+
+def request_background_encoder_pins(pipe: Any) -> None:
+ """Mark ``pipe`` so the next group offload defers its streamed encoder pins; denoisers still pin up front."""
+ try:
+ setattr(pipe, _ENCODER_PIN_REQUEST_ATTR, True)
+ except Exception: # noqa: BLE001 - a pipe refusing attributes pins eagerly, as before
+ pass
+
+
+def finish_encoder_pins_at_load(pipe: Any, logger: Any = None) -> float:
+ """Wait for the encoder pins; left running into the first prompt they cost what they saved (FLUX.1 B200)."""
+ if pipe is None:
+ return 0.0
+ start_background_pins(pipe)
+ waited = finish_background_pins(pipe)
+ if waited >= 0.5 and logger is not None:
+ logger.info("diffusion.memory: the load waited %.1f s for the encoder pins", waited)
+ return waited
+
+
+def _encoder_background_pin_wanted(pipe: Any) -> bool:
+ # Needs the registered pin: per-tensor pin_memory() rounds to a power of two, past the weight-byte budget.
+ return (
+ bool(getattr(pipe, _ENCODER_PIN_REQUEST_ATTR, False))
+ and not _env_off(ENCODER_BACKGROUND_PIN_ENV)
+ and _background_pin_enabled()
+ and _fast_pin_supported()
+ )
+
+
+def _streamed_pin_leftover_mib(transformer_mib: int, pin_transformer: bool) -> int:
+ """Pin budget MiB left after the transformer; 0 wherever ``_streamed_pin_plan`` would not pin by budget."""
+ if _env_off(PARTIAL_ENCODER_PIN_ENV) or not host_pinning_allowed():
+ return 0
+ forced = str(os.environ.get(GROUP_OFFLOAD_PIN_ENV, "")).strip().lower()
+ if forced in ("0", "off", "false", "no", "1", "on", "true", "yes") or _pinned_memory_capped():
+ return 0
+ budget = _pin_budget_mib()
+ if budget is None:
+ return 0
+ left = int(budget) - (int(transformer_mib) if pin_transformer else 0)
+ return left if left >= _PARTIAL_PIN_MIN_MIB else 0
+
+
_DENOISER_NAMES = ("transformer", "transformer_2", "unconditional_transformer", "unet")
@@ -6368,10 +6440,13 @@ class _GroupPinner:
device: Any,
logger: Any = None,
fast: bool = False,
+ byte_cap: Optional[int] = None,
):
import threading
self.fast = bool(fast)
+ # Pin whole groups in order while they fit; the rest stay pageable (diffusers pins them per onload).
+ self.byte_cap = None if byte_cap is None else max(0, int(byte_cap))
self.module = module
self.label = type(module).__name__
self.groups = groups
@@ -6443,6 +6518,19 @@ class _GroupPinner:
except Exception: # noqa: BLE001 - registration refused: the allocator's pin for this tensor
return src.pin_memory()
+ def _capped_groups(self) -> list:
+ if self.byte_cap is None:
+ return list(self.groups)
+ left = self.byte_cap
+ out: list = []
+ for group in self.groups:
+ need = sum(_page_bytes(src.nbytes) for _t, src in self._unpinned(group))
+ if need > left:
+ break
+ left -= need
+ out.append(group)
+ return out
+
def _run(self) -> None:
import time
@@ -6452,6 +6540,14 @@ class _GroupPinner:
failed = None
pool = None
try:
+ if self.byte_cap is not None:
+ kept = self._capped_groups()
+ kept_ids = {id(g) for g in kept}
+ # A group past the cap never pins here: its onload must not wait for the prefix.
+ for group in self.groups:
+ if id(group) not in kept_ids:
+ self._done[id(group)].set()
+ self.groups = kept
if (
getattr(self.device, "type", None) == "cuda"
and getattr(self.device, "index", None) is not None
@@ -6597,12 +6693,22 @@ def _drop_deferred_pinning(pipe: Any, module: Any) -> None:
pending[:] = [pinner for pinner in pending if pinner.module is not module]
-def _defer_pinning(pipe: Any, module: Any, device: Any, logger: Any) -> bool:
+def _defer_pinning(
+ pipe: Any,
+ module: Any,
+ device: Any,
+ logger: Any,
+ *,
+ fast: Optional[bool] = None,
+ byte_cap: Optional[int] = None,
+) -> bool:
groups = _offload_groups(module)
if not groups:
return False
- fast = bool(getattr(pipe, _FAST_PIN_REQUEST_ATTR, False)) and _fast_pin_supported()
- pinner = _GroupPinner(module, groups, device, logger, fast = fast)
+ if fast is None:
+ fast = bool(getattr(pipe, _FAST_PIN_REQUEST_ATTR, False))
+ fast = bool(fast) and _fast_pin_supported()
+ pinner = _GroupPinner(module, groups, device, logger, fast = fast, byte_cap = byte_cap)
pending = getattr(pipe, _PENDING_PINS_ATTR, None)
if pending is None:
pending = []
@@ -7007,22 +7113,48 @@ def _apply_group_offload(
)
# an up-front pin packs into slabs (_apply_group_offloading_packed); a deferred one pins per tensor
pin_mib = _module_host_mib if defer else _module_pin_mib
+ # Image loads: only the streamed encoders defer (registered pins, priced at weight bytes); torchao ones cannot.
+ encoders_defer = (
+ not defer
+ and stream_text_encoders
+ and use_stream
+ and "low_cpu_mem_usage" in _params
+ and _encoder_background_pin_wanted(pipe)
+ )
+
+ def _encoder_defers(module: Any) -> bool:
+ return encoders_defer and not _torchao_weight_classes(module)
+
+ def enc_pin_mib(module: Any) -> int:
+ return _module_registered_mib(module) if _encoder_defers(module) else pin_mib(module)
+
pin_streamed = (True, True)
+ dit_pin_mib = 0
if stream_text_encoders and "low_cpu_mem_usage" in _params:
# The streamed path PINS every offloaded parameter in host RAM when a copy stream is in use (diffusers
# group_offloading `_init_cpu_param_dict`), which is a fine trade when group offload was already the plan.
# Pin only what host RAM covers (unbounded pinning hurt #8188); unpinned re-pins on every onload.
+ dit_pin_mib = sum(pin_mib(m) for m in streamed.values())
pin_streamed = _streamed_pin_plan(
- sum(pin_mib(m) for m in streamed.values()),
- sum(pin_mib(m) for m in streamed_encoders.values()),
+ dit_pin_mib,
+ sum(enc_pin_mib(m) for m in streamed_encoders.values()),
logger,
)
gkwargs["low_cpu_mem_usage"] = not pin_streamed[0]
- if getattr(pipe, "_unsloth_small_host", None) and "low_cpu_mem_usage" in _params:
+ small_host = bool(getattr(pipe, "_unsloth_small_host", None))
+ if small_host and "low_cpu_mem_usage" in _params:
# pinning would copy the small-host route's memory-mapped bytes back into host RAM
pin_streamed = (False, False)
gkwargs["low_cpu_mem_usage"] = True
- if defer:
+ encoder_cap_mib = 0
+ if encoders_defer and stream_text_encoders and not pin_streamed[1] and not small_host:
+ encoder_cap_mib = _streamed_pin_leftover_mib(dit_pin_mib, pin_streamed[0])
+ if encoder_cap_mib and logger is not None:
+ logger.info(
+ "diffusion.memory: streamed encoders pin a %d MiB prefix of their offload groups in the background",
+ encoder_cap_mib,
+ )
+ if defer or encoders_defer:
install_group_pin_wait()
# Place the smaller components resident BEFORE attaching the transformer group-offload hooks: a companion .to()
# OOM then returns False with no hooks installed, and diffusers rejects enable_model_cpu_offload once group
@@ -7034,9 +7166,9 @@ def _apply_group_offload(
comp.to(onload)
# Encoders the plan pins count against the same budget as any torchao denoiser pinned below.
pinned_mib = [
- sum(pin_mib(m) for m in streamed_encoders.values())
+ sum(enc_pin_mib(m) for m in streamed_encoders.values())
if stream_text_encoders and pin_streamed[1]
- else 0
+ else encoder_cap_mib
]
for module in streamed.values():
# torchao weights need their up-front pin (lazy pinning refuses them), so they never defer.
@@ -7080,11 +7212,19 @@ def _apply_group_offload(
ekwargs["low_cpu_mem_usage"] = not pin_streamed[1]
transformer_demoted = False
te_room = int(resident_text_encoder_mib or 0)
+ encoder_left_mib = encoder_cap_mib
for name, module in streamed_encoders.items():
try:
- if defer and not ekwargs.get("low_cpu_mem_usage", False):
+ whole = not ekwargs.get("low_cpu_mem_usage", False)
+ if defer and whole:
apply_group_offloading(module, **{**ekwargs, "low_cpu_mem_usage": True})
_defer_pinning(pipe, module, onload, logger)
+ 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)
+ if not whole:
+ encoder_left_mib = max(0, encoder_left_mib - _module_registered_mib(module))
else:
_apply_group_offloading_packed(apply_group_offloading, module, ekwargs, logger)
installed += 1
@@ -7781,19 +7921,45 @@ def _apply_streaming_offload(
)
# an up-front pin packs into slabs (_apply_group_offloading_packed); a deferred one pins per tensor
pin_mib = _module_host_mib if defer else _module_pin_mib
+ encoders_defer = not defer and prefetch and _encoder_background_pin_wanted(pipe)
+
+ def _encoder_defers(name: Any, module: Any, offload_type: str) -> bool:
+ return (
+ encoders_defer
+ and offload_type != "block_level"
+ and str(name).startswith("text_encoder")
+ and not _torchao_weight_classes(module)
+ )
+
+ def leaf_pin_mib(name: Any, module: Any, offload_type: str) -> int:
+ if _encoder_defers(name, module, offload_type):
+ return _module_registered_mib(module)
+ return pin_mib(module)
+
+ dit_pin_mib = sum(pin_mib(m) for m, t in streamed.values() if t == "block_level")
+ leaf_mib = 0
if prefetch:
- pin_dits, pin_encoders = _streamed_pin_plan(
- sum(pin_mib(m) for m, t in streamed.values() if t == "block_level"),
- sum(pin_mib(m) for m, t in streamed.values() if t != "block_level"),
- logger,
+ leaf_mib = sum(
+ leaf_pin_mib(n, m, t) for n, (m, t) in streamed.items() if t != "block_level"
)
- if defer:
+ pin_dits, pin_encoders = _streamed_pin_plan(dit_pin_mib, leaf_mib, logger)
+ encoder_left_mib = 0
+ if encoders_defer and not pin_encoders:
+ encoder_left_mib = _streamed_pin_leftover_mib(dit_pin_mib, pin_dits)
+ if encoder_left_mib and logger is not None:
+ logger.info(
+ "diffusion.memory: streamed encoders pin a %d MiB prefix of their offload groups in the background",
+ encoder_left_mib,
+ )
+ if defer or encoders_defer:
install_group_pin_wait()
# pinned encoders count against the budget a torchao denoiser pins within, as on the group tier
if pin_encoders:
- pinned_mib[0] = sum(pin_mib(m) for m, t in streamed.values() if t != "block_level")
+ pinned_mib[0] = leaf_mib
+ else:
+ pinned_mib[0] = encoder_left_mib
- for module, offload_type in streamed.values():
+ for comp_name, (module, offload_type) in streamed.items():
kwargs: dict[str, Any] = {
"onload_device": onload,
"offload_device": offload,
@@ -7808,12 +7974,20 @@ def _apply_streaming_offload(
if use_stream and "record_stream" in params:
kwargs["record_stream"] = prefetch
pin = pin_dits if offload_type == "block_level" else pin_encoders
+ enc_defer = _encoder_defers(comp_name, module, offload_type) and (
+ pin or encoder_left_mib > 0
+ )
if use_stream and "low_cpu_mem_usage" in params:
- kwargs["low_cpu_mem_usage"] = not (pin and not defer)
+ kwargs["low_cpu_mem_usage"] = not (pin and not defer and not enc_defer)
kwargs = _torchao_group_offload_kwargs(module, kwargs, pinned_mib)
_apply_group_offloading_packed(apply_group_offloading, module, kwargs, logger)
if pin and defer and kwargs.get("use_stream") and kwargs.get("low_cpu_mem_usage"):
_defer_pinning(pipe, module, onload, logger)
+ elif enc_defer and kwargs.get("use_stream") and kwargs.get("low_cpu_mem_usage"):
+ cap = None if pin else int(encoder_left_mib) << 20
+ _defer_pinning(pipe, module, onload, logger, fast = True, byte_cap = cap)
+ if not pin:
+ encoder_left_mib = max(0, encoder_left_mib - _module_registered_mib(module))
installed += 1
if (
use_stream
diff --git a/studio/backend/tests/test_image_encoder_background_pin.py b/studio/backend/tests/test_image_encoder_background_pin.py
new file mode 100644
index 00000000000..2f858cad2a6
--- /dev/null
+++ b/studio/backend/tests/test_image_encoder_background_pin.py
@@ -0,0 +1,313 @@
+# 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 loads pin their streamed text encoders after the load returns, and pin the prefix that fits the budget."""
+
+import ast
+import pathlib
+import threading
+import types
+
+import pytest
+
+torch = pytest.importorskip("torch")
+
+import core.inference.diffusion_memory as dm
+
+_BACKEND = pathlib.Path(__file__).resolve().parents[1]
+_CUDA = torch.cuda.is_available()
+
+
+def budget(monkeypatch):
+ for name in (
+ dm.GROUP_OFFLOAD_PIN_ENV,
+ dm.PARTIAL_ENCODER_PIN_ENV,
+ dm.ENCODER_BACKGROUND_PIN_ENV,
+ ):
+ monkeypatch.delenv(name, raising = False)
+ monkeypatch.setattr(dm, "host_pinning_allowed", lambda *a, **k: True)
+ monkeypatch.setattr(dm, "_pinned_memory_capped", lambda: False)
+
+ def set_budget(mib):
+ monkeypatch.setattr(dm, "_pin_budget_mib", lambda: mib)
+
+ set_budget(4387)
+ return set_budget
+
+
+def test_the_leftover_is_the_budget_after_a_pinned_transformer(budget):
+ # the Kaggle T4 klein loads: nothing pinned at 4387 MiB, the transformer alone at 9868 MiB
+ assert dm._streamed_pin_leftover_mib(7680, False) == 4387
+ budget(9868)
+ assert dm._streamed_pin_leftover_mib(7680, True) == 9868 - 7680
+
+
[email protected]("mib", [None, 0, dm._PARTIAL_PIN_MIN_MIB - 1])
+def test_no_leftover_without_a_useful_budget(budget, mib):
+ budget(mib)
+ assert dm._streamed_pin_leftover_mib(0, False) == 0
+
+
+ "env, value",
+ [
+ (dm.PARTIAL_ENCODER_PIN_ENV, "0"),
+ (dm.GROUP_OFFLOAD_PIN_ENV, "0"),
+ (dm.GROUP_OFFLOAD_PIN_ENV, "1"),
+ ],
+)
+def test_the_kill_switch_and_a_forced_plan_leave_nothing_to_split(budget, monkeypatch, env, value):
+ monkeypatch.setenv(env, value)
+ assert dm._streamed_pin_leftover_mib(0, False) == 0
+
+
+def test_no_leftover_on_an_integrated_gpu_or_capped_pinned_memory(budget, monkeypatch):
+ monkeypatch.setattr(dm, "_pinned_memory_capped", lambda: True)
+ assert dm._streamed_pin_leftover_mib(0, False) == 0
+ monkeypatch.setattr(dm, "_pinned_memory_capped", lambda: False)
+ monkeypatch.setattr(dm, "host_pinning_allowed", lambda *a, **k: False)
+ assert dm._streamed_pin_leftover_mib(0, False) == 0
+
+
+def wanted(monkeypatch):
+ monkeypatch.delenv(dm.ENCODER_BACKGROUND_PIN_ENV, raising = False)
+ monkeypatch.delenv(dm.BACKGROUND_PIN_ENV, raising = False)
+ monkeypatch.setattr(dm, "host_pinning_allowed", lambda *a, **k: True)
+ monkeypatch.setattr(dm, "_fast_pin_supported", lambda: True)
+ pipe = types.SimpleNamespace()
+ dm.request_background_encoder_pins(pipe)
+ return pipe
+
+
+def test_a_requested_pipe_defers_its_encoder_pins(wanted):
+ assert dm._encoder_background_pin_wanted(wanted)
+ assert not dm._encoder_background_pin_wanted(types.SimpleNamespace())
+ video = types.SimpleNamespace()
+ dm.request_background_pins(video)
+ assert not dm._encoder_background_pin_wanted(video)
+
+
[email protected]("env", ["ENCODER_BACKGROUND_PIN_ENV", "BACKGROUND_PIN_ENV"])
+def test_the_kill_switches_restore_the_up_front_pin(wanted, monkeypatch, env):
+ monkeypatch.setenv(getattr(dm, env), "0")
+ assert not dm._encoder_background_pin_wanted(wanted)
+
+
+def test_no_deferral_without_the_registered_pin_or_on_an_integrated_gpu(wanted, monkeypatch):
+ # the allocator's pin_memory() rounds every tensor to a power of two, past the weight-byte budget
+ monkeypatch.setattr(dm, "_fast_pin_supported", lambda: False)
+ assert not dm._encoder_background_pin_wanted(wanted)
+ monkeypatch.setattr(dm, "_fast_pin_supported", lambda: True)
+ monkeypatch.setattr(dm, "host_pinning_allowed", lambda *a, **k: False)
+ assert not dm._encoder_background_pin_wanted(wanted)
+
+
+def test_a_registered_pin_is_priced_at_page_rounded_bytes_not_powers_of_two():
+ module = torch.nn.Linear(1500, 1000, bias = False).to(torch.bfloat16) # 3,000,000 bytes
+ assert dm._module_host_mib(module) == 4 # the allocator's 4 MiB block
+ assert dm._module_registered_mib(module) == 3
+
+
+def test_the_load_starts_and_waits_for_the_encoder_pins(monkeypatch):
+ calls = []
+ monkeypatch.setattr(dm, "start_background_pins", lambda pipe: calls.append("start") or 1)
+ monkeypatch.setattr(dm, "finish_background_pins", lambda pipe: calls.append("finish") or 0.0)
+ dm.finish_encoder_pins_at_load(types.SimpleNamespace())
+ assert calls == ["start", "finish"]
+ assert dm.finish_encoder_pins_at_load(None) == 0.0
+
+
+def _fake_groups(sizes):
+ groups = []
+ for n in sizes:
+ weight = torch.nn.Parameter(torch.zeros(n, dtype = torch.uint8), requires_grad = False)
+ groups.append(types.SimpleNamespace(cpu_param_dict = {weight: weight.data}))
+ return groups
+
+
+def test_a_capped_pinner_pins_the_prefix_that_fits_and_never_blocks_the_rest(monkeypatch):
+ monkeypatch.setattr(torch.Tensor, "is_pinned", lambda self: getattr(self, "_fake_pin", False))
+
+ def pin_memory(self):
+ out = self.clone()
+ out._fake_pin = True
+ return out
+
+ monkeypatch.setattr(torch.Tensor, "pin_memory", pin_memory)
+ # registered copies are page-rounded: 1 + 2 + 1 + 1 pages
+ groups = _fake_groups([100, 5000, 300, 50])
+ sources = [dict(g.cpu_param_dict) for g in groups]
+ pinner = dm._GroupPinner(
+ torch.nn.Module(), groups, torch.device("cpu"), byte_cap = 3 * 4096 + 100
+ )
+ assert [id(g) for g in pinner._capped_groups()] == [id(groups[0]), id(groups[1])]
+ pinner._run()
+ assert pinner.pinned == 5100
+ for group, before in zip(groups, sources):
+ assert pinner._done[id(group)].is_set()
+ for tensor, src in group.cpu_param_dict.items():
+ pinned = getattr(src, "_fake_pin", False)
+ assert pinned is (group in groups[:2])
+ assert tensor.data_ptr() == src.data_ptr()
+ if not pinned:
+ assert src is before[tensor]
+
+
+def test_an_onload_past_the_cap_does_not_wait_for_the_prefix(monkeypatch):
+ groups = _fake_groups([10, 1000])
+ release = threading.Event()
+
+ def slow_pin(self):
+ release.wait(5) # the prefix group is still copying
+ return self.clone()
+
+ monkeypatch.setattr(torch.Tensor, "is_pinned", lambda self: False)
+ monkeypatch.setattr(torch.Tensor, "pin_memory", slow_pin)
+ pinner = dm._GroupPinner(torch.nn.Module(), groups, torch.device("cpu"), byte_cap = 4096)
+ pinner.start()
+ try:
+ assert pinner._done[id(groups[1])].wait(2)
+ assert not pinner._done[id(groups[0])].is_set()
+ finally:
+ release.set()
+ pinner.join(5)
+ assert pinner._done[id(groups[0])].is_set()
+
+
+def _calls(tree, name):
+ return [
+ n
+ for n in ast.walk(tree)
+ if isinstance(n, ast.Call) and getattr(n.func, "id", getattr(n.func, "attr", None)) == name
+ ]
+
+
+def test_the_image_load_requests_starts_and_stops_the_encoder_pins():
+ tree = ast.parse((_BACKEND / "core" / "inference" / "diffusion.py").read_text())
+ request = _calls(tree, "request_background_encoder_pins")
+ apply = _calls(tree, "apply_memory_plan")
+ assert request and apply and min(c.lineno for c in request) < min(c.lineno for c in apply)
+ starts = _calls(tree, "start_background_pins")
+ assert starts and min(c.lineno for c in starts) > min(c.lineno for c in apply)
+ assert _calls(tree, "finish_encoder_pins_at_load")
+ unload = next(
+ n for n in ast.walk(tree) if isinstance(n, ast.FunctionDef) and n.name == "_unload_locked"
+ )
+ stops = _calls(unload, "stop_background_pins")
+ releases = _calls(unload, "release_pinned_host_memory")
+ assert stops and releases and stops[0].lineno < releases[0].lineno
+
+
+class _Pipe:
+ pass
+
+
+def _encoder():
+ torch.manual_seed(0)
+ # 2 MiB of bf16 weight per Linear, one leaf group each
+ return torch.nn.Sequential(*[torch.nn.Linear(1024, 1024) for _ in range(4)]).to(torch.bfloat16)
+
+
+def _tiny_pipe():
+ pipe = _Pipe()
+ pipe.transformer = torch.nn.Linear(1024, 1024).to(torch.bfloat16)
+ pipe.text_encoder = _encoder()
+ pipe.components = {"transformer": pipe.transformer, "text_encoder": pipe.text_encoder}
+ return pipe
+
+
+def _host_copies(module):
+ return [t for g in dm._offload_groups(module) for t in g.cpu_param_dict.values()]
+
+
[email protected](not _CUDA, reason = "needs a CUDA device")
[email protected]("cap_mib", [None, 0])
+def test_a_streamed_encoder_pins_after_the_load_and_encodes_identically(
+ budget, monkeypatch, cap_mib
+):
+ pytest.importorskip("diffusers")
+ monkeypatch.delenv(dm.BACKGROUND_PIN_ENV, raising = False)
+ x = torch.randn(4, 1024, dtype = torch.bfloat16, device = "cuda")
+ with torch.no_grad():
+ ref = _encoder().to("cuda")(x)
+ budget(1 << 20)
+ pipe = _tiny_pipe()
+ dm.request_background_encoder_pins(pipe)
+ if cap_mib == 0:
+ # whole pin refused, 5 MiB left: the first two 2 MiB groups fit, the third does not
+ monkeypatch.setattr(dm, "_streamed_pin_plan", lambda *a, **k: (True, False))
+ monkeypatch.setattr(dm, "_streamed_pin_leftover_mib", lambda *a: 5)
+ assert dm._apply_group_offload(
+ pipe, "cuda", None, stream_text_encoders = True, stream_transformer = False
+ )
+ hosts = _host_copies(pipe.text_encoder)
+ assert hosts and not any(t.is_pinned() for t in hosts)
+ assert dm.start_background_pins(pipe) == 1
+ with torch.no_grad():
+ out = pipe.text_encoder(x)
+ torch.cuda.synchronize()
+ dm.finish_background_pins(pipe)
+ assert torch.equal(out, ref)
+ pinned = [t.is_pinned() for t in _host_copies(pipe.text_encoder)]
+ if cap_mib is None:
+ assert all(pinned)
+ else:
+ assert pinned == [True] * 4 + [False] * 4 # weight + bias of the first two groups, in order
+ with torch.no_grad():
+ assert torch.equal(pipe.text_encoder(x), ref)
+ dm.stop_background_pins(pipe)
+
+
[email protected](not _CUDA, reason = "needs a CUDA device")
+def test_the_kill_switch_pins_the_encoder_into_slabs_during_the_apply(budget, monkeypatch):
+ pytest.importorskip("diffusers")
+ monkeypatch.setenv(dm.ENCODER_BACKGROUND_PIN_ENV, "0")
+ budget(1 << 20)
+ pipe = _tiny_pipe()
+ dm.request_background_encoder_pins(pipe)
+ assert dm._apply_group_offload(
+ pipe, "cuda", None, stream_text_encoders = True, stream_transformer = False
+ )
+ assert dm.start_background_pins(pipe) == 0
+ assert all(t.is_pinned() for t in _host_copies(pipe.text_encoder))
+
+
+def test_an_uncommitted_load_stops_the_pinners_it_started():
+ import ast
+ import inspect
+
+ from core.inference import diffusion
+
+ tree = ast.parse(inspect.getsource(diffusion))
+ for fn in ast.walk(tree):
+ if not isinstance(fn, (ast.FunctionDef, ast.AsyncFunctionDef)):
+ continue
+ calls = {
+ node.func.id
+ for node in ast.walk(fn)
+ if isinstance(node, ast.Call) and isinstance(node.func, ast.Name)
+ }
+ if "start_background_pins" not in calls:
+ continue
+ rollbacks = [
+ node
+ for node in ast.walk(fn)
+ if isinstance(node, ast.If)
+ and isinstance(node.test, ast.UnaryOp)
+ and isinstance(node.test.op, ast.Not)
+ and isinstance(node.test.operand, ast.Name)
+ and node.test.operand.id == "state_committed"
+ ]
+ assert rollbacks, fn.name
+ stopped = any(
+ isinstance(node, ast.Call)
+ and isinstance(node.func, ast.Name)
+ and node.func.id == "stop_background_pins"
+ for rollback in rollbacks
+ for node in ast.walk(rollback)
+ )
+ assert (
+ stopped
+ ), f"{fn.name} starts encoder pinners but its uncommitted-load rollback never stops them"