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: stream offloaded denoiser blocks without host waits (B200 FLUX.1 16 GB 0.59x, L4 0.90x per step) (#12664)

Daniel Han3d0a0e66ab04
diff --git a/studio/backend/core/inference/diffusion_memory.py b/studio/backend/core/inference/diffusion_memory.py
index 5b0498cbcbc..174a2a48843 100644
--- a/studio/backend/core/inference/diffusion_memory.py
+++ b/studio/backend/core/inference/diffusion_memory.py
@@ -2511,7 +2511,11 @@ def _keep_groups_resident(
def _resident_onload(stream: Any) -> Callable[[], None]:
# a prefetching predecessor skips its own copy-stream wait and relies on this onload_ to do it
def onload_(*args: Any, **kwargs: Any) -> None:
- if stream is not None and state["streamed"]:
+ # event-fenced prefetch: streamed groups wait on their own copy; a resident block may start the forward's fill
+ kick = state.get("kick")
+ if callable(kick):
+ kick()
+ if stream is not None and state["streamed"] and not state.get("fenced"):
stream.synchronize()
return disable(onload_) if callable(disable) else onload_
@@ -3910,6 +3914,8 @@ def _apply_group_offload(
installed += 1
if use_stream and not _pin_top_level_group(module, logger, pinned_mib):
_skip_top_level_copy_back(module, logger)
+ if use_stream and gkwargs.get("record_stream"):
+ install_group_prefetch(module, onload, logger)
if resident_transformer_mib:
room = int(resident_transformer_mib)
for module in streamed.values():
@@ -4469,6 +4475,16 @@ def raise_on_image_activation_shortfall(
STREAMING_PREFETCH_ENV = "UNSLOTH_DIFFUSION_STREAMING_PREFETCH"
+def install_group_prefetch(
+ module: Any,
+ device: Any,
+ logger: Any = None,
+) -> int:
+ """Event-fenced, deeper prefetch for a block-streamed module's offload groups (diffusion_offload_prefetch)."""
+ from .diffusion_offload_prefetch import install_group_prefetch as _install
+ return _install(module, device, logger)
+
+
def _streaming_prefetch_enabled() -> bool:
"""Kill switch for the streaming tier's overlapped onload (pinned host copies + record_stream); default on."""
return (os.environ.get(STREAMING_PREFETCH_ENV) or "").strip().lower() not in (
@@ -4575,6 +4591,8 @@ def _apply_streaming_offload(
and not _pin_top_level_group(module, logger, pinned_mib)
):
_skip_top_level_copy_back(module, logger)
+ if use_stream and prefetch and offload_type == "block_level":
+ install_group_prefetch(module, onload, logger)
if offload_type == "leaf_level":
_pin_vision_embedding_device(module)
if resident_transformer_mib:
diff --git a/studio/backend/core/inference/diffusion_offload_prefetch.py b/studio/backend/core/inference/diffusion_offload_prefetch.py
new file mode 100644
index 00000000000..7091650952e
--- /dev/null
+++ b/studio/backend/core/inference/diffusion_offload_prefetch.py
@@ -0,0 +1,581 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Event-fenced prefetch for a block-streamed denoiser's diffusers offload groups.
+
+diffusers fences its stream prefetch on the host (``stream.synchronize()`` per onload) and copies one group ahead.
+Here the compute stream waits on a per-group CUDA event instead, and up to ``depth`` streamed groups are copied ahead
+in the order the first forward recorded.
+
+A forward's first copies are queued at the first block's onload (behind a compute-stream event when the top-level
+group uploads on the compute stream): queued earlier they hold that upload back on the copy engine.
+
+Memory stays bounded without a host wait: each offload records a compute-stream event the copy stream waits on, so a
+freed block goes to the next prefetch only after the compute that read it. Bytes in flight never pass ``window``.
+Hooks are per-group / per-module instance attributes; diffusers' classes are untouched.
+"""
+
+from __future__ import annotations
+
+import os
+from typing import Any, Optional
+
+ASYNC_PREFETCH_ENV = "UNSLOTH_DIFFUSION_ASYNC_PREFETCH"
+PREFETCH_DEPTH_ENV = "UNSLOTH_DIFFUSION_PREFETCH_DEPTH"
+DEFAULT_PREFETCH_DEPTH = 2
+MAX_PREFETCH_DEPTH = 8
+PREFETCHER_ATTR = "_unsloth_group_prefetcher"
+_BG_PIN_ATTR = "_unsloth_background_pin"
+
+
+def async_prefetch_enabled() -> bool:
+ return (os.environ.get(ASYNC_PREFETCH_ENV) or "").strip().lower() not in (
+ "0",
+ "off",
+ "false",
+ "no",
+ )
+
+
+def prefetch_depth() -> int:
+ raw = (os.environ.get(PREFETCH_DEPTH_ENV) or "").strip()
+ try:
+ depth = int(raw) if raw else DEFAULT_PREFETCH_DEPTH
+ except ValueError:
+ depth = DEFAULT_PREFETCH_DEPTH
+ return max(1, min(MAX_PREFETCH_DEPTH, depth))
+
+
+def _go() -> Any:
+ from diffusers.hooks import group_offloading as go
+ return go
+
+
+def _group_tensors(group: Any) -> list:
+ """The tensors diffusers' stream onload moves, in its order (module params, module buffers, then the group's)."""
+ out: list = []
+ seen: set = set()
+ for module in getattr(group, "modules", None) or ():
+ for t in module.parameters():
+ if id(t) not in seen:
+ seen.add(id(t))
+ out.append(t)
+ for t in module.buffers():
+ if id(t) not in seen:
+ seen.add(id(t))
+ out.append(t)
+ for t in list(getattr(group, "parameters", None) or ()) + list(
+ getattr(group, "buffers", None) or ()
+ ):
+ if id(t) not in seen:
+ seen.add(id(t))
+ out.append(t)
+ return out
+
+
+_GENERIC_TO_COPY_DROPS_NON_BLOCKING: dict = {}
+
+
+def _generic_to_copy_drops_non_blocking(cls: Any) -> bool:
+ """torchao < 0.18's common ``aten._to_copy`` (every tensor class declaring ``tensor_data_names``, e.g. ``Int8Tensor``)
+ moves the inner tensors with ``.to(device)``, dropping ``non_blocking``: one host wait per inner tensor. 0.18 passes
+ it through. True only for that generic handler on such a torchao, never for a class with its own ``_to_copy``."""
+ hit = _GENERIC_TO_COPY_DROPS_NON_BLOCKING.get(cls)
+ if hit is not None:
+ return hit
+ hit = False
+ try:
+ import torch
+ import torchao
+
+ major, minor = (int(x) for x in str(torchao.__version__).split("+")[0].split(".")[:2])
+ if (
+ (major, minor) < (0, 18)
+ and hasattr(cls, "tensor_data_names")
+ and hasattr(cls, "tensor_attribute_names")
+ ):
+ fn = (
+ (getattr(cls, "_ATEN_OP_TABLE", {}) or {})
+ .get(cls, {})
+ .get(torch.ops.aten._to_copy.default)
+ )
+ inner = getattr(fn, "__wrapped__", None)
+ hit = bool(
+ inner is not None
+ and getattr(inner, "__module__", "") == "torchao.utils"
+ and "_implements_common_tensor_ops" in getattr(inner, "__qualname__", "")
+ )
+ except Exception: # noqa: BLE001 - unknown layout: keep the stock to()
+ hit = False
+ _GENERIC_TO_COPY_DROPS_NON_BLOCKING[cls] = hit
+ return hit
+
+
+def _generic_to_device(src: Any, device: Any) -> Any:
+ """torchao 0.18's common ``_to_copy`` (same constructor call, inner tensors moved with ``non_blocking=True``)."""
+
+ def move(t: Any) -> Any:
+ return None if t is None else t.to(device, non_blocking = True)
+
+ tensors = [move(getattr(src, n)) for n in src.tensor_data_names]
+ optional = [move(getattr(src, n)) for n in getattr(src, "optional_tensor_data_names", ())]
+ attrs = [getattr(src, a) if a != "device" else device for a in src.tensor_attribute_names]
+ optional_attrs = [
+ getattr(src, a) if a != "device" else device
+ for a in getattr(src, "optional_tensor_attribute_names", ())
+ ]
+ return type(src)(*tensors, *attrs, *optional, *optional_attrs)
+
+
+def _to_device(src: Any, device: Any) -> Any:
+ """``src.to(device, non_blocking=True)``; torchao <= 0.17 int8 payloads (whose ``to`` drops it) are moved directly."""
+ if _generic_to_copy_drops_non_blocking(type(src)):
+ return _generic_to_device(src, device)
+ name = type(src).__name__
+ if name == "LinearActivationQuantizedTensor":
+ inner = getattr(src, "original_weight_tensor", None)
+ if type(inner).__name__ == "AffineQuantizedTensor" and type(
+ getattr(inner, "tensor_impl", None)
+ ).__name__ == ("PlainAQTTensorImpl"):
+ return src._apply_fn_to_data(lambda w: _to_device(w, device))
+ elif name == "AffineQuantizedTensor":
+ if type(getattr(src, "tensor_impl", None)).__name__ == "PlainAQTTensorImpl":
+ return src._apply_fn_to_data(
+ lambda impl: impl._apply_fn_to_data(lambda x: x.to(device, non_blocking = True))
+ )
+ return src.to(device, non_blocking = True)
+
+
+def _group_nbytes(group: Any) -> int:
+ from .diffusion_memory import _storage_nbytes
+
+ cpu = getattr(group, "cpu_param_dict", None) or {}
+ total = 0
+ for t in _group_tensors(group):
+ total += sum(_storage_nbytes(cpu.get(t, t)))
+ return int(total)
+
+
+class GroupPrefetcher:
+ """``ready``: group id -> CUDA event of its queued copy (None once waited on); a group is on the device exactly
+ while its id is in ``ready``."""
+
+ def __init__(
+ self,
+ module: Any,
+ groups: list,
+ device: Any,
+ depth: int,
+ window_bytes: Optional[int] = None,
+ ):
+ import torch
+
+ self.module = module
+ self.device = torch.device(device)
+ self.depth = int(depth)
+ self.groups = list(groups)
+ self.by_id = {id(g): g for g in self.groups}
+ self.nbytes = {id(g): _group_nbytes(g) for g in self.groups}
+ largest = max(self.nbytes.values()) if self.nbytes else 0
+ self.window = int(window_bytes) if window_bytes else (self.depth + 1) * largest
+ self.ready: dict = {}
+ self.inflight_bytes = 0
+ self.peak_inflight_bytes = 0
+ self.order: list = []
+ self.seen: list = []
+ self.pos = 0
+ self.active = False
+ self.on_order = False
+ self.pending = False
+ streams = [g.stream for g in self.groups if getattr(g, "stream", None) is not None]
+ self.stream = streams[0] if streams else None
+ self.fence_first = False
+ self.stats = {"forwards": 0, "copies": 0, "prefetched": 0, "missed": 0, "dropped": 0}
+
+ def owns(self, group: Any) -> bool:
+ return getattr(group, "__dict__", {}).get("onload_") is getattr(
+ group, "_unsloth_prefetch_onload", None
+ )
+
+ def _compute(self) -> Any:
+ import torch
+ return torch.cuda.current_stream(self.device)
+
+ def _issue(self, group: Any) -> None:
+ """Queue ``group``'s host-to-device copy on its copy stream and point its tensors at the destinations."""
+ import torch
+
+ pinner = getattr(group, _BG_PIN_ATTR, None)
+ if pinner is not None:
+ pinner.wait(group)
+ go = _go()
+ is_torchao = getattr(go, "_is_torchao_tensor", lambda t: False)
+ swap = getattr(go, "_swap_torchao_tensor", None)
+ cpu = group.cpu_param_dict
+ stream = group.stream
+ with torch.cuda.stream(stream):
+ for t in _group_tensors(group):
+ src = cpu[t]
+ if not src.is_pinned():
+ src = (
+ src.pin_memory()
+ ) # diffusers' low_cpu_mem_usage path: the host allocator fences reuse
+ moved = _to_device(src, self.device)
+ if is_torchao(t) and swap is not None:
+ swap(t, moved)
+ else:
+ t.data = moved
+ ready = torch.cuda.Event()
+ ready.record(stream)
+ gid = id(group)
+ self.ready[gid] = ready
+ self.inflight_bytes += self.nbytes.get(gid, 0)
+ self.peak_inflight_bytes = max(self.peak_inflight_bytes, self.inflight_bytes)
+ self.stats["copies"] += 1
+
+ def onload(self, group: Any) -> None:
+ gid = id(group)
+ self.kick() # first block of the forward: this group is order[pos], so it is queued first
+ if self.active:
+ self.seen.append(gid)
+ if self.on_order and self.pos < len(self.order) and self.order[self.pos] == gid:
+ self.pos += 1
+ else:
+ self.on_order = False # off the recorded order: no prefetch this forward, the next one re-records
+ if gid not in self.ready:
+ self._issue(group)
+ if self.active and self.order:
+ self.stats["missed"] += 1
+ elif self.ready[gid] is not None:
+ self.stats["prefetched"] += 1
+ event = self.ready[gid]
+ if event is not None:
+ self._compute().wait_event(event)
+ self.ready[gid] = None
+ self._fill()
+
+ def offload(self, group: Any) -> None:
+ gid = id(group)
+ if gid in self.ready:
+ self._release(group, self.ready.pop(gid))
+ else:
+ self._release(
+ group, None, counted = False
+ ) # placed by someone else (a resident group demoted)
+ self._fill()
+
+ def _release(
+ self,
+ group: Any,
+ event: Any,
+ counted: bool = True,
+ ) -> None:
+ import torch
+
+ compute = self._compute()
+ if event is not None:
+ compute.wait_event(
+ event
+ ) # copied ahead but never run: the copy must land before the block is freed
+ self.stats["dropped"] += 1
+ done = torch.cuda.Event()
+ done.record(compute)
+ # later copy-stream work runs after the compute that read this group, so its freed blocks are reusable at once
+ group.stream.wait_event(done)
+ if counted:
+ self.inflight_bytes -= self.nbytes.get(id(group), 0)
+ type(group).offload_(group)
+
+ def _forget_disowned(self) -> None:
+ """Groups made resident while on the device (their onload_ replaced) leave the window without a release."""
+ compute = None
+ for gid in list(self.ready):
+ group = self.by_id.get(gid)
+ if group is not None and self.owns(group):
+ continue
+ event = self.ready.pop(gid)
+ if event is not None:
+ compute = compute or self._compute()
+ compute.wait_event(event)
+ self.inflight_bytes -= self.nbytes.get(gid, 0)
+
+ def _fill(self) -> None:
+ if not (self.active and self.on_order):
+ return
+ ahead = 0
+ for gid in self.order[self.pos :]:
+ if ahead >= self.depth:
+ break
+ group = self.by_id.get(gid)
+ if group is None or not self.owns(group):
+ continue # made resident since the order was recorded
+ if gid in self.ready:
+ ahead += 1
+ continue
+ if self.inflight_bytes + self.nbytes.get(gid, 0) > self.window and self.ready:
+ break
+ self._issue(group)
+ ahead += 1
+
+ def begin(self) -> None:
+ self.stats["forwards"] += 1
+ self._forget_disowned()
+ self.seen = []
+ self.pos = 0
+ self.active = True
+ self.on_order = bool(self.order)
+ self.pending = True
+
+ def kick(self) -> None:
+ """First block onload of a forward (streamed or resident): queue the first ``depth`` streamed groups."""
+ if self.pending:
+ self.pending = False
+ if self.fence_first and self.stream is not None and self.on_order:
+ import torch
+
+ after_top = torch.cuda.Event()
+ after_top.record(self._compute())
+ self.stream.wait_event(after_top)
+ self._fill()
+
+ def end(self) -> None:
+ if not self.active:
+ return
+ self.active = False
+ self.on_order = False
+ self.pending = False
+ self._forget_disowned()
+ for gid in list(self.ready):
+ group = self.by_id.get(gid)
+ if group is not None:
+ self._release(group, self.ready.pop(gid))
+ self.ready.clear()
+ self.inflight_bytes = 0
+ if self.seen:
+ self.order = list(self.seen)
+
+
+def _adopt_top_group(
+ module: Any,
+ stream: Any,
+ logger: Any = None,
+) -> Optional[Any]:
+ """Give a torchao top-level group (no stream in diffusers: synchronous upload, copy-back every forward) pinned host
+ copies and the module's copy stream, so the prefetcher drives it like a block. None if left as it was."""
+ import torch
+
+ from .diffusion_memory import (
+ GROUP_OFFLOAD_PIN_ENV,
+ PIN_TOP_GROUP_ENV,
+ _module_host_mib,
+ _pin_budget_mib,
+ _pinned_memory_capped,
+ )
+
+ off = ("0", "off", "false", "no")
+ if (os.environ.get(PIN_TOP_GROUP_ENV) or "").strip().lower() in off:
+ return None
+ if str(os.environ.get(GROUP_OFFLOAD_PIN_ENV, "")).strip().lower() in off:
+ return None
+ go = _go()
+ registry = getattr(module, "_diffusers_hook", None)
+ get_hook = getattr(registry, "get_hook", None)
+ hook = (
+ get_hook(getattr(go, "_GROUP_OFFLOADING", "group_offloading"))
+ if callable(get_hook)
+ else None
+ )
+ group = getattr(hook, "group", None)
+ if (
+ group is None
+ or getattr(group, "stream", None) is not None
+ or getattr(group, "offload_to_disk_path", None)
+ or getattr(getattr(group, "onload_device", None), "type", None) != "cuda"
+ or "onload_" in getattr(group, "__dict__", {})
+ or getattr(group, "_unsloth_resident", False)
+ ):
+ return None
+ tensors = _group_tensors(group)
+ is_torchao = getattr(go, "_is_torchao_tensor", lambda t: False)
+ if not tensors or not any(is_torchao(t) for t in tensors):
+ return None # dense: _pin_top_level_group's compute-stream upload already has no host wait
+ holder = _tensor_holder(tensors)
+ need = _module_host_mib(holder)
+ budget = None if _pinned_memory_capped() else _pin_budget_mib()
+ if budget is None or need > budget:
+ return None
+ to_cpu = getattr(type(group), "_to_cpu", None)
+ if to_cpu is None:
+ return None
+ host = {}
+ for t in tensors:
+ src = t if t.device.type == "cpu" else t.cpu()
+ copy = to_cpu(src, False)
+ if not copy.is_pinned():
+ return None
+ host[t] = copy
+ group.cpu_param_dict = host
+ group.stream = stream
+ group.record_stream = True
+ group.non_blocking = True
+ group.low_cpu_mem_usage = False
+ type(group).offload_(group)
+ if logger is not None:
+ logger.info(
+ "diffusion.memory: %s torchao top-level weights (%d MiB) stream from a pinned copy on the copy stream",
+ type(module).__name__,
+ need,
+ )
+ return group
+
+
+def _tensor_holder(tensors: list) -> Any:
+ class _Holder:
+ def parameters(self, recurse: bool = True):
+ return iter(tensors)
+
+ def buffers(self, recurse: bool = True):
+ return iter(())
+
+ return _Holder()
+
+
+def install_group_prefetch(
+ module: Any,
+ device: Any,
+ logger: Any = None,
+ *,
+ depth: Optional[int] = None,
+) -> int:
+ """Drive ``module``'s streamed diffusers offload groups with a ``GroupPrefetcher``. Returns the number of groups
+ covered (0: unchanged, e.g. kill switch, no CUDA, disk offload, or an older diffusers without stream groups)."""
+ if not async_prefetch_enabled():
+ return 0
+ top = None
+ try:
+ import torch
+
+ if torch.device(device).type != "cuda" or not torch.cuda.is_available():
+ return 0
+ if getattr(module, PREFETCHER_ATTR, None) is not None:
+ return 0
+ from .diffusion_memory import _offload_groups
+
+ go = _go()
+ hook_name = getattr(go, "_GROUP_OFFLOADING", "group_offloading")
+ hooks = []
+ for sub in module.modules():
+ registry = getattr(sub, "_diffusers_hook", None)
+ get_hook = getattr(registry, "get_hook", None)
+ hook = get_hook(hook_name) if callable(get_hook) else None
+ if hook is not None and getattr(hook, "group", None) is not None:
+ hooks.append(hook)
+ groups = [g for g in _offload_groups(module) if getattr(g, "stream", None) is not None]
+
+ def _refusal(g: Any) -> Optional[str]:
+ if getattr(g, "offload_to_disk_path", None):
+ return "disk offload"
+ if getattr(g, "_unsloth_resident", False) or "onload_" in getattr(g, "__dict__", {}):
+ return "onload already replaced"
+ cpu = getattr(g, "cpu_param_dict", None)
+ if not isinstance(cpu, dict) or any(t not in cpu for t in _group_tensors(g)):
+ return "no host copies"
+ if not getattr(g, "record_stream", False):
+ return "record_stream off"
+ return None
+
+ # All or nothing: a stream group left to diffusers would onload itself with no fence once the chain is cut.
+ refused = (
+ next((r for r in map(_refusal, groups) if r), None) if groups else "no stream groups"
+ )
+ if refused:
+ if logger is not None:
+ logger.info(
+ "diffusion.memory: %s keeps diffusers' stream prefetch (%s)",
+ type(module).__name__,
+ refused,
+ )
+ return 0
+ streams = {id(g.stream) for g in groups}
+ if len(streams) != 1:
+ return 0
+ top = _adopt_top_group(module, groups[0].stream, logger)
+ if top is not None:
+ groups = [top] + groups
+ pf = GroupPrefetcher(module, groups, device, prefetch_depth() if depth is None else depth)
+ pf.fence_first = top is None
+ disable = getattr(getattr(torch, "compiler", None), "disable", None)
+
+ def _eager(fn: Any) -> Any:
+ return disable(fn) if callable(disable) else fn
+
+ owned = {id(g) for g in groups}
+ # diffusers' prefetch chain and its tracer would onload the next group with a host sync
+ registry = getattr(module, "_diffusers_hook", None)
+ for name in ("_LAZY_PREFETCH_GROUP_OFFLOADING", "_LAYER_EXECUTION_TRACKER"):
+ key = getattr(go, name, None)
+ if isinstance(key, str) and registry is not None:
+ try:
+ registry.remove_hook(key, recurse = True)
+ except Exception: # noqa: BLE001 - not registered on this module
+ pass
+ for hook in hooks:
+ group = hook.group
+ nxt = getattr(hook, "next_group", None)
+ if id(group) in owned or (nxt is not None and id(nxt) in owned):
+ hook.next_group = None
+ if id(group) in owned:
+ group.onload_self = True
+ group.non_blocking = True
+ for group in groups:
+
+ def onload_(
+ *_a: Any,
+ _g: Any = group,
+ **_k: Any,
+ ) -> None:
+ pf.onload(_g)
+
+ def offload_(
+ *_a: Any,
+ _g: Any = group,
+ **_k: Any,
+ ) -> None:
+ pf.offload(_g)
+
+ group.onload_ = _eager(onload_)
+ group.offload_ = _eager(offload_)
+ group._unsloth_prefetch_onload = group.onload_
+ group._unsloth_prefetcher = pf
+ module.register_forward_pre_hook(_eager(lambda *_a, **_k: pf.begin()))
+ module.register_forward_hook(_eager(lambda *_a, **_k: pf.end()), always_call = True)
+ setattr(module, PREFETCHER_ATTR, pf)
+ state = getattr(module, "_unsloth_stream_state", None)
+ if not isinstance(state, dict):
+ state = {"streamed": 1}
+ try:
+ module._unsloth_stream_state = state
+ except AttributeError:
+ pass
+ state["fenced"] = True
+ state["kick"] = pf.kick
+ if logger is not None:
+ logger.info(
+ "diffusion.memory: %s streams %d offload groups with event-fenced prefetch (%d ahead, %d MiB window)",
+ type(module).__name__,
+ len(groups),
+ pf.depth,
+ pf.window >> 20,
+ )
+ return len(groups)
+ except Exception as exc: # noqa: BLE001 - diffusers' own onload stays
+ if top is not None and "onload_" not in getattr(top, "__dict__", {}):
+ top.stream = None
+ top.record_stream = False
+ if logger is not None:
+ logger.warning("diffusion.memory: event-fenced prefetch unavailable (%s)", exc)
+ return 0
+
+
+def module_prefetcher(module: Any) -> Optional[GroupPrefetcher]:
+ return getattr(module, PREFETCHER_ATTR, None)
diff --git a/studio/backend/tests/test_diffusion_offload_prefetch.py b/studio/backend/tests/test_diffusion_offload_prefetch.py
new file mode 100644
index 00000000000..36830299de6
--- /dev/null
+++ b/studio/backend/tests/test_diffusion_offload_prefetch.py
@@ -0,0 +1,556 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Event-fenced prefetch for block-streamed denoisers (``diffusion_offload_prefetch.py``).
+
+The order / depth / window logic runs on CPU with the copies stubbed. The CUDA cases build real diffusers block-level
+stream group offload through Studio's ``_apply_group_offload`` and check: no host synchronization per group (torch's
+sync debug mode), bit-identical outputs against the resident model, device memory bounded by the window while the host
+runs ahead of a slow GPU, no copy landing in a block the compute stream still reads, and a dropped prefetch never
+landing in a reused block.
+"""
+
+from __future__ import annotations
+
+import copy
+import types
+import warnings
+
+import pytest
+import torch
+
+import core.inference.diffusion_memory as dm
+import core.inference.diffusion_offload_prefetch as op
+
+
[email protected](autouse = True)
+def _clean_env(monkeypatch):
+ for name in (
+ op.ASYNC_PREFETCH_ENV,
+ op.PREFETCH_DEPTH_ENV,
+ "UNSLOTH_DIFFUSION_PARTIAL_RESIDENT",
+ "UNSLOTH_DIFFUSION_GROUP_OFFLOAD_PIN",
+ "UNSLOTH_DIFFUSION_PIN_TOP_GROUP",
+ ):
+ monkeypatch.delenv(name, raising = False)
+
+
+class _Group:
+ def __init__(self, name: str):
+ self.name = name
+
+
+def _cpu_prefetcher(
+ names,
+ nbytes = 10,
+ depth = 2,
+ window = None,
+):
+ groups = [_Group(n) for n in names]
+ pf = op.GroupPrefetcher.__new__(op.GroupPrefetcher)
+ pf.module = None
+ pf.device = torch.device("cpu")
+ pf.depth = depth
+ pf.groups = groups
+ pf.by_id = {id(g): g for g in groups}
+ pf.nbytes = {id(g): nbytes for g in groups}
+ pf.window = window if window is not None else (depth + 1) * nbytes
+ pf.ready, pf.inflight_bytes, pf.peak_inflight_bytes = {}, 0, 0
+ pf.order, pf.seen, pf.pos, pf.active, pf.on_order, pf.pending = [], [], 0, False, False, False
+ pf.stream, pf.fence_first = None, False
+ pf.stats = {"forwards": 0, "copies": 0, "prefetched": 0, "missed": 0, "dropped": 0}
+ log: list = []
+
+ def issue(group):
+ log.append(("copy", group.name))
+ pf.ready[id(group)] = object()
+ pf.inflight_bytes += pf.nbytes[id(group)]
+ pf.peak_inflight_bytes = max(pf.peak_inflight_bytes, pf.inflight_bytes)
+
+ def release(
+ group,
+ event,
+ counted = True,
+ ):
+ log.append(("free", group.name))
+ if counted:
+ pf.inflight_bytes -= pf.nbytes[id(group)]
+
+ class _Compute:
+ def wait_event(self, event):
+ log.append(("wait", None))
+
+ pf._issue = issue
+ pf._release = release
+ pf._compute = lambda: _Compute()
+ pf.owns = lambda g: not getattr(g, "resident", False)
+ return pf, groups, log
+
+
+def _forward(
+ pf,
+ groups,
+ skip = (),
+):
+ pf.begin()
+ for g in groups:
+ if g.name in skip:
+ continue
+ pf.onload(g)
+ pf.offload(g)
+ pf.end()
+
+
+def test_first_forward_records_the_order_and_copies_each_group_when_it_runs():
+ pf, groups, log = _cpu_prefetcher("abcd")
+ _forward(pf, groups)
+ assert pf.order == [id(g) for g in groups]
+ assert [e for e in log if e[0] == "copy"] == [("copy", n) for n in "abcd"]
+ assert pf.stats["missed"] == 0 and pf.inflight_bytes == 0
+
+
+def test_later_forwards_keep_depth_groups_in_flight_ahead():
+ pf, groups, log = _cpu_prefetcher("abcdef", depth = 2)
+ _forward(pf, groups)
+ log.clear()
+ pf.begin()
+ # nothing at the forward start: a top-level upload on the compute stream must reach the copy engine first
+ assert not log
+ pf.onload(groups[0])
+ # the first block queues itself first; running a, b and c are in flight: depth 2 ahead
+ assert [n for k, n in log if k == "copy"] == ["a", "b", "c"]
+ for g in groups:
+ if g is not groups[0]:
+ pf.onload(g)
+ pf.offload(g)
+ pf.end()
+ assert pf.stats["missed"] == 0 and pf.stats["prefetched"] == 6
+ assert pf.peak_inflight_bytes <= pf.window
+
+
+def test_window_bounds_bytes_in_flight():
+ pf, groups, log = _cpu_prefetcher("abcdef", nbytes = 10, depth = 4, window = 25)
+ _forward(pf, groups)
+ for _ in range(2):
+ _forward(pf, groups)
+ assert pf.peak_inflight_bytes <= 25
+
+
+def test_one_group_larger_than_the_window_still_progresses():
+ pf, groups, log = _cpu_prefetcher("abc", nbytes = 10, depth = 2, window = 5)
+ _forward(pf, groups)
+ _forward(pf, groups)
+ assert pf.stats["forwards"] == 2 and pf.inflight_bytes == 0
+
+
+def test_resident_groups_are_skipped_and_not_counted():
+ pf, groups, log = _cpu_prefetcher("abcdef", depth = 2)
+ _forward(pf, groups)
+ for g in groups[:3]:
+ g.resident = True
+ log.clear()
+ pf.begin()
+ assert not log
+ pf.kick()
+ # the streamed tail is queued while the resident head runs
+ assert [n for k, n in log if k == "copy"] == ["d", "e"]
+ pf.kick()
+ assert [n for k, n in log if k == "copy"] == ["d", "e"]
+ pf.end()
+
+
+def test_off_order_forward_stops_prefetch_and_rerecords():
+ pf, groups, log = _cpu_prefetcher("abcdef", depth = 2)
+ _forward(pf, groups)
+ _forward(pf, groups, skip = "c") # a conditional block did not run
+ # the copied-ahead c was freed at the end, and the order now omits it
+ assert ("free", "c") in log
+ assert pf.order == [id(g) for g in groups if g.name != "c"]
+ assert pf.inflight_bytes == 0 and not pf.ready
+
+
+def test_exception_mid_forward_releases_everything_on_the_device():
+ pf, groups, log = _cpu_prefetcher("abcdef", depth = 2)
+ _forward(pf, groups)
+ pf.begin()
+ pf.onload(groups[0])
+ pf.end()
+ assert not pf.ready and pf.inflight_bytes == 0
+
+
+def test_kill_switch_and_cpu_leave_diffusers_alone(monkeypatch):
+ m = torch.nn.Linear(4, 4)
+ assert op.install_group_prefetch(m, "cpu") == 0
+ monkeypatch.setenv(op.ASYNC_PREFETCH_ENV, "0")
+ assert op.install_group_prefetch(m, "cuda") == 0
+
+
+def test_depth_env(monkeypatch):
+ assert op.prefetch_depth() == op.DEFAULT_PREFETCH_DEPTH
+ monkeypatch.setenv(op.PREFETCH_DEPTH_ENV, "1")
+ assert op.prefetch_depth() == 1
+ monkeypatch.setenv(op.PREFETCH_DEPTH_ENV, "99")
+ assert op.prefetch_depth() == op.MAX_PREFETCH_DEPTH
+ monkeypatch.setenv(op.PREFETCH_DEPTH_ENV, "x")
+ assert op.prefetch_depth() == op.DEFAULT_PREFETCH_DEPTH
+
+
+def test_resident_onload_skips_the_copy_stream_wait_when_fenced(monkeypatch):
+ pytest.importorskip(
+ "diffusers.hooks"
+ ) # _keep_groups_resident imports it and leaves the groups alone without it
+
+ class Stream:
+ waits = 0
+
+ def synchronize(self):
+ Stream.waits += 1
+
+ module = types.SimpleNamespace(_unsloth_stream_state = {"streamed": 1, "fenced": True})
+ stream = Stream()
+ groups = [
+ types.SimpleNamespace(
+ modules = [],
+ parameters = [],
+ buffers = [],
+ offload_leader = object(),
+ stream = stream,
+ cpu_param_dict = {},
+ offload_to_disk_path = None,
+ )
+ for _ in range(2)
+ ]
+ monkeypatch.setattr(dm, "_offload_groups", lambda m: groups)
+ dm._keep_groups_resident(module, 1, "cpu")
+ module._unsloth_stream_state["streamed"] = 1
+ for g in groups:
+ g.onload_()
+ assert Stream.waits == 0
+ kicks = []
+ module._unsloth_stream_state["kick"] = lambda: kicks.append(1)
+ for g in groups:
+ g.onload_()
+ assert (
+ Stream.waits == 0 and len(kicks) == 2
+ ) # each resident onload may start the forward's prefetch
+ del module._unsloth_stream_state["kick"]
+ module._unsloth_stream_state["fenced"] = False
+ for g in groups:
+ g.onload_()
+ assert Stream.waits == 2
+
+
+def _cuda():
+ if not torch.cuda.is_available():
+ pytest.skip("needs CUDA: diffusers stream group offload")
+ pytest.importorskip("diffusers.hooks")
+
+
+class _Net(torch.nn.Module):
+ def __init__(
+ self,
+ width = 1024,
+ blocks = 8,
+ sleep_cycles = 0,
+ ):
+ super().__init__()
+ self.proj_in = torch.nn.Linear(64, width)
+ self.blocks = torch.nn.ModuleList(torch.nn.Linear(width, width) for _ in range(blocks))
+ self.proj_out = torch.nn.Linear(width, 64)
+ self.sleep_cycles = sleep_cycles
+
+ def forward(
+ self,
+ x,
+ upto = None,
+ ):
+ x = self.proj_in(x)
+ for i, block in enumerate(self.blocks):
+ if upto is not None and i >= upto:
+ break
+ if self.sleep_cycles:
+ # a slow GPU: the host runs ahead and later copies are queued long before this block reads its weights
+ torch.cuda._sleep(self.sleep_cycles)
+ x = torch.nn.functional.gelu(block(x))
+ return self.proj_out(x)
+
+
+def _streamed(
+ net,
+ resident_mib = None,
+ **kwargs,
+):
+ pipe = types.SimpleNamespace(transformer = net, components = {"transformer": net})
+ if resident_mib:
+ kwargs["resident_transformer_mib"] = resident_mib
+ assert dm._apply_group_offload(pipe, "cuda", None, **kwargs)
+ return pipe
+
+
+def _count_syncs(fn):
+ """Host synchronizations torch reports (stream / device synchronize, blocking copies) while ``fn`` runs."""
+ n = 0
+ prev = torch.cuda.get_sync_debug_mode()
+ torch.cuda.set_sync_debug_mode("warn")
+ try:
+ with warnings.catch_warnings(record = True) as caught:
+ warnings.simplefilter("always")
+ out = fn()
+ n = sum(1 for w in caught if "synchroniz" in str(w.message).lower())
+ finally:
+ torch.cuda.set_sync_debug_mode(prev)
+ return out, n
+
+
[email protected]("depth", ["1", "2", "3"])
[email protected]("resident_mib", [None, 13])
+def test_streamed_forward_is_bit_identical_with_no_host_sync(depth, resident_mib, monkeypatch):
+ _cuda()
+ monkeypatch.setenv(op.PREFETCH_DEPTH_ENV, depth)
+ torch.manual_seed(0)
+ net = _Net()
+ ref = copy.deepcopy(net).cuda()
+ _streamed(net, resident_mib)
+ pf = op.module_prefetcher(net)
+ assert pf is not None and pf.depth == int(depth)
+ x = torch.randn(4, 64, device = "cuda")
+ with torch.no_grad():
+ want = ref(x)
+ net(x)
+ for _ in range(3):
+ got, syncs = _count_syncs(lambda: net(x))
+ assert syncs == 0
+ torch.cuda.synchronize()
+ assert torch.equal(got, want)
+ assert pf.stats["prefetched"] > 0 and pf.stats["missed"] == 0
+ assert pf.peak_inflight_bytes <= pf.window
+ assert net.blocks[-1].weight.device.type == "cpu"
+
+
+def test_dense_top_level_upload_never_waits_behind_a_block_copy(tmp_path):
+ """The dense top-level group uploads on the compute stream at the forward start. Block copies sharing the copy
+ engine with it would hold it back, and the previous forward's last offload already lets the copy stream run, so
+ the first block copies of a forward are fenced behind it: no compute-stream upload overlaps a block copy."""
+ _cuda()
+ import json
+
+ from torch.profiler import ProfilerActivity, profile
+
+ torch.manual_seed(0)
+ net = _Net(width = 4096, blocks = 6)
+ _streamed(net)
+ pf = op.module_prefetcher(net)
+ top = net._diffusers_hook.get_hook("group_offloading").group
+ assert top not in pf.groups and "onload_" in top.__dict__ and pf.fence_first
+ x = torch.randn(4, 64, device = "cuda")
+ with torch.no_grad():
+ net(x)
+ net(x)
+ torch.cuda.synchronize()
+ with profile(activities = [ProfilerActivity.CPU, ProfilerActivity.CUDA]) as prof:
+ for _ in range(4):
+ net(x)
+ torch.cuda.synchronize()
+ trace = tmp_path / "trace.json"
+ prof.export_chrome_trace(str(trace))
+ events = [e for e in json.loads(trace.read_text())["traceEvents"] if e.get("ph") == "X"]
+ compute = {e["args"].get("stream") for e in events if e.get("cat") == "kernel"}
+ h2d = [e for e in events if e.get("cat") == "gpu_memcpy" and "HtoD" in e["name"]]
+ top_up = [(e["ts"], e["ts"] + e["dur"]) for e in h2d if e["args"].get("stream") in compute]
+ blocks = [(e["ts"], e["ts"] + e["dur"]) for e in h2d if e["args"].get("stream") not in compute]
+ assert len(top_up) == 4 * 4 and len(blocks) == 4 * 2 * len(net.blocks)
+ assert not [(a, b) for a in top_up for b in blocks if a[0] < b[1] and b[0] < a[1]]
+ assert pf.stats["missed"] == 0
+
+
+def test_diffusers_stream_path_synchronizes_per_group(monkeypatch):
+ """The base this replaces: the same streamed model through diffusers' own prefetch syncs the host per group."""
+ _cuda()
+ monkeypatch.setenv(op.ASYNC_PREFETCH_ENV, "0")
+ torch.manual_seed(0)
+ net = _Net()
+ _streamed(net)
+ assert op.module_prefetcher(net) is None
+ x = torch.randn(4, 64, device = "cuda")
+ with torch.no_grad():
+ net(x)
+ _out, syncs = _count_syncs(lambda: net(x))
+ assert syncs >= len(net.blocks)
+
+
+def test_slow_gpu_keeps_memory_in_the_window_and_reads_the_right_weights(monkeypatch):
+ """Host far ahead of the GPU: every later copy is queued before the block that frees its memory has run. The copy
+ stream's wait on the offload event keeps those copies out of blocks still being read (outputs bit-identical) and
+ the allocator never grows past the window."""
+ _cuda()
+ monkeypatch.setenv(op.PREFETCH_DEPTH_ENV, "1")
+ torch.manual_seed(0)
+ net = _Net(width = 2048, blocks = 12, sleep_cycles = 20_000_000)
+ with torch.no_grad():
+ for b in net.blocks:
+ b.weight.mul_(
+ 1.0 + torch.rand(())
+ ) # distinct blocks: a wrong-weight read changes the output
+ ref = copy.deepcopy(net).cuda()
+ _streamed(net)
+ pf = op.module_prefetcher(net)
+ x = torch.randn(4, 64, device = "cuda")
+ with torch.no_grad():
+ want = ref(x)
+ net(x)
+ torch.cuda.synchronize()
+ torch.cuda.empty_cache()
+ base = torch.cuda.memory_reserved()
+ torch.cuda.reset_peak_memory_stats()
+ got = net(x)
+ host_ahead = not torch.cuda.current_stream().query()
+ torch.cuda.synchronize()
+ # reserved, not allocated: a block freed under record_stream leaves the allocated count but stays reserved
+ peak = torch.cuda.max_memory_reserved() - base
+ assert torch.equal(got, want)
+ assert host_ahead # the forward returned while the GPU was still running its blocks
+ block_bytes = 2048 * 2048 * 4 + 2048 * 4
+ # window (2 groups) + activations + top-level group; diffusers' record_stream path reserved 204 vs 44 MiB here
+ assert peak <= pf.window + 2 * block_bytes, (peak, pf.window)
+
+
[email protected]("drop", ["exception", "prefix"])
+def test_dropped_prefetch_never_lands_in_a_reused_block(drop, monkeypatch):
+ _cuda()
+ monkeypatch.setenv(op.PREFETCH_DEPTH_ENV, "3")
+ H = 2048
+
+ class Net(torch.nn.Module):
+ def __init__(self):
+ super().__init__()
+ self.blocks = torch.nn.ModuleList(torch.nn.Linear(H, H, bias = False) for _ in range(8))
+
+ def forward(
+ self,
+ x,
+ upto = 8,
+ boom = False,
+ ):
+ for i, m in enumerate(self.blocks):
+ if i >= upto:
+ break
+ if boom and i == 2:
+ raise RuntimeError("boom")
+ x = m(x)
+ return x
+
+ net = Net().to(torch.bfloat16).eval()
+ with torch.no_grad():
+ for p in net.parameters():
+ p.fill_(1.0)
+ _streamed(net)
+ x = torch.zeros(1, H, dtype = torch.bfloat16, device = "cuda")
+ with torch.no_grad():
+ net(x)
+ for _ in range(6):
+ try:
+ net(x, upto = 2, boom = drop == "exception")
+ except RuntimeError:
+ pass
+ outs = [torch.empty(H, H, dtype = torch.bfloat16, device = "cuda") for _ in range(8)]
+ for o in outs:
+ o.fill_(-2.0)
+ torch.cuda.synchronize()
+ assert all(bool((o == -2.0).all()) for o in outs)
+ del outs
+ net(x)
+ torch.cuda.synchronize()
+ pf = op.module_prefetcher(net)
+ assert not pf.ready and pf.inflight_bytes == 0
+
+
+def test_partial_residency_release_and_restore_stay_bit_identical():
+ _cuda()
+ torch.manual_seed(0)
+ net = _Net()
+ ref = copy.deepcopy(net).cuda()
+ pipe = _streamed(net, resident_mib = 17)
+ pf = op.module_prefetcher(net)
+ groups = dm._offload_groups(net)
+ resident = [g for g in groups if getattr(g, "_unsloth_resident", False)]
+ assert resident and len(resident) < len(groups)
+ x = torch.randn(4, 64, device = "cuda")
+ with torch.no_grad():
+ want = ref(x)
+ for _ in range(2):
+ assert torch.equal(net(x), want)
+ restore = dm.release_resident_groups(pipe, 100, None)
+ assert restore is not None
+ for _ in range(2):
+ got, syncs = _count_syncs(lambda: net(x))
+ assert torch.equal(got, want)
+ assert syncs == 0
+ restore()
+ for _ in range(2):
+ assert torch.equal(net(x), want)
+ assert pf.stats["missed"] <= len(groups)
+
+
+def test_unpinned_host_copies_stream_bit_identical(monkeypatch):
+ """low_cpu_mem_usage (host RAM too small to pin): each onload pins through the host allocator."""
+ _cuda()
+ monkeypatch.setenv("UNSLOTH_DIFFUSION_GROUP_OFFLOAD_PIN", "0")
+ torch.manual_seed(0)
+ net = _Net()
+ ref = copy.deepcopy(net).cuda()
+ _streamed(net, stream_text_encoders = True)
+ assert not any(
+ t.is_pinned() for g in dm._offload_groups(net) for t in g.cpu_param_dict.values()
+ )
+ x = torch.randn(4, 64, device = "cuda")
+ with torch.no_grad():
+ want = ref(x)
+ for _ in range(3):
+ assert torch.equal(net(x), want)
+ assert op.module_prefetcher(net).stats["prefetched"] > 0
+
+
[email protected]("version", [None, 2])
+def test_torchao_int8_weights_stream_bit_identical(version):
+ """torchao's default int8 weight (v1 on 0.17) and ``Int8Tensor`` (version 2), whose 0.17 ``to`` drops
+ ``non_blocking`` in its common ``_to_copy``."""
+ _cuda()
+ 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")
+ torch.manual_seed(0)
+ net = _Net().to(torch.bfloat16)
+ try:
+ cfg = Cfg() if version is None else Cfg(version = version)
+ except TypeError:
+ pytest.skip(f"torchao {torchao.__version__} has no versioned Int8WeightOnlyConfig")
+ quantize_(net, cfg)
+ ref = copy.deepcopy(net).cuda()
+ _streamed(net)
+ pf = op.module_prefetcher(net)
+ assert pf is not None
+ # the torchao top-level group (proj_in / proj_out) is driven too, from pinned copies on the copy stream
+ top = net._diffusers_hook.get_hook("group_offloading").group
+ assert top.stream is not None and pf.owns(top)
+ assert all(c.is_pinned() for c in top.cpu_param_dict.values())
+ x = torch.randn(4, 64, device = "cuda", dtype = torch.bfloat16)
+ with torch.no_grad():
+ ref(x)
+ want, ref_syncs = _count_syncs(
+ lambda: ref(x)
+ ) # whatever the resident int8 op itself syncs (torchao 0.17: 1)
+ net(x)
+ for _ in range(3):
+ got, syncs = _count_syncs(lambda: net(x))
+ torch.cuda.synchronize()
+ assert torch.equal(got, want)
+ # offload adds none: torchao 0.17's v1 int8 ``to`` drops non_blocking (6 waits per block without the fix)
+ assert syncs == ref_syncs
+ assert pf.stats["prefetched"] > 0
+ go = pytest.importorskip("diffusers.hooks.group_offloading")
+ # judged by the inner tensors: the torchao wrapper keeps reporting the device it was onloaded to
+ assert dm._placed_on(net.proj_in.weight, "cpu", go._is_torchao_tensor)