Skip to content

Studio: fix First Block Cache on FLUX.2 (dual-stream head, single-stream tail) - #14401

Merged
danielhanchen merged 3 commits into
mainfrom
studio-diffusion-fbcache-tuple-head
Oct 20, 2026
Merged

danielhanchen merged 3 commits into
mainfrom
studio-diffusion-fbcache-tuple-head

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 20, 2026 •

Copy link
Copy Markdown
Member

Summary

First Block Cache (the fbcache step cache) crashed on every FLUX.2 render, klein and dev. This adds a small patch to the diffusers FBCache tail hook so it works when a model's first block is dual-stream and its last block is single-stream. Every other family still runs the stock hook.

What was broken

FLUX.2 runs Flux2TransformerBlock first. It returns (encoder_hidden_states, hidden_states). Then it concatenates the two streams and runs Flux2SingleTransformerBlock over the joint sequence, which returns a single tensor. diffusers' FBCache stores the head block's output as a [hidden, encoder] list, but the tail hook decides its branch from the tail's output type. With a tensor tail it computes output - head_block_output, so the first cached step fails with:

File ".../diffusers/hooks/first_block_cache.py", line 179, in new_forward
    hidden_states_residual = output - shared_state.head_block_output
TypeError: unsupported operand type(s) for -: 'Tensor' and 'list'

The bug shows up with any diffusers that registers the FLUX.2 blocks for caching, which includes the diffusers main pin Studio installs by default. Flux2KleinPipeline opens cache_context and does not reuse a prefix KV, so apply_step_cache turns the cache on and the render then fails. I scanned every block class in the diffusers registry. FLUX.2 is the only family whose head registers an encoder output while its tail does not.

The fix

install_fbcache_mixed_stream_tail() in core/inference/diffusion_cache.py wraps FBCBlockHook.new_forward. apply_step_cache installs it before enable_cache, because diffusers binds the hook method at registration time.

  • The new path is taken only by a tail block whose metadata has no encoder output, when the head stored a (hidden, encoder) pair, on a computed step. In every other case the stock hook runs, so families that already work are not affected.
  • On that path the joint tail output is split at the text length: tail[:, text_len:] - head_hidden and tail[:, :text_len] - head_encoder. The resulting residuals have the shapes the head's skip branch adds them to. ParaAttention's first block cache splits its FLUX single blocks the same way (cat([encoder, hidden]), then split by encoder length).
  • If the tail output can't be mapped onto the head (wrong length or width), the head residual is cleared. The next step then computes in full instead of skipping with the wrong residuals.
  • The existing length guard still applies, since the stored hidden residual now has the head's hidden shape.
  • diffusers binds hook.new_forward when it registers a hook, so an FBCache that was enabled before the patch (one apply_step_cache adopts instead of re-enabling) is rebound to the patched tail as well.

Tests

New file studio/backend/tests/test_diffusion_fbcache_mixed_stream.py. It uses the real diffusers hooks on tiny random transformers and runs on CPU in seconds:

  • the stock hook on a tiny FLUX.2 raises the 'Tensor' and 'list' error (this pins the bug)
  • apply_step_cache on a FLUX.2 stand-in pipeline engages and the cached render completes, matching the uncached render (fails on main with the error above, passes here)
  • with constant inputs, steps 2 and 3 skip the stack (1 tail call instead of 3) and match the full pass within 1e-5
  • a moving residual recomputes every step
  • the residual split helper is checked, including the unmappable cases
  • FLUX.1 (dual-stream head and tail) gives byte-identical outputs, with the same skip count, before and after the patch is installed

The existing step-cache tests (test_diffusion_cache.py, test_diffusion_cache_block_registry.py, test_diffusion_step_skip_defaults.py, test_diffusion_static_skip.py, test_diffusion_backend.py, test_video_backend.py, test_diffusion_int8_fused.py, test_dynamo_import_window.py) have the same failing test IDs on base and head. The only failures on both sides are environment import errors on this host (triton.ops from bitsandbytes, or no fastapi).

Real render on one B200 (shared card), unsloth/FLUX.2-klein-base-4B bf16, 768x768, 28 steps, guidance 4.0, seed 0:

arm s/step tail block calls LPIPS vs off
FBCache off (2 runs) 0.133, 0.151 56 0.0 (runs identical)
FBCache on, main fails: TypeError ... 'Tensor' and 'list'
FBCache on, this PR (2 runs) 0.137, 0.141 54 0.022

At the default threshold (0.08), klein-base skips one step per CFG branch out of 28, so the speed change is inside run-to-run noise. This PR is about the crash, not speed tuning.

Not verified

  • The real render used diffusers 0.41.0 with the FLUX.2 block metadata registered by hand, matching what diffusers main registers. It did not run through the full Studio install with the diffusers main pin, and it did not go through the Studio UI or the compiled / CUDA graph speed tiers.
  • No timing on an exclusive card. The s/step numbers above come from a shared card and only show the render completes at a similar speed.
  • No threshold tuning for FLUX.2 and no run on the distilled 4-step klein-4B or on FLUX.2-dev.
  • A head block that returns a plain list still fails inside diffusers' own head hook, which checks isinstance(output, tuple). No registered diffusers block returns a list today.
  • diffusers 0.41.0 (the release pin) does not register the FLUX.2 blocks, so there FBCache stays refused on FLUX.2, as before.

FLUX.2 runs Flux2TransformerBlock, which returns (encoder, hidden), and then
Flux2SingleTransformerBlock over the concatenated sequence, which returns one
tensor. The diffusers FBCache tail hook picks its branch from the tail output
type, so it subtracts the head's stored [hidden, encoder] list from a tensor
and every cached FLUX.2 render fails on the first step with
"unsupported operand type(s) for -: 'Tensor' and 'list'".

Patch the tail hook for that combination only: split the joint tail output
at the text length back into hidden and encoder residuals, the same split
ParaAttention's first block cache uses. Every other family calls the stock
hook unchanged. A tail output that cannot be mapped onto the head drops the
head residual so the next step computes in full instead of skipping.
@danielhanchen danielhanchen self-assigned this Oct 20, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 20, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review 🔄 Running since 2026-10-20T20:21:38.959350Z 79726a9 New commits
🔒 Security Review ⚠️ Failed 2026-10-20T19:56:38.933209Z a80b43f PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: a80b43fc79

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

# 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()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Rebind already-installed tail hooks before adopting the cache

When apply_step_cache encounters an FBCache that was enabled previously—either through enable_cache with the same threshold or the public low-level API—this assignment only changes the class method. HookRegistry.register_hook captured the old bound hook.new_forward when those hooks were registered, and the existing adoption paths deliberately return without rebuilding them, so an adopted FLUX.2 cache still executes the stock tail hook and fails with the same Tensor - list error. Update the installed hook's function reference or rebuild affected hooks before reporting the adopted cache as active.

Useful? React with 👍 / 👎.

@danielhanchen danielhanchen Oct 20, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch, fixed in e6a8167. Both adoption paths (same-threshold no-op and the low-level install recovery) now rebind each registered fbc_block_hook's fn_ref.forward to the current FBCBlockHook.new_forward, so an FBCache enabled before the patch runs the patched tail. Test: test_apply_step_cache_adopts_a_cache_enabled_before_the_patch (fails on the previous head with the Tensor - list error, passes now).

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 🚀

Reviewed commit: e6a81674b7

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

[skip ci]
@danielhanchen
danielhanchen merged commit 4c5e4bd into main Oct 20, 2026
@danielhanchen
danielhanchen deleted the studio-diffusion-fbcache-tuple-head branch October 20, 2026 21:15
danielhanchen added a commit that referenced this pull request Oct 21, 2026
… in the CFG routers, and test fixes (#14420)

## Summary

Follow-up fixes for the recently merged Studio diffusion work: two
runtime fixes (the VAE OOM ladder under a multi-GPU component split, and
bitwise comparison of expanded timesteps in the CFG routers) and five
test fixes. Each change is its own commit.

### 1. VAE OOM step (a) frees only what sits on the VAE's card (#13802
with #13725)

**What was broken.** Under a component split the VAE decodes on a
secondary card while the denoiser stays resident on the primary. When
that decode ran out of memory, `DecodeSession.free_others` reset the
denoiser's CUDA graphs on the primary card and counted that as
"released". The ladder then retried the same untiled decode on the
secondary card, which ran out of memory again before it reached the
tiled rung, and the denoiser lost its captured graphs for nothing.
`_release_groups` had the same problem with resident offload groups on
the primary card. A failed re-pin was also deferred against the VAE's
card instead of the groups' own card.

**Fix.** Graph handles are filtered to the VAE's card, using the card
the graph was recorded on (or its module's card when nothing has been
recorded yet). Resident-group modules are filtered by
`_unsloth_resident_device`. This is the same filtering
`_hook_torchao_resident` and `_move_components` already do with
`_placement(comp, self.device)`. `release_resident_groups` takes an
optional `device` filter. It is only passed when the pipeline has
resident groups on more than one card, so single-card calls are
unchanged. Anything whose card cannot be read is still freed, as before.

**Tests** (`test_diffusion_vae_oom.py`, all fail on main):
- `test_split_vae_oom_leaves_the_other_cards_graphs_alone`: a decode on
cuda:1 with graphs on cuda:0 goes straight from the untiled decode to
the tiled one, and no graph is reset.
- `test_split_vae_oom_still_drops_graphs_on_its_own_card`: only the
cuda:1 handle is reset.
- `test_split_vae_oom_releases_only_groups_on_its_own_card`: groups on
cuda:0 are left alone and nothing is deferred against them. With groups
on both cards, the release is limited to cuda:1.
- `test_release_resident_groups_device_filter`: the new filter releases
only the matching card's groups, and with no filter every card's groups
are released.

### 2. Expanded scalars compare bitwise in the CFG routers (#13725,
#13787)

**What was broken.** `_bitwise_equal` in `diffusion_multigpu.py`
flattens both tensors, calls `contiguous()` and views them as `uint8`.
WanPipeline passes `timestep = t.expand(batch)`. For a one-element
tensor `contiguous()` is a no-op whatever the stride, so the stride-0
timestep reached `view(torch.uint8)`, which raised, and the comparison
returned False for two equal timesteps. #13787 CFG batching uses it
through `_record_template`, `_matches` and the branch merge. On Wan it
missed three times in a row and turned itself off. CFG-parallel's
prediction check uses the same helper.

**Fix.** A small `_as_bytes` helper takes a dense copy only when the
flattened tensor still has a non-unit stride. `_bitwise_equal` and
`_unchanged_since_launch` both use it. Bitwise semantics are unchanged:
equal NaN bits match, and -0.0 and 0.0 do not. The CFG batcher's three
call sites all go through `_bitwise_equal`, so they are covered by the
same fix.

**Tests** (both fail on main):
- `test_bitwise_equal_on_an_expanded_scalar`
(`test_diffusion_multigpu.py`): `torch.tensor(941).expand(1)` against a
clone and a fresh expand, plus NaN, signed zero and
`_unchanged_since_launch`.
- `test_wan_expanded_timesteps_serve_the_second_branch`
(`test_diffusion_cfg_batch.py`): a Wan-style loop that passes
`t.expand(batch)` to each branch. It matches the two-call reference with
4 hits, 0 misses, and batching stays on. On main it gets 0 hits.

### 3. Seeded denoiser cancel test pins the text encoder (#13715)

**What was broken.** On a CUDA host, an unset `text_encoder_quant` also
plans the hosted FP8 Wan text encoder. The load then fetched two
artifacts and
`test_the_seeded_denoiser_artifact_is_fetched_under_the_load_cancel_event`
failed its exact single-fetch assertion. It passed only with the GPU
hidden.

**Fix.** The test passes `text_encoder_quant = "off"`, so it checks only
what it is about: the denoiser fetch carries the load's cancel event.

**Test.** Fails on main with a GPU visible and passes after. It passes
both ways with the GPU hidden.

### 4. FLUX.2 FBCache test invalidates the child registry cache (#14401)

**What was broken.** On diffusers 0.39 and 0.40, `enable_cache` does not
drop the child-registry list that an earlier uncached render cached.
`test_fbcache_on_flux2_skips_and_matches_the_full_pass` then failed with
`ValueError: No context is set`. Production already calls
`_invalidate_child_registry_cache` after `enable_cache` in
`apply_step_cache`. Only the test helper skipped it. diffusers 0.41
invalidates the list itself.

**Fix.** The test's `_render` helper calls
`dc._invalidate_child_registry_cache(model)` after `enable_cache`.

**Test.** With diffusers 0.39.0 the test failed before and the whole
file passes after (7 passed). It also passes on the pinned diffusers.

### 5. Stream encode tests skip when diffusers cannot import the Wan VAE
(#14405)

**What was broken.** `pytest.importorskip("diffusers")` succeeds on the
lazy top-level module. The next line, `from diffusers import
AutoencoderKLWan`, can then raise `RuntimeError` (for example with a
broken bitsandbytes), which aborted collection of the whole pytest run.

**Fix.** Catch `ImportError` and `RuntimeError` on those imports and
skip the module, as the other diffusion tests do.

**Test.** In an environment with a broken bitsandbytes, collection
errored before and the module is skipped after. In the Studio
environment all 9 tests still run and pass.

### 6. Multi-GPU planner tests pin the host facts they read (#13725,
#13793)

**What was broken.** On a host with one GPU, 11 tests in
`test_diffusion_multigpu.py` failed. `make_selection` drops ordinals at
or above the real `torch.cuda.device_count()` and cards below the
primary's capability, so `make_selection(0, [0, 1])` returned None on a
one-card machine. An AMD Strix Halo CI runner (one integrated gfx1151)
showed exactly these 11. `test_diffusion_fp8_unit_scale.py` gated on
`get_device_capability() >= (8, 9)`, which passes on ROCm because ROCm
reports the gfx version (gfx1151 gives (11, 5)), and torchao then
refuses fp8 there.

**Fix.** Tests only. The autouse fixture pins the card count and the
capability check (tests that probe those filters still override them),
and the fp8 GPU gate returns False on a HIP torch, matching Studio,
which already declines torchao fp8 on ROCm. New test
`test_two_discrete_rocm_cards_split_like_cuda`: with HIP set and two
cards at capability (11, 0), the planner selects both and splits onto
card 1, as on CUDA.

**Tests.** Spoofed host (HIP + one integrated card, HIP + two discrete
cards, one CUDA card without HIP): 11 failed before, 114 passed after on
each. Normal CPU host: 133 passed, 1 skipped.

### 7. The ROCm APU pool discount applies only to HIP device snapshots
(#14379)

**What was broken.** `_rocm_linux_apu_os_room_outside_pool`
(`diffusion_memory.py`) gave any unified-memory reading the smaller
Linux ROCm APU reserve on a ROCm build, without checking the snapshot's
device. On a ROCm host, a mocked Apple (`mps`) snapshot in
`test_diffusion_unified_load_override.py` got that reserve, so two
refusal tests failed. A real ROCm build never produces an `mps` reading,
so the user impact is close to zero.

**Fix.** The discount now requires a `cuda` device snapshot (`cuda` or
`cuda:N`). `test_flux3_prompt_upsampler.py` also pins
`torch.__version__` in the tests that stand in for a CUDA build (Studio
reads `+rocm` there too) and pins the card count in its warm fixture,
which read the real host.

**Tests.** The new `mps` / `cpu` reserve test fails without the fix and
passes with it. Prompt upsampler: 164 passed on a spoofed APU, two
discrete ROCm cards, two CUDA cards and plain CPU.

## Tests

Base is origin/main and head is this branch. Same host and same Studio
venv (diffusers 0.41 dev, torch 2.13). Failing test IDs were compared,
not counts.

- CPU, GPU hidden: test_diffusion_vae_oom.py,
test_diffusion_vae_oom_faults.py, test_diffusion_measured_placement.py,
test_diffusion_offload_cuda_graph.py, test_diffusion_learned_peaks.py,
test_diffusion_int8_gemm.py, test_video_stream_residency.py,
test_diffusion_offload_prefetch.py,
test_diffusion_small_host_prefetch.py,
test_diffusion_fbcache_mixed_stream.py, test_video_stream_encode.py,
test_diffusion_multigpu.py. Base: 3912 passed, 125 skipped, 0 failed.
Head: 3916 passed (the 4 new tests), 125 skipped, 0 failed. No failing
IDs on either side.
- One GPU visible: test_video_prequant.py. Base: 1 failed
(`test_the_seeded_denoiser_artifact_is_fetched_under_the_load_cancel_event`),
85 passed. Head: 86 passed.
- CPU, GPU hidden: test_diffusion_cfg_batch.py,
test_diffusion_multigpu.py, test_diffusion_multigpu_wiring.py,
test_video_multigpu_wiring.py. Base: 128 passed. Head: 130 passed (the 2
new tests). No failures on either side.
- test_diffusion_fbcache_mixed_stream.py on diffusers 0.39.0: 1 failed
before, 7 passed after.

Wan2.1-T2V-1.3B end to end on a Kaggle T4 capped at 7.25 GiB (streamed
offload, fp32, 480x320, 17 frames, 6 steps, guidance 5, seed 1234). Base
and head ran on the two T4s of one kernel, each on its own CPU slice:

| Run | s/step | CFG batch |
|---|---|---|
| base, CFG batching off | 5.96 | not armed |
| base, auto | 8.55 | 0 hits, 3 misses (timestep 941 vs 941), then off |
| head, CFG batching off | 5.58 | not armed |
| head, auto | 5.55 | 2 hits, 0 misses, then off: measured no gain
(batched pair 5.42 s vs plain pair 5.39 s) |

- The 43% slowdown on base is gone. On this streamed T4 placement a
batched pair is no faster than two plain calls, so the batcher's own
timing gate turns it off, as designed.
- The batching-off latents are identical on base and head
(`829b889b587d13f6`), so the plain path is unchanged. The two batched
steps are not bit-exact, as documented for CFG batching.

## Not verified

- CFG-parallel on two real cards: test_diffusion_multigpu_cuda.py needs
two CUDA cards in one process and was skipped.

- No real two-GPU decode that runs out of memory. The split case is
covered by CPU tests that use real `torch.device("cuda", N)` indices
with fake graph handles and resident modules.
- diffusers 0.40.0 was not run. Its source lacks the same invalidation
as 0.39.0.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant