Skip to content

Studio: stop a compiled Qwen-Image-2.1 render holding 2 GiB of prefix K/V it does not need - #11882

Merged
danielhanchen merged 5 commits into
mainfrom
studio-prefix-kv-compact
Sep 25, 2026
Merged

danielhanchen merged 5 commits into
mainfrom
studio-prefix-kv-compact

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Sep 25, 2026 •

Copy link
Copy Markdown
Member

Why

Qwen-Image-2.1 keeps a prefix KV cache across the denoise: on the first step every block stores the keys and values of the text (and condition image) tokens with key[:, prefix].clone(), and later steps only recompute the image tokens. Under Studio's regional compile, inductor lowers that clone to a view of the block's freshly allocated full-sequence K/V buffer. The cache then holds every block's whole prefill K/V (text plus all 4096 image tokens at 1024x1024) for the rest of the render, where it needs a few MB.

A CUDA memory snapshot taken at VAE decode entry on a compiled int8 render shows it directly: 7.43 GiB of weights, plus two 1.006 GiB groups of 32 blocks each, both allocated inside the compiled attention call, and nothing else. The same pattern reproduces in a five-line torch.compile function on CPU and CUDA (the stored slice reports 8192 bytes of storage for 384 bytes of data).

That 2 GiB sits on top of the VAE decode peak, which is the peak of the whole render, so it decides whether a card fits.

What changes

  • New diffusion_prefix_kv.py: a forward hook on a denoiser whose forward takes kv_cache and kv_cache_mode. After the extract (prefill) call it walks the cache (the one passed in, or the one the call returns, as FLUX.2 does) and replaces every tensor whose storage is larger than its data with its own copy, which frees the full-sequence buffers. Cached steps are not touched.
  • _compile_repeated_blocks installs the hook on every DiT it compiles. Eager runs already store a real copy, so they are left alone.
  • Generic over the cache layouts diffusers ships (Qwen-Image-2.1 layer_caches with k/v, FLUX.2 klein KV double_block_caches / single_block_caches with k_ref/v_ref, Wan-Animate-2 key/value). Values are unchanged; only where they live changes.

Results

Qwen-Image-2.1, 1024x1024, 25 steps, CFG 1, speed default (regional compile), B200 shared with other jobs.

case peak allocated before after
bf16, everything resident 30.98 GiB 28.98 GiB
int8, transformer resident, text encoder streamed (24 GiB cap) 15.73 GiB 13.73 GiB
VAE decode entry, same int8 load 9.45 GiB 7.45 GiB

At 1536x1536 (bf16 resident) the cache pins more, since it holds the full sequence: peak 41.34 -> 36.84 GiB, VAE decode entry 27.20 -> 22.70 GiB. Render time is unchanged: at 1024, interleaved on an idle GPU (main, this PR, main, this PR, 6 steady renders each), the fastest renders were 1.81 and 1.69 s before and 1.67 and 1.70 s after (medians 2.01 and 1.70 before, 1.71 and 2.00 after; another job came back onto the GPU during the last arm); at 1536, 6.18 s before and 6.06 to 6.22 s after.

The compaction costs 2.3 ms once per render (32 blocks, K and V), measured on the real cache shape.

Output is bit-identical. With deterministic kernels (cuDNN benchmark off, native attention), bf16 resident before and after gave identical images for all 5 prompts, and so did int8 resident (peak 24.49 -> 22.49 GiB).

Which torch versions are affected: a compiled k[:, :3].clone() keeps the full buffer on torch 2.10, 2.11, 2.12 and 2.13 (CUDA) and 2.14 (CPU inductor on Linux x64, Linux ARM64 and Apple Silicon macOS, in CI), and is a real copy on 2.6 and 2.8 (CPU inductor), where the hook finds nothing to do.

Tests

tests/test_diffusion_prefix_kv.py:

  • views into a larger buffer are copied out with identical values and the released bytes are counted; compact caches are left alone;
  • the FLUX.2 klein layout and empty layers, and a cache the prefill call builds and returns instead of receiving (FLUX.2 klein), as a tuple or an output field;
  • the hook compacts after the prefill call only, is idempotent, and skips denoisers without a prefix cache;
  • the real QwenImage21KVCache class;
  • the premise itself: a compiled k[:, :prefix].clone() keeps the full buffer (skips if the installed inductor ever copies it out);
  • _compile_repeated_blocks installs the hook.

Reverting the diffusion_speed.py hunk fails the wiring test. test_diffusion_speed.py, test_diffusion_prefix_kv.py, test_diffusion_backend.py, test_video_backend.py, test_diffusion_cache.py, test_diffusion_cuda_graph.py: 1013 passed, 1 skipped (the premise test skips on torch 2.6 and 2.8, where inductor already copies the slice; on 2.10 to 2.13 it runs). test_diffusion_prefix_kv.py also passes on torch 2.6, 2.8, 2.11 and 2.12, and on CPU torch 2.14 on Linux x64, Linux ARM64, macOS 15 (Apple Silicon) and Windows (the premise test skips on Windows, which has no compiler for CPU inductor).

Not measured

  • FLUX.2 klein KV and Wan-Animate-2 on real weights. Both store their reference K/V the same way; the hook is covered by unit tests only for their layouts.
  • Consumer GPUs. The saving is allocator bytes, so it does not depend on the card, but a real 16 or 24 GB render was only run with the resident-transformer placement from the related PR.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 25, 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-25T03:32:40.023777Z ee44aaf Manual request
🔒 Security Review ⚠️ Failed 2026-09-25T02:01:24.043135Z b825955 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

Copy link
Copy Markdown
Member Author

@codex review

@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: b825955b7d

ℹ️ 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".

def _after_prefill(_module, _args, kwargs, _output):
if kwargs.get("kv_cache_mode") != "extract":
return None
cache = kwargs.get("kv_cache")

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 Compact the cache returned by FLUX.2 extract forwards

For FLUX.2 Klein reference-image renders, Flux2KleinPipeline does not pass a kv_cache during the extract call: Flux2Transformer2DModel.forward creates the cache internally and returns it as (output, kv_cache). Consequently this lookup always yields None, so the hook never compacts FLUX.2's double_block_caches or single_block_caches, leaving the compiled full-sequence K/V buffers pinned. The extract hook needs to obtain the returned cache from _output when it is absent from kwargs.

Useful? React with 👍 / 👎.

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.

Right, FLUX.2 builds the cache inside the extract forward and returns it, so the hook never saw it. Fixed in ee44aaf: the hook now takes the cache from the output (the tuple or the kv_cache field) when none was passed in. Regression test: test_a_cache_returned_by_the_prefill_call_is_compacted (both return shapes); it fails without the fix.

danielhanchen added a commit to Imagineer99/unsloth that referenced this pull request Sep 25, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep it up!

Reviewed commit: ee44aaf446

ℹ️ 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".

@danielhanchen danielhanchen self-assigned this Sep 25, 2026
@danielhanchen
danielhanchen merged commit fbf50af into main Sep 25, 2026
54 of 56 checks passed
@danielhanchen
danielhanchen deleted the studio-prefix-kv-compact branch September 25, 2026 17:28
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
… K/V it does not need (unslothai#11882)

* Studio: keep a compiled denoiser's prefix KV cache at its real size

* Studio: tests for the prefix KV compaction

* Format

* Compact the prefix cache a FLUX.2 extract call returns

* Trim comments in prefix KV compaction
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant