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: run the Qwen-Image-2.1 CFG branch on the replica with its own prefix KV cache (#14954)

Daniel Han036bf6ab7d6d
diff --git a/studio/backend/core/inference/diffusion_multigpu.py b/studio/backend/core/inference/diffusion_multigpu.py
index cdfa46941e9..0b9865ffce5 100644
--- a/studio/backend/core/inference/diffusion_multigpu.py
+++ b/studio/backend/core/inference/diffusion_multigpu.py
@@ -1350,9 +1350,14 @@ def placement_status(pipe: Any) -> Optional[dict[str, Any]]:
elif declined is not None:
out["cfg_parallel"] = {"armed": False, "declined": declined}
if decision is not None:
- out["decision"] = _live_decision(
- pipe, decision, info, layer, declined if cfg is None else None
- )
+ if cfg is None:
+ cfg_rejected = declined
+ elif cfg.disabled_reason not in (None, "uninstalled"):
+ # armed, then fell back to one card at run time: say so where the placement is reported
+ cfg_rejected = f"disabled at run time: {cfg.disabled_reason}"
+ else:
+ cfg_rejected = None
+ out["decision"] = _live_decision(pipe, decision, info, layer, cfg_rejected)
return out
@@ -1898,12 +1903,95 @@ def _holds_opaque_tensors(obj: Any, depth: int = 0) -> bool:
isinstance(value, (list, tuple, dict)) and next(_iter_tensors(value), None) is not None
):
return True
- if not isinstance(value, (*_PLAIN_TYPES, list, tuple, dict)) and depth < 4:
- if _holds_opaque_tensors(value, depth + 1):
- return True
+ if (
+ depth < 4
+ and not isinstance(value, _PLAIN_TYPES)
+ and _holds_opaque_tensors(value, depth + 1)
+ ):
+ return True
return False
+# Prefix-KV cache (Qwen-Image-2.1): step-0 prefill ("extract") runs on the primary; "cached" odd branches use a replica copy.
+_KV_KWARG = "kv_cache"
+_KV_MODE_KWARG = "kv_cache_mode"
+
+
+class _Unmirrorable(Exception):
+ pass
+
+
+def _walk_cache(
+ obj: Any,
+ move: Optional[Callable[[Any], Any]],
+ found: list,
+ depth: int = 0,
+) -> Any:
+ """Structural copy of a cache object (``move`` applied to every tensor), or with ``move`` None only the tensors
+ collected into ``found``. Raises :class:`_Unmirrorable` on anything but plain values, containers and ``__dict__``
+ value holders (a module, a slotted or foreign object), which then stays on the primary."""
+ torch = _torch()
+ if isinstance(obj, torch.Tensor):
+ found.append(obj)
+ return move(obj) if move is not None else obj
+ if isinstance(obj, (*_PLAIN_TYPES, torch.device, torch.dtype)):
+ return obj
+ if depth >= 4 or isinstance(obj, torch.nn.Module):
+ raise _Unmirrorable(type(obj).__name__)
+ if isinstance(obj, list):
+ out = [_walk_cache(v, move, found, depth + 1) for v in obj]
+ return out if move is not None else obj
+ if isinstance(obj, tuple) and not hasattr(obj, "_fields"):
+ out_t = tuple(_walk_cache(v, move, found, depth + 1) for v in obj)
+ return out_t if move is not None else obj
+ if isinstance(obj, dict) and type(obj) is dict:
+ out_d = {k: _walk_cache(v, move, found, depth + 1) for k, v in obj.items()}
+ return out_d if move is not None else obj
+ attrs = getattr(obj, "__dict__", None)
+ if type(attrs) is not dict or hasattr(type(obj), "__slots__"):
+ raise _Unmirrorable(type(obj).__name__)
+ copied = {k: _walk_cache(v, move, found, depth + 1) for k, v in attrs.items()}
+ if move is None:
+ return obj
+ cls = type(obj)
+ clone = cls.__new__(cls) # not object.__new__: a C base (SimpleNamespace) refuses it
+ clone.__dict__.update(copied)
+ return clone
+
+
+def _cache_tensors(cache: Any) -> Optional[list]:
+ """Tensors held by a mirrorable cache, in fixed order; None if not mirrorable."""
+ torch = _torch()
+ if cache is None or isinstance(cache, (torch.Tensor, list, tuple, dict, *_PLAIN_TYPES)):
+ return None
+ found: list = []
+ try:
+ _walk_cache(cache, None, found)
+ except _Unmirrorable:
+ return None
+ return found
+
+
+def _prefix_kv_mode(kwargs: Any) -> Optional[str]:
+ if not isinstance(kwargs, dict) or kwargs.get(_KV_KWARG) is None:
+ return None
+ mode = kwargs.get(_KV_MODE_KWARG)
+ if mode not in ("extract", "cached"):
+ return None
+ return mode if _cache_tensors(kwargs[_KV_KWARG]) is not None else None
+
+
+def _is_prefill(kwargs: Any) -> bool:
+ """A prefill writes (or returns, FLUX.2) the cache the pipeline reads back: always on the primary."""
+ return isinstance(kwargs, dict) and kwargs.get(_KV_MODE_KWARG) == "extract"
+
+
+def _without_prefix_kv(args: tuple, kwargs: dict) -> tuple:
+ if _prefix_kv_mode(kwargs) != "cached":
+ return args, kwargs
+ return args, {k: v for k, v in kwargs.items() if k != _KV_KWARG}
+
+
def _iter_tensors(obj: Any, depth: int = 0) -> Iterator[Any]:
torch = _torch()
if isinstance(obj, torch.Tensor):
@@ -2237,6 +2325,9 @@ def _call_signature(args: tuple, kwargs: dict) -> tuple:
sig.append((path, leaf))
elif isinstance(leaf, (int, float)):
sig.append((path, type(leaf), leaf))
+ elif path and path[-1] == _KV_KWARG and (held := _cache_tensors(leaf)) is not None:
+ # a new prefix length (another prompt) may compile: it must not count as warm
+ sig.append((path, type(leaf), tuple((tuple(t.shape), t.dtype) for t in held)))
else:
sig.append((path, type(leaf)))
return (
@@ -2323,7 +2414,15 @@ class CfgParallelRouter:
"opaque_primary_calls": 0,
"pairs_parallel": 0,
"exclusion_skips": 0,
+ "kv_cache_copies": 0,
+ "kv_cache_declined": 0,
+ "kv_prefill_primary_calls": 0,
+ "replica_failures": 0,
}
+ # source prefix-KV cache id -> (source cache, the tensors it held when copied, the replica's copy)
+ self.kv_mirrors: dict[int, tuple[Any, list, Any]] = {}
+ self.kv_declined: dict[int, tuple[Any, list]] = {}
+ self._opaque_logged = False
# Set when replica work was refused by a long recording: until that capture ends, later replica attempts go
# straight to the source instead of each waiting OUTSIDE_WAIT_S again.
self.exclusion_refused = False
@@ -2343,6 +2442,7 @@ class CfgParallelRouter:
def describe(self) -> dict[str, Any]:
return {
"secondary": str(self.secondary),
+ "armed": self.disabled_reason is None,
"replica_built": self.replica is not None,
"replica_compiled_submodules": getattr(self.replica, "_unsloth_replica_compiled", None),
"disabled_reason": self.disabled_reason,
@@ -2352,6 +2452,8 @@ class CfgParallelRouter:
def disable(self, reason: str) -> None:
if self.disabled_reason is None:
self.disabled_reason = reason
+ if reason.startswith("replica "):
+ self.stats["replica_failures"] += 1
if self.logger is not None:
self.logger.warning(
"diffusion.multigpu: CFG-parallel disabled (%s); one card from here", reason
@@ -2364,6 +2466,8 @@ class CfgParallelRouter:
self.worker = None
self._drop_pending()
self.replica = None
+ self.kv_mirrors.clear()
+ self.kv_declined.clear()
self.pairs = []
self.warm_primary.clear()
self.warm_replica.clear()
@@ -2377,6 +2481,8 @@ class CfgParallelRouter:
def end_render(self) -> None:
self._drop_pending()
self.prefetched.clear()
+ self.kv_mirrors.clear()
+ self.kv_declined.clear()
self.carry = []
self.next_carry = []
self.prev_latent = None
@@ -2451,21 +2557,33 @@ class CfgParallelRouter:
self._prefetch(args, kwargs)
sig = _call_signature(args, kwargs)
self._launch_prediction(latent, sig)
+ prefill = self.branch % 2 == 1 and _is_prefill(kwargs)
if (
self.branch % 2 == 1
and self.disabled_reason is None
- and _holds_opaque_tensors((args, kwargs))
+ and not prefill
+ and _holds_opaque_tensors(_without_prefix_kv(args, kwargs))
):
self._drop_pending()
self.template = None
self.stats["opaque_primary_calls"] += 1
+ if not self._opaque_logged and self.logger is not None:
+ self._opaque_logged = True
+ self.logger.info(
+ "diffusion.multigpu: a guidance branch carries tensors inside an object the replica cannot copy;"
+ " that branch stays on %s",
+ self.primary,
+ )
elif self.branch % 2 == 1 and self.disabled_reason is None:
self.singles = 0
if self.replica is None:
self.cfg_seen = True
self._build_replica()
- if self.branch == 1:
+ if self.branch == 1 and not prefill:
self._record_template(args, kwargs, latent)
+ elif prefill:
+ self._drop_pending()
+ self.template = None
elif self.cfg_seen and self._refused_this_capture():
# this step's prefetch or prediction was refused: the branch runs on the source, no further wait
self._drop_pending()
@@ -2480,10 +2598,14 @@ class CfgParallelRouter:
if self.branch == 1:
self.stats["steps_parallel"] += 1
return out
+ except _KVMirrorDeclined:
+ self._drop_pending()
except Exception as exc: # noqa: BLE001 - this branch is recomputed on the primary below
self._note_refusal(exc)
self.disable(f"replica call failed: {type(exc).__name__}: {exc}")
self.cfg_seen = True
+ if prefill:
+ self.stats["kv_prefill_primary_calls"] += 1
self.stats["primary_calls"] += 1
return self._primary_noting(sig, args, kwargs)
@@ -2517,6 +2639,8 @@ class CfgParallelRouter:
try:
r_args = self._to_replica(args)
r_kwargs = self._to_replica(kwargs)
+ except _KVMirrorDeclined:
+ return None # the prefix cache does not fit on the replica card: both halves run on the source
except Exception as exc: # noqa: BLE001 - e.g. no room left on the replica card: both halves run on the source
self.disable(f"replica input copy failed: {type(exc).__name__}: {exc}")
return None
@@ -2601,6 +2725,8 @@ class CfgParallelRouter:
if predicted is None or self.worker is None:
return
p_args, p_kwargs = predicted
+ if _is_prefill(p_kwargs):
+ return
if (
sig not in self.warm_primary
or _call_signature(p_args, p_kwargs) not in self.warm_replica
@@ -2725,14 +2851,7 @@ class CfgParallelRouter:
need_mib = sum(
t.numel() * t.element_size() for t in (*module.parameters(), *module.buffers())
) // (1 << 20)
- free, _total = _free_total_mib(self.secondary.index)
- if free is not None:
- with contextlib.suppress(Exception):
- torch = _torch()
- free += (
- torch.cuda.memory_reserved(self.secondary)
- - torch.cuda.memory_allocated(self.secondary)
- ) // (1 << 20)
+ free = self._secondary_free_mib()
if free is not None and need_mib + 1024 > free:
raise RuntimeError(
f"replica needs {need_mib} MiB, {free} MiB free on {self.secondary}"
@@ -2795,6 +2914,11 @@ class CfgParallelRouter:
def walk(value: Any, depth: int = 0) -> Any:
if isinstance(value, torch.Tensor):
return one(value)
+ if depth == 0 and isinstance(value, dict) and _prefix_kv_mode(value) == "cached":
+ return type(value)(
+ (k, self._kv_mirror(v) if k == _KV_KWARG else walk(v, depth + 1))
+ for k, v in value.items()
+ )
if depth < 4 and isinstance(value, tuple) and not hasattr(value, "_fields"):
return tuple(walk(v, depth + 1) for v in value)
if depth < 4 and isinstance(value, list):
@@ -2808,6 +2932,61 @@ class CfgParallelRouter:
with outside_capture():
return walk(obj)
+ def _kv_mirror(self, cache: Any) -> Any:
+ """Replica copy of a filled prefix-KV cache, reused while the source holds the same K/V tensors."""
+ held = _cache_tensors(cache) or []
+ entry = self.kv_mirrors.get(id(cache))
+ if (
+ entry is not None
+ and entry[0] is cache
+ and len(entry[1]) == len(held)
+ and all(a is b for a, b in zip(entry[1], held))
+ ):
+ return entry[2]
+ declined = self.kv_declined.get(id(cache))
+ if (
+ declined is not None
+ and declined[0] is cache
+ and len(declined[1]) == len(held)
+ and all(a is b for a, b in zip(declined[1], held))
+ ):
+ raise _KVMirrorDeclined("prefix cache does not fit on the replica card")
+ # Admission's 1 GiB margin: decline before copying rather than OOM mid-copy and lose the replica.
+ need = sum(t.numel() * t.element_size() for t in held)
+ free = self._secondary_free_mib()
+ if free is not None and need + (1024 << 20) > free * (1 << 20):
+ self.kv_declined[id(cache)] = (cache, held)
+ self.stats["kv_cache_declined"] += 1
+ if self.logger is not None:
+ self.logger.info(
+ "diffusion.multigpu: prefix KV cache (%d MiB) does not fit on %s (%d MiB free);"
+ " its guidance branch stays on %s this render",
+ need >> 20,
+ self.secondary,
+ free,
+ self.primary,
+ )
+ raise _KVMirrorDeclined("prefix cache does not fit on the replica card")
+ secondary = self.secondary
+ mirror = _walk_cache(cache, lambda t: t if t.device == secondary else t.to(secondary), [])
+ while len(self.kv_mirrors) >= 4:
+ self.kv_mirrors.pop(next(iter(self.kv_mirrors)))
+ self.kv_mirrors[id(cache)] = (cache, held, mirror)
+ self.stats["kv_cache_copies"] += 1
+ return mirror
+
+ def _secondary_free_mib(self) -> Optional[int]:
+ """Free MiB on the replica card, counting its allocator's cached-but-unused blocks (as the admission does)."""
+ free, _total = _free_total_mib(self.secondary.index)
+ if free is not None:
+ with contextlib.suppress(Exception):
+ torch = _torch()
+ free += (
+ torch.cuda.memory_reserved(self.secondary)
+ - torch.cuda.memory_allocated(self.secondary)
+ ) // (1 << 20)
+ return free
+
def _run_replica(self, args: tuple, kwargs: dict) -> Any:
# Unpredicted: nothing verified the copies made before the primary branch ran, and an input edited in place
# since then would reach the replica stale. Copy this call's inputs now (ordered after the primary branch).
@@ -2822,6 +3001,10 @@ class CfgParallelRouter:
return _to_primary(out, self.primary)
+class _KVMirrorDeclined(RuntimeError):
+ """A prefix-KV cache too large for the replica card's free memory: the branch runs on the primary."""
+
+
def _replica_call(replica: Any, args: tuple, kwargs: dict) -> Callable[[], Any]:
return lambda: replica(*args, **kwargs)
diff --git a/studio/backend/tests/test_diffusion_multigpu.py b/studio/backend/tests/test_diffusion_multigpu.py
index 6ca47457142..3afcf3822d8 100644
--- a/studio/backend/tests/test_diffusion_multigpu.py
+++ b/studio/backend/tests/test_diffusion_multigpu.py
@@ -1476,6 +1476,169 @@ def test_branch_with_a_cache_object_stays_on_the_primary():
assert mg._holds_opaque_tensors({"kv_cache": _Cache()})
+class _KVLayer:
+ """Qwen-Image-2.1's ``QwenImage21KVLayerCache``: one layer's prefix K, filled by the prefill."""
+
+ def __init__(self):
+ self.k = None
+
+
+class _KVCache:
+ """Qwen-Image-2.1's ``QwenImage21KVCache``: the per-layer holders sit in a list inside the cache object."""
+
+ def __init__(self, layers):
+ self.layer_caches = [_KVLayer() for _ in range(layers)]
+
+
+class _PrefixKVDit(_Dit):
+ """Step 0 stores the prefix K (``extract``); later steps concatenate it with the step's own (``cached``)."""
+
+ # (thread, mode, cache) per layer read; on the class, so the replica's copy logs here too
+ seen: list = []
+
+ def forward(
+ self,
+ hidden_states,
+ timestep,
+ encoder_hidden_states,
+ kv_cache = None,
+ kv_cache_mode = None,
+ return_dict = False,
+ ):
+ out = self.proj(hidden_states) * timestep
+ prefix = self.proj(encoder_hidden_states)
+ for layer in kv_cache.layer_caches:
+ self.seen.append((threading.current_thread(), kv_cache_mode, kv_cache))
+ if kv_cache_mode == "extract":
+ layer.k = prefix.clone()
+ else:
+ out = out + torch.cat([layer.k, out], dim = 0)[: out.shape[0]].sum(0)
+ return (out,)
+
+
+def _kv_render(
+ dit,
+ latents,
+ steps = 5,
+):
+ cond, neg = (
+ torch.randn(3, 4, generator = torch.Generator().manual_seed(1)),
+ torch.randn(3, 4, generator = torch.Generator().manual_seed(2)),
+ )
+ caches = (_KVCache(2), _KVCache(2))
+ for i in range(steps):
+ t = torch.tensor(1.0 - i / steps)
+ mode = "extract" if i == 0 else "cached"
+ a, b = (
+ dit(
+ hidden_states = latents,
+ timestep = t,
+ encoder_hidden_states = e,
+ kv_cache = c,
+ kv_cache_mode = mode,
+ )[0]
+ for e, c in zip((cond, neg), caches)
+ )
+ latents = latents - 0.1 * (b + 4.0 * (a - b))
+ return latents, caches
+
+
+def test_prefix_kv_cache_branch_runs_on_the_replica_against_its_own_copy():
+ torch.manual_seed(0)
+ dit = _PrefixKVDit()
+ latents = torch.randn(2, 4)
+ references = [_kv_render(dit, latents.clone())[0] for _ in range(2)]
+ router, replicas = _router(dit)
+ main = threading.current_thread()
+ for render in range(2):
+ _PrefixKVDit.seen.clear()
+ out, (cond_cache, neg_cache) = _kv_render(dit, latents.clone())
+ assert torch.equal(out, references[render])
+ assert all(th is main for th, mode, _c in _PrefixKVDit.seen if mode == "extract")
+ assert neg_cache.layer_caches[0].k is not None
+ # the replica reads its own copy, never the pipeline's (mutable) object
+ replica_caches = [c for th, mode, c in _PrefixKVDit.seen if th is not main]
+ assert replica_caches and all(
+ c is not neg_cache and c is not cond_cache for c in replica_caches
+ )
+ router.end_render()
+ assert router.describe()["disabled_reason"] is None and router.describe()["armed"]
+ assert router.stats["steps_parallel"] >= 6
+ assert router.stats["kv_cache_copies"] == 2
+ assert router.stats["kv_prefill_primary_calls"] == 2
+ assert router.kv_mirrors == {} # dropped at end_render
+
+
+def test_prefix_kv_cache_too_large_for_the_replica_card_stays_on_the_primary(monkeypatch):
+ torch.manual_seed(0)
+ dit = _PrefixKVDit()
+ latents = torch.randn(2, 4)
+ reference = _kv_render(dit, latents.clone())[0]
+ # the replica (no weights to speak of) passes admission with exactly 1 GiB free; the cache on top of it does not
+ monkeypatch.setattr(mg, "_free_total_mib", lambda ordinal: (1024, 2048))
+ router, replicas = _router(dit)
+ copies = []
+ real_walk = mg._walk_cache
+
+ def walk(
+ obj,
+ move,
+ found,
+ depth = 0,
+ ):
+ if move is not None and depth == 0:
+ copies.append(obj)
+ return real_walk(obj, move, found, depth)
+
+ monkeypatch.setattr(mg, "_walk_cache", walk)
+ main = threading.current_thread()
+ _PrefixKVDit.seen.clear()
+ out, _caches = _kv_render(dit, latents.clone())
+ assert torch.equal(out, reference)
+ assert copies == [] and router.stats["kv_cache_copies"] == 0
+ assert router.stats["kv_cache_declined"] == 1 # probed once per cache, not per step
+ assert all(th is main for th, _mode, _c in _PrefixKVDit.seen)
+ # declined for this render only: the replica stays built and armed
+ assert replicas and router.replica is not None
+ assert router.describe()["disabled_reason"] is None
+ router.end_render()
+ assert router.kv_declined == {}
+
+
+def test_opaque_detection_sees_tensors_in_a_list_of_value_holders():
+ cache = _KVCache(2)
+ assert not mg._holds_opaque_tensors({"kv_cache": cache}) # empty before the prefill
+ cache.layer_caches[1].k = torch.ones(2)
+ assert mg._holds_opaque_tensors({"kv_cache": cache})
+ # a filled cache in cached mode is copied for the replica, the rest of the call is checked as before
+ kwargs = {"kv_cache": cache, "kv_cache_mode": "cached", "x": torch.ones(1)}
+ assert mg._prefix_kv_mode(kwargs) == "cached"
+ assert not mg._holds_opaque_tensors(mg._without_prefix_kv((), kwargs))
+ assert mg._prefix_kv_mode({**kwargs, "kv_cache_mode": "extract"}) == "extract"
+ assert mg._prefix_kv_mode({**kwargs, "kv_cache_mode": None}) is None
+ # a prefill stays on the primary even when its cache could not be copied, or is returned (FLUX.2)
+ assert mg._is_prefill({"kv_cache": object(), "kv_cache_mode": "extract"})
+ assert mg._is_prefill({"kv_cache_mode": "extract"}) and not mg._is_prefill(kwargs)
+ longer = _KVCache(2)
+ longer.layer_caches[1].k = torch.ones(3)
+ assert mg._call_signature((), kwargs) != mg._call_signature((), {**kwargs, "kv_cache": longer})
+
+
+def test_replica_failure_is_reported_in_the_status():
+ torch.manual_seed(0)
+ dit = _Dit()
+
+ def broken():
+ raise RuntimeError("no card")
+
+ router = mg.CfgParallelRouter(dit, primary = "cpu", secondary = "cpu", replica_factory = broken)
+ dit.forward = router
+ _cfg_loop(dit, torch.randn(2, 4), steps = 3)
+ info = router.describe()
+ assert info["armed"] is False and info["replica_failures"] == 1
+ assert info["disabled_reason"].startswith("replica unavailable")
+
+
def test_split_video_request_is_guarded_on_every_card():
from core.inference import video as vid
diff --git a/studio/backend/tests/test_diffusion_multigpu_cuda.py b/studio/backend/tests/test_diffusion_multigpu_cuda.py
index 0da7f902d0a..71397b7cb57 100644
--- a/studio/backend/tests/test_diffusion_multigpu_cuda.py
+++ b/studio/backend/tests/test_diffusion_multigpu_cuda.py
@@ -273,6 +273,82 @@ def test_an_in_place_edit_of_inference_weights_rebuilds_the_replica():
assert torch.equal(out, reference)
+class _PrefixKVDit(torch.nn.Module):
+ """Qwen-Image-2.1 prefix KV cache shape: a list of per-layer K/V holders."""
+
+ def __init__(self):
+ super().__init__()
+ self.proj = torch.nn.Linear(4, 4)
+
+ def forward(
+ self,
+ hidden_states,
+ timestep,
+ encoder_hidden_states,
+ kv_cache = None,
+ kv_cache_mode = None,
+ return_dict = False,
+ ):
+ key = self.proj(hidden_states)
+ for layer in kv_cache.layer_caches:
+ if kv_cache_mode == "extract":
+ layer.k = self.proj(encoder_hidden_states).clone()
+ key = torch.cat([layer.k, key], dim = 0)[-hidden_states.shape[0] :] + layer.k.sum(0)
+ return (key * timestep,)
+
+
+def _kv_cache(layers = 3):
+ from types import SimpleNamespace
+ class Cache:
+ def __init__(self):
+ self.layer_caches = [SimpleNamespace(k = None) for _ in range(layers)]
+
+ return Cache()
+
+
+def _kv_render(dit, latents, cond, neg, steps):
+ x = latents.clone()
+ caches = (_kv_cache(), _kv_cache())
+ for i in range(steps):
+ t = torch.tensor(1.0 - i / steps, device = x.device)
+ mode = "extract" if i == 0 else "cached"
+ a = dit(
+ hidden_states = x,
+ timestep = t,
+ encoder_hidden_states = cond,
+ kv_cache = caches[0],
+ kv_cache_mode = mode,
+ )[0]
+ b = dit(
+ hidden_states = x,
+ timestep = t,
+ encoder_hidden_states = neg,
+ kv_cache = caches[1],
+ kv_cache_mode = mode,
+ )[0]
+ x = x - 0.1 * (b + 4.0 * (a - b))
+ return x
+
+
+def test_prefix_kv_cache_branch_runs_on_the_second_card_and_stays_exact():
+ torch.manual_seed(0)
+ dit = _PrefixKVDit().cuda(0)
+ latents = torch.randn(2, 4, device = "cuda:0")
+ cond = torch.randn(3, 4, device = "cuda:0")
+ neg = torch.randn(3, 4, device = "cuda:0")
+ with torch.no_grad():
+ reference = [_kv_render(dit, latents, cond, neg, 5) for _ in range(2)]
+ router = _arm(dit)
+ outs = []
+ for _ in range(2):
+ outs.append(_kv_render(dit, latents, cond, neg, 5))
+ router.end_render()
+ torch.cuda.synchronize()
+ assert router.disabled_reason is None, router.disabled_reason
+ assert router.stats["steps_parallel"] >= 6 and router.stats["kv_cache_copies"] == 2
+ assert all(torch.equal(o, r) for o, r in zip(outs, reference))
+
+
def test_a_step_graph_on_the_second_card_records_its_forward():
# Regression: cuda:1 captured on torch's cuda:0 default capture stream, so replays returned the recording's output.
from core.inference import diffusion_cuda_graph as cg