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 MiniMax-H3's lazily streamed blocks with the background pinner (#15297)

Daniel Hanafcf0fcef302
diff --git a/studio/backend/core/inference/video.py b/studio/backend/core/inference/video.py
index 3331afbbc1f..a5d9d388385 100644
--- a/studio/backend/core/inference/video.py
+++ b/studio/backend/core/inference/video.py
@@ -11133,24 +11133,47 @@ class VideoBackend:
pin_streamed_top_level_group(denoiser, logger = logger)
except Exception as exc: # noqa: BLE001 -- a speed-up only
logger.warning("video.h3_top_group: %s", exc)
+ block_pinner = None
if denoiser_streamed == "stream_lazy":
- from .video_minimax_h3_residency import pin_streamed_block_groups
+ from .video_minimax_h3_residency import (
+ defer_streamed_block_pins,
+ pin_streamed_block_groups,
+ )
try:
- done, total = pin_streamed_block_groups(denoiser, logger = logger)
- except Exception as exc: # noqa: BLE001 -- a speed-up only
- done, total = 0, 0
+ # the 9-12 s slab copy, off the load path
+ block_pinner = defer_streamed_block_pins(
+ pipe, denoiser, device, logger = logger
+ )
+ except Exception as exc: # noqa: BLE001 -- pin up front instead
logger.warning("video.h3_block_pin: %s", exc)
- if total and done == total:
- # every group now holds one pinned copy: the prefetch below engages
+ if block_pinner is not None:
denoiser_streamed = "stream"
denoiser_single_host_copy = True
+ else:
+ try:
+ done, total = pin_streamed_block_groups(
+ denoiser, logger = logger
+ )
+ except Exception as exc: # noqa: BLE001 -- a speed-up only
+ done, total = 0, 0
+ logger.warning("video.h3_block_pin: %s", exc)
+ if total and done == total:
+ # every group now holds one pinned copy: the prefetch below engages
+ denoiser_streamed = "stream"
+ denoiser_single_host_copy = True
# after the top-level pin (it becomes one of the prefetched groups), before the residency fit
from .video_minimax_h3_residency import install_h3_stream_prefetch
+ covered = 0
try:
- install_h3_stream_prefetch(denoiser, device, logger = logger)
+ covered = install_h3_stream_prefetch(
+ denoiser, device, logger = logger
+ )
except Exception as exc: # noqa: BLE001 -- a speed-up only
logger.warning("video.h3_stream_prefetch: %s", exc)
+ if block_pinner is not None and not covered:
+ # Only the prefetcher's onload is sure to wait for a group's pin: finish it now.
+ block_pinner.join()
if h3_dit_resident_enabled() and denoiser_streamed in (
"stream",
"stream_lazy",
@@ -11577,6 +11600,7 @@ class VideoBackend:
)
with self._lock:
if _load_token is not None and _load_token != self._load_token:
+ stop_background_pins(pipe)
del pipe
clear_gpu_cache()
raise RuntimeError("Video load was cancelled or superseded.")
diff --git a/studio/backend/core/inference/video_minimax_h3_residency.py b/studio/backend/core/inference/video_minimax_h3_residency.py
index aa00a3334be..68d6150656a 100644
--- a/studio/backend/core/inference/video_minimax_h3_residency.py
+++ b/studio/backend/core/inference/video_minimax_h3_residency.py
@@ -528,6 +528,252 @@ def pin_streamed_block_groups(transformer: Any, logger: Any = None) -> tuple[int
return pinned, len(blocks)
+H3_BLOCK_BACKGROUND_PIN_ENV = "UNSLOTH_H3_BACKGROUND_BLOCK_PIN"
+# Groups queued ahead of the swap: keeps 8 copy threads busy while bounding pageable sources held beside pins.
+_H3_PIN_LOOKAHEAD = 2
+
+
+def _host_leaves(tensor: Any) -> list:
+ from .diffusion_pinned_arena import _plain_leaves
+ return [leaf for leaf in _plain_leaves(tensor) if leaf.numel() > 0]
+
+
+def _pin_host_tensor(src: Any) -> Any:
+ """Pinned copy of ``src``; torchao wrapper subclasses are rebuilt from pinned inner tensors like ``PinnedArena.pin``."""
+ import torch
+ from torch.utils._python_dispatch import is_traceable_wrapper_subclass
+
+ from .diffusion_memory import registered_host_copy
+ from .diffusion_pinned_arena import _packable
+
+ if is_traceable_wrapper_subclass(src):
+ names, ctx = src.__tensor_flatten__()
+ inner = {name: _pin_host_tensor(getattr(src, name)) for name in names}
+ return type(src).__tensor_unflatten__(inner, ctx, src.size(), src.stride())
+ if type(src) is torch.Tensor and _packable(src):
+ try:
+ return registered_host_copy(src)
+ except Exception: # noqa: BLE001 -- registration refused: the allocator's pin for this tensor
+ pass
+ return src.pin_memory()
+
+
+def _reads(tensor: Any, src: Any) -> bool:
+ try:
+ if getattr(tensor, "device", None) is None or tensor.device.type != "cpu":
+ return False
+ mine, theirs = _host_leaves(tensor), _host_leaves(src)
+ return len(mine) == len(theirs) and all(
+ a.data_ptr() == b.data_ptr() for a, b in zip(mine, theirs)
+ )
+ except Exception: # noqa: BLE001 -- unreadable: leave it, its next offload re-points it
+ return False
+
+
+def _h3_block_pinner_cls() -> Any:
+ from .diffusion_memory import _FAST_PIN_THREADS, _bump_placement_epoch, _GroupPinner
+ from .diffusion_pinned_arena import _repoint
+
+ class _H3BlockPinner(_GroupPinner):
+ """Pins torchao weights too and re-reads the budget per group; refused groups are pinned per onload."""
+
+ def __init__(
+ self,
+ module: Any,
+ groups: list,
+ device: Any,
+ logger: Any = None,
+ admit: Any = None,
+ ):
+ super().__init__(module, groups, device, logger, fast = True)
+ self.admit = admit
+ self.groups_pinned = 0
+ self.stopped_at: Optional[int] = None
+ # (seconds since start, pinned bytes) after each group
+ self.timeline: list = []
+
+ def _unpinned(self, group: Any) -> list:
+ out = []
+ for tensor, src in list(group.cpu_param_dict.items()):
+ if getattr(src, "device", None) is None or src.device.type != "cpu":
+ continue
+ leaves = _host_leaves(src)
+ if leaves and not all(leaf.is_pinned() for leaf in leaves):
+ out.append((tensor, src))
+ return out
+
+ def _run(self) -> None:
+ import time
+
+ import torch
+
+ start = time.perf_counter()
+ failed = None
+ pool = None
+ try:
+ if (
+ getattr(self.device, "type", None) == "cuda"
+ and getattr(self.device, "index", None) is not None
+ ):
+ torch.cuda.set_device(self.device)
+ from concurrent.futures import ThreadPoolExecutor
+
+ pool = ThreadPoolExecutor(
+ max_workers = _FAST_PIN_THREADS,
+ thread_name_prefix = "unsloth-fast-pin",
+ initializer = torch.cuda.set_device,
+ initargs = (torch.cuda.current_device(),),
+ )
+ order = list(self.groups)
+ queued: dict = {}
+ nxt = 0
+ for i, group in enumerate(order):
+ if self._stop.is_set():
+ break
+ while (
+ nxt < min(i + 1 + _H3_PIN_LOOKAHEAD, len(order)) and self.stopped_at is None
+ ):
+ ahead = order[nxt]
+ if self.admit is not None and not self.admit(ahead):
+ self.stopped_at = nxt
+ break
+ queued[id(ahead)] = [
+ (tensor, src, pool.submit(_pin_host_tensor, src))
+ for tensor, src in self._unpinned(ahead)
+ ]
+ nxt += 1
+ if id(group) not in queued:
+ break
+ placed = [
+ (tensor, src, self._fast_result(future, src))
+ for tensor, src, future in queued.pop(id(group))
+ ]
+ cpu = group.cpu_param_dict
+ for tensor, src, pinned in placed:
+ if cpu.get(tensor) is src:
+ cpu[tensor] = pinned
+ if _reads(tensor, src):
+ _repoint(tensor, pinned)
+ self.pinned += sum(leaf.nbytes for leaf in _host_leaves(src))
+ del placed
+ self.groups_pinned += 1
+ self.timeline.append((time.perf_counter() - start, self.pinned))
+ # Done before the epoch: a capture check that sees the new epoch must also see this group ready.
+ self._done[id(group)].set()
+ _bump_placement_epoch()
+ except Exception as exc: # noqa: BLE001 -- the rest is pinned per onload
+ failed = exc
+ finally:
+ if pool is not None:
+ pool.shutdown(wait = True, cancel_futures = True)
+ for event in self._done.values():
+ event.set()
+ if failed is not None:
+ _bump_placement_epoch()
+ if self.logger is not None:
+ try:
+ if failed is not None:
+ self.logger.warning(
+ "video.h3_block_pin: background pin stopped (%s); the rest pins on each onload",
+ failed,
+ )
+ self.logger.info(
+ "video.h3_block_pin: %d of %d streamed block groups pinned in place in the background "
+ "(%.2f GB in %.1f s, onloads waited %.1f s%s)",
+ self.groups_pinned,
+ len(self.groups),
+ self.pinned / 1e9,
+ time.perf_counter() - start,
+ self.waited_s,
+ ", stopped by the pin budget" if self.stopped_at is not None else "",
+ )
+ except Exception: # noqa: BLE001
+ pass
+
+ return _H3BlockPinner
+
+
+def defer_streamed_block_pins(
+ pipe: Any,
+ transformer: Any,
+ device: Any,
+ logger: Any = None,
+) -> Any:
+ """``pin_streamed_block_groups`` on Studio's background pinner: the same in-place pin, off the load path.
+
+ Each group's onload waits for its pin, so nothing reads a copy being replaced. Returns the pinner, or None for
+ the up-front pin. ``UNSLOTH_H3_BACKGROUND_BLOCK_PIN=0`` off."""
+ off = ("0", "off", "false", "no")
+ if str(os.environ.get(H3_BLOCK_PIN_ENV, "")).strip().lower() in off:
+ return None
+ if str(os.environ.get(H3_BLOCK_BACKGROUND_PIN_ENV, "")).strip().lower() in off:
+ return None
+ _top, blocks = h3_offload_groups(transformer)
+ lazy = [
+ g
+ for g in blocks
+ if getattr(g, "low_cpu_mem_usage", False)
+ and getattr(g, "stream", None) is not None
+ and not getattr(g, "offload_to_disk_path", None)
+ and isinstance(getattr(g, "cpu_param_dict", None), dict)
+ and not is_resident(g)
+ ]
+ if not blocks or len(lazy) != len(blocks):
+ return None
+ from .diffusion_memory import (
+ _PENDING_PINS_ATTR,
+ _background_pin_enabled,
+ _fast_pin_supported,
+ _pinned_memory_capped,
+ install_group_pin_wait,
+ )
+ from .diffusion_pinned_arena import pin_arena_enabled
+ from .video_minimax_h3_te import h3_te_pin_allowed
+
+ if not pin_arena_enabled() or _pinned_memory_capped():
+ return None
+ if not _background_pin_enabled() or not _fast_pin_supported():
+ return None
+ for group in lazy:
+ cpu = group.cpu_param_dict
+ for tensor in _group_tensors(group):
+ if (
+ getattr(tensor, "device", None) is None
+ or tensor.device.type != "cpu"
+ or tensor not in cpu
+ ):
+ return None
+ if not h3_te_pin_allowed(group_payload_bytes(lazy[0])):
+ return None
+ pending = getattr(pipe, _PENDING_PINS_ATTR, None)
+ if pending is None:
+ pending = []
+ try:
+ setattr(pipe, _PENDING_PINS_ATTR, pending)
+ except Exception: # noqa: BLE001 -- nowhere to park it: pin up front
+ return None
+ install_group_pin_wait()
+ pinner = _h3_block_pinner_cls()(
+ transformer,
+ lazy,
+ device,
+ logger,
+ admit = lambda g: h3_te_pin_allowed(group_payload_bytes(g)),
+ )
+ # cpu_param_dict already maps each tensor to its pageable host copy; onloads read it until the pin swaps it
+ for group in lazy:
+ group.low_cpu_mem_usage = False
+ pending.append(pinner)
+ pinner.start()
+ if logger is not None:
+ logger.info(
+ "video.h3_block_pin: pinning %d streamed block groups in place in the background (%.2f GB)",
+ len(lazy),
+ sum(group_payload_bytes(g) for g in lazy) / 1e9,
+ )
+ return pinner
+
+
H3_STREAM_PREFETCH_ENV = "UNSLOTH_H3_STREAM_PREFETCH"
diff --git a/studio/backend/tests/test_h3_background_block_pin.py b/studio/backend/tests/test_h3_background_block_pin.py
new file mode 100644
index 00000000000..b24c3dc1f06
--- /dev/null
+++ b/studio/backend/tests/test_h3_background_block_pin.py
@@ -0,0 +1,264 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Background in-place block pin for a lazily streamed H3 denoiser: per-group waits, budget, bit-identical output."""
+
+from __future__ import annotations
+
+import copy
+import threading
+
+import pytest
+
+torch = pytest.importorskip("torch")
+pytest.importorskip("diffusers.hooks")
+
+import core.inference.diffusion_memory as dm # noqa: E402
+import core.inference.video_minimax_h3_residency as res # noqa: E402
+import core.inference.video_minimax_h3_te as te # noqa: E402
+
+
[email protected](autouse = True)
+def _clean_env(monkeypatch):
+ for name in (
+ res.H3_BLOCK_PIN_ENV,
+ res.H3_BLOCK_BACKGROUND_PIN_ENV,
+ res.H3_STREAM_PREFETCH_ENV,
+ dm.BACKGROUND_PIN_ENV,
+ dm.FAST_PIN_ENV,
+ "UNSLOTH_DIFFUSION_PIN_ARENA",
+ "UNSLOTH_DIFFUSION_GROUP_OFFLOAD_PIN",
+ "UNSLOTH_H3_TOP_GROUP_PIN",
+ ):
+ monkeypatch.delenv(name, raising = False)
+ monkeypatch.setattr(dm, "_pinned_memory_capped", lambda: False)
+
+
+def _cuda():
+ if not torch.cuda.is_available():
+ pytest.skip("needs CUDA: registered pins and diffusers stream group offload")
+
+
+class _Pipe:
+ pass
+
+
+class _Block(torch.nn.Module):
+ def __init__(self, width):
+ super().__init__()
+ self.lin = torch.nn.Linear(width, width)
+
+ def forward(self, x):
+ return torch.nn.functional.gelu(self.lin(x))
+
+
+class _DiT(torch.nn.Module):
+ def __init__(
+ self,
+ width = 256,
+ blocks = 6,
+ ):
+ super().__init__()
+ self.proj_in = torch.nn.Linear(64, width)
+ self.transformer_blocks = torch.nn.ModuleList(_Block(width) for _ in range(blocks))
+ self.proj_out = torch.nn.Linear(width, 64)
+
+ def forward(self, x):
+ x = self.proj_in(x)
+ for block in self.transformer_blocks:
+ x = block(x)
+ return self.proj_out(x)
+
+
+def _lazy_stream(net):
+ import inspect
+
+ from diffusers.hooks import apply_group_offloading
+
+ from core.inference.diffusion_prequant import _move_groups_outside_inference_mode
+
+ params = inspect.signature(apply_group_offloading).parameters
+ if "record_stream" not in params or "low_cpu_mem_usage" not in params:
+ pytest.skip("diffusers without record_stream / low_cpu_mem_usage")
+ apply_group_offloading(
+ net,
+ onload_device = torch.device("cuda"),
+ offload_device = torch.device("cpu"),
+ offload_type = "block_level",
+ num_blocks_per_group = 1,
+ use_stream = True,
+ record_stream = True,
+ non_blocking = True,
+ low_cpu_mem_usage = True,
+ )
+ _move_groups_outside_inference_mode(net)
+ return net
+
+
+def _host_ptrs(net):
+ return [b.lin.weight.data_ptr() for b in net.transformer_blocks]
+
+
+def test_pin_host_tensor_keeps_bits_and_rebuilds_wrapper_subclasses():
+ _cuda()
+ src = torch.randn(33, 17).to(torch.bfloat16)
+ out = res._pin_host_tensor(src)
+ assert out.is_pinned() and torch.equal(out, src) and out.data_ptr() != src.data_ptr()
+ torchao = pytest.importorskip("torchao")
+ from torchao.quantization import quantize_
+
+ try:
+ from torchao.quantization import Int8WeightOnlyConfig as Cfg
+ except ImportError:
+ pytest.skip(f"torchao {torchao.__version__} has no Int8WeightOnlyConfig")
+ lin = torch.nn.Linear(64, 64).to(torch.bfloat16)
+ quantize_(lin, Cfg())
+ weight = lin.weight
+ pinned = res._pin_host_tensor(weight)
+ assert type(pinned) is type(weight)
+ leaves, want = res._host_leaves(pinned), res._host_leaves(weight)
+ assert leaves and len(leaves) == len(want)
+ for a, b in zip(leaves, want):
+ assert a.is_pinned() and torch.equal(a, b)
+
+
[email protected]("prefetch", [True, False])
+def test_background_pin_streams_bit_identical_and_frees_the_pageable_copy(monkeypatch, prefetch):
+ _cuda()
+ from core.inference.diffusion_offload_prefetch import module_prefetcher
+
+ monkeypatch.setattr(te, "h3_te_pin_allowed", lambda *_a, **_k: True)
+ if not prefetch:
+ monkeypatch.setenv(res.H3_STREAM_PREFETCH_ENV, "0")
+ torch.manual_seed(0)
+ net = _DiT().eval()
+ ref = copy.deepcopy(net).cuda()
+ _lazy_stream(net)
+ pageable = _host_ptrs(net)
+ assert res.pin_streamed_top_level_group(net)
+ pipe = _Pipe()
+ gate = threading.Event()
+ real = res._pin_host_tensor
+ # hold the first copy so the install below runs while the pin is still in flight
+ monkeypatch.setattr(res, "_pin_host_tensor", lambda src: (gate.wait(5), real(src))[1])
+ pinner = res.defer_streamed_block_pins(pipe, net, torch.device("cuda"), logger = None)
+ assert pinner is not None and pinner in pipe._unsloth_background_pins
+ _top, blocks = res.h3_offload_groups(net)
+ assert all(not g.low_cpu_mem_usage for g in blocks)
+ covered = res.install_h3_stream_prefetch(net, "cuda")
+ assert (covered == 1 + len(blocks)) is prefetch
+ assert (module_prefetcher(net) is not None) is prefetch
+ gate.set()
+ if not covered:
+ pinner.join()
+ dm.finish_background_pins(pipe)
+ assert pinner.groups_pinned == len(blocks) and pinner.stopped_at is None
+ for block, old in zip(net.transformer_blocks, pageable):
+ weight = block.lin.weight
+ assert weight.device.type == "cpu" and weight.is_pinned() and weight.data_ptr() != old
+ x = torch.randn(8, 64, device = "cuda")
+ with torch.inference_mode():
+ want = ref(x)
+ for _ in range(3):
+ assert torch.equal(net(x), want)
+ dm.stop_background_pins(pipe)
+
+
+def test_an_onload_waits_for_its_groups_pin(monkeypatch):
+ _cuda()
+ monkeypatch.setattr(te, "h3_te_pin_allowed", lambda *_a, **_k: True)
+ torch.manual_seed(0)
+ net = _DiT(blocks = 4).eval()
+ ref = copy.deepcopy(net).cuda()
+ _lazy_stream(net)
+ assert res.pin_streamed_top_level_group(net)
+ gate = threading.Event()
+ real = res._pin_host_tensor
+ monkeypatch.setattr(res, "_pin_host_tensor", lambda src: (gate.wait(5), real(src))[1])
+ pipe = _Pipe()
+ pinner = res.defer_streamed_block_pins(pipe, net, torch.device("cuda"))
+ assert res.install_h3_stream_prefetch(net, "cuda") > 0
+ threading.Timer(0.3, gate.set).start()
+ x = torch.randn(8, 64, device = "cuda")
+ # no finish_background_pins: the forward itself must wait per group and still read the right bits
+ with torch.inference_mode():
+ assert torch.equal(net(x), ref(x))
+ assert pinner.waited_s > 0
+ pinner.join()
+ assert pinner.groups_pinned == 4
+
+
+def test_budget_reread_per_group_stops_and_leaves_the_rest_pageable(monkeypatch):
+ _cuda()
+ torch.manual_seed(0)
+ net = _DiT(blocks = 5).eval()
+ ref = copy.deepcopy(net).cuda()
+ _lazy_stream(net)
+ monkeypatch.setattr(te, "h3_te_pin_allowed", lambda *_a, **_k: True)
+ assert res.pin_streamed_top_level_group(net)
+ answers = iter([True, True, True, False])
+ monkeypatch.setattr(te, "h3_te_pin_allowed", lambda *_a, **_k: next(answers, False))
+ pipe = _Pipe()
+ pinner = res.defer_streamed_block_pins(pipe, net, torch.device("cuda"))
+ assert res.install_h3_stream_prefetch(net, "cuda") > 0
+ dm.finish_background_pins(pipe)
+ assert pinner.groups_pinned == 2 and pinner.stopped_at == 2
+ pinned = [b.lin.weight.is_pinned() for b in net.transformer_blocks]
+ assert pinned == [True, True, False, False, False]
+ x = torch.randn(8, 64, device = "cuda")
+ with torch.inference_mode():
+ want = ref(x)
+ for _ in range(2):
+ assert torch.equal(net(x), want)
+
+
+class _FakeGroup:
+ def __init__(self, lazy = True):
+ self.low_cpu_mem_usage = lazy
+ self.stream = object()
+ self.offload_to_disk_path = None
+ lin = torch.nn.Linear(4, 4)
+ self.modules = [lin]
+ self.parameters = []
+ self.buffers = []
+ self.cpu_param_dict = {p: p.data for p in lin.parameters()}
+
+
+ "env, value",
+ [
+ (res.H3_BLOCK_PIN_ENV, "0"),
+ (res.H3_BLOCK_BACKGROUND_PIN_ENV, "0"),
+ (dm.BACKGROUND_PIN_ENV, "0"),
+ (dm.FAST_PIN_ENV, "0"),
+ ("UNSLOTH_DIFFUSION_PIN_ARENA", "0"),
+ ],
+)
+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.setenv(env, value)
+ pipe = _Pipe()
+ assert res.defer_streamed_block_pins(pipe, torch.nn.Module(), "cuda") is None
+ assert all(g.low_cpu_mem_usage for g in groups)
+ assert not getattr(pipe, "_unsloth_background_pins", None)
+
+
[email protected]("case", ["capped", "refused", "mixed", "none"])
+def test_hosts_and_layouts_the_up_front_pin_owns(monkeypatch, case):
+ groups = [_FakeGroup(lazy = case != "mixed" or i != 1) for i in range(3)]
+ if case == "none":
+ groups = []
+ 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)
+ 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] == [
+ case != "mixed" or i != 1 for i in range(len(groups))
+ ]