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: block-offload re-pins land at the addresses the step graph recorded (#14765)

Daniel Han0291ac9c3128
diff --git a/studio/backend/core/inference/diffusion_cuda_graph.py b/studio/backend/core/inference/diffusion_cuda_graph.py
index 8bd05a52197..b8ea363a293 100644
--- a/studio/backend/core/inference/diffusion_cuda_graph.py
+++ b/studio/backend/core/inference/diffusion_cuda_graph.py
@@ -1195,6 +1195,13 @@ class GraphedForward:
"traceback": traceback.format_exc()[-6000:],
}
self.poisoned = True
+ if (
+ getattr(self, "fallback", None) is None
+ and getattr(self, "fallback_handle", None) is None
+ ):
+ # A pending or armed per-block fallback still keys its graphs on the resident groups' addresses: the
+ # stable re-pin stays until it is known to be gone (``_engage_fallback`` / ``free``).
+ _retire_stable_placement(self.placement)
# ``__call__`` short-circuits to eager on ``poisoned`` before it reads the cache, so every
# entry is now unreachable and only pins its statics, outputs and slice of the pool for the
# life of the load. Freeing is left to the caller's ``_release``, which runs once the failed
@@ -1218,6 +1225,7 @@ class GraphedForward:
self.uninstall()
if self.placement is not None:
self.placement.release_slots()
+ _retire_stable_placement(getattr(self, "placement", None))
self.enabled = False
_LIVE_WRAPPERS.discard(self)
return self
@@ -1296,6 +1304,13 @@ class GraphedForward:
if other != key:
self.cache.pop(other, None)
self._dropped.add(other)
+ if (
+ getattr(self, "fallback", None) is None
+ and getattr(self, "fallback_handle", None) is None
+ ):
+ _retire_stable_placement(
+ placement
+ ) # no per-block graphs either: nothing records again
self._slower = reason
self._dropped.add(key)
if self.logger is not None:
@@ -1402,6 +1417,10 @@ class GraphedForward:
args, kwargs = _rebuild(spec, live)
return self._eager(args, kwargs)
+ def _placement_declined(self) -> bool:
+ # A declined placement refuses every later recording for the load (a merely dropped key does not).
+ return getattr(getattr(self, "placement", None), "_declined", None) is not None
+
def _engage_fallback(self) -> None:
"""Arm the per-block graphs once this whole-step graph dropped a key or failed: the calls it now leaves eager
run through them. Between forwards' blocks (the step has not started), so the slot ring can change."""
@@ -1411,6 +1430,8 @@ class GraphedForward:
except Exception as exc: # noqa: BLE001
_warn(self.logger, "per-block fallback", exc)
self.fallback_handle = None
+ if self.fallback_handle is None and (self.poisoned or self._placement_declined()):
+ _retire_stable_placement(self.placement) # nothing left that records over the placement
if self.fallback_handle is not None and self.logger is not None:
self.logger.info(
"diffusion.cuda_graph: %s records per block for the steps its whole-step graph leaves eager",
@@ -1915,7 +1936,8 @@ class OffloadPlacement:
replaces the module's hooked forward, so ONE graph records the whole step: the copy-stream copies of every
streamed group from its pinned host tensor into the graph pool, the compute stream waiting on each copy's event,
and the resident groups read in place. The pool holds the in-flight window at fixed addresses, so it plays the
- prefetch ring. Recorded again when a residency change, a release / restore or a host-copy swap moves an address.
+ prefetch ring. Recorded again when a residency change or a host-copy swap moves an address. A prompt encode's
+ release / restore does not: once armed, the re-pin lands in each group's stable range (diffusion_stable_arena).
``model``: whole-module CPU offload (accelerate). By default only over the stable device range
(``diffusion_stable_arena``: every onload lands at the same addresses, so render 1's recording replays on every
@@ -2268,6 +2290,21 @@ def _detach_stable_range(module: Any) -> None:
pass
+def _retire_stable_placement(placement: Any) -> None:
+ """No graph of this placement can replay again (a poisoned or freed handle): stop paying for stable addresses. A
+ re-arm attaches afresh."""
+ if placement is None:
+ return
+ if placement.mode == "model":
+ _detach_stable_range(placement.module)
+ return
+ try:
+ from .diffusion_stable_arena import drop_stable_repin
+ drop_stable_repin(placement.module)
+ except Exception: # noqa: BLE001
+ pass
+
+
def _stable_range_failure(module: Any) -> Optional[str]:
"""Why ``module``'s stable range stopped placing its onloads, else None."""
try:
@@ -2393,6 +2430,10 @@ def arm_after_placement(
)
stable = placement.mode == "model" and _stable_range(module)
modes.append("model_stable" if stable else placement.mode)
+ if placement.mode == "group":
+ # Encode re-pins now land at the addresses this step records (diffusion_stable_arena.GroupRange).
+ from .diffusion_stable_arena import want_stable_repin
+ want_stable_repin(module)
except Exception as exc: # noqa: BLE001
if placement is not None and placement.mode == "model":
_detach_stable_range(module)
@@ -2691,6 +2732,11 @@ def stats(handles: Any) -> dict:
arena = arena_of(placement.module)
if arena is not None:
out["stable_range"] = arena.describe()
+ if placement is not None and placement.mode == "group":
+ from .diffusion_stable_arena import repin_stats
+ repin = repin_stats(placement.module)
+ if repin is not None:
+ out["stable_repin"] = repin
if handle.poisoned:
out["poisoned"] = True
error = handle.capture_error
diff --git a/studio/backend/core/inference/diffusion_measured_peaks.py b/studio/backend/core/inference/diffusion_measured_peaks.py
index ed5d49b097e..1b631288676 100644
--- a/studio/backend/core/inference/diffusion_measured_peaks.py
+++ b/studio/backend/core/inference/diffusion_measured_peaks.py
@@ -484,7 +484,8 @@ class PeakProbe:
self.window = open_window(dev)
torch.cuda.synchronize(dev)
torch.cuda.reset_peak_memory_stats(dev)
- self.base = int(torch.cuda.memory_allocated(dev))
+ _reset_range_peak(dev)
+ self.base = int(torch.cuda.memory_allocated(dev)) + _range_bytes(dev)
self.device = dev
except Exception: # noqa: BLE001 - measurement only
self.device = None
@@ -495,7 +496,13 @@ class PeakProbe:
try:
import torch
torch.cuda.synchronize(self.device)
- peak = int(torch.cuda.max_memory_allocated(self.device)) - self.base
+ # Stable-range bytes sit outside the allocator: count their high-water mark (not what is still mapped:
+ # a model-offload range is unmapped before decode ends) so the peak stays on the stock scale.
+ peak = (
+ int(torch.cuda.max_memory_allocated(self.device))
+ + _range_peak_bytes(self.device)
+ - self.base
+ )
except Exception: # noqa: BLE001
peak = None
# closed only after the read: a render arming in between would otherwise reset the peak unseen
@@ -504,6 +511,30 @@ class PeakProbe:
return -(-peak // (1024 * 1024)) if peak > 0 else None
+def _range_bytes(dev: Any) -> int:
+ try:
+ from .diffusion_stable_arena import mapped_bytes
+ return mapped_bytes(dev.index)
+ except Exception: # noqa: BLE001 - no stable ranges
+ return 0
+
+
+def _range_peak_bytes(dev: Any) -> int:
+ try:
+ from .diffusion_stable_arena import peak_mapped_bytes
+ return peak_mapped_bytes(dev.index)
+ except Exception: # noqa: BLE001 - no stable ranges
+ return 0
+
+
+def _reset_range_peak(dev: Any) -> None:
+ try:
+ from .diffusion_stable_arena import reset_peak_mapped
+ reset_peak_mapped(dev.index)
+ except Exception: # noqa: BLE001 - no stable ranges
+ pass
+
+
def current_device_name() -> Optional[str]:
"""Name of the current CUDA device (None without CUDA); the planner's snapshot reads this device."""
try:
diff --git a/studio/backend/core/inference/diffusion_memory.py b/studio/backend/core/inference/diffusion_memory.py
index a27622813c1..5133f7fa090 100644
--- a/studio/backend/core/inference/diffusion_memory.py
+++ b/studio/backend/core/inference/diffusion_memory.py
@@ -3760,21 +3760,12 @@ def _keep_groups_resident(
onload = torch.device(device)
left = int(room_mib) * 1024 * 1024
kept = 0
-
- def _tensors(group: Any) -> list:
- out: list = []
- seen: set[int] = set()
- for t in (
- [p for m in group.modules for p in m.parameters()]
- + [b for m in group.modules for b in m.buffers()]
- + list(group.parameters or [])
- + list(group.buffers or [])
- ):
- if id(t) not in seen:
- seen.add(id(t))
- out.append(t)
- return out
-
+ try:
+ from .diffusion_stable_arena import pin_group_in_range, stable_repin_wanted
+ stable = stable_repin_wanted(module)
+ except Exception: # noqa: BLE001 - re-pins move the stock way
+ stable = False
+ _tensors = _resident_tensors
disable = getattr(getattr(torch, "compiler", None), "disable", None)
def _noop(*args: Any, **kwargs: Any) -> None:
@@ -3838,8 +3829,35 @@ def _keep_groups_resident(
continue
for member in closure:
cpu = getattr(member, "cpu_param_dict", None) or {}
- for t in _tensors(member):
- if _placed_on(t, onload.type, is_torchao):
+ members_tensors = _tensors(member)
+ placed: set = set()
+ if stable and onload.type == "cuda":
+ # The step graph recorded the resident groups' addresses: a re-pin lands where the last one did.
+ try:
+ placed = pin_group_in_range(
+ module,
+ member,
+ members_tensors,
+ lambda t: not _placed_on(t, onload.type, is_torchao),
+ lambda t, cpu = cpu: cpu.get(t, t),
+ onload,
+ go._swap_torchao_tensor,
+ )
+ except Exception as exc: # noqa: BLE001 - the stock move still places the group
+ placed = set()
+ # Unmap an empty range so the stock move below does not pay for a second copy.
+ try:
+ from .diffusion_stable_arena import release_group_range
+ release_group_range(module, member, members_tensors)
+ except Exception: # noqa: BLE001
+ pass
+ if logger is not None:
+ logger.warning(
+ "diffusion.memory: stable re-pin range unavailable (%s); the group moves the stock way",
+ exc,
+ )
+ for t in members_tensors:
+ if id(t) in placed or _placed_on(t, onload.type, is_torchao):
continue
moved = cpu.get(t, t).to(onload)
if is_torchao(t):
@@ -3922,6 +3940,22 @@ def _streamed_group_count(groups: list) -> int:
)
+def _resident_tensors(group: Any) -> list:
+ """Every tensor of an offload group, each once (its modules' parameters, their buffers, then the group's own)."""
+ out: list = []
+ seen: set[int] = set()
+ for t in (
+ [p for m in group.modules for p in m.parameters()]
+ + [b for m in group.modules for b in m.buffers()]
+ + list(group.parameters or [])
+ + list(group.buffers or [])
+ ):
+ if id(t) not in seen:
+ seen.add(id(t))
+ out.append(t)
+ return out
+
+
def _release_group(group: Any) -> None:
onload_, offload_ = getattr(group, "_unsloth_streamed_hooks", (None, None))
for name, fn in (("onload_", onload_), ("offload_", offload_)):
@@ -3934,6 +3968,14 @@ def _release_group(group: Any) -> None:
_bump_placement_epoch()
+def _release_group_range(owner: Any, group: Any) -> None:
+ """A released group's weights are on their host copies again: its stable re-pin range gives the physical memory
+ back (the addresses stay reserved)."""
+ if "_unsloth_repin_range" in getattr(group, "__dict__", {}):
+ from .diffusion_stable_arena import release_group_range
+ release_group_range(owner, group, _resident_tensors(group))
+
+
def release_resident_groups(
pipe: Any,
need_mib: int,
@@ -4011,6 +4053,7 @@ def release_resident_groups(
# Recorded before demoting: a release that fails part way is still re-pinned by ``restore``.
streamed.add(id(member))
_release_group(member)
+ _release_group_range(module, member)
left -= int(getattr(member, "_unsloth_resident_bytes", 0))
if not released:
return None
diff --git a/studio/backend/core/inference/diffusion_stable_arena.py b/studio/backend/core/inference/diffusion_stable_arena.py
index 944658f6031..3fc0ac2d57d 100644
--- a/studio/backend/core/inference/diffusion_stable_arena.py
+++ b/studio/backend/core/inference/diffusion_stable_arena.py
@@ -16,6 +16,9 @@ ComfyUI does the same for its graph replays over offloaded weights (comfy_aimdo
Plain dense tensors (with their strides) and torchao-style wrapper weights (int8 / fp8: their plain inner tensors,
rebuilt over the range) are placed; a module holding any other parameter type (GGUF) is left to the stock hook.
Opt out with ``UNSLOTH_DIFFUSION_MODEL_OFFLOAD_ARENA=0``.
+
+Block offload uses the same ranges per resident group, for the groups a prompt encode streams and pins again
+(``GroupRange``, below; opt out with ``UNSLOTH_DIFFUSION_GROUP_REPIN_RANGE=0``).
"""
from __future__ import annotations
@@ -112,6 +115,37 @@ def _driver() -> Any:
return _LIB
+# Physical bytes mapped through every range, per CUDA ordinal: memory the caching allocator's counters do not see.
+_MAPPED: dict = {}
+# High-water mark of ``_MAPPED`` since the last ``reset_peak_mapped`` (the stable ranges' max_memory_allocated).
+_PEAK_MAPPED: dict = {}
+_MAPPED_LOCK = threading.Lock()
+
+
+def mapped_bytes(device_index: Optional[int]) -> int:
+ """Bytes currently mapped in stable ranges on ``device_index`` (outside ``torch.cuda.memory_allocated``)."""
+ with _MAPPED_LOCK:
+ return int(_MAPPED.get(device_index, 0))
+
+
+def peak_mapped_bytes(device_index: Optional[int]) -> int:
+ """Most bytes mapped at once on ``device_index`` since the last ``reset_peak_mapped``."""
+ with _MAPPED_LOCK:
+ return int(max(_PEAK_MAPPED.get(device_index, 0), _MAPPED.get(device_index, 0)))
+
+
+def reset_peak_mapped(device_index: Optional[int]) -> None:
+ with _MAPPED_LOCK:
+ _PEAK_MAPPED[device_index] = _MAPPED.get(device_index, 0)
+
+
+def _count_mapped(device_index: int, delta: int) -> None:
+ with _MAPPED_LOCK:
+ now = _MAPPED.get(device_index, 0) + int(delta)
+ _MAPPED[device_index] = now
+ _PEAK_MAPPED[device_index] = max(_PEAK_MAPPED.get(device_index, 0), now)
+
+
def _check(rc: int, what: str) -> None:
if rc != 0:
raise RuntimeError(f"{what} failed (CUresult {rc})")
@@ -221,8 +255,17 @@ class VmmArena:
except Exception:
lib.cuMemRelease(handle.value)
raise
+ try:
+ base = torch.as_tensor(_CudaArray(self.va, self.size), device = self.device)
+ except Exception:
+ # nothing may keep the mapping a failed map() leaves no tensor over: unmap and release it, so the
+ # arena is unmapped and retryable and the caller's stock fallback holds the only copy
+ lib.cuMemUnmap(self.va, self.size)
+ lib.cuMemRelease(handle.value)
+ raise
self._handle = int(handle.value)
- self._base = torch.as_tensor(_CudaArray(self.va, self.size), device = self.device)
+ self._base = base
+ _count_mapped(self.device_index, self.size)
self.maps += 1
return self._base
@@ -263,6 +306,7 @@ class VmmArena:
_check(lib.cuMemUnmap(self.va, self.size), "cuMemUnmap")
_check(lib.cuMemRelease(self._handle), "cuMemRelease")
self._handle = None
+ _count_mapped(self.device_index, -self.size)
self.unmaps += 1
def close(self) -> None:
@@ -353,7 +397,7 @@ class ModuleArena:
self.arena: Optional[VmmArena] = None
self.failed: Optional[str] = None
self.retiring = False
- self.stats = {"onloads": 0, "placed": 0, "stock": 0, "maps": 0, "unmaps": 0}
+ self.stats = {"onloads": 0, "placed": 0, "stock": 0, "maps": 0, "unmaps": 0, "rebuilds": 0}
self._module = weakref.ref(module)
self._stock_to = type(module).to
module.__dict__["to"] = self._to
@@ -380,7 +424,15 @@ class ModuleArena:
pass
def detach(self) -> None:
+ """Give the module its stock onload back and close the range. Detached while the weights still live in the
+ range (graphing stopped mid-render), it stops placing at once and finishes on the offload that moves them
+ out, so the range is never left mapped."""
module = self._module()
+ if self.arena is not None and module is not None and self._referenced(module):
+ self.failed = self.failed or "detached"
+ self.retiring = True
+ return
+ self.retiring = False
if module is not None and module.__dict__.get("to") == self._to:
module.__dict__.pop("to", None)
try:
@@ -430,6 +482,26 @@ class ModuleArena:
self.layout = layout
self.arena = VmmArena(max(offset, _ALIGN), self.device.index)
+ def _stale(self, entries: list) -> bool:
+ """Whether a placeable host weight has no slot of its shape, stride and dtype in the layout, or a slot outlived
+ its weight (an unloaded adapter): a removed piece must not keep its share of the range mapped."""
+ assert self.layout is not None
+ seen: set = set()
+ for name, regs, _kind, whole in entries:
+ if whole.device.type != "cpu" or not _placeable(whole):
+ continue
+ for key, t in _pieces(name, whole):
+ slot = self.layout.get(key)
+ if slot is None or (tuple(t.shape), tuple(t.stride()), t.dtype) != (
+ slot[1],
+ slot[2],
+ slot[3],
+ ):
+ return True
+ suffix = key[len(name) :]
+ seen.update(qual + suffix for _owner, _leaf, qual in regs)
+ return not seen.issuperset(self.layout)
+
def _referenced(self, module: Any) -> bool:
if self.arena is None or not self.arena.mapped:
return False
@@ -455,6 +527,13 @@ class ModuleArena:
import torch
entries = _entries(module)
+ if self.layout is not None and self._stale(entries):
+ # Host weights changed (adapter, dtype, shape): re-lay out, else the stale range stays mapped beside them.
+ if self.arena is not None:
+ self.arena.close()
+ self.arena = None
+ self.layout = None
+ self.stats["rebuilds"] += 1
if self.layout is None:
self._build(entries)
assert self.arena is not None and self.layout is not None
@@ -605,3 +684,253 @@ def arena_of(module: Any) -> Optional[ModuleArena]:
return module.__dict__.get(_ARENA_ATTR)
except Exception: # noqa: BLE001
return None
+
+
+# ---------------------------------------------------------------------------------------------------------------------
+# Block offload: stable addresses for the resident groups a prompt encode streams and pins again.
+#
+# The stock re-pin after an encode release lands at new allocator addresses, re-recording the step graph every new
+# prompt. A reserved range per group unmaps on release and remaps at the same addresses, so the step keeps replaying.
+# Opt out with UNSLOTH_DIFFUSION_GROUP_REPIN_RANGE=0.
+
+REPIN_ENV = "UNSLOTH_DIFFUSION_GROUP_REPIN_RANGE"
+_REPIN_ATTR = "_unsloth_repin_range"
+_REPIN_WANTED = "_unsloth_repin_wanted"
+_REPIN_STATS = "_unsloth_repin_stats"
+
+
+def repin_disabled() -> bool:
+ return (os.environ.get(REPIN_ENV) or "").strip().lower() in _OFF
+
+
+def want_stable_repin(module: Any) -> Optional[str]:
+ """Mark ``module`` (a block-offloaded denoiser whose step records a graph) so its group re-pins land in stable
+ ranges from now on. Returns why not, else None."""
+ if repin_disabled():
+ return f"disabled by {REPIN_ENV}=0"
+ try:
+ import torch
+ if not torch.cuda.is_available():
+ return "no CUDA device"
+ _driver()
+ except Exception as exc: # noqa: BLE001
+ return f"CUDA virtual memory unavailable ({exc})"
+ try:
+ module.__dict__[_REPIN_WANTED] = True
+ module.__dict__.setdefault(
+ _REPIN_STATS,
+ {
+ "groups": 0,
+ "pins": 0,
+ "placed": 0,
+ "stock": 0,
+ "maps": 0,
+ "unmaps": 0,
+ "bytes": 0,
+ "rebuilds": 0,
+ },
+ )
+ except Exception as exc: # noqa: BLE001
+ return f"module not writable ({exc})"
+ return None
+
+
+def drop_stable_repin(module: Any) -> None:
+ """Graphing stopped for ``module``: later re-pins move the stock way. A mapped range is unmapped by the next
+ release as before; the address ranges themselves go with the module."""
+ try:
+ module.__dict__.pop(_REPIN_WANTED, None)
+ except Exception: # noqa: BLE001
+ pass
+
+
+def stable_repin_wanted(module: Any) -> bool:
+ try:
+ return bool(module.__dict__.get(_REPIN_WANTED)) and not repin_disabled()
+ except Exception: # noqa: BLE001
+ return False
+
+
+def repin_stats(module: Any) -> Optional[dict]:
+ try:
+ stats = module.__dict__.get(_REPIN_STATS)
+ except Exception: # noqa: BLE001
+ return None
+ return dict(stats) if isinstance(stats, dict) else None
+
+
+def _host_pieces(t: Any) -> Optional[list]:
+ """(attr or None, plain tensor) for each storage of a host copy, else None (a type the range cannot hold)."""
+ if _plain(t):
+ return [(None, t.data)]
+ inner = _inner(t)
+ return None if inner is None else list(inner)
+
+
+def _span(t: Any) -> int:
+ if not t.numel():
+ return 0
+ return (1 + sum((n - 1) * st for n, st in zip(t.shape, t.stride()))) * t.element_size()
+
+
+class GroupRange:
+ """The reserved device range of one offload group's resident copy: ``layout[i]`` holds the (offset, shape, stride,
+ dtype) of each storage of the group's i-th tensor, fixed at the first re-pin."""
+
+ def __init__(self, layout: dict, nbytes: int, device_index: int) -> None:
+ self.layout = layout
+ self.arena = VmmArena(max(nbytes, _ALIGN), device_index)
+
+ def referenced(self, tensors: list) -> bool:
+ if not self.arena.mapped:
+ return False
+ lo, hi = self.arena.va, self.arena.va + self.arena.size
+ for t in tensors:
+ try:
+ pieces = _host_pieces(t) or [(None, t)]
+ if any(x.device.type == "cuda" and lo <= x.data_ptr() < hi for _, x in pieces):
+ return True
+ except Exception: # noqa: BLE001 - unreadable: keep the memory
+ return True
+ return False
+
+
+def _close_ranges(ranges: list) -> None:
+ for rng in ranges:
+ try:
+ rng.arena.close()
+ except Exception: # noqa: BLE001 - process teardown
+ pass
+
+
+def _range_for(owner: Any, group: Any, sources: list, device: Any) -> Optional[GroupRange]:
+ """``group``'s range, built on first use from the host copies ``sources`` (index -> tensor) it places."""
+ offset = 0
+ layout: dict = {}
+ for i, src in sources:
+ pieces = _host_pieces(src)
+ if pieces is None or any(x.device.type != "cpu" for _, x in pieces):
+ continue
+ slots = []
+ for _attr, x in pieces:
+ slots.append((offset, tuple(x.shape), tuple(x.stride()), x.dtype))
+ offset += -(-max(_span(x), 1) // _ALIGN) * _ALIGN
+ layout[i] = tuple(slots)
+ held = owner.__dict__.get("_unsloth_repin_ranges")
+ stats = owner.__dict__.get(_REPIN_STATS)
+ rng = getattr(group, "__dict__", {}).get(_REPIN_ATTR)
+ if rng is not None:
+ if rng.layout == layout or rng.arena.mapped:
+ # unchanged, or still holding weights (a release that could not move them all out): reused as is
+ return rng
+ # Host tensors changed (LoRA, dtype, shape): re-lay out, else the stale range stays mapped beside them.
+ rng.arena.close()
+ group.__dict__.pop(_REPIN_ATTR, None)
+ if held is not None and rng in held:
+ held.remove(rng)
+ if isinstance(stats, dict):
+ stats["rebuilds"] = stats.get("rebuilds", 0) + 1
+ stats["groups"] -= 1
+ stats["bytes"] -= rng.arena.size
+ if not layout:
+ return None
+ rng = GroupRange(layout, offset, device.index)
+ group.__dict__[_REPIN_ATTR] = rng
+ # The ranges outlive any one group object only as long as the denoiser does.
+ if held is None:
+ held = []
+ owner.__dict__["_unsloth_repin_ranges"] = held
+ weakref.finalize(owner, _close_ranges, held)
+ held.append(rng)
+ if isinstance(stats, dict):
+ stats["groups"] += 1
+ stats["bytes"] += rng.arena.size
+ return rng
+
+
+def pin_group_in_range(
+ owner: Any,
+ group: Any,
+ tensors: list,
+ pending: Any,
+ host_of: Any,
+ device: Any,
+ swap_wrapper: Any,
+) -> set:
+ """Place ``group``'s ``tensors`` for which ``pending`` holds (not on the card yet) into its stable range, copied
+ from ``host_of(t)`` (queued on the current stream: the caller synchronizes). The range is laid out over the
+ tensors pending at the first re-pin (a tied tensor another group placed takes no room here); a slot is keyed on
+ the tensor's position in ``tensors``. Returns the ids placed; the caller moves the rest the stock way."""
+ import torch
+
+ device = torch.device(device)
+ if device.index is None:
+ device = torch.device("cuda", torch.cuda.current_device())
+ todo = [(i, t, host_of(t)) for i, t in enumerate(tensors) if pending(t)]
+ rng = _range_for(owner, group, [(i, src) for i, _t, src in todo], device)
+ if rng is None:
+ return set()
+ rng.arena.map()
+ stats = owner.__dict__.get(_REPIN_STATS)
+ placed: set = set()
+ undo: list = [] # how to point each tensor installed so far back at its original storage
+ try:
+ for i, t, src in todo:
+ slots = rng.layout.get(i)
+ pieces = _host_pieces(src)
+ if (
+ slots is None
+ or pieces is None
+ or len(slots) != len(pieces)
+ or any(
+ (tuple(x.shape), tuple(x.stride()), x.dtype) != slot[1:]
+ for slot, (_attr, x) in zip(slots, pieces)
+ )
+ ):
+ continue
+ views = []
+ for slot, (_attr, x) in zip(slots, pieces):
+ view = rng.arena.view(slot[0], slot[1], slot[3], slot[2])
+ view.copy_(x, non_blocking = True)
+ views.append(view)
+ if pieces[0][0] is None:
+ prev = t.data
+ t.data = views[0]
+ undo.append((t, prev, False))
+ else:
+ _names, ctx = src.__tensor_flatten__()
+ rebuilt = type(src).__tensor_unflatten__(
+ dict(zip([a for a, _ in pieces], views)), ctx, src.shape, src.stride()
+ )
+ swap_wrapper(t, rebuilt) # a swap: ``rebuilt`` now holds t's original contents
+ undo.append((t, rebuilt, True))
+ placed.add(id(t))
+ except BaseException:
+ # Leave the range empty so the caller unmaps it and moves the whole group the stock way.
+ for t, prev, wrapped in reversed(undo):
+ if wrapped:
+ swap_wrapper(t, prev)
+ else:
+ t.data = prev
+ raise
+ if isinstance(stats, dict):
+ stats["pins"] += 1
+ stats["maps"] = sum(r.arena.maps for r in owner.__dict__.get("_unsloth_repin_ranges", ()))
+ stats["placed"] += len(placed)
+ stats["stock"] += len(todo) - len(placed)
+ return placed
+
+
+def release_group_range(owner: Any, group: Any, tensors: list) -> bool:
+ """After ``group`` streamed again (its tensors back on their host copies): unmap its range. False when a tensor
+ still lives in it (the memory then stays until the next re-pin reuses it)."""
+ rng = getattr(group, "__dict__", {}).get(_REPIN_ATTR)
+ if rng is None or not rng.arena.mapped:
+ return True
+ if rng.referenced(tensors):
+ return False
+ rng.arena.unmap()
+ stats = owner.__dict__.get(_REPIN_STATS) if owner is not None else None
+ if isinstance(stats, dict):
+ stats["unmaps"] += 1
+ return True
diff --git a/studio/backend/tests/test_diffusion_offload_cuda_graph.py b/studio/backend/tests/test_diffusion_offload_cuda_graph.py
index 6e7a545162d..0e080695a43 100644
--- a/studio/backend/tests/test_diffusion_offload_cuda_graph.py
+++ b/studio/backend/tests/test_diffusion_offload_cuda_graph.py
@@ -167,6 +167,231 @@ def test_release_and_restore_records_again_and_stays_exact():
assert handles[0].stats["invalidations"] >= 1 and handles[0].stats["captures"] >= 2
+class _Encoder(torch.nn.Module):
+ """A text encoder whose output takes the VRAM the encode release frees, as a real encode's weights and activations
+ do: the stock re-pin then cannot land on the blocks the resident groups gave back."""
+
+ def __init__(self, net, nbytes):
+ super().__init__()
+ self.net = net
+ self.nbytes = nbytes
+ self.proj = torch.nn.Linear(8, 8).cuda()
+ self.mapped: list = []
+
+ def forward(self, x):
+ ranges = self.net.__dict__.get("_unsloth_repin_ranges") or []
+ self.mapped.append([r.arena.mapped for r in ranges])
+ held = torch.empty(self.nbytes, dtype = torch.uint8, device = "cuda")
+ return self.proj(x), held
+
+
[email protected]("stable", [True, False])
+def test_an_encode_release_re_pins_where_the_step_recorded(monkeypatch, stable):
+ """12 GiB tier (partial residency + the encode release): every new prompt encode streams resident groups and pins
+ them again before step 0. The re-pin lands in each group's stable range, so the step recorded on prompt 1 replays
+ on every later prompt (captures per prompt 1, 0, 0, 0), bit-identical to the eager forward; the ranges hold no
+ memory during the encode. UNSLOTH_DIFFUSION_GROUP_REPIN_RANGE=0 is the stock re-pin: later prompts record again."""
+ _cuda()
+ if not stable:
+ monkeypatch.setenv(sa.REPIN_ENV, "0")
+ prompts = 4
+ seeds = list(range(2 * prompts))
+ want = _eager_reference(6, seeds)
+ torch.manual_seed(0)
+ net = _streamed(_Net(), 6)
+ resident = [g for g in dm._offload_groups(net) if getattr(g, "_unsloth_resident", False)]
+ streamed = [g for g in dm._offload_groups(net) if not getattr(g, "_unsloth_resident", False)]
+ assert (
+ len(resident) >= 4 and streamed
+ ) # partial residency: some blocks pinned, the rest streamed
+ enc = _Encoder(net, 6 << 20)
+ pipe = types.SimpleNamespace(
+ transformer = net, components = {"transformer": net, "text_encoder": enc}
+ )
+ plan = types.SimpleNamespace(
+ resident_transformer_mib = 6, estimates = {"encode_resident_transformer_mib": 2}
+ )
+ handles, reason = cg.arm_after_placement(pipe)
+ assert len(handles) == 1 and handles[0].placement.mode == "group", reason
+ assert dm.install_encode_release(pipe, plan, None) == 1
+ h = handles[0]
+ got, per_prompt = [], []
+ for prompt in range(prompts):
+ with torch.no_grad():
+ out = enc(torch.randn(2, 8, device = "cuda")) # releases, then pins back before step 0
+ before = h.stats["captures"]
+ got += _run(net, seeds[2 * prompt : 2 * prompt + 2])
+ per_prompt.append(h.stats["captures"] - before)
+ del out
+ for a, b in zip(got, want):
+ assert torch.equal(a, b)
+ repin = cg.stats(handles).get("stable_repin")
+ if stable:
+ assert per_prompt == [1, 0, 0, 0]
+ assert h.stats["replays"] == 2 * prompts # the recording call replays too
+ assert repin["groups"] >= 1 and repin["unmaps"] == repin["groups"] * (prompts - 1)
+ # the first encode released the load's stock pins; every later one found the ranges unmapped during it
+ assert all(not any(m) for m in enc.mapped[1:]) and all(enc.mapped[1:])
+ assert all(r.arena.mapped for r in net.__dict__["_unsloth_repin_ranges"])
+ else:
+ # the stock re-pin lands wherever the allocator has room after the encode: a later prompt records again
+ assert per_prompt[0] == 1 and sum(per_prompt[1:]) >= 1
+ assert repin is None or repin["groups"] == 0
+ cg.uninstall_all(handles)
+
+
+def test_the_render_peak_counts_weights_moved_into_a_stable_range():
+ """A render that first moves resident groups into their ranges drops the allocator by their size; the learned peak
+ counts the mapped range, so it never reads low on the stock scale."""
+ _cuda()
+ from core.inference.diffusion_measured_peaks import PeakProbe
+
+ try:
+ sa._driver()
+ except Exception as exc: # noqa: BLE001
+ pytest.skip(f"CUDA VMM unavailable ({exc})")
+ dev = torch.cuda.current_device()
+ held = torch.empty(
+ 8 << 20, dtype = torch.uint8, device = "cuda"
+ ) # a resident group, pinned the stock way
+ arena = sa.VmmArena(8 << 20, dev)
+ before = sa.mapped_bytes(dev)
+ probe = PeakProbe("cuda")
+ del held # the re-pin: the group leaves the allocator ...
+ arena.map() # ... and lands in its range
+ assert sa.mapped_bytes(dev) == before + arena.size
+ peak = probe.finish()
+ assert peak is not None and peak >= arena.size >> 20
+ arena.close()
+ assert sa.mapped_bytes(dev) == before
+
+
+def test_the_render_peak_counts_a_stable_range_unmapped_before_the_probe_ends():
+ """A model-offload denoiser range is mapped for the denoise and unmapped again before the render's probe ends:
+ the peak still counts it (the allocator never saw those bytes)."""
+ _cuda()
+ from core.inference.diffusion_measured_peaks import PeakProbe
+
+ try:
+ sa._driver()
+ except Exception as exc: # noqa: BLE001
+ pytest.skip(f"CUDA VMM unavailable ({exc})")
+ dev = torch.cuda.current_device()
+ arena = sa.VmmArena(16 << 20, dev)
+ before = sa.mapped_bytes(dev)
+ probe = PeakProbe("cuda")
+ arena.map() # the denoiser onloads into its range ...
+ arena.unmap() # ... and offloads before the decode
+ assert sa.mapped_bytes(dev) == before
+ peak = probe.finish()
+ assert peak is not None and peak >= arena.size >> 20
+ arena.close()
+
+
+def _repin_cycle(
+ net,
+ pipe,
+ enc_bytes = 6 << 20,
+):
+ restore = dm.release_resident_groups(pipe, 10_000, None)
+ hold = torch.empty(
+ enc_bytes, dtype = torch.uint8, device = "cuda"
+ ) # the encoder takes the freed room
+ restore()
+ del hold
+
+
+def test_a_group_range_is_rebuilt_when_its_host_tensors_change():
+ """A LoRA load or unload can change a released group's tensors: the re-pin lays the range out again, so every
+ weight of the group lands in it (none beside a fully mapped stale range at a new address each re-pin)."""
+ _cuda()
+ torch.manual_seed(0)
+ net = _streamed(_Net(), 6)
+ pipe = _pipe(net)
+ handles, _ = cg.arm_after_placement(pipe)
+ _repin_cycle(net, pipe) # the first re-pin lays the ranges out
+ ranged = [g for g in dm._offload_groups(net) if "_unsloth_repin_range" in g.__dict__]
+ assert ranged
+ group = ranged[-1]
+ restore = dm.release_resident_groups(pipe, 10_000, None)
+ block = group.modules[0]
+ block.extra = torch.nn.Parameter(
+ torch.randn(256, 256)
+ ) # a new adapter weight, on the host like the rest
+ restore()
+ rng = group.__dict__["_unsloth_repin_range"]
+ lo, hi = rng.arena.va, rng.arena.va + rng.arena.size
+ assert all(lo <= t.data_ptr() < hi for t in dm._resident_tensors(group))
+ assert sa.repin_stats(net)["rebuilds"] == 1
+ cg.uninstall_all(handles)
+
+
+def test_a_failed_stable_re_pin_leaves_no_range_mapped(monkeypatch):
+ """A re-pin into the range that raises after mapping it (rebuilding a wrapper weight, say) unmaps the range
+ before the group moves the stock way: the fallback never holds two copies of the group."""
+ _cuda()
+ seeds = [0, 1, 2]
+ want = _eager_reference(6, seeds)
+ torch.manual_seed(0)
+ net = _streamed(_Net(), 6)
+ pipe = _pipe(net)
+ handles, _ = cg.arm_after_placement(pipe)
+ got = _run(net, seeds[:1])
+ _repin_cycle(net, pipe)
+ got += _run(net, seeds[1:2])
+ real = sa.pin_group_in_range
+
+ def fails_after_mapping(owner, group, tensors, pending, host_of, device, swap):
+ rng = group.__dict__.get("_unsloth_repin_range")
+ if rng is not None:
+ rng.arena.map()
+ raise RuntimeError("wrapper rebuild failed")
+
+ monkeypatch.setattr(sa, "pin_group_in_range", fails_after_mapping)
+ _repin_cycle(net, pipe)
+ ranges = net.__dict__["_unsloth_repin_ranges"]
+ assert ranges and not any(r.arena.mapped for r in ranges)
+ assert all(
+ g._unsloth_resident for g in dm._offload_groups(net) if "_unsloth_repin_range" in g.__dict__
+ ) # placed the stock way
+ got += _run(net, seeds[2:])
+ for a, b in zip(got, want):
+ assert torch.equal(a, b)
+ monkeypatch.setattr(sa, "pin_group_in_range", real)
+ cg.uninstall_all(handles)
+
+
+def test_a_re_pin_failing_midway_rolls_back_the_tensors_it_placed(monkeypatch):
+ """A re-pin that raises after it already put an earlier tensor into the range (a later copy or wrapper rebuild
+ failing) points that tensor back at its original storage before re-raising: the caller can then unmap the range
+ and move the whole group the stock way, instead of keeping the range mapped beside the stock copies. CPU only:
+ a fake range whose second view raises."""
+ buf = torch.zeros(64)
+ calls = [0]
+
+ def view(offset, shape, dtype, stride):
+ calls[0] += 1
+ if calls[0] == 2:
+ raise RuntimeError("wrapper rebuild failed")
+ return buf[offset // 4 : offset // 4 + 8].view(shape)
+
+ arena = types.SimpleNamespace(map = lambda: None, view = view, maps = 0)
+ a = torch.nn.Parameter(torch.randn(8), requires_grad = False)
+ b = torch.nn.Parameter(torch.randn(8), requires_grad = False)
+ host_a = a.data
+ slot = ((0, (8,), (1,), torch.float32),)
+ rng = types.SimpleNamespace(arena = arena, layout = {0: slot, 1: ((128,) + slot[0][1:],)})
+ monkeypatch.setattr(sa, "_range_for", lambda *args: rng)
+ owner, group = types.SimpleNamespace(), types.SimpleNamespace()
+ with pytest.raises(RuntimeError):
+ sa.pin_group_in_range(
+ owner, group, [a, b], lambda t: True, lambda t: t, "cuda:0", lambda t, s: None
+ )
+ lo, hi = buf.data_ptr(), buf.data_ptr() + buf.numel() * 4
+ assert not any(lo <= t.data_ptr() < hi for t in (a, b))
+ assert a.data.data_ptr() == host_a.data_ptr()
+
+
def _reset_retired(monkeypatch):
if hasattr(cg, "_RETIRED_POOLS"):
monkeypatch.setattr(cg, "_RETIRED_POOLS", [0, 0])
@@ -192,8 +417,9 @@ def test_an_offloaded_re_record_hands_the_dropped_pool_back_first(monkeypatch):
"""Each new prompt encode moves the resident groups (release, the encoder takes the room, re-pin elsewhere), so
the step records again. The encode release no longer flushes the allocator; the re-record itself hands the
dropped recording's pool back before it records, so the reserved memory stays flat instead of growing by a pool
- per prompt, and every output stays exact."""
+ per prompt, and every output stays exact. The stock re-pin (no stable group range): with it the step replays."""
_cuda()
+ monkeypatch.setenv(sa.REPIN_ENV, "0")
_reset_retired(monkeypatch)
seeds = list(range(6))
want = _eager_reference(3, seeds)
@@ -236,8 +462,9 @@ def _two_shapes(net, shapes = (16, 8)):
def test_one_invalidation_flushes_the_retired_pool_once_for_every_re_recorded_key(monkeypatch):
"""Two keys re-recorded under one new placement share one retired pool: the first re-record flushes it, the second
- does not flush the allocator again."""
+ does not flush the allocator again. The stock re-pin (no stable group range): with it nothing records again."""
_cuda()
+ monkeypatch.setenv(sa.REPIN_ENV, "0")
_reset_retired(monkeypatch)
torch.manual_seed(0)
net = _streamed(_Net(), 3)
@@ -886,6 +1113,150 @@ def test_a_failed_capture_gives_the_stable_range_back(monkeypatch):
cg.uninstall_all(handles)
+def test_a_poisoned_model_offload_graph_gives_back_the_stable_range():
+ """A failed capture poisons the handle for the load: no graph replays again, so the module goes back to the stock
+ onload. Poisoned mid-render (the weights in the range), the range is closed on the offload that moves them out."""
+ _cuda()
+ pytest.importorskip("accelerate")
+ ref, net, hook = _model_offloaded()
+ handles, reason = cg.arm_after_placement(_pipe(net))
+ assert len(handles) == 1 and "stable device range" in reason, reason
+ arena = sa.arena_of(net)
+ _run(net, [0, 1])
+ assert arena.arena.mapped
+ handles[0].poison(RuntimeError("capture failed"))
+ assert arena.arena.mapped # the weights still live in it
+ hook.offload()
+ assert net.proj_in.weight.device.type == "cpu"
+ assert sa.arena_of(net) is None and "to" not in net.__dict__
+ assert arena.arena is None # closed: no mapping left behind
+ maps = arena.stats["maps"]
+ for a, b in zip(_run(net, [2, 3]), _run(ref, [2, 3])):
+ assert torch.equal(a, b)
+ assert arena.stats["maps"] == maps and arena.stats["onloads"] == 1
+ cg.uninstall_all(handles)
+
+
+def test_freed_block_offload_graphs_stop_the_stable_repin():
+ _cuda()
+ net = _streamed(_Net(), 3)
+ handles, _ = cg.arm_after_placement(_pipe(net))
+ assert sa.stable_repin_wanted(net)
+ cg.uninstall_all(handles)
+ assert not sa.stable_repin_wanted(net)
+
+
+def test_a_poisoned_block_offload_step_keeps_the_stable_repin_for_its_block_fallback():
+ """The per-block fallback a poisoned step arms keys its graphs on the resident groups' addresses: the stable re-pin
+ stays while it can still record, and stops once no fallback is left."""
+ _cuda()
+ net = _streamed(_Net(), 3)
+ handles, _ = cg.arm_after_placement(_pipe(net))
+ step = handles[0]
+ assert sa.stable_repin_wanted(net)
+ step.fallback = lambda: object()
+ step.poison(RuntimeError("capture failed"))
+ assert sa.stable_repin_wanted(net)
+ step._engage_fallback()
+ assert step.fallback_handle is not None and sa.stable_repin_wanted(net)
+ step.fallback_handle = None
+ step.fallback = lambda: None # the fallback could not arm: nothing records over the placement
+ step._engage_fallback()
+ assert not sa.stable_repin_wanted(net)
+ cg.uninstall_all(handles)
+
+
+def test_a_declined_block_offload_step_retires_the_stable_repin_once_no_fallback_records():
+ """A speed-declined placement refuses every later recording; a per-block fallback that then fails to arm (or none
+ at all) leaves nothing recording, so the re-pin stops paying for stable addresses. A dropped key alone keeps it."""
+ _cuda()
+ net = _streamed(_Net(), 3)
+ handles, _ = cg.arm_after_placement(_pipe(net))
+ step = handles[0]
+ assert sa.stable_repin_wanted(net)
+ step.fallback = lambda: None
+ step._dropped.add("k")
+ step._engage_fallback() # a dropped key, placement still recording
+ assert sa.stable_repin_wanted(net)
+ step.placement.decline("slower than eager")
+ step.fallback = lambda: None
+ step._engage_fallback()
+ assert not sa.stable_repin_wanted(net)
+ cg.uninstall_all(handles)
+
+
+def test_model_offload_stable_range_is_rebuilt_when_a_weight_changes_on_the_host():
+ """A weight added or reshaped on the host after the range was laid out (a new adapter) lands in a rebuilt range,
+ not beside a fully mapped stale one at a new address every onload."""
+ _cuda()
+ pytest.importorskip("accelerate")
+ ref, net, hook = _model_offloaded()
+ arena, why = sa.attach(net)
+ assert arena is not None, why
+ _run(net, [0])
+ hook.offload()
+ net.extra = torch.nn.Parameter(
+ torch.randn(512, 512)
+ ) # on the host, like the rest between renders
+ for render in range(2):
+ for a, b in zip(_run(net, [render + 1]), _run(ref, [render + 1])):
+ assert torch.equal(a, b)
+ lo, hi = arena.arena.va, arena.arena.va + arena.arena.size
+ assert all(lo <= p.data_ptr() < hi for p in net.parameters())
+ hook.offload()
+ assert not arena.arena.mapped
+ assert arena.stats["rebuilds"] == 1
+ arena.detach()
+
+
+def test_model_offload_stable_range_is_rebuilt_when_a_weight_is_removed():
+ """An adapter unloaded after the range was laid out frees its slots: the next onload maps a rebuilt, smaller range
+ instead of the old full-size one."""
+ _cuda()
+ pytest.importorskip("accelerate")
+ ref, net, hook = _model_offloaded()
+ net.extra = torch.nn.Parameter(
+ torch.randn(2048, 2048)
+ ) # 16 MiB: well past the mapping granularity
+ arena, why = sa.attach(net)
+ assert arena is not None, why
+ _run(net, [0])
+ full = arena.arena.size
+ hook.offload()
+ del net.extra
+ for a, b in zip(_run(net, [1]), _run(ref, [1])):
+ assert torch.equal(a, b)
+ assert arena.stats["rebuilds"] == 1 and arena.arena.size < full
+ hook.offload()
+ arena.detach()
+
+
+def test_a_failed_wrap_of_the_mapped_range_leaves_it_unmapped_and_retryable(monkeypatch):
+ _cuda()
+ try:
+ sa._driver()
+ except Exception as exc: # noqa: BLE001
+ pytest.skip(f"CUDA VMM unavailable ({exc})")
+ dev = torch.cuda.current_device()
+ arena = sa.VmmArena(4 << 20, dev)
+ before = sa.mapped_bytes(dev)
+ real = torch.as_tensor
+
+ def refuse(*args, **kwargs):
+ raise TypeError("unsupported __cuda_array_interface__")
+
+ monkeypatch.setattr(torch, "as_tensor", refuse)
+ with pytest.raises(TypeError):
+ arena.map()
+ assert not arena.mapped and sa.mapped_bytes(dev) == before
+ monkeypatch.setattr(torch, "as_tensor", real)
+ base = arena.map()
+ base.fill_(7)
+ assert arena.mapped and int(base[0]) == 7
+ arena.close()
+ assert sa.mapped_bytes(dev) == before
+
+
def test_model_offload_stops_recording_only_when_moves_outpace_replays():
placement = cg.OffloadPlacement.__new__(cg.OffloadPlacement)
placement.mode = "model"