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 video: pin offloaded weights at their size, not a power of two (#15179)

Daniel Han494a857b6319
diff --git a/studio/backend/core/inference/diffusion_memory.py b/studio/backend/core/inference/diffusion_memory.py
index ced29fa8ea0..583389fcfa9 100644
--- a/studio/backend/core/inference/diffusion_memory.py
+++ b/studio/backend/core/inference/diffusion_memory.py
@@ -251,6 +251,12 @@ def _wrap_cpu_offload_hooks(
continue
try:
_wrap_cpu_offload_hook(hook, module, logger)
+ module.__dict__[_KEEP_ATTR]["exact_pin"] = bool(
+ getattr(pipe, _FAST_PIN_REQUEST_ATTR, False)
+ )
+ module.__dict__[_KEEP_ATTR]["exact_pin_device"] = getattr(
+ hook, "execution_device", None
+ )
wrapped += 1
except Exception as exc: # noqa: BLE001 - that module keeps the stock copy
if logger is not None:
@@ -312,9 +318,12 @@ def _pin_host_weights(
logger: Any = None,
buffer_host: Optional[dict] = None,
layout: Optional[list] = None,
+ exact: bool = False,
+ device: Any = None,
) -> int:
"""Pack kept host weights and buffers into page-locked chunks; returns bytes pinned. Each copy keeps its source strides.
- ``layout`` (if given) receives ``(chunk, [(name, start, view), ...])`` per chunk for ``_upload_pinned_chunks``."""
+ ``layout`` (if given) receives ``(chunk, [(name, start, view), ...])`` per chunk for ``_upload_pinned_chunks``.
+ ``exact`` (video loads, see ``_exact_pin_supported``) sizes each chunk to its bytes instead of a power of two."""
import torch
mode = _pin_mode()
@@ -358,6 +367,13 @@ def _pin_host_weights(
slots.append((len(chunks) - 1, off))
off += size
left -= size
+ exact = exact and _exact_pin_supported()
+ if exact:
+ # The same slots, so the device copies are unchanged; only the host side loses the rounding.
+ used = [0] * len(chunks)
+ for size, (index, start) in zip(sizes, slots):
+ used[index] = max(used[index], start + size)
+ chunks = [-(-n // _EXACT_PIN_PAGE) * _EXACT_PIN_PAGE for n in used]
need = sum(chunks)
if mode == "auto":
# Pinned pages are charged to an enforcing cgroup: size from the cgroup-capped readings.
@@ -376,6 +392,19 @@ def _pin_host_weights(
available / 2**30,
)
return 0
+ if exact:
+ try:
+ return _pin_host_weights_exact(
+ module, host, logger, buffer_host, layout, params, slots, chunks, device
+ )
+ except Exception as exc: # noqa: BLE001 - registration refused before any weight moved: the pinned allocator
+ if logger is not None:
+ logger.info(
+ "diffusion.memory: exact pin of %s failed (%s); using the pinned allocator",
+ type(module).__name__,
+ exc,
+ )
+ return _pin_host_weights(module, host, logger, buffer_host = buffer_host, layout = layout)
bufs: list = []
placed: list = []
try:
@@ -425,6 +454,114 @@ def _pin_host_weights(
return need
+# Video loads only. "0" restores the power-of-two pinned chunks of the whole-module offload tier.
+EXACT_PIN_ENV = "UNSLOTH_VIDEO_EXACT_PIN"
+_EXACT_PIN_PAGE = 4096
+
+
+def _exact_pin_supported() -> bool:
+ if (os.environ.get(EXACT_PIN_ENV) or "").strip().lower() in ("0", "off", "false", "no"):
+ return False
+ return _fast_pin_supported()
+
+
+def _pin_host_weights_exact(
+ module: Any,
+ host: dict,
+ logger: Any,
+ buffer_host: Optional[dict],
+ layout: Optional[list],
+ params: list,
+ slots: list,
+ chunks: list,
+ device: Any = None,
+) -> int:
+ """``_pin_host_weights`` into page-granular registered chunks (torch's allocator rounds up to a power of two).
+ Weights move per chunk so the module is never held twice; a refusal after the first chunk keeps the moved
+ weights pinned and leaves the rest pageable (a first-chunk refusal raises)."""
+ import torch
+
+ target = torch.device(device) if device is not None else None
+ scope = (
+ torch.cuda.device(target)
+ if target is not None and target.type == "cuda" and target.index is not None
+ else contextlib.nullcontext()
+ )
+ with scope:
+ return _fill_exact_chunks(module, host, logger, buffer_host, layout, params, slots, chunks)
+
+
+def _fill_exact_chunks(
+ module: Any,
+ host: dict,
+ logger: Any,
+ buffer_host: Optional[dict],
+ layout: Optional[list],
+ params: list,
+ slots: list,
+ chunks: list,
+) -> int:
+ import numpy as np
+ import torch
+
+ members: list = [[] for _ in chunks]
+ for item, (index, start) in zip(range(len(params)), slots):
+ members[index].append((item, start))
+ done: list = []
+ pinned = 0
+ for index, size in enumerate(chunks):
+ try:
+ holder = _RegisteredHostBuffer(size)
+ buf = torch.from_numpy(np.asarray(holder))
+ placed = []
+ for item, start in members[index]:
+ name, p, attr, src = params[item]
+ view = buf[start : start + src.nbytes].view(src.dtype)
+ view = (
+ view.view(src.shape)
+ if src.is_contiguous()
+ else view.as_strided(src.shape, src.stride())
+ )
+ view.copy_(src)
+ placed.append((item, start, view))
+ holder.register()
+ except Exception:
+ if not done:
+ raise
+ if logger is not None:
+ logger.info(
+ "diffusion.memory: pinned %d of %d chunks of %s; the rest stays pageable",
+ len(done),
+ len(chunks),
+ type(module).__name__,
+ )
+ break
+ entries = []
+ wrapped: dict = {}
+ for item, start, view in placed:
+ name, p, attr, _src = params[item]
+ params[item] = None
+ entries.append((name, start, view))
+ if name.startswith("\0"):
+ name = name[1:]
+ _set_buffer(module, name, view)
+ buffer_host[name] = view
+ continue
+ if attr is not None:
+ setattr(p, attr, view)
+ wrapped[name] = p
+ continue
+ p.data = view
+ host[name] = view
+ for name, p in wrapped.items():
+ host[name] = p.data # the kept host weight now reads the pinned inner tensors
+ done.append((buf, entries))
+ pinned += size
+ if layout is not None:
+ layout[:] = [(buf, entries) for buf, entries in done if entries]
+ return pinned
+
+
OFFLOAD_FAST_UPLOAD_ENV = "UNSLOTH_DIFFUSION_OFFLOAD_FAST_UPLOAD"
@@ -783,7 +920,13 @@ def _wrap_cpu_offload_hook(
layout: list = []
try:
pinned = _pin_host_weights(
- mod, host, logger, buffer_host = buffer_host, layout = layout
+ mod,
+ host,
+ logger,
+ buffer_host = buffer_host,
+ layout = layout,
+ exact = bool(state.get("exact_pin")),
+ device = state.get("exact_pin_device"),
)
except Exception: # noqa: BLE001 - pinning is an optimisation, never a failure
pinned = 0
@@ -6179,6 +6322,21 @@ def registered_host_copy(src: Any) -> Any:
return out
+def _registered_pin(src: Any) -> 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():
+ 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():
+ pinned = registered_host_copy(src.as_tensor())
+ return gguf(pinned, requires_grad = False, quant_type = src.quant_type)
+ return src.pin_memory()
+
+
class _GroupPinner:
"""Pins a streamed module's offload groups on a worker thread, first block first.
@@ -6299,12 +6457,7 @@ class _GroupPinner:
(
tensor,
src,
- pool.submit(
- registered_host_copy
- if type(src) is torch.Tensor
- else src.pin_memory,
- *((src,) if type(src) is torch.Tensor else ()),
- ),
+ pool.submit(_registered_pin, src),
)
for tensor, src in self._unpinned(group)
]
diff --git a/studio/backend/tests/test_video_exact_pin.py b/studio/backend/tests/test_video_exact_pin.py
new file mode 100644
index 00000000000..b0f8a4388f2
--- /dev/null
+++ b/studio/backend/tests/test_video_exact_pin.py
@@ -0,0 +1,228 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Video whole-module offload pins each chunk page-granular, not a power of two (CPU fakes registration)."""
+
+from __future__ import annotations
+
+import types
+
+import pytest
+
+torch = pytest.importorskip("torch")
+np = pytest.importorskip("numpy")
+
+from core.inference import diffusion_memory as dm # noqa: E402
+
+
+class _FakeRegistered:
+ """``_RegisteredHostBuffer`` without CUDA: a numpy buffer, ``register`` records or refuses."""
+
+ made: list = []
+ refuse_at: int = -1
+
+ def __init__(self, nbytes):
+ self.size = int(nbytes)
+ self._arr = np.zeros(self.size, dtype = np.uint8)
+ self.__array_interface__ = self._arr.__array_interface__
+ self.registered = False
+ _FakeRegistered.made.append(self)
+
+ def register(self):
+ if len(_FakeRegistered.made) - 1 == _FakeRegistered.refuse_at:
+ raise RuntimeError("cudaHostRegister failed (2)")
+ self.registered = True
+
+
+def fake(monkeypatch):
+ real_empty = torch.empty
+ stock: list = []
+
+ def empty(*args, **kwargs):
+ if kwargs.pop("pin_memory", False):
+ stock.append(args[0])
+ return real_empty(*args, **kwargs)
+
+ _FakeRegistered.made = []
+ _FakeRegistered.refuse_at = -1
+ monkeypatch.setenv(dm.OFFLOAD_PIN_ENV, "1")
+ monkeypatch.delenv(dm.EXACT_PIN_ENV, raising = False)
+ monkeypatch.setattr(dm, "_PIN_CHUNK_BYTES", 1 << 15)
+ 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, "_RegisteredHostBuffer", _FakeRegistered)
+ return stock
+
+
+def _module():
+ torch.manual_seed(0)
+ # ~13 KB weights, 200 B biases: two layers per 32 KiB chunk, and a tail chunk far from a power of two
+ return torch.nn.Sequential(*(torch.nn.Linear(64, 50) for _ in range(7)))
+
+
+def _host(module):
+ return {name: p.data for name, p in module.named_parameters()}
+
+
+def _payload(module):
+ return {name: p.detach().clone() for name, p in module.named_parameters()}
+
+
+def _check_values(module, ref):
+ for name, p in module.named_parameters():
+ assert torch.equal(p.data, ref[name]), name
+
+
+def test_exact_chunks_are_sized_to_their_bytes(fake):
+ module = _module()
+ ref = _payload(module)
+ host = _host(module)
+ layout: list = []
+ need = dm._pin_host_weights(module, host, None, buffer_host = {}, layout = layout, exact = True)
+ assert not fake, "the exact path must not touch the pinned allocator"
+ assert len(_FakeRegistered.made) > 1
+ sizes = [h.size for h in _FakeRegistered.made]
+ assert all(h.registered for h in _FakeRegistered.made)
+ assert need == sum(sizes)
+ assert all(size % dm._EXACT_PIN_PAGE == 0 for size in sizes)
+ payload = sum(p.nbytes for p in module.parameters())
+ assert payload <= need < payload + len(sizes) * dm._EXACT_PIN_PAGE
+ twin = _module()
+ stock_need = dm._pin_host_weights(
+ twin, _host(twin), None, buffer_host = {}, layout = [], exact = False
+ )
+ assert need < stock_need
+ _check_values(module, ref)
+ bufs = [buf for buf, _ in layout]
+ for name, p in module.named_parameters():
+ assert host[name].data_ptr() == p.data_ptr()
+ assert any(
+ buf.data_ptr() <= p.data_ptr() < buf.data_ptr() + buf.nbytes for buf in bufs
+ ), name
+ assert sum(len(entries) for _, entries in layout) == len(list(module.parameters()))
+
+
+def test_same_slots_as_the_stock_pin(fake):
+ """Device uploads copy ``buf[:used]`` per chunk: the exact path keeps the stock slots, so they are unchanged."""
+ a, b = _module(), _module()
+ la: list = []
+ lb: list = []
+ dm._pin_host_weights(a, _host(a), None, buffer_host = {}, layout = la, exact = True)
+ dm._pin_host_weights(b, _host(b), None, buffer_host = {}, layout = lb, exact = False)
+ assert [[(n, s) for n, s, _ in e] for _, e in la] == [[(n, s) for n, s, _ in e] for _, e in lb]
+ assert fake, "the stock path pins through the allocator"
+ assert all(n == 1 << (n - 1).bit_length() for n in fake)
+
+
[email protected]("value", ["0", "off"])
+def test_the_kill_switch_restores_the_power_of_two_chunks(fake, monkeypatch, value):
+ monkeypatch.setenv(dm.EXACT_PIN_ENV, value)
+ module = _module()
+ dm._pin_host_weights(module, _host(module), None, buffer_host = {}, layout = [], exact = True)
+ assert not _FakeRegistered.made
+ assert fake
+
+
+def test_unsupported_registration_keeps_the_stock_pin(fake, monkeypatch):
+ monkeypatch.setattr(dm, "_fast_pin_supported", lambda: False)
+ module = _module()
+ dm._pin_host_weights(module, _host(module), None, buffer_host = {}, layout = [], exact = True)
+ assert not _FakeRegistered.made
+ assert fake
+
+
+def test_a_refused_first_chunk_falls_back_to_the_stock_pin(fake):
+ _FakeRegistered.refuse_at = 0
+ module = _module()
+ ref = _payload(module)
+ layout: list = []
+ need = dm._pin_host_weights(
+ module, _host(module), None, buffer_host = {}, layout = layout, exact = True
+ )
+ assert need == sum(fake) and fake
+ _check_values(module, ref)
+ assert sum(len(e) for _, e in layout) == len(list(module.parameters()))
+
+
+def test_a_refused_later_chunk_keeps_the_pinned_ones(fake):
+ _FakeRegistered.refuse_at = 1
+ module = _module()
+ ref = _payload(module)
+ host = _host(module)
+ before = {name: p.data_ptr() for name, p in module.named_parameters()}
+ layout: list = []
+ need = dm._pin_host_weights(module, host, None, buffer_host = {}, layout = layout, exact = True)
+ assert not fake
+ assert len(layout) == 1 and need == _FakeRegistered.made[0].size
+ moved = {name for name, _, _ in layout[0][1]}
+ assert moved
+ for name, p in module.named_parameters():
+ assert (p.data_ptr() != before[name]) == (name in moved), name
+ _check_values(module, ref)
+
+
+def test_only_a_video_pipe_asks_for_exact_chunks(monkeypatch):
+ hooks = pytest.importorskip("accelerate.hooks")
+ monkeypatch.delenv(dm.OFFLOAD_KEEP_CPU_ENV, raising = False)
+
+ def pipe(video):
+ module = _module()
+ hook = hooks.CpuOffload(execution_device = "cpu")
+ hooks.add_hook_to_module(module, hook)
+ p = types.SimpleNamespace(components = {"transformer": module}, transformer = module)
+ if video:
+ dm.request_fast_pins(p)
+ dm._wrap_cpu_offload_hooks(p, hooks.CpuOffload)
+ return module.__dict__[dm._KEEP_ATTR].get("exact_pin")
+
+ assert pipe(True) is True
+ assert pipe(False) is False
+
+
+def _gguf_weight():
+ utils = pytest.importorskip("diffusers.quantizers.gguf.utils")
+ gguf = pytest.importorskip("gguf")
+ q4k = gguf.GGMLQuantizationType.Q4_K
+ block, type_size = gguf.GGML_QUANT_SIZES[q4k]
+ rows, cols = 8, 2 * block
+ data = torch.randint(0, 255, (rows, cols // block * type_size), dtype = torch.uint8)
+ return utils.GGUFParameter(data, quant_type = q4k)
+
+
+def test_a_gguf_weight_pins_registered_and_keeps_its_quant_type(monkeypatch):
+ src = _gguf_weight()
+ made = []
+
+ def fake_copy(t):
+ assert type(t) is torch.Tensor
+ made.append(t.nbytes)
+ return t.clone()
+
+ monkeypatch.setattr(dm, "registered_host_copy", fake_copy)
+ monkeypatch.setattr(dm, "_fast_pin_supported", lambda: True)
+ monkeypatch.delenv(dm.EXACT_PIN_ENV, raising = False)
+ out = dm._registered_pin(src)
+ assert made == [src.nbytes]
+ assert type(out) is type(src) and out.quant_type == src.quant_type
+ assert out.quant_shape == src.quant_shape and not out.requires_grad
+ assert torch.equal(out.as_tensor(), src.as_tensor())
+
+
+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.setenv(dm.EXACT_PIN_ENV, "0")
+ calls = []
+ monkeypatch.setattr(torch.Tensor, "pin_memory", lambda self: calls.append(1) or self.clone())
+ out = dm._registered_pin(src)
+ assert calls and type(out) is type(src)
+
+
+def test_a_plain_tensor_still_takes_the_registered_copy(monkeypatch):
+ monkeypatch.setattr(dm, "registered_host_copy", lambda t: ("registered", t))
+ src = torch.randn(4)
+ assert dm._registered_pin(src)[0] == "registered"