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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio MiniMax-H3: price the slab compaction against the host reserve so a 16 GiB L4 render is not OOM-killed (#16849)
Daniel Han8d54207a9bb0
diff --git a/studio/backend/core/inference/video_minimax_h3_residency.py b/studio/backend/core/inference/video_minimax_h3_residency.pyindex 9c19f2c0a9b..892acaf8884 100644--- a/studio/backend/core/inference/video_minimax_h3_residency.py+++ b/studio/backend/core/inference/video_minimax_h3_residency.py@@ -250,43 +250,161 @@ def _is_wrapper(tensor: Any) -> bool:# is compacted: those weights move to their own pinned copies so the slab is freed. Fraction of the slab still used.H3_COMPACT_MAX_LIVE_FRACTION = 0.25_H3_COMPACT_MIN_SLAB = 64 << 20+# The compaction's new pinned copies exist before any old slab is freed and pinned pages cannot be reclaimed: an L4 at+# a 16 GiB budget was OOM-killed when the first request's re-fit re-pinned 13.2 GB of whole weights next to a+# conditioner share sized to leave only the load's reserve. Priced (default): only the inner tensors that live in the+# compacted slab move, the move is checked against the load's reserve (the conditioner share yields first) and slabs+# that do not fit wait for a later re-fit. ``UNSLOTH_H3_COMPACT_PRICED=0`` restores the unpriced whole-weight move.+H3_COMPACT_PRICED_ENV = "UNSLOTH_H3_COMPACT_PRICED"-def compact_host_slabs(groups: list, logger: Any = None) -> int:+def h3_compact_priced_enabled() -> bool:+ return str(os.environ.get(H3_COMPACT_PRICED_ENV, "")).strip().lower() not in (+ "0",+ "off",+ "false",+ "no",+ )+++def _storage_key(leaf: Any) -> Optional[int]:+ try:+ if leaf.device.type != "cpu" or leaf.numel() == 0:+ return None+ return int(leaf.untyped_storage().data_ptr())+ except Exception: # noqa: BLE001 -- no storage (meta / sparse): never compacted+ return None+++def _pin_cost(leaf: Any) -> int:+ """Pinned bytes ``_pin_host_tensor`` takes for plain ``leaf``: page-exact when registered, else the host+ allocator's power-of-two block."""+ import torch++ from .diffusion_pinned_arena import _packable, _pow2_ceil++ nbytes = int(leaf.numel()) * int(leaf.element_size())+ if type(leaf) is torch.Tensor and _packable(leaf):+ return -(-nbytes // 4096) * 4096+ return _pow2_ceil(nbytes)+++def _repin_leaves_in(+ src: Any,+ keys: set,+ depth: int = 0,+) -> tuple[Any, int]:+ """``src`` with only its inner tensors stored in one of ``keys`` re-pinned (exact copies); the others are shared.+ Returns ``(src, 0)`` when none is."""+ from torch.utils._python_dispatch import is_traceable_wrapper_subclass++ if depth < 4 and is_traceable_wrapper_subclass(src):+ names, ctx = src.__tensor_flatten__()+ inner = {}+ moved = 0+ for name in names:+ inner[name], n = _repin_leaves_in(getattr(src, name), keys, depth + 1)+ moved += n+ if not moved:+ return src, 0+ return type(src).__tensor_unflatten__(inner, ctx, src.size(), src.stride()), moved+ if _storage_key(src) not in keys:+ return src, 0+ return _pin_host_tensor(src), int(src.numel()) * int(src.element_size())+++def _compact_headroom_bytes(cost: int, host_yield: Any, logger: Any) -> Optional[int]:+ """Bytes of new pinned copies the host can take above the load's reserve, after asking ``host_yield`` (the+ conditioner's resident share) for the deficit. None when host RAM is unreadable (no bound)."""+ from .diffusion_small_host import encoder_resident_keep_mib, host_ram_mib++ total, available = host_ram_mib()+ if available is None:+ return None+ keep = max(H3_REBUILD_KEEP_MIB, int(encoder_resident_keep_mib(total)))+ deficit = -(-cost >> 20) + keep - int(available)+ if deficit > 0 and host_yield is not None:+ try:+ host_yield(deficit << 20)+ except Exception as exc: # noqa: BLE001 -- price against what is available now+ if logger is not None:+ logger.warning(+ "video.h3_residency: host RAM yield before a compaction failed: %s", exc+ )+ _total, now = host_ram_mib()+ if now is not None:+ available = now+ return max(0, int(available) - keep) << 20+++def compact_host_slabs(+ groups: list,+ logger: Any = None,+ *,+ host_yield: Any = None,+ report: Optional[dict] = None,+) -> int:"""Move the host weights that keep a mostly-released pinned slab alive into fresh pinned copies (exact copies,- re-pointed like the arena's own pin), so the slab returns to the OS. Returns bytes of slabs freed (estimated)."""+ re-pointed like the arena's own pin), so the slab returns to the OS. Returns bytes of slabs freed (estimated).+ ``report["deferred"]``: eligible slabs left for a later call because their copies did not fit the host reserve."""from .diffusion_pinned_arena import _repoint+ priced = h3_compact_priced_enabled()live: dict = {}sizes: dict = {}for group in groups:cpu = getattr(group, "cpu_param_dict", None) or {}for tensor, host in list(cpu.items()):for leaf in _host_leaves(host):- if leaf.device.type != "cpu":+ key = _storage_key(leaf)+ if key is None:continue- storage = leaf.untyped_storage()- key = storage.data_ptr()- sizes[key] = int(storage.nbytes())+ sizes[key] = int(leaf.untyped_storage().nbytes())live.setdefault(key, []).append(- (group, tensor, host, int(leaf.numel()) * int(leaf.element_size()))+ (group, tensor, host, int(leaf.numel()) * int(leaf.element_size()), leaf))+ eligible = [+ key+ for key, entries in live.items()+ if sizes[key] >= _H3_COMPACT_MIN_SLAB+ and sum(e[3] for e in entries) <= H3_COMPACT_MAX_LIVE_FRACTION * sizes[key]+ ]+ chosen = eligible+ deferred = 0+ if priced and eligible:+ costs = {key: sum(_pin_cost(e[4]) for e in live[key]) for key in eligible}+ room = _compact_headroom_bytes(sum(costs.values()), host_yield, logger)+ if room is not None:+ chosen = []+ for key in eligible:+ if costs[key] <= room:+ chosen.append(key)+ room -= costs[key]+ deferred = len(eligible) - len(chosen)+ keys = set(chosen)freed = moved = 0- for key, entries in live.items():- size = sizes[key]- used = sum(e[3] for e in entries)- if size < _H3_COMPACT_MIN_SLAB or used > H3_COMPACT_MAX_LIVE_FRACTION * size:- continue- for group, tensor, host, _n in entries:+ for key in chosen:+ for group, tensor, host, _n, _leaf in live[key]:cpu = group.cpu_param_dictif cpu.get(tensor) is not host:continue # already moved through another leaf- new = _pin_host_tensor(host)+ if priced:+ new, n = _repin_leaves_in(host, keys)+ else:+ new, n = _pin_host_tensor(host), _host_leaf_bytes(host)cpu[tensor] = newif _reads(tensor, host):_repoint(tensor, new)- moved += _host_leaf_bytes(host)- freed += size+ moved += n+ freed += sizes[key]+ del live+ if report is not None:+ report["deferred"] = deferred+ if deferred and logger is not None:+ logger.info(+ "video.h3_residency: %d pinned slab(s) left for a later re-fit (their copies do not fit the host reserve)",+ deferred,+ )if freed:try:from .diffusion_offload_prefetch import bump_placement_epoch@@ -392,6 +510,9 @@ class H3Residency:self.host_top_up: Any = Noneself.released_bytes = 0self.topped_bytes = 0+ # bytes of slabs the last ``apply`` compacted; a compaction that could not fit every slab retries next re-fit+ self.compacted_bytes = 0+ self.compact_pending = False@propertydef usable(self) -> bool:@@ -443,13 +564,21 @@ class H3Residency:make_resident(self.blocks[i])# Block groups only: the top-level group keeps its own pinned copy (it is re-pinned by its own path).freed = sum(release_host_copy(self.blocks[i], logger = self.logger) for i in range(n))- if freed:+ self.compacted_bytes = 0+ if freed or getattr(self, "compact_pending", False):groups = list(self.blocks) + ([self.top] if self.top is not None else [])+ report: dict = {}try:- compact_host_slabs(groups, logger = self.logger)+ self.compacted_bytes = compact_host_slabs(+ groups,+ logger = self.logger,+ host_yield = getattr(self, "host_yield", None),+ report = report,+ )except Exception as exc: # noqa: BLE001 -- the released copies are still droppedif self.logger is not None:self.logger.warning("video.h3_residency: slab compaction skipped: %s", exc)+ self.compact_pending = bool(report.get("deferred"))_host_empty_cache()self.released_bytes = sum(released_host_bytes(g) for g in self.blocks)@@ -466,7 +595,9 @@ class H3Residency:self.max_blocks = nreleased = getattr(self, "released_bytes", 0)top_up = getattr(self, "host_top_up", None)- if released > getattr(self, "topped_bytes", 0) and callable(top_up):+ # A compaction may have taken the conditioner share back to fit its copies: it is re-sized after the pins.+ compacted = getattr(self, "compacted_bytes", 0) and h3_compact_priced_enabled()+ if (released > getattr(self, "topped_bytes", 0) or compacted) and callable(top_up):try:top_up()except Exception as exc: # noqa: BLE001 -- the conditioner stays mappeddiff --git a/studio/backend/tests/test_h3_compact_priced.py b/studio/backend/tests/test_h3_compact_priced.pynew file mode 100644index 00000000000..b0588180655--- /dev/null+++ b/studio/backend/tests/test_h3_compact_priced.py@@ -0,0 +1,217 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""MiniMax-H3 streamed denoiser: the slab compaction after a re-fit pins new copies before any old slab is freed. On+an L4 at a 16 GiB budget the first request's re-fit re-pinned 13.2 GB of whole weights next to a conditioner share+sized to leave only the load's reserve, and the renderer was OOM-killed. The compaction now moves only the inner+tensors that live in the compacted slab, checks the move against the reserve (the conditioner share yields first),+defers slabs that do not fit, and re-sizes the share after the pins exist."""++from __future__ import annotations++import types++import pytest++torch = pytest.importorskip("torch")++KEEP_MIB = 7982+++class _Q(torch.Tensor):+ """A minimal traceable wrapper subclass (int8 data + scale), like the hosted int8 denoiser's weights."""++ @staticmethod+ def __new__(cls, qdata, scale):+ return torch.Tensor._make_wrapper_subclass(+ cls, qdata.shape, dtype = torch.float32, device = qdata.device+ )++ def __init__(self, qdata, scale):+ self.qdata = qdata+ self.scale = scale++ def __tensor_flatten__(self):+ return ["qdata", "scale"], None++ @staticmethod+ def __tensor_unflatten__(inner, ctx, size, stride):+ return _Q(inner["qdata"], inner["scale"])++ @classmethod+ def __torch_dispatch__(+ cls,+ func,+ types,+ args = (),+ kwargs = None,+ ):+ raise NotImplementedError(func)+++MIB = 1 << 20+++def _layout():+ """``healthy``: a slab fully used by one weight's 8 MiB int8 data. ``tail``: a 64 MiB slab whose only live bytes+ are that weight's scale (the rest belonged to now-resident blocks)."""+ healthy = torch.zeros(8 * MIB, dtype = torch.int8)+ tail = torch.zeros(16 * MIB, dtype = torch.float32)+ healthy.copy_(torch.randint(-128, 127, (8 * MIB,), dtype = torch.int8))+ tail[:256].copy_(torch.randn(256))+ qd = healthy.view(1024, 8192)+ sc = tail[:256]+ param = _Q(qd, sc)+ host = _Q(qd, sc)+ group = types.SimpleNamespace(cpu_param_dict = {param: host})+ return group, param, host, healthy, tail+++class _FakeHost:+ """MemAvailable that pinned copies consume and the conditioner share's yield gives back."""++ def __init__(self, available_mib: float):+ self.available = float(available_mib)+ self.floor = self.available+ self.yields: list = []+ self.events: list = []++ def ram(self):+ return 53000, int(self.available)++ def pin(self, src):+ if isinstance(src, _Q):+ return _Q(self.pin(src.qdata), self.pin(src.scale))+ self.available -= src.numel() * src.element_size() / MIB+ self.floor = min(self.floor, self.available)+ self.events.append("pin")+ return src.clone()++ def host_yield(self, nbytes):+ self.yields.append(nbytes)+ self.events.append("yield")+ self.available += nbytes / MIB+ return nbytes++[email protected](autouse = True)+def _env(monkeypatch):+ from core.inference import diffusion_small_host+ from core.inference import video_minimax_h3_residency as res++ monkeypatch.setattr(torch.cuda, "is_available", lambda: False)+ monkeypatch.delenv("UNSLOTH_H3_COMPACT_PRICED", raising = False)+ monkeypatch.delenv("UNSLOTH_H3_RESIDENT_UNPIN", raising = False)+ monkeypatch.setattr(res, "_H3_COMPACT_MIN_SLAB", 0)+ monkeypatch.setattr(diffusion_small_host, "encoder_resident_keep_mib", lambda total: KEEP_MIB)+++def _install(monkeypatch, host: _FakeHost):+ from core.inference import diffusion_small_host+ from core.inference import video_minimax_h3_residency as res++ monkeypatch.setattr(diffusion_small_host, "host_ram_mib", host.ram)+ monkeypatch.setattr(res, "_pin_host_tensor", host.pin)+++def test_only_the_inner_tensor_in_the_slab_moves(monkeypatch):+ """The scale in the dying slab moves; the 8 MiB int8 data in its own healthy slab is not copied again."""+ from core.inference import video_minimax_h3_residency as res++ host = _FakeHost(KEEP_MIB + 4096)+ _install(monkeypatch, host)+ group, param, old, healthy, tail = _layout()+ want_q, want_s = old.qdata.clone(), old.scale.clone()+ assert res.compact_host_slabs([group]) > 0+ new = group.cpu_param_dict[param]+ assert new.qdata.data_ptr() == healthy.data_ptr() # shared, not re-pinned+ assert new.scale.untyped_storage().data_ptr() != tail.untyped_storage().data_ptr()+ assert torch.equal(new.qdata, want_q) and torch.equal(new.scale, want_s)+ assert param.scale.data_ptr() == new.scale.data_ptr() # the streamed weight reads its new copy+ assert host.available > KEEP_MIB + 4096 - 1 # 1 KiB pinned, not 8 MiB+++def test_the_compaction_never_takes_the_host_under_the_load_reserve(monkeypatch):+ """The L4 16 GiB OOM: the conditioner share left exactly the reserve; the compaction's pins must not eat it."""+ from core.inference import video_minimax_h3_residency as res++ host = _FakeHost(KEEP_MIB + 2)+ _install(monkeypatch, host)+ group, *_ = _layout()+ res.compact_host_slabs([group])+ assert host.floor >= KEEP_MIB+++def test_the_conditioner_share_yields_before_the_compaction_pins(monkeypatch):+ from core.inference import video_minimax_h3_residency as res++ host = _FakeHost(KEEP_MIB) # share sized to leave exactly the reserve+ _install(monkeypatch, host)+ group, param, old, _healthy, tail = _layout()+ freed = res.compact_host_slabs([group], host_yield = host.host_yield)+ assert host.events[0] == "yield" and "pin" in host.events+ assert host.yields == [+ 1 * MIB+ ] # the move's cost (1 KiB, priced at one page, rounded up to a MiB)+ assert freed == tail.untyped_storage().nbytes()+ assert host.floor >= KEEP_MIB+++def test_a_slab_that_does_not_fit_waits_for_a_later_refit(monkeypatch):+ """Nothing to yield and no room: the slab stays, nothing is pinned, and the next re-fit retries it."""+ from core.inference import video_minimax_h3_residency as res++ host = _FakeHost(KEEP_MIB - 100)+ _install(monkeypatch, host)+ group, param, old, _healthy, tail = _layout()+ report: dict = {}+ assert res.compact_host_slabs([group], host_yield = lambda n: 0, report = report) == 0+ assert report["deferred"] == 1 and "pin" not in host.events+ assert group.cpu_param_dict[param] is old++ r = res.H3Residency.__new__(res.H3Residency)+ r.top, r.blocks, r.block_bytes, r.logger = None, [group], [0], None+ r.host_yield, r.host_top_up = None, None+ r.released_bytes = r.topped_bytes = r.compacted_bytes = 0+ r.compact_pending = True+ host.available = KEEP_MIB + 100+ r.apply(False, 0) # no new release: the pending slab is compacted anyway+ assert not r.compact_pending and r.compacted_bytes == tail.untyped_storage().nbytes()+ assert (+ group.cpu_param_dict[param].scale.untyped_storage().data_ptr()+ != tail.untyped_storage().data_ptr()+ )+++def test_the_share_is_resized_after_a_compaction(monkeypatch):+ """A re-fit whose compaction took RAM from the conditioner share tops the share up after the pins exist."""+ from core.inference import video_minimax_h3_residency as res++ calls = []+ r = res.H3Residency.__new__(res.H3Residency)+ r.top, r.blocks, r.block_bytes, r.logger = None, [], [], None+ r.max_blocks = 0+ r.host_yield = None+ r.host_top_up = lambda: calls.append(1)+ r.released_bytes = r.topped_bytes = 0+ r.compact_pending = False++ def apply(top, n):+ r.compacted_bytes = 64 * MIB+ r.released_bytes = 0++ monkeypatch.setattr(r, "apply", apply)+ r.fit(0)+ assert calls == [1]+++def test_the_kill_switch_moves_whole_weights_unpriced(monkeypatch):+ from core.inference import video_minimax_h3_residency as res++ monkeypatch.setenv("UNSLOTH_H3_COMPACT_PRICED", "0")+ host = _FakeHost(KEEP_MIB)+ _install(monkeypatch, host)+ group, param, _old, healthy, _tail = _layout()+ assert res.compact_host_slabs([group], host_yield = host.host_yield) > 0+ assert host.yields == []+ assert group.cpu_param_dict[param].qdata.data_ptr() != healthy.data_ptr()