Skip to content

Qwen-Image-2.1 fails every render at 20+ steps: FBCache cannot run on a prefix KV cache - #11546

Merged
danielhanchen merged 1 commit into
mainfrom
studio-q21-fbcache
Sep 22, 2026
Merged

danielhanchen merged 1 commit into
mainfrom
studio-q21-fbcache

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Sep 22, 2026 •

Copy link
Copy Markdown
Member

Qwen-Image-2.1 fails every generation on main at 20 steps or more. The load succeeds, the first denoise step succeeds, and the second one dies:

RuntimeError: The size of tensor a (4096) must match the size of tensor b (4297) at non-singleton dimension 1
  diffusers/hooks/first_block_cache.py:139 in _should_compute_remaining_blocks
    absmean = (hidden_states_residual - prev_hidden_states_residual).abs().mean()

Why

Qwen-Image-2.1 caches the prompt and condition-image prefix K and V. QwenImage21Transformer2DModel.forward runs the first step over the whole joint sequence to populate that cache, and every later step over the target image tokens alone:

if kv_cache_mode == "cached":
    joint_hidden_states = joint_hidden_states[:, prefix_len:]

So the per-block sequence length changes between step 0 and step 1: 4096 + 201 prompt tokens, then 4096. FBCache stores the first block's residual at step 0 and subtracts the next step's from it elementwise, and reuses the remaining blocks' cached residual the same way. Neither survives a length change.

The step-count rule is what makes this the default rather than an opt-in: FBCACHE_MIN_STEPS is 20, so an unset cache request engages at 20 steps, which is the step count our own model card recommends for this family.

The fix

Refuse the cache when the pipeline drives a prefix KV cache, before enable_cache rather than after, and run uncached with a logged reason. Read structurally instead of by family name: the transformer's forward accepts a kv_cache_mode and the pipeline's denoise loop passes one. Qwen-Image-2.1 is the only family Studio routes there today, but FLUX.2 klein KV and Wan-Animate-2 have the same shape upstream and are covered without another edit.

The guard is deliberately conservative in one direction. A checkpoint that carries the parameter but whose pipeline never populates the cache 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.

Evidence

Differential on a B200, both arms identical except for which diffusion_cache.py is loaded: same model, prompt, 20 steps, 1024px, seed 42, true_cfg_scale 4.0. diffusers is the exact commit diffusers-main.txt pins (80c7ed26), so this is the tree an install actually gets.

arm cache engaged result
main fbcache FAILED, RuntimeError at first_block_cache.py:139, step 2
this branch None, refused with a reason OK, 20/20 steps, image renders correctly

The refusal reads:

diffusion.cache: fbcache unavailable (transformer reuses a prefix KV cache, so the block
sequence length changes after the first step; running uncached); running uncached

The base arm reproduces the reported failure at the same file and line. The token counts differ only because my prompt is shorter than the reported one (4117 against 4297); the mismatch is the prompt length either way.

What this does not disable

The guard's predicate, evaluated over the whole installed diffusers tree: 2 of 350 pipelines drive a prefix KV cache (qwenimage21, flux2_klein_kv). The other 348 are untouched and keep FBCache exactly as before. Three transformers accept kv_cache_mode; the third, Wan-Animate-2, has no pipeline that drives one, and the guard's "the loop must actually pass it" half is what keeps that one cached. There is a test for each of those three cases.

Tests

test_diffusion_cache.py: 65 passed. Three new cases, each failing on the parent commit for the right reason:

  • a prefix-KV transformer is refused and enable_cache is never called
  • an ordinary CacheMixin transformer still engages, which is the control
  • a transformer that accepts kv_cache_mode inside a loop that never passes one still engages

test_diffusion_gguf_compile.py does not collect in my environment (bitsandbytes CUDA setup), which is unrelated to this change and reproduces without it.

Diffusers pin

Checked, no change needed. 0.41.0 is still unreleased, so diffusers-pin.txt stays at 0.40.0 and diffusers-main.txt stays at 80c7ed26. Upstream main is 7 commits ahead of that pin and none of them touch qwenimage21, first_block_cache or hooks/, so the defect is live on upstream main too and moving the pin would not have fixed it.

Follow-up, not in this PR

A shape-aware FBCache could keep the speed here by storing only the target-token slice of the prefill residual, which would make both stored tensors line up from step 1 on. That means patching diffusers hook internals, and the prefill residual carries cross-attention the decode steps never recompute, so whether reuse is even sound needs measuring rather than asserting. Worth doing separately; not worth blocking a broken default on.

Pre-existing failures, checked not assumed

The wider diffusion selection has three failures on this branch:

test_diffusion_more_families.py::test_qwen_image_21_gguf_reaches_sd_cpp_with_its_own_vae_and_a_qwen3vl_encoder
test_diffusion_more_families.py::test_create_causal_mask_patch_is_self_disabling_and_idempotent
test_diffusion_train_perf.py::test_gather_sigmas_matches_search_based_gather

All three fail identically on a pristine origin/main worktree at the same commit this branch forks from, so they are already red and none of them touch the file this PR changes. They still need fixing, separately.

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for security reviews. Please try again later.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 22, 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 ✅ Completed 2026-09-22T15:19:18.644954Z 335c74b 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.

@danielhanchen
danielhanchen merged commit c23f8b0 into main Sep 22, 2026
1 of 38 checks passed
@danielhanchen
danielhanchen deleted the studio-q21-fbcache branch September 22, 2026 15:16
LeoBorcherding added a commit to LeoBorcherding/unsloth that referenced this pull request Sep 22, 2026
…ustify FBCache metadata

The crash this branch opened against was already fixed on its base by unslothai#11546, whose
_reuses_prefix_kv refuses the cache before the registry is consulted, so the entry is
restored and only the warning is kept. The earlier cause was wrong too: the sequence
shortens between step 0 and step 1 under prefix KV reuse, not between the cond and
uncond passes, which cache_context keeps in separate states anyway.

Also reverts the pre-commit.ci formatter churn in five unrelated files.
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
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