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: do not engage FBCache on a transformer that reuses a prefix KV cache (#11546)

Daniel Hanc23f8b06df63
diff --git a/studio/backend/core/inference/diffusion_cache.py b/studio/backend/core/inference/diffusion_cache.py
index 6cdd8b2bfe5..2313f78e05b 100644
--- a/studio/backend/core/inference/diffusion_cache.py
+++ b/studio/backend/core/inference/diffusion_cache.py
@@ -287,6 +287,52 @@ def _pipeline_opens_cache_context(pipe: Any) -> bool:
return "cache_context(" in src
+def _reuses_prefix_kv(pipe: Any, transformer: Any) -> bool:
+ """Whether the denoise loop feeds the blocks a SHORTER sequence after the first step.
+
+ A transformer that caches the prompt/condition prefix K and V runs its first step over the
+ whole joint sequence and every later step over the target tokens alone, so the per-block
+ sequence length changes between step 0 and step 1. FBCache compares the first block's residual
+ against the previous step's and reuses the remaining blocks' cached residual, and both are
+ plain elementwise ops on a stored tensor, so the length change makes them raise:
+
+ RuntimeError: The size of tensor a (4096) must match the size of tensor b (4297)
+ at non-singleton dimension 1
+
+ (Qwen-Image-2.1 at 1024px: 4096 image tokens against 4096 + 201 prompt tokens.) The cache is
+ not merely unsupported here, it takes the generation down at the second step, so refuse it.
+
+ Read structurally rather than by family name, because the shape is shared: the transformer's
+ forward accepts a ``kv_cache_mode`` and the pipeline passes one. Qwen-Image-2.1, FLUX.2 klein
+ KV and Wan-Animate-2 all match today, and a family that adopts prefix reuse later is covered
+ without touching this file.
+
+ Conservative on purpose. A checkpoint that carries the parameter but never populates the cache
+ (the pipeline gates on its own config) keeps a constant length and would have been safe, and it
+ loses the cache anyway. That costs speed on a model we have not seen; guessing the other way
+ costs a failed render on one we have."""
+ import inspect
+
+ forward = getattr(transformer, "forward", None)
+ if forward is None:
+ return False
+ try:
+ if "kv_cache_mode" not in inspect.signature(forward).parameters:
+ return False
+ except (TypeError, ValueError): # not introspectable: assume no prefix reuse
+ return False
+ call = getattr(pipe, "__call__", None)
+ if call is None:
+ return False
+ try:
+ src = inspect.getsource(call)
+ except (OSError, TypeError):
+ # The transformer takes the parameter and the loop cannot be read, so whether it is driven
+ # is unknown. Unknown is the crashing side here, so treat it as driven.
+ return True
+ return "kv_cache_mode" in src
+
+
def apply_step_cache(
pipe: Any,
*,
@@ -325,6 +371,19 @@ def apply_step_cache(
logger, mode, RuntimeError("pipeline __call__ opens no cache_context; running uncached")
)
return None
+ # Prefix KV reuse shortens the block sequence after the first step, which the cache's stored
+ # residuals cannot be subtracted from. Checked before enable_cache: engaging here does not fail
+ # at load, it fails at step 2 of the user's generation.
+ if _reuses_prefix_kv(pipe, transformer):
+ _warn(
+ logger,
+ mode,
+ RuntimeError(
+ "transformer reuses a prefix KV cache, so the block sequence length changes "
+ "after the first step; running uncached"
+ ),
+ )
+ return None
# enable_cache RAISES when is_cache_enabled, so without this a redundant call lands in the
# recovery branch below and loses the cache. Different settings must disable first.
if getattr(transformer, "is_cache_enabled", False):
diff --git a/studio/backend/tests/test_diffusion_cache.py b/studio/backend/tests/test_diffusion_cache.py
index a1908b2c20e..f6ab99c1e3b 100644
--- a/studio/backend/tests/test_diffusion_cache.py
+++ b/studio/backend/tests/test_diffusion_cache.py
@@ -95,6 +95,26 @@ class _NoCtxPipe:
return None
+class _PrefixKVTransformer(_MixinTransformer):
+ """A CacheMixin transformer that caches the prompt/condition prefix K and V (Qwen-Image-2.1,
+ FLUX.2 klein KV, Wan-Animate-2): its blocks see the whole joint sequence on the first step and
+ the target tokens alone afterwards."""
+
+ def forward(self, hidden_states, *, kv_cache = None, kv_cache_mode = None):
+ return hidden_states
+
+
+class _PrefixKVPipe(_CtxPipe):
+ """A denoise loop that drives the prefix cache: prefill once, then decode. FBCache must not
+ engage, or step 2 dies subtracting a 4096-row residual from a 4297-row one."""
+
+ def __call__(self, *args, **kwargs):
+ with self.transformer.cache_context("cond"):
+ self.transformer(None, kv_cache = object(), kv_cache_mode = "extract")
+ self.transformer(None, kv_cache = object(), kv_cache_mode = "cached")
+ return None
+
+
def _pipe(transformer):
return _CtxPipe(transformer)
@@ -195,6 +215,36 @@ def test_pipeline_without_cache_context_runs_uncached(monkeypatch):
assert t.enabled_with is None # enable_cache was never called
+def test_prefix_kv_transformer_runs_uncached(monkeypatch):
+ # Qwen-Image-2.1 / FLUX.2 klein KV / Wan-Animate-2 cache the prompt prefix, so the blocks see
+ # the whole joint sequence on step 0 and the target tokens alone from step 1. FBCache subtracts
+ # the stored residual elementwise, so engaging here raises "The size of tensor a (4096) must
+ # match the size of tensor b (4297)" at step 2 of a user's generation, not at load.
+ _stub_diffusers(monkeypatch)
+ t = _PrefixKVTransformer()
+ assert apply_step_cache(_PrefixKVPipe(t), mode = "fbcache") is None
+ assert t.enabled_with is None # enable_cache was never called
+
+
+def test_prefix_kv_guard_does_not_catch_an_ordinary_transformer(monkeypatch):
+ # The control for the guard above: a CacheMixin transformer whose forward takes no
+ # kv_cache_mode (Flux, Qwen-Image) keeps a constant sequence length and must still be cached.
+ _stub_diffusers(monkeypatch)
+ t = _MixinTransformer()
+ assert apply_step_cache(_pipe(t), mode = "fbcache") == "fbcache"
+ assert t.enabled_with is not None
+
+
+def test_prefix_kv_guard_ignores_a_parameter_the_loop_never_drives(monkeypatch):
+ # A transformer that ACCEPTS kv_cache_mode inside a pipeline that never passes one runs at a
+ # constant length, so the cache stays available. This keeps the guard on the loop's behaviour
+ # rather than on the signature alone.
+ _stub_diffusers(monkeypatch)
+ t = _PrefixKVTransformer()
+ assert apply_step_cache(_CtxPipe(t), mode = "fbcache") == "fbcache"
+ assert t.enabled_with is not None
+
+
def test_incompatible_model_runs_uncached(monkeypatch):
# enable_cache raising (e.g. unrecognised block signature) must not fail the load.
_stub_diffusers(monkeypatch)