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: carry the next forward's first offload groups into the idle copy tail (#15088)

Daniel Hana31803a76ee7
diff --git a/studio/backend/core/inference/diffusion.py b/studio/backend/core/inference/diffusion.py
index 6de7e1de12d..dadb5f1bf8e 100644
--- a/studio/backend/core/inference/diffusion.py
+++ b/studio/backend/core/inference/diffusion.py
@@ -279,6 +279,7 @@ from .diffusion_speed import (
settle_compile_fallback,
snapshot_backend_flags,
)
+from .diffusion_offload_prefetch import cross_forward_render, cross_forward_step
from .diffusion_vae_fp16 import enable_fp16_vae_decode
from .diffusion_vae_upcast import pipeline_upcasts_keep_storage
from .diffusion_vae_tiling import install as install_wide_vae_tiles
@@ -13860,6 +13861,7 @@ class DiffusionBackend:
_report(chunk_ticker[0].completed())
if cancel.is_set():
pipe._interrupt = True
+ cross_forward_step(pipe, step_index)
return callback_kwargs
if "callback_on_step_end" in call_params:
@@ -13892,6 +13894,8 @@ class DiffusionBackend:
sd_controls.variation_strength if sd_controls is not None else None,
),
pipeline_upcasts_keep_storage(pipe),
+ # Only with the step callback: it stops the carry before the last step's decode.
+ cross_forward_render(pipe, enabled = "callback_on_step_end" in chunk_kwargs),
):
return pipe(**chunk_kwargs).images
diff --git a/studio/backend/core/inference/diffusion_cuda_graph.py b/studio/backend/core/inference/diffusion_cuda_graph.py
index adc752f7759..605651d4973 100644
--- a/studio/backend/core/inference/diffusion_cuda_graph.py
+++ b/studio/backend/core/inference/diffusion_cuda_graph.py
@@ -2128,10 +2128,23 @@ class OffloadPlacement:
if self._inner is not None:
self._inner.forward = self._inner_safe
self.module.__dict__["forward"] = handle
+ self._hold_carry(True)
self._enable_slots()
else:
self.module._old_forward = handle
+ def _hold_carry(self, hold: bool) -> None:
+ """A replay bypasses the prefetcher's onloads: nothing is carried into a forward that may replay."""
+ try:
+ pf = self._prefetcher()
+ if pf is None:
+ return
+ pf.graph_hold = hold
+ if hold and not getattr(pf, "active", False):
+ pf.drop_carried()
+ except Exception: # noqa: BLE001
+ pass
+
def _prefetcher(self) -> Any:
from .diffusion_offload_prefetch import module_prefetcher
return module_prefetcher(self.module)
@@ -2216,6 +2229,7 @@ class OffloadPlacement:
if self.mode == "group":
if self.module.__dict__.get("forward") is handle:
self.module.__dict__["forward"] = self.prev
+ self._hold_carry(False)
return
if getattr(self.module, "_old_forward", None) is handle:
self.module._old_forward = self.prev
diff --git a/studio/backend/core/inference/diffusion_offload_prefetch.py b/studio/backend/core/inference/diffusion_offload_prefetch.py
index 107ad19f63e..8d786c9f258 100644
--- a/studio/backend/core/inference/diffusion_offload_prefetch.py
+++ b/studio/backend/core/inference/diffusion_offload_prefetch.py
@@ -14,16 +14,26 @@ Memory stays bounded without a host wait: each offload records a compute-stream
freed block goes to the next prefetch only after the compute that read it. Bytes in flight never pass ``window``.
Unpinned copies' temporary pinned staging is capped at ``window`` (else T4 Z-Image pinned the whole denoiser).
Hooks are per-group / per-module instance attributes; diffusers' classes are untouched.
+
+Cross-forward carry: past the last recorded group, the NEXT forward's first groups are copied into free window
+bytes. Only while a render arms it (never into the last step's decode); held off under a slot ring, step graph,
+capture, or another prefetcher's forward in between (its copies would not be read next).
"""
from __future__ import annotations
import os
+import threading
+import weakref
from collections import deque
-from typing import Any, Optional
+from contextlib import contextmanager
+from typing import Any, Iterator, Optional
ASYNC_PREFETCH_ENV = "UNSLOTH_DIFFUSION_ASYNC_PREFETCH"
PREFETCH_DEPTH_ENV = "UNSLOTH_DIFFUSION_PREFETCH_DEPTH"
+CROSS_FORWARD_ENV = "UNSLOTH_DIFFUSION_PREFETCH_CROSS_FORWARD"
+# Groups carried while the last streamed block still runs (see GroupPrefetcher._carry).
+TAIL_CARRY_GROUPS = 1
DEFAULT_PREFETCH_DEPTH = 2
MAX_PREFETCH_DEPTH = 8
PREFETCHER_ATTR = "_unsloth_group_prefetcher"
@@ -53,6 +63,19 @@ def async_prefetch_enabled() -> bool:
)
+def cross_forward_enabled() -> bool:
+ return (os.environ.get(CROSS_FORWARD_ENV) or "").strip().lower() not in (
+ "0",
+ "off",
+ "false",
+ "no",
+ )
+
+
+# Per thread: the prefetcher whose forward began last (detects interleaved prefetchers).
+_LAST_BEGUN = threading.local()
+
+
def prefetch_depth() -> int:
raw = (os.environ.get(PREFETCH_DEPTH_ENV) or "").strip()
try:
@@ -339,6 +362,10 @@ class GroupPrefetcher:
# the capture at begin() and back at end(), so the copies become graph nodes refilling the same buffers.
self.capturing = False
self.stats = {"forwards": 0, "copies": 0, "prefetched": 0, "missed": 0, "dropped": 0}
+ self.carried: set = set()
+ self.armed = False
+ self.interleaved = False
+ self.graph_hold = False
# Slot ring (``enable_slots``): group id -> slot index; a streamed group's copy lands in place in that slot,
# always at the same offsets, so the blocks a CUDA graph recorded read the same addresses every step.
self.slot_of: dict = {}
@@ -478,6 +505,10 @@ class GroupPrefetcher:
self.stats["missed"] += 1
elif self.ready[gid] is not None:
self.stats["prefetched"] += 1
+ carried = getattr(self, "carried", None)
+ if carried and gid in carried:
+ carried.discard(gid)
+ self.stats["carried_hits"] = self.stats.get("carried_hits", 0) + 1
event = self.ready[gid]
if event is not None:
self._compute().wait_event(event)
@@ -486,6 +517,9 @@ class GroupPrefetcher:
def offload(self, group: Any) -> None:
gid = id(group)
+ carried = getattr(self, "carried", None)
+ if carried:
+ carried.discard(gid)
if gid in self.ready:
self._release(group, self.ready.pop(gid))
else:
@@ -526,6 +560,9 @@ class GroupPrefetcher:
if group is not None and self.owns(group):
continue
event = self.ready.pop(gid)
+ carried = getattr(self, "carried", None)
+ if carried:
+ carried.discard(gid)
if event is not None:
compute = compute or self._compute()
compute.wait_event(event)
@@ -547,7 +584,7 @@ class GroupPrefetcher:
ahead = 0
for gid in self.order[self.pos :]:
if ahead >= self.depth:
- break
+ return
group = self.by_id.get(gid)
if group is None or not self.owns(group):
continue # made resident since the order was recorded
@@ -555,13 +592,71 @@ class GroupPrefetcher:
ahead += 1
continue
if self.inflight_bytes + self.nbytes.get(gid, 0) > self.window and self.ready:
- break
+ return
if getattr(self, "slot_of", None):
if not self._issue(group, must = False):
- break # its slot still holds a group the compute has not finished with
+ return # its slot still holds a group the compute has not finished with
else:
self._issue(group)
ahead += 1
+ if ahead < self.depth and self.pos >= len(self.order) and self.may_carry():
+ self._carry(ahead)
+
+ def carry_usable(self) -> bool:
+ return bool(
+ not getattr(self, "interleaved", False)
+ and not getattr(self, "graph_hold", False)
+ and not getattr(self, "slot_of", None)
+ and cross_forward_enabled()
+ )
+
+ def may_carry(self) -> bool:
+ return bool(
+ getattr(self, "armed", False)
+ and not getattr(self, "capturing", False)
+ and self.carry_usable()
+ )
+
+ def _carry(self, ahead: int) -> None:
+ """While the last block runs, at most ``TAIL_CARRY_GROUPS``: its activations are live and the allocator's peak
+ follows host order, so a second group beside them lifts the peak (FLUX at 32k tokens); after it frees, the
+ rest of the depth follows."""
+ carried = self.__dict__.setdefault("carried", set())
+ running = any(gid not in carried for gid in self.ready)
+ limit = min(self.depth, TAIL_CARRY_GROUPS) if running else self.depth
+ due = set(self.order[self.pos :])
+ for gid in self.order:
+ if ahead >= limit or gid in due:
+ return # a short order wraps onto groups this forward still runs: no carry past them
+ group = self.by_id.get(gid)
+ if group is None or not self.owns(group):
+ continue
+ if gid in self.ready:
+ if gid not in carried:
+ return # still on the device from this forward (a group reused in the order)
+ ahead += 1
+ continue
+ if self.inflight_bytes + self.nbytes.get(gid, 0) > self.window and self.ready:
+ return
+ self._issue(group)
+ carried.add(gid)
+ self.stats["carried"] = self.stats.get("carried", 0) + 1
+ ahead += 1
+
+ def drop_carried(self) -> int:
+ """Release carried copies (outside a capture). Returns how many."""
+ carried = getattr(self, "carried", None)
+ if not carried:
+ return 0
+ n = 0
+ for gid in list(carried):
+ group = self.by_id.get(gid)
+ if gid in self.ready and group is not None:
+ self._release(group, self.ready.pop(gid))
+ n += 1
+ carried.clear()
+ self.stats["carried_dropped"] = self.stats.get("carried_dropped", 0) + n
+ return n
def _holds_slot(self, group: Any) -> bool:
where = self.slot_of.get(id(group))
@@ -574,6 +669,8 @@ class GroupPrefetcher:
first use). The top-level group keeps fresh copies: no graph reads it."""
if self.slot_of:
return self.slot_bytes_planned >> 20
+ if not self.active:
+ self.drop_carried() # carried copies sit at fresh addresses, not in a slot a graph would read
members: list = []
size = 0
for group in self.groups:
@@ -687,18 +784,39 @@ class GroupPrefetcher:
def begin(self) -> None:
self.stats["forwards"] += 1
self._forget_disowned()
+ capturing = False
+ if self.stream is not None:
+ import torch
+ capturing = bool(torch.cuda.is_current_stream_capturing())
+ if getattr(self, "carried", None):
+ if capturing:
+ raise RuntimeError(
+ "copies carried from the previous forward are still on the device"
+ )
+ if not self.carry_usable() and not getattr(self, "active", False):
+ self.drop_carried()
+ self._note_begun()
self.seen = []
self.pos = 0
self.active = True
self.on_order = bool(self.order)
self.pending = True
self.capturing = False
- if self.stream is not None:
- import torch
- if torch.cuda.is_current_stream_capturing():
- # fork the copy stream into the capture before anything is queued on it
- self.capturing = True
- self.stream.wait_stream(self._compute())
+ if capturing:
+ self.capturing = True
+ self.stream.wait_stream(self._compute())
+
+ def _note_begun(self) -> None:
+ prev_ref = getattr(_LAST_BEGUN, "pf", None)
+ prev = prev_ref() if prev_ref is not None else None
+ if prev is not None and prev is not self and getattr(prev, "armed", False):
+ prev.interleaved = True
+ if not getattr(prev, "active", False):
+ prev.drop_carried()
+ try:
+ _LAST_BEGUN.pf = weakref.ref(self)
+ except TypeError:
+ _LAST_BEGUN.pf = None
def kick(self) -> None:
"""First block onload of a forward (streamed or resident): queue the first ``depth`` streamed groups."""
@@ -715,16 +833,29 @@ class GroupPrefetcher:
def end(self) -> None:
if not self.active:
return
+ # carried copies survive only an on-order (or skipped) forward: otherwise the next may read other groups
+ finished = bool(self.on_order and self.pos == len(self.order)) or not self.seen
self.active = False
self.on_order = False
self.pending = False
self._forget_disowned()
+ carried = getattr(self, "carried", None) or set()
+ keep = set(carried) if carried and finished and self.may_carry() else set()
+ if carried and not keep:
+ self.stats["carried_dropped"] = self.stats.get("carried_dropped", 0) + sum(
+ 1 for gid in carried if gid in self.ready
+ )
+ carried.clear()
for gid in list(self.ready):
+ if gid in keep:
+ continue
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
+ for gid in list(self.ready):
+ if gid not in keep:
+ self.ready.pop(gid)
+ self.inflight_bytes = sum(self.nbytes.get(gid, 0) for gid in self.ready)
if getattr(self, "capturing", False):
self.capturing = False
self._compute().wait_stream(
@@ -742,6 +873,8 @@ class GroupPrefetcher:
self.active = self.on_order = self.pending = self.capturing = False
self.ready.clear()
+ if getattr(self, "carried", None):
+ self.carried.clear()
self.inflight_bytes = 0
self._staging().clear() # nothing is staged under capture; the synchronize below lands the rest
self.staged_bytes = 0
@@ -1025,3 +1158,73 @@ def capture_refusal(module: Any) -> Optional[str]:
except Exception as exc: # noqa: BLE001 - unknown layout: never capture it
return f"offload layout unreadable ({type(exc).__name__})"
return None
+
+
+def _pipe_prefetchers(pipe: Any) -> list:
+ out: list = []
+ seen: set = set()
+ comps = getattr(pipe, "components", None)
+ values = list(comps.values()) if isinstance(comps, dict) else [pipe]
+ for value in values:
+ pf = module_prefetcher(value) if value is not None else None
+ if pf is not None and id(pf) not in seen:
+ seen.add(id(pf))
+ out.append(pf)
+ return out
+
+
+def _disarm(pf: Any) -> None:
+ pf.armed = False
+ if not getattr(pf, "active", False):
+ pf.drop_carried()
+
+
+@contextmanager
+def cross_forward_render(pipe: Any, enabled: bool = True) -> Iterator[list]:
+ """Arm carry for one pipeline call; nothing carried stays on exit. Not beside a ControlNet (runs between forwards)."""
+ comps = getattr(pipe, "components", None)
+ beside = isinstance(comps, dict) and any(
+ "controlnet" in str(name).lower() and value is not None for name, value in comps.items()
+ )
+ pfs = _pipe_prefetchers(pipe) if enabled and not beside and cross_forward_enabled() else []
+ if pfs:
+ _LAST_BEGUN.pf = None # interleaving counts within this render only
+ for pf in pfs:
+ pf.interleaved = False
+ pf.armed = True
+ try:
+ yield pfs
+ finally:
+ for pf in pfs:
+ try:
+ _disarm(pf)
+ except Exception: # noqa: BLE001 - leave the render's own error to surface
+ pass
+
+
+def cross_forward_step(
+ pipe: Any,
+ step_index: int,
+ total: Optional[int] = None,
+) -> None:
+ """From ``callback_on_step_end``: the final step drops carried copies so nothing is on the card at decode (also
+ interrupted or unknown-length renders)."""
+ pfs = [
+ pf
+ for pf in _pipe_prefetchers(pipe)
+ if getattr(pf, "armed", False) or getattr(pf, "carried", None)
+ ]
+ if not pfs:
+ return
+ if total is None:
+ total = getattr(pipe, "_num_timesteps", None)
+ try:
+ total = int(total) if total is not None else None
+ except (TypeError, ValueError):
+ total = None
+ stop = total is None or bool(getattr(pipe, "_interrupt", False))
+ for pf in pfs:
+ if stop or int(step_index) + 1 >= total:
+ _disarm(pf)
+ elif int(step_index) + 2 >= total:
+ pf.armed = False # the last step reads what this one carried, and carries nothing on
diff --git a/studio/backend/tests/test_diffusion_offload_cross_forward.py b/studio/backend/tests/test_diffusion_offload_cross_forward.py
new file mode 100644
index 00000000000..3f67051f618
--- /dev/null
+++ b/studio/backend/tests/test_diffusion_offload_cross_forward.py
@@ -0,0 +1,485 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Cross-forward carry of the next forward's first groups."""
+
+from __future__ import annotations
+
+import copy
+import types
+
+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,
+ op.CROSS_FORWARD_ENV,
+ "UNSLOTH_DIFFUSION_PARTIAL_RESIDENT",
+ "UNSLOTH_DIFFUSION_GROUP_OFFLOAD_PIN",
+ "UNSLOTH_DIFFUSION_PIN_TOP_GROUP",
+ ):
+ monkeypatch.delenv(name, raising = False)
+ op._LAST_BEGUN.pf = None
+ yield
+ op._LAST_BEGUN.pf = None
+
+
+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}
+ pf.carried, pf.armed, pf.interleaved, pf.graph_hold = set(), False, False, False
+ log: list = []
+
+ def issue(group, must = True):
+ assert id(group) not in pf.ready, "a group copied twice while on the device"
+ 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))
+
+ def wait_stream(self, stream):
+ log.append(("join", 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 _pipe(*pfs):
+ comps = {
+ f"transformer_{i}": types.SimpleNamespace(**{op.PREFETCHER_ATTR: pf})
+ for i, pf in enumerate(pfs)
+ }
+ return types.SimpleNamespace(components = comps, _interrupt = False)
+
+
+def _render(
+ pf,
+ groups,
+ steps,
+ forwards_per_step = 1,
+ pipe = None,
+):
+ pipe = pipe or _pipe(pf)
+ with op.cross_forward_render(pipe):
+ for i in range(steps):
+ for _ in range(forwards_per_step):
+ _forward(pf, groups)
+ op.cross_forward_step(pipe, i, steps)
+ return pipe
+
+
+def _copies(log):
+ return [n for k, n in log if k == "copy"]
+
+
+def test_carry_wraps_onto_the_next_forwards_first_groups():
+ pf, groups, log = _cpu_prefetcher("abcdef", depth = 2)
+ _forward(pf, groups) # records the order
+ pf.armed = True
+ log.clear()
+ _forward(pf, groups)
+ # the tail queued the next forward's first two groups; they stay on the device past end()
+ assert _copies(log)[-2:] == ["a", "b"]
+ assert pf.carried == {id(groups[0]), id(groups[1])}
+ assert set(pf.ready) == pf.carried and pf.inflight_bytes == 20
+ log.clear()
+ pf.begin()
+ pf.onload(groups[0])
+ assert _copies(log) == ["c"]
+ assert pf.stats["carried_hits"] == 1
+ 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["carried_hits"] == 2
+
+
+def test_while_the_last_block_runs_only_one_group_is_carried():
+ pf, groups, log = _cpu_prefetcher("abcdef", depth = 2)
+ _forward(pf, groups)
+ pf.armed = True
+ pf.begin()
+ for g in groups[:-1]:
+ pf.onload(g)
+ pf.offload(g)
+ assert not pf.carried # a block of this forward is still due: nothing carried
+ pf.onload(groups[-1])
+ # its activations are live: one group beside them, never the full depth
+ assert pf.carried == {id(groups[0])} and op.TAIL_CARRY_GROUPS == 1
+ pf.offload(groups[-1])
+ # the forward's activations are freed: the rest of the depth follows
+ assert pf.carried == {id(groups[0]), id(groups[1])}
+ pf.end()
+ assert set(pf.ready) == pf.carried and pf.peak_inflight_bytes <= pf.window
+
+
+def test_unarmed_prefetcher_is_unchanged():
+ pf, groups, log = _cpu_prefetcher("abcdef", depth = 2)
+ ref, ref_groups, ref_log = _cpu_prefetcher("abcdef", depth = 2)
+ for _ in range(4):
+ _forward(pf, groups)
+ _forward(ref, ref_groups)
+ assert not pf.ready and pf.inflight_bytes == 0
+ assert log == ref_log and not pf.stats.get("carried")
+
+
[email protected]("depth,window", [(2, None), (4, 25), (3, 35), (1, None)])
+def test_carry_never_passes_the_window(depth, window):
+ pf, groups, log = _cpu_prefetcher("abcdefgh", nbytes = 10, depth = depth, window = window)
+ _forward(pf, groups)
+ pf.armed = True
+ for _ in range(4):
+ _forward(pf, groups)
+ assert pf.peak_inflight_bytes <= pf.window
+ ahead = len(pf.carried)
+ assert ahead <= depth and pf.inflight_bytes == 10 * ahead
+ assert pf.stats["carried"] > 0 and pf.stats["missed"] == 0
+
+
+def test_final_step_carries_nothing_into_the_decode():
+ pf, groups, log = _cpu_prefetcher("abcdef", depth = 2)
+ _forward(pf, groups)
+ pipe = _pipe(pf)
+ with op.cross_forward_render(pipe):
+ for i in range(4):
+ _forward(pf, groups)
+ op.cross_forward_step(pipe, i, 4)
+ if i == 2:
+ # the second-to-last step's carry is kept for the last step, which carries nothing on
+ assert not pf.armed and len(pf.carried) == 2
+ # decode runs here (inside the pipeline call): no streamed group is on the device
+ assert not pf.ready and not pf.carried and pf.inflight_bytes == 0
+ assert pf.stats["carried_hits"] == 6 and pf.stats.get("carried_dropped", 0) == 0
+
+
+def test_skipped_final_forward_drops_the_carry_at_the_last_callback():
+ pf, groups, log = _cpu_prefetcher("abcdef", depth = 2)
+ _forward(pf, groups)
+ pipe = _pipe(pf)
+ with op.cross_forward_render(pipe):
+ for i in range(3):
+ if i < 2:
+ _forward(pf, groups)
+ op.cross_forward_step(pipe, i, 3) # step 2's forward skipped (step cache)
+ assert not pf.ready and not pf.carried and pf.inflight_bytes == 0
+ assert pf.stats["carried_dropped"] == 2
+
+
+def test_step_count_from_the_pipeline_and_unknown_count_disarms():
+ pf, groups, log = _cpu_prefetcher("abcdef", depth = 2)
+ _forward(pf, groups)
+ pipe = _pipe(pf)
+ pipe._num_timesteps = 5
+ with op.cross_forward_render(pipe):
+ _forward(pf, groups)
+ op.cross_forward_step(pipe, 0)
+ assert pf.armed and pf.carried
+ pf2, groups2, _ = _cpu_prefetcher("abcdef", depth = 2)
+ _forward(pf2, groups2)
+ pipe2 = _pipe(pf2) # no _num_timesteps: the last step cannot be told apart
+ with op.cross_forward_render(pipe2):
+ _forward(pf2, groups2)
+ op.cross_forward_step(pipe2, 0)
+ assert not pf2.armed and not pf2.carried and not pf2.ready
+
+
+def test_interrupted_render_drops_the_carry():
+ pf, groups, log = _cpu_prefetcher("abcdef", depth = 2)
+ _forward(pf, groups)
+ pipe = _pipe(pf)
+ with op.cross_forward_render(pipe):
+ _forward(pf, groups)
+ pipe._interrupt = True
+ op.cross_forward_step(pipe, 0, 10)
+ assert not pf.armed and not pf.ready and pf.inflight_bytes == 0
+
+
+def test_render_exit_drops_the_carry_even_on_error():
+ pf, groups, log = _cpu_prefetcher("abcdef", depth = 2)
+ _forward(pf, groups)
+ with pytest.raises(ValueError):
+ with op.cross_forward_render(_pipe(pf)):
+ _forward(pf, groups)
+ assert pf.carried
+ raise ValueError("boom")
+ assert not pf.armed and not pf.ready and not pf.carried and pf.inflight_bytes == 0
+
+
[email protected]("forwards_per_step", [1, 2])
+def test_cfg_double_forward_reads_every_carry(forwards_per_step):
+ pf, groups, log = _cpu_prefetcher("abcdefg", depth = 2)
+ _forward(pf, groups)
+ steps = 4
+ _render(pf, groups, steps, forwards_per_step)
+ forwards = steps * forwards_per_step
+ # the last step carries nothing (the callback cannot tell its forwards apart)
+ assert pf.stats["carried_hits"] == 2 * (forwards - forwards_per_step)
+ assert pf.stats["carried"] == 2 * (forwards - forwards_per_step)
+ assert pf.stats.get("carried_dropped", 0) == 0 and pf.stats["missed"] == 0
+ assert not pf.ready and pf.inflight_bytes == 0
+
+
+def test_kill_switch(monkeypatch):
+ monkeypatch.setenv(op.CROSS_FORWARD_ENV, "0")
+ pf, groups, log = _cpu_prefetcher("abcdef", depth = 2)
+ _forward(pf, groups)
+ ref, ref_groups, ref_log = _cpu_prefetcher("abcdef", depth = 2)
+ _forward(ref, ref_groups)
+ log.clear()
+ ref_log.clear()
+ _render(pf, groups, 3, 2)
+ for _ in range(6):
+ _forward(ref, ref_groups)
+ assert log == ref_log
+ assert not pf.stats.get("carried") and not pf.armed
+
+
+def test_graph_hold_and_slot_ring_block_and_drop_the_carry():
+ pf, groups, log = _cpu_prefetcher("abcdef", depth = 2)
+ _forward(pf, groups)
+ pf.armed = True
+ _forward(pf, groups)
+ assert pf.carried
+ pf.graph_hold = True # a step graph installed between forwards: a replay would not read them
+ pf.begin()
+ assert not pf.carried and pf.inflight_bytes == 0 and pf.stats["carried_dropped"] == 2
+ for g in groups:
+ pf.onload(g)
+ pf.offload(g)
+ pf.end()
+ assert not pf.ready and not pf.stats.get("carried_hits")
+ pf.graph_hold = False
+ pf.slot_of = {id(groups[0]): 0}
+ _forward(pf, groups)
+ assert not pf.ready and not pf.carried
+
+
+def test_capture_never_starts_on_carried_copies(monkeypatch):
+ pf, groups, log = _cpu_prefetcher("abcdef", depth = 2)
+ _forward(pf, groups)
+ pf.armed = True
+ _forward(pf, groups)
+ assert pf.carried
+ pf.stream = types.SimpleNamespace(wait_stream = lambda s: None)
+ monkeypatch.setattr(torch.cuda, "is_current_stream_capturing", lambda: True)
+ with pytest.raises(RuntimeError, match = "carried"):
+ pf.begin()
+
+
+def test_capturing_forward_carries_nothing(monkeypatch):
+ pf, groups, log = _cpu_prefetcher("abcdef", depth = 2)
+ _forward(pf, groups)
+ pf.armed = True
+ pf.stream = types.SimpleNamespace(wait_stream = lambda s: None)
+ monkeypatch.setattr(torch.cuda, "is_current_stream_capturing", lambda: True)
+ _forward(pf, groups)
+ assert not pf.carried and not pf.ready
+
+
+def test_another_prefetcher_between_forwards_drops_and_stops_the_carry():
+ a, ga, _ = _cpu_prefetcher("abcdef", depth = 2)
+ b, gb, _ = _cpu_prefetcher("uvwxyz", depth = 2)
+ _forward(a, ga)
+ _forward(b, gb)
+ pipe = _pipe(a, b)
+ with op.cross_forward_render(pipe):
+ _forward(a, ga)
+ assert a.carried
+ _forward(b, gb) # a second denoiser runs next: a's carried copies would sit through it
+ assert a.interleaved and not a.carried and not a.ready
+ for _ in range(2):
+ _forward(b, gb)
+ assert b.carried and not b.interleaved
+ _forward(a, ga)
+ assert not a.carried and b.interleaved and not b.ready
+ assert a.inflight_bytes == 0 and b.inflight_bytes == 0
+
+
+def test_not_armed_beside_a_controlnet():
+ pf, groups, log = _cpu_prefetcher("abcdef", depth = 2)
+ _forward(pf, groups)
+ pipe = _pipe(pf)
+ pipe.components["controlnet"] = object()
+ with op.cross_forward_render(pipe) as armed:
+ assert armed == [] and not pf.armed
+ _forward(pf, groups)
+ assert not pf.carried
+
+
+def test_off_order_forward_drops_the_carry():
+ pf, groups, log = _cpu_prefetcher("abcdef", depth = 2)
+ _forward(pf, groups)
+ pf.armed = True
+ _forward(pf, groups)
+ assert pf.carried
+ _forward(pf, groups, skip = "c") # off the recorded order: re-recorded, nothing carried on
+ assert not pf.carried and not pf.ready and pf.inflight_bytes == 0
+ _forward(pf, groups, skip = "c") # back on the (new) order: carries again
+ assert pf.carried
+
+
+def test_skipped_forward_keeps_the_carry():
+ pf, groups, log = _cpu_prefetcher("abcdef", depth = 2)
+ _forward(pf, groups)
+ pf.armed = True
+ _forward(pf, groups)
+ carried = set(pf.carried)
+ pf.begin()
+ pf.end() # a cached step: no block ran
+ assert pf.carried == carried and pf.inflight_bytes == 20
+ _forward(pf, groups)
+ assert pf.stats["carried_hits"] == 2
+
+
+def test_short_order_never_carries_a_group_still_due():
+ pf, groups, log = _cpu_prefetcher("ab", depth = 2)
+ _forward(pf, groups)
+ pf.armed = True
+ for _ in range(3):
+ _forward(pf, groups)
+ assert pf.inflight_bytes == 10 * len(pf.carried) <= pf.window
+ assert pf.stats["missed"] == 0
+
+
+def test_resident_groups_are_not_carried():
+ pf, groups, log = _cpu_prefetcher("abcdef", depth = 2)
+ _forward(pf, groups)
+ groups[0].resident = True
+ pf.armed = True
+ _forward(pf, groups)
+ assert pf.carried == {id(groups[1]), id(groups[2])}
+
+
+# CUDA: real diffusers stream group offload
+
+
+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):
+ x = self.proj_in(x)
+ for block in self.blocks:
+ if self.sleep_cycles:
+ torch.cuda._sleep(self.sleep_cycles)
+ x = torch.nn.functional.gelu(block(x))
+ return self.proj_out(x)
+
+
+def _streamed(net):
+ pipe = types.SimpleNamespace(transformer = net, components = {"transformer": net}, _interrupt = False)
+ assert dm._apply_group_offload(pipe, "cuda", None)
+ return pipe
+
+
[email protected]("sleep_cycles", [0, 2_000_000])
[email protected]("cfg", [False, True])
+def test_streamed_render_is_bit_identical_and_leaves_nothing_resident(sleep_cycles, cfg):
+ _cuda()
+ torch.manual_seed(0)
+ net = _Net(sleep_cycles = sleep_cycles)
+ ref = copy.deepcopy(net).cuda()
+ pipe = _streamed(net)
+ pf = op.module_prefetcher(net)
+ assert pf is not None
+ xs = [torch.randn(4, 64, device = "cuda") for _ in range(2)]
+ steps = 4
+
+ def run(model, on_step):
+ x = xs[0]
+ for i in range(steps):
+ v = model(x)
+ if cfg:
+ v = v + 0.5 * model(xs[1] + x)
+ x = x - 0.1 * v
+ on_step(i)
+ return x
+
+ with torch.no_grad():
+ want = run(ref, lambda i: None)
+ net(xs[0]) # records the order
+ with op.cross_forward_render(pipe):
+ got = run(net, lambda i: op.cross_forward_step(pipe, i, steps))
+ torch.cuda.synchronize()
+ # where the decode runs: no streamed block left on the device
+ assert all(b.weight.device.type == "cpu" for b in net.blocks)
+ assert not pf.ready and not pf.carried and pf.inflight_bytes == 0
+ assert torch.equal(got, want)
+ forwards = steps * (2 if cfg else 1)
+ assert pf.stats["carried_hits"] == pf.stats["carried"] > 0
+ assert pf.stats["carried_hits"] == 2 * (forwards - (2 if cfg else 1))
+ assert pf.stats["missed"] == 0 and pf.peak_inflight_bytes <= pf.window