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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: fix First Block Cache on FLUX.2 (dual-stream head, single-stream tail) (#14401)
Daniel Han4c5e4bda2923
diff --git a/studio/backend/core/inference/diffusion_cache.py b/studio/backend/core/inference/diffusion_cache.pyindex 66b3b118a7f..94c1fc8daee 100644--- a/studio/backend/core/inference/diffusion_cache.py+++ b/studio/backend/core/inference/diffusion_cache.py@@ -501,6 +501,110 @@ def install_fbcache_length_guard() -> bool:return True+def _split_mixed_stream_tail_residuals(tail_hidden: Any, head_output: Any) -> Optional[tuple]:+ """Tail residuals for a dual-stream head and a single-stream tail, or None when unmappable.++ The tail ran over ``cat([encoder, hidden], dim=1)``; splitting at the text length gives+ residuals shaped like the head's ``[hidden, encoder]`` outputs, which the skip branch adds to.+ """+ head_hidden, head_encoder = head_output[0], head_output[1]+ if head_encoder is None or getattr(tail_hidden, "ndim", 0) < 2:+ return None+ text_len = head_encoder.shape[1]+ if (+ tail_hidden.shape[1] != text_len + head_hidden.shape[1]+ or tail_hidden.shape[:1] != head_hidden.shape[:1]+ or tail_hidden.shape[2:] != head_hidden.shape[2:]+ or head_encoder.shape[2:] != head_hidden.shape[2:]+ ):+ return None+ return (+ tail_hidden[:, text_len:] - head_hidden,+ tail_hidden[:, :text_len] - head_encoder,+ )+++def _rebind_fbcache_block_hooks(transformer: Any) -> None:+ """Point already-registered FBCache block hooks at the current ``FBCBlockHook.new_forward``.++ ``HookRegistry.register_hook`` keeps ``partial(hook.new_forward, module)``, the method as it was+ at registration, so hooks installed before ``install_fbcache_mixed_stream_tail`` (an FBCache we+ adopt instead of re-enabling) would still run the stock tail and crash FLUX.2. Best-effort."""+ try:+ import functools++ from diffusers.hooks.first_block_cache import _FBC_BLOCK_HOOK, FBCBlockHook+ except Exception: # noqa: BLE001 - no FBCache in this diffusers+ return+ current = getattr(FBCBlockHook, "new_forward", None)+ if current is None:+ return+ for module in transformer.modules():+ registry = getattr(module, "_diffusers_hook", None)+ hooks = getattr(registry, "hooks", None) if registry is not None else None+ hook = hooks.get(_FBC_BLOCK_HOOK) if isinstance(hooks, dict) else None+ fn_ref = getattr(hook, "fn_ref", None) if hook is not None else None+ bound = getattr(fn_ref, "forward", None)+ if not isinstance(hook, FBCBlockHook) or not isinstance(bound, functools.partial):+ continue+ if getattr(bound.func, "__func__", None) is current:+ continue+ try:+ fn_ref.forward = functools.update_wrapper(+ functools.partial(hook.new_forward, *bound.args), hook.new_forward+ )+ except Exception: # noqa: BLE001 - diffusers internals moved; leave this hook as it is+ pass+++def install_fbcache_mixed_stream_tail() -> bool:+ """Make First-Block-Cache work when the head block is dual-stream and the tail single-stream.++ diffusers' tail hook picks its branch from the TAIL's output type, so on FLUX.2 (dual-stream+ head, single-stream tail) it subtracts the head's ``[hidden, encoder]`` list from a tensor and+ crashes on the first step. Only that combination takes the new path; every other family calls+ the original hook unchanged. An unmappable tail drops the head residual so the next step+ computes in full. Process-wide and idempotent; False when diffusers has no FBCache block hook."""+ try:+ from diffusers.hooks.first_block_cache import FBCBlockHook+ except Exception: # noqa: BLE001 - no FBCache in this diffusers+ return False+ original = getattr(FBCBlockHook, "new_forward", None)+ if original is None:+ return False+ if getattr(original, "_unsloth_mixed_stream_tail", False):+ return True++ def new_forward(self, module, *args, **kwargs):+ metadata = self._metadata+ if (+ not self.is_tail+ or getattr(metadata, "return_encoder_hidden_states_index", 0) is not None+ ):+ return original(self, module, *args, **kwargs)+ shared_state = self.state_manager.get_state()+ head_output = shared_state.head_block_output+ if not shared_state.should_compute or not isinstance(head_output, (list, tuple)):+ return original(self, module, *args, **kwargs)+ output = self.fn_ref.original_forward(*args, **kwargs)+ tail_hidden = (+ output[metadata.return_hidden_states_index]+ if isinstance(output, (list, tuple))+ else output+ )+ residuals = _split_mixed_stream_tail_residuals(tail_hidden, head_output)+ if residuals is None:+ # No skip may use these residuals: with no head residual the next step computes.+ shared_state.head_block_residual = None+ shared_state.tail_block_residuals = residuals+ return output++ new_forward._unsloth_mixed_stream_tail = True+ new_forward._unsloth_original = original+ FBCBlockHook.new_forward = new_forward+ return True++def _reuses_prefix_kv(pipe: Any, transformer: Any) -> bool:"""Whether the denoise loop feeds the blocks a SHORTER sequence after the first step.@@ -573,6 +677,8 @@ def apply_step_cache(return None# Before enable_cache, which is what raises on a block class the registry has never seen.register_unregistered_transformer_blocks(logger)+ # FLUX.2's dual-stream head + single-stream tail crashes the stock tail hook on the first step.+ install_fbcache_mixed_stream_tail()thr = (thresholdif threshold is not None@@ -622,6 +728,7 @@ def apply_step_cache(# May not be a cache we installed, so the post-enable integration cannot be assumed# done. Both idempotent; skipping the first strands the child-registry list._invalidate_child_registry_cache(transformer)+ _rebind_fbcache_block_hooks(transformer)_compile_hooked_block_inners(transformer, logger)try:transformer._unsloth_step_cache = f"{mode}@{thr}"@@ -675,6 +782,7 @@ def apply_step_cache(# _cache_config was None. register_hook refuses a duplicate name BEFORE changing# anything, so those hooks are intact and tearing them down would cost a healthy cache._invalidate_child_registry_cache(transformer)+ _rebind_fbcache_block_hooks(transformer)_compile_hooked_block_inners(transformer, logger)# The marker MUST be set before reporting success: it is what keeps the CUDA graph# wrapper eager over these live hooks. Mode only; the threshold is its installer's.diff --git a/studio/backend/tests/test_diffusion_fbcache_mixed_stream.py b/studio/backend/tests/test_diffusion_fbcache_mixed_stream.pynew file mode 100644index 00000000000..23c1bad451d--- /dev/null+++ b/studio/backend/tests/test_diffusion_fbcache_mixed_stream.py@@ -0,0 +1,263 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""First-Block-Cache on FLUX.2, whose dual-stream head feeds a single-stream tail.++Uses the REAL diffusers hooks on tiny random transformers (CPU, seconds). Stock diffusers raises+"unsupported operand type(s) for -: 'Tensor' and 'list'" in the tail hook on the first cached step.+"""++from __future__ import annotations++import pytest++from core.inference import diffusion_cache as dc+++def _diffusers():+ # Importing diffusers drags in optional integrations that can raise non-ImportErrors.+ try:+ import torch+ from diffusers.hooks import FirstBlockCacheConfig+ from diffusers.hooks._helpers import TransformerBlockMetadata, TransformerBlockRegistry+ from diffusers.hooks.first_block_cache import FBCBlockHook+ except Exception as exc: # noqa: BLE001+ pytest.skip(f"diffusers is not importable here: {type(exc).__name__}")+ return (+ torch,+ FirstBlockCacheConfig,+ TransformerBlockMetadata,+ TransformerBlockRegistry,+ FBCBlockHook,+ )+++def stock_tail_hook(monkeypatch):+ """Start from diffusers' own tail hook and put back whatever was there afterwards."""+ *_, FBCBlockHook = _diffusers()+ current = FBCBlockHook.new_forward+ stock = getattr(current, "_unsloth_original", current)+ monkeypatch.setattr(FBCBlockHook, "new_forward", stock)+ return stock+++def _tiny_flux2():+ torch, _, TransformerBlockMetadata, TransformerBlockRegistry, _ = _diffusers()+ try:+ from diffusers import Flux2Transformer2DModel+ from diffusers.models.transformers.transformer_flux2 import (+ Flux2SingleTransformerBlock,+ Flux2TransformerBlock,+ )+ except Exception as exc: # noqa: BLE001+ pytest.skip(f"this diffusers has no FLUX.2: {type(exc).__name__}")+ # The metadata diffusers main registers; older releases ship FLUX.2 without it.+ for cls, hidden, encoder in (+ (Flux2TransformerBlock, 1, 0),+ (Flux2SingleTransformerBlock, 0, None),+ ):+ try:+ TransformerBlockRegistry.get(cls)+ except Exception: # noqa: BLE001+ TransformerBlockRegistry.register(+ model_class = cls,+ metadata = TransformerBlockMetadata(+ return_hidden_states_index = hidden,+ return_encoder_hidden_states_index = encoder,+ ),+ )+ torch.manual_seed(0)+ model = Flux2Transformer2DModel(+ in_channels = 8,+ num_layers = 2,+ num_single_layers = 3,+ attention_head_dim = 16,+ num_attention_heads = 2,+ joint_attention_dim = 24,+ timestep_guidance_channels = 32,+ axes_dims_rope = (4, 4, 4, 4),+ guidance_embeds = False,+ ).eval()+ img_ids = torch.zeros(16, 4)+ img_ids[:, 1] = torch.arange(16) // 4+ img_ids[:, 2] = torch.arange(16) % 4+ txt_ids = torch.zeros(6, 4)+ txt_ids[:, 3] = torch.arange(6)+ inputs = dict(+ hidden_states = torch.randn(1, 16, 8),+ encoder_hidden_states = torch.randn(1, 6, 24),+ img_ids = img_ids,+ txt_ids = txt_ids,+ )+ return model, inputs+++def _tiny_flux1():+ torch, *_ = _diffusers()+ try:+ from diffusers import FluxTransformer2DModel+ except Exception as exc: # noqa: BLE001+ pytest.skip(f"this diffusers has no FLUX.1: {type(exc).__name__}")+ torch.manual_seed(0)+ model = FluxTransformer2DModel(+ patch_size = 1,+ in_channels = 8,+ num_layers = 2,+ num_single_layers = 3,+ attention_head_dim = 16,+ num_attention_heads = 2,+ joint_attention_dim = 24,+ pooled_projection_dim = 12,+ axes_dims_rope = (4, 6, 6),+ ).eval()+ inputs = dict(+ hidden_states = torch.randn(1, 16, 8),+ encoder_hidden_states = torch.randn(1, 6, 24),+ pooled_projections = torch.randn(1, 12),+ img_ids = torch.zeros(16, 3),+ txt_ids = torch.zeros(6, 3),+ )+ return model, inputs+++def _render(+ model,+ inputs,+ timesteps,+ *,+ threshold = None,+):+ """One forward per timestep inside a cache context, FBCache on when ``threshold`` is set."""+ torch, FirstBlockCacheConfig, *_ = _diffusers()+ if threshold is not None:+ model.enable_cache(FirstBlockCacheConfig(threshold = threshold))+ tail_attn = model.single_transformer_blocks[-1].attn+ calls = []+ handle = tail_attn.register_forward_hook(lambda *_: calls.append(1))+ outs = []+ try:+ with torch.no_grad(), model.cache_context("cond"):+ for t in timesteps:+ outs.append(model(**inputs, timestep = torch.tensor([t]), return_dict = False)[0])+ finally:+ handle.remove()+ if threshold is not None:+ model.disable_cache()+ return outs, len(calls)+++def test_stock_fbcache_on_flux2_fails_with_tensor_minus_list(stock_tail_hook):+ """The bug itself, pinned so a diffusers that fixes it upstream is noticed."""+ model, inputs = _tiny_flux2()+ with pytest.raises(TypeError, match = "'Tensor' and 'list'"):+ _render(model, inputs, (1.0, 1.0), threshold = 0.5)+++def test_fbcache_on_flux2_skips_and_matches_the_full_pass(stock_tail_hook):+ torch, *_ = _diffusers()+ assert dc.install_fbcache_mixed_stream_tail() is True+ assert dc.install_fbcache_mixed_stream_tail() is True # idempotent+ model, inputs = _tiny_flux2()+ steps = (1.0, 1.0, 1.0)+ full, full_calls = _render(model, inputs, steps)+ cached, cached_calls = _render(model, inputs, steps, threshold = 0.5)+ assert full_calls == 3+ # Same input every step: the head residual does not move, so steps 2 and 3 skip the stack.+ assert cached_calls == 1+ assert torch.equal(full[0], cached[0])+ # A skip reapplies the stored tail residual, which must rebuild the full pass's output.+ for a, b in zip(full[1:], cached[1:]):+ torch.testing.assert_close(b, a, rtol = 1e-5, atol = 1e-5)+++def test_fbcache_on_flux2_recomputes_when_the_residual_moves(stock_tail_hook):+ dc.install_fbcache_mixed_stream_tail()+ model, inputs = _tiny_flux2()+ _, calls = _render(model, inputs, (1.0, 0.5, 0.1), threshold = 1e-9)+ assert calls == 3+++def test_unmappable_tail_never_skips(stock_tail_hook):+ """A tail output that is not the joint [encoder, hidden] sequence cannot seed a skip."""+ torch, *_ = _diffusers()+ hidden, encoder = torch.zeros(1, 4, 8), torch.zeros(1, 3, 8)+ assert dc._split_mixed_stream_tail_residuals(torch.zeros(1, 9, 8), [hidden, encoder]) is None+ assert dc._split_mixed_stream_tail_residuals(torch.zeros(1, 7, 8), [hidden, None]) is None+ res_hidden, res_encoder = dc._split_mixed_stream_tail_residuals(+ torch.arange(56.0).reshape(1, 7, 8), (hidden, encoder)+ )+ assert torch.equal(res_hidden, torch.arange(24.0, 56.0).reshape(1, 4, 8))+ assert torch.equal(res_encoder, torch.arange(24.0).reshape(1, 3, 8))+++def test_working_family_output_is_byte_identical(stock_tail_hook):+ """FLUX.1 (dual-stream tuple head and tail) must not see the patch at all."""+ torch, *_ = _diffusers()+ steps = (1.0, 1.0, 0.5) # step 2 skips, step 3 computes+ model, inputs = _tiny_flux1()+ before, before_calls = _render(model, inputs, steps, threshold = 0.05)+ dc.install_fbcache_mixed_stream_tail()+ model, inputs = _tiny_flux1()+ after, after_calls = _render(model, inputs, steps, threshold = 0.05)+ assert before_calls == after_calls == 2+ for a, b in zip(before, after):+ assert torch.equal(a, b)+++class _Flux2Pipe:+ """Stands in for Flux2KleinPipeline: a denoise loop that opens ``cache_context``."""++ def __init__(self, transformer, inputs):+ self.transformer = transformer+ self.inputs = inputs++ def __call__(self, timesteps):+ import torch++ outs = []+ with torch.no_grad():+ for t in timesteps:+ with self.transformer.cache_context("cond"):+ outs.append(+ self.transformer(+ **self.inputs, timestep = torch.tensor([t]), return_dict = False+ )[0]+ )+ return outs+++def test_apply_step_cache_on_flux2_renders(stock_tail_hook):+ """The Studio entry point: FBCache engages on FLUX.2 and the cached render completes."""+ torch, *_ = _diffusers()+ model, inputs = _tiny_flux2()+ pipe = _Flux2Pipe(model, inputs)+ steps = (1.0, 1.0, 1.0)+ full = pipe(steps)+ assert dc.apply_step_cache(pipe, mode = "fbcache", threshold = 0.5) == "fbcache"+ try:+ cached = pipe(steps)+ finally:+ model.disable_cache()+ assert torch.equal(full[0], cached[0])+ for a, b in zip(full[1:], cached[1:]):+ torch.testing.assert_close(b, a, rtol = 1e-5, atol = 1e-5)+++def test_apply_step_cache_adopts_a_cache_enabled_before_the_patch(stock_tail_hook):+ """An FBCache enabled with the stock tail hook (same threshold, so apply_step_cache adopts it rather than+ re-enabling) must run the patched tail too, not the bound stock method diffusers captured at registration."""+ torch, FirstBlockCacheConfig, *_ = _diffusers()+ model, inputs = _tiny_flux2()+ pipe = _Flux2Pipe(model, inputs)+ steps = (1.0, 1.0, 1.0)+ full = pipe(steps)+ model.enable_cache(FirstBlockCacheConfig(threshold = 0.5)) # hooks bound to the stock tail+ try:+ assert dc.apply_step_cache(pipe, mode = "fbcache", threshold = 0.5) == "fbcache"+ cached = pipe(steps)+ finally:+ model.disable_cache()+ assert torch.equal(full[0], cached[0])+ for a, b in zip(full[1:], cached[1:]):+ torch.testing.assert_close(b, a, rtol = 1e-5, atol = 1e-5)