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: classify host pinning by the target device, not the current one (#15463)

Daniel Han4f84e8f7ac0a
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.py
index ba4aac6a7bc..6cd4dee6944 100644
--- a/studio/backend/core/inference/diffusion.py
+++ b/studio/backend/core/inference/diffusion.py
@@ -14990,7 +14990,7 @@ def _offload_controlnet_module(cn_model: Any, device: str, logger: Any) -> bool:
kwargs["record_stream"] = True
_apply_group_offloading_packed(apply_group_offloading, cn_model, kwargs, logger)
if prefetch:
- if not _pin_top_level_group(cn_model, logger):
+ if not _pin_top_level_group(cn_model, logger, device = onload):
_skip_top_level_copy_back(cn_model, logger)
install_group_prefetch(cn_model, onload, logger)
return True
diff --git a/studio/backend/core/inference/diffusion_memory.py b/studio/backend/core/inference/diffusion_memory.py
index 51278639b0f..4e29acc9bf4 100644
--- a/studio/backend/core/inference/diffusion_memory.py
+++ b/studio/backend/core/inference/diffusion_memory.py
@@ -323,7 +323,7 @@ def _pin_host_weights(
import torch
mode = _pin_mode()
- if mode == "off" or not torch.cuda.is_available() or not host_pinning_allowed():
+ if mode == "off" or not torch.cuda.is_available() or not host_pinning_allowed(device):
return 0
# (name, owner tensor, inner attribute or None, the tensor to pin)
params: list = []
@@ -363,7 +363,7 @@ def _pin_host_weights(
slots.append((len(chunks) - 1, off))
off += size
left -= size
- exact = exact and _exact_pin_supported()
+ exact = exact and _exact_pin_supported(device)
if exact:
# The same slots, so the device copies are unchanged; only the host side loses the rounding.
used = [0] * len(chunks)
@@ -400,7 +400,9 @@ def _pin_host_weights(
type(module).__name__,
exc,
)
- return _pin_host_weights(module, host, logger, buffer_host = buffer_host, layout = layout)
+ return _pin_host_weights(
+ module, host, logger, buffer_host = buffer_host, layout = layout, device = device
+ )
bufs: list = []
placed: list = []
try:
@@ -455,10 +457,10 @@ EXACT_PIN_ENV = "UNSLOTH_VIDEO_EXACT_PIN"
_EXACT_PIN_PAGE = 4096
-def _exact_pin_supported() -> bool:
+def _exact_pin_supported(device: Any = None) -> bool:
if (os.environ.get(EXACT_PIN_ENV) or "").strip().lower() in ("0", "off", "false", "no"):
return False
- return _fast_pin_supported()
+ return _fast_pin_supported(device)
def _pin_host_weights_exact(
@@ -5160,7 +5162,7 @@ def hook_resident_denoiser(
return False
dit_mib = _module_pin_mib(transformer)
# the load's _torchao_stream_pinnable rule: unpinned, the apply copies the whole transformer to pageable host RAM
- if not _streamed_pin_plan(dit_mib, 0)[0]:
+ if not _streamed_pin_plan(dit_mib, 0, device = onload)[0]:
if logger is not None:
logger.info(
"diffusion.memory: the resident transformer keeps no offload hooks (%d MiB cannot be pinned)",
@@ -5195,7 +5197,7 @@ def hook_resident_denoiser(
_torchao_group_offload_kwargs(transformer, gkwargs, pinned_mib),
logger,
)
- if not _pin_top_level_group(transformer, logger, pinned_mib):
+ if not _pin_top_level_group(transformer, logger, pinned_mib, device = onload):
_skip_top_level_copy_back(transformer, logger)
if gkwargs.get("record_stream"):
install_group_prefetch(transformer, onload, logger)
@@ -6088,7 +6090,7 @@ def _apply_group_offloading_packed(
pack = (
bool(kwargs.get("use_stream"))
and not kwargs.get("low_cpu_mem_usage", False)
- and host_pinning_allowed()
+ and host_pinning_allowed(kwargs.get("onload_device"))
)
expected = None
if pack:
@@ -6173,10 +6175,11 @@ def _streamed_pin_plan(
transformer_mib: int,
encoder_mib: int,
logger: Any = None,
+ device: Any = None,
) -> tuple[bool, bool]:
- """(pin transformer, pin encoders), transformer first."""
+ """(pin transformer, pin encoders), transformer first. ``device``: the onload target the pins serve."""
forced = str(os.environ.get(GROUP_OFFLOAD_PIN_ENV, "")).strip().lower()
- if forced in ("0", "off", "false", "no") or not host_pinning_allowed():
+ if forced in ("0", "off", "false", "no") or not host_pinning_allowed(device):
return False, False
if forced in ("1", "on", "true", "yes"):
return True, True
@@ -6244,13 +6247,13 @@ def request_background_pins(pipe: Any) -> None:
pass
-def _background_pin_enabled() -> bool:
+def _background_pin_enabled(device: Any = None) -> bool:
return (os.environ.get(BACKGROUND_PIN_ENV) or "").strip().lower() not in (
"0",
"off",
"false",
"no",
- ) and host_pinning_allowed()
+ ) and host_pinning_allowed(device)
# "0": image-load streamed encoders pin into slabs up front instead of on a background worker.
@@ -6280,19 +6283,23 @@ def finish_encoder_pins_at_load(pipe: Any, logger: Any = None) -> float:
return waited
-def _encoder_background_pin_wanted(pipe: Any) -> bool:
+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 (
bool(getattr(pipe, _ENCODER_PIN_REQUEST_ATTR, False))
and not _env_off(ENCODER_BACKGROUND_PIN_ENV)
- and _background_pin_enabled()
- and _fast_pin_supported()
+ and _background_pin_enabled(device)
+ and _fast_pin_supported(device)
)
-def _streamed_pin_leftover_mib(transformer_mib: int, pin_transformer: bool) -> int:
+def _streamed_pin_leftover_mib(
+ transformer_mib: int,
+ pin_transformer: bool,
+ device: Any = None,
+) -> 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():
+ if _env_off(PARTIAL_ENCODER_PIN_ENV) or not host_pinning_allowed(device):
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():
@@ -6372,7 +6379,7 @@ def request_fast_pins(pipe: Any) -> None:
pass
-def _fast_pin_supported() -> bool:
+def _fast_pin_supported(device: Any = None) -> bool:
if (os.environ.get(FAST_PIN_ENV) or "").strip().lower() in ("0", "off", "false", "no"):
return False
# WDDM / WSL2 cap page-locked memory; ROCm's register path is unmeasured.
@@ -6381,7 +6388,11 @@ def _fast_pin_supported() -> bool:
try:
import torch
- if is_rocm_torch(torch) or not torch.cuda.is_available() or not host_pinning_allowed():
+ if (
+ is_rocm_torch(torch)
+ or not torch.cuda.is_available()
+ or not host_pinning_allowed(device)
+ ):
return False
cudart = torch.cuda.cudart()
return hasattr(cudart, "cudaHostRegister") and hasattr(cudart, "cudaHostUnregister")
@@ -6454,16 +6465,16 @@ def registered_host_copy(src: Any) -> Any:
return out
-def _registered_pin(src: Any) -> Any:
+def _registered_pin(src: Any, device: Any = None) -> Any:
"""``src.pin_memory()`` in registered host memory where the type allows (GGUF re-wrapped, avoiding pow2 rounding)."""
import torch
- if not host_pinning_allowed():
+ if not host_pinning_allowed(device):
return src # integrated GPU: a pinned copy only takes RAM from the card
if type(src) is torch.Tensor:
return registered_host_copy(src)
gguf = _gguf_parameter_class()
- if gguf is not None and type(src) is gguf and _exact_pin_supported():
+ if gguf is not None and type(src) is gguf and _exact_pin_supported(device):
pinned = registered_host_copy(src.as_tensor())
return gguf(pinned, requires_grad = False, quant_type = src.quant_type)
return src.pin_memory()
@@ -6613,7 +6624,7 @@ class _GroupPinner:
(
tensor,
src,
- pool.submit(_registered_pin, src),
+ pool.submit(_registered_pin, src, self.device),
)
for tensor, src in self._unpinned(group)
]
@@ -6746,7 +6757,7 @@ def _defer_pinning(
return False
if fast is None:
fast = bool(getattr(pipe, _FAST_PIN_REQUEST_ATTR, False))
- fast = bool(fast) and _fast_pin_supported()
+ fast = bool(fast) and _fast_pin_supported(device)
pinner = _GroupPinner(module, groups, device, logger, fast = fast, byte_cap = byte_cap)
pending = getattr(pipe, _PENDING_PINS_ATTR, None)
if pending is None:
@@ -6864,11 +6875,13 @@ def _pin_top_level_group(
module: Any,
logger: Any = None,
pinned_mib: Optional[list] = None,
+ device: Any = None,
) -> bool:
- """Onloads from one pinned host copy, async; skipped for torchao weights (not re-pointable) and when the copy does not fit pinnable host RAM."""
+ """Onloads from one pinned host copy, async; skipped for torchao weights (not re-pointable) and when the copy does not fit pinnable host RAM.
+ ``device``: the group's onload target (None: the current device)."""
if (os.environ.get(PIN_TOP_GROUP_ENV) or "").strip().lower() in ("0", "off", "false", "no"):
return False
- if not host_pinning_allowed():
+ if not host_pinning_allowed(device):
return False
try:
import torch
@@ -7129,7 +7142,7 @@ def _apply_group_offload(
background_pin
and use_stream
and "low_cpu_mem_usage" in _params
- and _background_pin_enabled()
+ and _background_pin_enabled(onload)
)
# 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
@@ -7139,7 +7152,7 @@ def _apply_group_offload(
and stream_text_encoders
and use_stream
and "low_cpu_mem_usage" in _params
- and _encoder_background_pin_wanted(pipe)
+ and _encoder_background_pin_wanted(pipe, onload)
)
def _encoder_defers(module: Any) -> bool:
@@ -7159,6 +7172,7 @@ def _apply_group_offload(
dit_pin_mib,
sum(enc_pin_mib(m) for m in streamed_encoders.values()),
logger,
+ device = onload,
)
gkwargs["low_cpu_mem_usage"] = not pin_streamed[0]
small_host = bool(getattr(pipe, "_unsloth_small_host", None))
@@ -7168,7 +7182,7 @@ def _apply_group_offload(
gkwargs["low_cpu_mem_usage"] = True
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])
+ encoder_cap_mib = _streamed_pin_leftover_mib(dit_pin_mib, pin_streamed[0], onload)
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",
@@ -7206,7 +7220,7 @@ def _apply_group_offload(
logger,
)
installed += 1
- if use_stream and not _pin_top_level_group(module, logger, pinned_mib):
+ if use_stream and not _pin_top_level_group(module, logger, pinned_mib, device = onload):
_skip_top_level_copy_back(module, logger)
if use_stream and gkwargs.get("record_stream"):
install_group_prefetch(module, onload, logger)
@@ -7349,7 +7363,9 @@ def stream_text_encoders_onto(
if str(n).startswith("text_encoder") and isinstance(m, torch.nn.Module)
}
if "low_cpu_mem_usage" in params:
- pin = _streamed_pin_plan(0, sum(_module_pin_mib(m) for m in encoders.values()), logger)
+ pin = _streamed_pin_plan(
+ 0, sum(_module_pin_mib(m) for m in encoders.values()), logger, device = onload
+ )
kwargs["low_cpu_mem_usage"] = not pin[1]
done: list[str] = []
try:
@@ -7873,11 +7889,11 @@ def _apply_streaming_offload(
defer = (
prefetch
and bool(getattr(pipe, _BACKGROUND_PIN_REQUEST_ATTR, False))
- and _background_pin_enabled()
+ and _background_pin_enabled(onload)
)
# 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)
+ encoders_defer = not defer and prefetch and _encoder_background_pin_wanted(pipe, onload)
def _encoder_defers(name: Any, module: Any, offload_type: str) -> bool:
return (
@@ -7898,10 +7914,12 @@ def _apply_streaming_offload(
leaf_mib = sum(
leaf_pin_mib(n, m, t) for n, (m, t) in streamed.items() if t != "block_level"
)
- pin_dits, pin_encoders = _streamed_pin_plan(dit_pin_mib, leaf_mib, logger)
+ pin_dits, pin_encoders = _streamed_pin_plan(
+ dit_pin_mib, leaf_mib, logger, device = onload
+ )
encoder_left_mib = 0
if encoders_defer and not pin_encoders:
- encoder_left_mib = _streamed_pin_leftover_mib(dit_pin_mib, pin_dits)
+ encoder_left_mib = _streamed_pin_leftover_mib(dit_pin_mib, pin_dits, onload)
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",
@@ -7948,7 +7966,7 @@ def _apply_streaming_offload(
if (
use_stream
and offload_type == "block_level"
- and not _pin_top_level_group(module, logger, pinned_mib)
+ and not _pin_top_level_group(module, logger, pinned_mib, device = onload)
):
_skip_top_level_copy_back(module, logger)
if use_stream and prefetch and offload_type == "block_level":
diff --git a/studio/backend/core/inference/diffusion_offload_prefetch.py b/studio/backend/core/inference/diffusion_offload_prefetch.py
index 8fbe1ab74f7..895f2760cee 100644
--- a/studio/backend/core/inference/diffusion_offload_prefetch.py
+++ b/studio/backend/core/inference/diffusion_offload_prefetch.py
@@ -890,6 +890,7 @@ def _adopt_top_group(
module: Any,
stream: Any,
logger: Any = None,
+ device: Any = None,
) -> Optional[Any]:
"""Give a torchao top-level group (no stream in diffusers: synchronous upload, copy-back every forward) pinned host
copies and the module's copy stream, so the prefetcher drives it like a block. None if left as it was."""
@@ -910,7 +911,8 @@ def _adopt_top_group(
return None
from .host_pinning import host_pinning_allowed
- if not host_pinning_allowed():
+ # ``device``: the module's onload target (None: the current device)
+ if not host_pinning_allowed(device):
return None
go = _go()
registry = getattr(module, "_diffusers_hook", None)
@@ -1034,7 +1036,7 @@ def install_group_prefetch(
streams = {id(g.stream) for g in groups}
if len(streams) != 1:
return 0
- top = _adopt_top_group(module, groups[0].stream, logger)
+ top = _adopt_top_group(module, groups[0].stream, logger, device = device)
if top is not None:
groups = [top] + groups
pf = GroupPrefetcher(module, groups, device, prefetch_depth() if depth is None else depth)
diff --git a/studio/backend/core/inference/diffusion_prequant.py b/studio/backend/core/inference/diffusion_prequant.py
index 4252c11b50f..a6fcbeec3af 100644
--- a/studio/backend/core/inference/diffusion_prequant.py
+++ b/studio/backend/core/inference/diffusion_prequant.py
@@ -3225,7 +3225,9 @@ def stream_prequantized_module(
payload_mib = sum(
tensor_payload_bytes(t) for t in chain(module.parameters(), module.buffers())
) // (1024 * 1024)
- kwargs["low_cpu_mem_usage"] = not _streamed_pin_plan(payload_mib, 0, logger)[0]
+ kwargs["low_cpu_mem_usage"] = not _streamed_pin_plan(
+ payload_mib, 0, logger, device = onload
+ )[0]
# Pin through one slab arena: per-tensor pin_memory() rounds each weight to a power of two.
from .diffusion_pinned_arena import pinned_arena_for_group_offload
diff --git a/studio/backend/core/inference/diffusion_segment.py b/studio/backend/core/inference/diffusion_segment.py
index e60b098973c..370d2626ebe 100644
--- a/studio/backend/core/inference/diffusion_segment.py
+++ b/studio/backend/core/inference/diffusion_segment.py
@@ -1444,7 +1444,7 @@ class MaskSegmenter:
from .host_pinning import host_pinning_allowed
host = self._host or _HostWeights(
- pin = (os.environ.get(ENV_PARK_PIN) or "").strip() == "1" and host_pinning_allowed()
+ pin = (os.environ.get(ENV_PARK_PIN) or "").strip() == "1" and host_pinning_allowed(device)
)
try:
host.park(model)
diff --git a/studio/backend/core/inference/video_minimax_h3_residency.py b/studio/backend/core/inference/video_minimax_h3_residency.py
index 59c4f2e51fd..7cdfe21c7c5 100644
--- a/studio/backend/core/inference/video_minimax_h3_residency.py
+++ b/studio/backend/core/inference/video_minimax_h3_residency.py
@@ -390,7 +390,9 @@ def pin_streamed_top_level_group(transformer: Any, logger: Any = None) -> bool:
from .video_minimax_h3_te import h3_te_pin_allowed
top, blocks = h3_offload_groups(transformer)
- if not h3_te_pin_allowed(group_payload_bytes(top) if top is not None else 0):
+ if not h3_te_pin_allowed(
+ group_payload_bytes(top) if top is not None else 0, getattr(top, "onload_device", None)
+ ):
if logger is not None:
logger.info(
"video.h3_top_group: left as diffusers built it (pinning not allowed on this host)"
@@ -493,7 +495,9 @@ def pin_streamed_block_groups(transformer: Any, logger: Any = None) -> tuple[int
tensors = _group_tensors(group)
if any(getattr(t, "device", None) is None or t.device.type != "cpu" for t in tensors):
break
- if not h3_te_pin_allowed(group_payload_bytes(group)):
+ if not h3_te_pin_allowed(
+ group_payload_bytes(group), getattr(group, "onload_device", None)
+ ):
break
saved = (group.low_cpu_mem_usage, group.cpu_param_dict)
try:
@@ -723,7 +727,7 @@ def defer_streamed_block_pins(
if not pin_arena_enabled() or _pinned_memory_capped():
return None
- if not _background_pin_enabled() or not _fast_pin_supported():
+ if not _background_pin_enabled(device) or not _fast_pin_supported(device):
return None
for group in lazy:
cpu = group.cpu_param_dict
@@ -734,7 +738,7 @@ def defer_streamed_block_pins(
or tensor not in cpu
):
return None
- if not h3_te_pin_allowed(group_payload_bytes(lazy[0])):
+ if not h3_te_pin_allowed(group_payload_bytes(lazy[0]), device):
return None
pending = getattr(pipe, _PENDING_PINS_ATTR, None)
if pending is None:
@@ -749,7 +753,7 @@ def defer_streamed_block_pins(
lazy,
device,
logger,
- admit = lambda g: h3_te_pin_allowed(group_payload_bytes(g)),
+ admit = lambda g: h3_te_pin_allowed(group_payload_bytes(g), device),
)
# cpu_param_dict already maps each tensor to its pageable host copy; onloads read it until the pin swaps it
for group in lazy:
diff --git a/studio/backend/core/inference/video_minimax_h3_te.py b/studio/backend/core/inference/video_minimax_h3_te.py
index eee02024799..20bbe2028ff 100644
--- a/studio/backend/core/inference/video_minimax_h3_te.py
+++ b/studio/backend/core/inference/video_minimax_h3_te.py
@@ -426,10 +426,11 @@ def h3_te_stream_enabled() -> bool:
)
-def h3_te_pin_allowed(payload_bytes: int = 0) -> bool:
+def h3_te_pin_allowed(payload_bytes: int = 0, device: Any = None) -> bool:
"""Whether ``payload_bytes`` (at least one arena) may be pinned. The full payload, not one arena: the hosted
weights are mmap views already counted as available, so pinning them takes that much. Honours the group offload
- pin switch and the ~1 GiB pinned cap of Windows / WSL. Never raises."""
+ pin switch and the ~1 GiB pinned cap of Windows / WSL. ``device``: the onload target (None: the current one).
+ Never raises."""
try:
import os
@@ -438,7 +439,7 @@ def h3_te_pin_allowed(payload_bytes: int = 0) -> bool:
from .host_pinning import host_pinning_allowed
forced = str(os.environ.get(GROUP_OFFLOAD_PIN_ENV, "")).strip().lower()
- if forced in ("0", "off", "false", "no") or not host_pinning_allowed():
+ if forced in ("0", "off", "false", "no") or not host_pinning_allowed(device):
return False
if forced in ("1", "on", "true", "yes"):
return True
@@ -566,7 +567,7 @@ def stream_h3_text_encoder(
if not stream:
pin = False
elif pin is None:
- pin = h3_te_pin_allowed(_module_payload_bytes(text_encoder))
+ pin = h3_te_pin_allowed(_module_payload_bytes(text_encoder), onload)
if pin:
try:
pin_module_in_place(text_encoder)
diff --git a/studio/backend/tests/test_diffusion_memory.py b/studio/backend/tests/test_diffusion_memory.py
index 8cd3cce3d5c..51e8ab85e32 100644
--- a/studio/backend/tests/test_diffusion_memory.py
+++ b/studio/backend/tests/test_diffusion_memory.py
@@ -3062,4 +3062,6 @@ def test_both_offload_tiers_fall_back_to_the_no_copy_back_top_group():
for fn in (mem._apply_group_offload, mem._apply_streaming_offload):
src = ast.unparse(ast.parse(inspect.getsource(fn).lstrip()))
assert "_skip_top_level_copy_back(module, logger)" in src, fn.__name__
- assert "not _pin_top_level_group(module, logger, pinned_mib)" in src, fn.__name__
+ assert (
+ "not _pin_top_level_group(module, logger, pinned_mib, device=onload)" in src
+ ), fn.__name__
diff --git a/studio/backend/tests/test_h3_background_block_pin.py b/studio/backend/tests/test_h3_background_block_pin.py
index b24c3dc1f06..9bb2f1d1d48 100644
--- a/studio/backend/tests/test_h3_background_block_pin.py
+++ b/studio/backend/tests/test_h3_background_block_pin.py
@@ -238,8 +238,8 @@ def test_kill_switches_fall_back_to_the_up_front_pin(monkeypatch, env, value):
groups = [_FakeGroup() for _ in range(3)]
monkeypatch.setattr(res, "h3_offload_groups", lambda _t: (None, groups))
monkeypatch.setattr(te, "h3_te_pin_allowed", lambda *_a, **_k: True)
- monkeypatch.setattr(dm, "_fast_pin_supported", lambda: env != dm.FAST_PIN_ENV)
- monkeypatch.setattr(dm, "host_pinning_allowed", lambda: True)
+ monkeypatch.setattr(dm, "_fast_pin_supported", lambda *_a, **_k: env != dm.FAST_PIN_ENV)
+ monkeypatch.setattr(dm, "host_pinning_allowed", lambda *_a, **_k: True)
monkeypatch.setenv(env, value)
pipe = _Pipe()
assert res.defer_streamed_block_pins(pipe, torch.nn.Module(), "cuda") is None
@@ -255,8 +255,8 @@ def test_hosts_and_layouts_the_up_front_pin_owns(monkeypatch, case):
monkeypatch.setattr(res, "h3_offload_groups", lambda _t: (None, groups))
monkeypatch.setattr(te, "h3_te_pin_allowed", lambda *_a, **_k: case != "refused")
monkeypatch.setattr(dm, "_pinned_memory_capped", lambda: case == "capped")
- monkeypatch.setattr(dm, "_fast_pin_supported", lambda: True)
- monkeypatch.setattr(dm, "host_pinning_allowed", lambda: True)
+ monkeypatch.setattr(dm, "_fast_pin_supported", lambda *_a, **_k: True)
+ monkeypatch.setattr(dm, "host_pinning_allowed", lambda *_a, **_k: True)
pipe = _Pipe()
assert res.defer_streamed_block_pins(pipe, torch.nn.Module(), "cuda") is None
assert [g.low_cpu_mem_usage for g in groups] == [
diff --git a/studio/backend/tests/test_image_encoder_background_pin.py b/studio/backend/tests/test_image_encoder_background_pin.py
index 90203d9952f..e65c211b6a9 100644
--- a/studio/backend/tests/test_image_encoder_background_pin.py
+++ b/studio/backend/tests/test_image_encoder_background_pin.py
@@ -75,7 +75,7 @@ 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)
+ monkeypatch.setattr(dm, "_fast_pin_supported", lambda *_a, **_k: True)
pipe = types.SimpleNamespace()
dm.request_background_encoder_pins(pipe)
return pipe
@@ -97,9 +97,9 @@ def test_the_kill_switches_restore_the_up_front_pin(wanted, monkeypatch, env):
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)
+ monkeypatch.setattr(dm, "_fast_pin_supported", lambda *_a, **_k: False)
assert not dm._encoder_background_pin_wanted(wanted)
- monkeypatch.setattr(dm, "_fast_pin_supported", lambda: True)
+ monkeypatch.setattr(dm, "_fast_pin_supported", lambda *_a, **_k: True)
monkeypatch.setattr(dm, "host_pinning_allowed", lambda *a, **k: False)
assert not dm._encoder_background_pin_wanted(wanted)
diff --git a/studio/backend/tests/test_integrated_gpu_no_host_pin.py b/studio/backend/tests/test_integrated_gpu_no_host_pin.py
index 30f4c8b59ad..3761be30042 100644
--- a/studio/backend/tests/test_integrated_gpu_no_host_pin.py
+++ b/studio/backend/tests/test_integrated_gpu_no_host_pin.py
@@ -464,6 +464,11 @@ _REACHED_THROUGH_A_GATE = {
"core/inference/video_minimax_h3_te.py",
"pin_module_in_place",
): "h3_te_pin_allowed / stream_h3_text_encoder",
+ (
+ "core/inference/video_minimax_h3_residency.py",
+ "_pin_host_tensor",
+ ): "_H3BlockPinner._run only, built by defer_streamed_block_pins behind _background_pin_enabled / "
+ "_fast_pin_supported / h3_te_pin_allowed (the admit too), all on the target device",
("core/inference/diffusion_preview.py", "_device_map"): "exempt: tiny, async preview",
(
"core/inference/diffusion_preview.py",
@@ -531,3 +536,165 @@ def test_every_cuda_group_offload_stream_asks_the_predicate():
if "'cuda'" in text and "host_pinning_allowed" not in text and "pinning" not in text:
loose.append(f"{path.name}:{getattr(value, 'lineno', '?')} {text}")
assert not loose, loose
+
+
+def test_the_h3_block_pin_helper_is_reached_only_through_the_gated_deferral():
+ # _pin_host_tensor has no gate of its own: its one caller is _H3BlockPinner, built only by the deferral.
+ tree = ast.parse(
+ (BACKEND / "core/inference/video_minimax_h3_residency.py").read_text(encoding = "utf-8")
+ )
+ funcs = {
+ n.name: n for n in ast.walk(tree) if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef))
+ }
+
+ def users(name):
+ return sorted(
+ f
+ for f, node in funcs.items()
+ if f != name and any(isinstance(x, ast.Name) and x.id == name for x in ast.walk(node))
+ )
+
+ assert users("_pin_host_tensor") == ["_h3_block_pinner_cls", "_run"]
+ assert users("_h3_block_pinner_cls") == ["defer_streamed_block_pins"]
+ gate = ast.unparse(funcs["defer_streamed_block_pins"])
+ for asked in (
+ "_background_pin_enabled(device)",
+ "_fast_pin_supported(device)",
+ "h3_te_pin_allowed(group_payload_bytes(lazy[0]), device)",
+ ):
+ assert asked in gate
+ assert gate.index("_fast_pin_supported(device)") < gate.index("_h3_block_pinner_cls()")
+
+
+# Mixed hosts: the current device (0) and the target (1) differ, one integrated and one discrete.
+def mixed_gpu(monkeypatch):
+ """``mixed_gpu(current_integrated, target_integrated)``: device 0 is current, device 1 is the target."""
+
+ def make(current_integrated: bool, target_integrated: bool) -> None:
+ props = {0: _props(current_integrated), 1: _props(target_integrated)}
+ monkeypatch.setattr(torch.cuda, "is_available", lambda: True)
+ monkeypatch.setattr(torch.cuda, "current_device", lambda: 0)
+ monkeypatch.setattr(torch.cuda, "get_device_properties", lambda i, *a, **k: props[int(i)])
+ _forget_answers()
+
+ yield make
+ _forget_answers()
+
+
+_MIXED = [(True, False), (False, True)]
+_TARGET = "cuda:1"
+
+
[email protected]("current_integrated, target_integrated", _MIXED)
+def test_keep_cpu_weights_follow_the_target_device(
+ monkeypatch, mixed_gpu, pins, current_integrated, target_integrated
+):
+ mixed_gpu(current_integrated, target_integrated)
+ monkeypatch.delenv(dm.OFFLOAD_PIN_ENV, raising = False)
+ monkeypatch.setattr(dm, "_available_system_memory_mib", lambda: 64 << 10)
+ monkeypatch.setattr(dm, "_host_ram_capacity_mib", lambda: 128 << 10)
+ lin = torch.nn.Linear(8, 8)
+ pinned = dm._pin_host_weights(lin, _host_of(lin), device = _TARGET)
+ if target_integrated:
+ assert pinned == 0 and pins == []
+ else:
+ assert pinned > 0 and pins
+
+
[email protected]("current_integrated, target_integrated", _MIXED)
+def test_pin_planners_follow_the_target_device(
+ monkeypatch, mixed_gpu, current_integrated, target_integrated
+):
+ from core.inference import video_minimax_h3_te as te
+
+ mixed_gpu(current_integrated, target_integrated)
+ allowed = not target_integrated
+ monkeypatch.delenv(dm.BACKGROUND_PIN_ENV, raising = False)
+ monkeypatch.delenv(dm.FAST_PIN_ENV, raising = False)
+ monkeypatch.delenv(dm.PARTIAL_ENCODER_PIN_ENV, raising = False)
+ monkeypatch.delenv(dm.GROUP_OFFLOAD_PIN_ENV, raising = False)
+ monkeypatch.setattr(dm.sys, "platform", "linux")
+ monkeypatch.setattr(dm, "_pinned_memory_capped", lambda: False)
+ monkeypatch.setattr(dm, "_pin_budget_mib", lambda: 1 << 20)
+ cudart = types.SimpleNamespace(cudaHostRegister = lambda *a: 0, cudaHostUnregister = lambda *a: 0)
+ monkeypatch.setattr(torch.cuda, "cudart", lambda: cudart)
+ assert dm._streamed_pin_plan(1024, 1024, device = _TARGET) == (allowed, allowed)
+ assert (dm._streamed_pin_leftover_mib(0, False, _TARGET) > 0) is allowed
+ assert dm._background_pin_enabled(_TARGET) is allowed
+ assert dm._fast_pin_supported(_TARGET) is allowed
+ assert te.h3_te_pin_allowed(1 << 20, _TARGET) is allowed
+ pipe = types.SimpleNamespace(**{dm._ENCODER_PIN_REQUEST_ATTR: True})
+ assert dm._encoder_background_pin_wanted(pipe, _TARGET) is allowed
+ # forced on: the user's switch never overrides an integrated target
+ monkeypatch.setenv(dm.GROUP_OFFLOAD_PIN_ENV, "1")
+ assert dm._streamed_pin_plan(1024, 1024, device = _TARGET) == (allowed, allowed)
+ assert te.h3_te_pin_allowed(1 << 20, _TARGET) is allowed
+
+
[email protected]("current_integrated, target_integrated", _MIXED)
+def test_top_level_group_pins_follow_the_target_device(
+ monkeypatch, mixed_gpu, current_integrated, target_integrated
+):
+ from core.inference import diffusion_offload_prefetch as op
+
+ mixed_gpu(current_integrated, target_integrated)
+ monkeypatch.delenv(dm.PIN_TOP_GROUP_ENV, raising = False)
+ monkeypatch.delenv(dm.GROUP_OFFLOAD_PIN_ENV, raising = False)
+ looked: list = []
+ module = types.SimpleNamespace(
+ _diffusers_hook = types.SimpleNamespace(get_hook = lambda name: looked.append(name))
+ )
+ assert dm._pin_top_level_group(module, device = _TARGET) is False
+ assert bool(looked) is (not target_integrated)
+ asked: list = []
+ monkeypatch.setattr(op, "_go", lambda: asked.append(1) or types.SimpleNamespace())
+ assert op._adopt_top_group(types.SimpleNamespace(), object(), device = _TARGET) is None
+ assert bool(asked) is (not target_integrated)
+
+
[email protected]("current_integrated, target_integrated", _MIXED)
+def test_streamed_text_encoders_pin_by_the_target_device(
+ monkeypatch, mixed_gpu, current_integrated, target_integrated
+):
+ pytest.importorskip("diffusers")
+ mixed_gpu(current_integrated, target_integrated)
+ monkeypatch.setenv(dm.GROUP_OFFLOAD_PIN_ENV, "1")
+ seen = _record_group_offload(monkeypatch)
+ monkeypatch.setattr(dm, "_pin_vision_embedding_device", lambda module: 0)
+ pipe = types.SimpleNamespace(components = {"text_encoder": torch.nn.Linear(4, 4)})
+ assert dm.stream_text_encoders_onto(pipe, _TARGET) == ["text_encoder"]
+ (kwargs,) = seen
+ assert kwargs["use_stream"] is (not target_integrated)
+ if not target_integrated:
+ # a forced pin on a discrete target pins up front instead of re-pinning on every onload
+ assert kwargs["low_cpu_mem_usage"] is False
+
+
+def test_only_deviceless_sites_ask_the_predicate_without_a_device():
+ # Every other site knows its onload target; asking the current device there misclassifies mixed hosts.
+ allowed = {
+ # probes and keys the current device by contract
+ ("core/inference/diffusion_memory.py", "_offload_cost_measurements"),
+ # device == "cuda" (the current device) is checked first
+ ("core/training/diffusion_dit_trainer.py", "_build_latent_cache"),
+ ("core/training/diffusion_dit_trainer.py", "_load_warm_conditioning"),
+ ("core/training/diffusion_lora_trainer.py", "_build_sdxl_latent_cache"),
+ }
+ bare = set()
+ for path in sorted((BACKEND / "core").rglob("*.py")):
+ tree = ast.parse(path.read_text(encoding = "utf-8"))
+ rel = path.relative_to(BACKEND).as_posix()
+ for fn in ast.walk(tree):
+ if not isinstance(fn, (ast.FunctionDef, ast.AsyncFunctionDef)):
+ continue
+ for node in ast.walk(fn):
+ if (
+ isinstance(node, ast.Call)
+ and isinstance(node.func, ast.Name)
+ and node.func.id == "host_pinning_allowed"
+ and not node.args
+ and not node.keywords
+ ):
+ bare.add((rel, fn.name))
+ assert bare <= allowed, sorted(bare - allowed)
diff --git a/studio/backend/tests/test_video_exact_pin.py b/studio/backend/tests/test_video_exact_pin.py
index b0f8a4388f2..d94a936f0e6 100644
--- a/studio/backend/tests/test_video_exact_pin.py
+++ b/studio/backend/tests/test_video_exact_pin.py
@@ -52,7 +52,7 @@ def fake(monkeypatch):
monkeypatch.setattr(dm, "host_pinning_allowed", lambda *a, **k: True)
monkeypatch.setattr(torch.cuda, "is_available", lambda: True)
monkeypatch.setattr(torch, "empty", empty)
- monkeypatch.setattr(dm, "_fast_pin_supported", lambda: True)
+ monkeypatch.setattr(dm, "_fast_pin_supported", lambda *_a, **_k: True)
monkeypatch.setattr(dm, "_RegisteredHostBuffer", _FakeRegistered)
return stock
@@ -127,7 +127,7 @@ def test_the_kill_switch_restores_the_power_of_two_chunks(fake, monkeypatch, val
def test_unsupported_registration_keeps_the_stock_pin(fake, monkeypatch):
- monkeypatch.setattr(dm, "_fast_pin_supported", lambda: False)
+ monkeypatch.setattr(dm, "_fast_pin_supported", lambda *_a, **_k: False)
module = _module()
dm._pin_host_weights(module, _host(module), None, buffer_host = {}, layout = [], exact = True)
assert not _FakeRegistered.made
@@ -202,7 +202,7 @@ def test_a_gguf_weight_pins_registered_and_keeps_its_quant_type(monkeypatch):
return t.clone()
monkeypatch.setattr(dm, "registered_host_copy", fake_copy)
- monkeypatch.setattr(dm, "_fast_pin_supported", lambda: True)
+ monkeypatch.setattr(dm, "_fast_pin_supported", lambda *_a, **_k: True)
monkeypatch.delenv(dm.EXACT_PIN_ENV, raising = False)
out = dm._registered_pin(src)
assert made == [src.nbytes]
@@ -214,7 +214,7 @@ def test_a_gguf_weight_pins_registered_and_keeps_its_quant_type(monkeypatch):
def test_the_kill_switch_pins_a_gguf_weight_through_the_allocator(monkeypatch):
src = _gguf_weight()
monkeypatch.setattr(dm, "registered_host_copy", lambda t: pytest.fail("registered"))
- monkeypatch.setattr(dm, "_fast_pin_supported", lambda: True)
+ monkeypatch.setattr(dm, "_fast_pin_supported", lambda *_a, **_k: True)
monkeypatch.setenv(dm.EXACT_PIN_ENV, "0")
calls = []
monkeypatch.setattr(torch.Tensor, "pin_memory", lambda self: calls.append(1) or self.clone())
diff --git a/studio/backend/tests/test_video_fast_pin.py b/studio/backend/tests/test_video_fast_pin.py
index a6772edc037..0af755fc1c3 100644
--- a/studio/backend/tests/test_video_fast_pin.py
+++ b/studio/backend/tests/test_video_fast_pin.py
@@ -33,7 +33,7 @@ def test_fast_pins_are_requested_per_pipe_and_have_a_kill_switch(monkeypatch):
def test_a_pipe_without_the_request_keeps_the_allocator_pin(monkeypatch):
- monkeypatch.setattr(mem, "_fast_pin_supported", lambda: True)
+ monkeypatch.setattr(mem, "_fast_pin_supported", lambda *_a, **_k: True)
monkeypatch.setattr(mem, "_offload_groups", lambda module: [types.SimpleNamespace()])
plain, fast = _Pipe(), _Pipe()
mem.request_fast_pins(fast)