Skip to content

Studio Qwen-Image-2.1: encode prompts without the text encoder's unused K/V cache - #17118

Merged
danielhanchen merged 2 commits into
mainfrom
q21-te-no-kv-cache
Nov 9, 2026
Merged

danielhanchen merged 2 commits into
mainfrom
q21-te-no-kv-cache

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Nov 8, 2026 •

Copy link
Copy Markdown
Member

Problem

Qwen-Image-2.1's prompt encode (QwenImage21Pipeline._get_qwen_prompt_embeds, diffusers 0.42.1) runs one Qwen3-VL forward with output_hidden_states=True and reads only hidden_states[-1]. It never passes use_cache. The released text encoder config has use_cache: true, so transformers builds a DynamicCache holding every decoder layer's K/V for the whole prompt, and nothing reads it. With 36 layers, 8 K/V heads and head dim 128 in bf16, that is 144 KiB per prompt token, held at the encode's peak next to the hidden states.

Fix

New core/inference/diffusion_qwenimage21_te.py: at load, Studio wraps the pipeline's _get_qwen_prompt_embeds on the instance. During that call only, a forward pre-hook on the text encoder sets use_cache=False; the hook is removed when the call returns.

  • The returned hidden states and embeddings do not change. The cache is an output, not an input, for a single full-prompt forward.
  • Any other forward of the same encoder keeps its configured use_cache.
  • It applies only to pipelines that have _get_qwen_prompt_embeds and a Qwen3-VL text encoder. The encoder is read at call time, so a quantised or swapped encoder is covered, and the hook works alongside offload hooks.
  • Kill switch: UNSLOTH_QWEN21_TE_NO_KV=0.

Tests

studio/backend/tests/test_diffusion_qwenimage21_te_no_kv.py (CPU, the real pipeline method on a tiny random Qwen3-VL):

  • The stock call builds a cache. After the change it builds none, and the embeddings, attention mask and image-pad mask are bitwise equal.
  • A direct forward of the same encoder still caches.
  • Install is idempotent, the kill switch keeps the stock call, and other pipelines and encoders are left alone.

Measurements

A100-SXM4-80GB, torch 2.14.1, transformers 5.17.0, diffusers 0.42.1. The real pipeline method runs with the released Qwen-Image-2.1 processor and text encoder config: 36 layers, hidden 4096, random bf16 weights. The peak is allocated memory over the encode's start, on the second call. Arms were interleaved, 3 runs each, plus 1 kill-switch run.

prompt tokens encode peak before after max reserved before after encode ms before after embeddings
1,330 1012.3 MiB 820.6 MiB 17962 MiB 17866 MiB 131 - 147 130 - 146 identical
5,326 3986.3 MiB 3229.2 MiB 21500 MiB 20618 MiB 501 - 504 497 - 503 identical
10,652 7930.8 MiB 6429.9 MiB 25984 MiB 24304 MiB 1066 - 1070 1061 - 1062 identical
  • The saving is 144 KiB per token, the size of the K/V cache: -192 MiB at 1.3K tokens and -1.5 GiB at 10.7K tokens. Reference images add vision tokens to the prompt, so edits with several references sit at the long end.
  • Encode time is unchanged.
  • Embedding sha256 is identical in every run, in both arms and with the kill switch. The kill-switch run reproduces the base peaks exactly.

Not proven here

  • No full image render was run; this changes only the prompt encode, and its output is bitwise unchanged.
  • Only A100 (sm80) was measured. The change does not depend on the device, but ROCm, XPU, MPS and CPU encodes were not run.
  • transformers 4.57.x was not tested. The diffusers releases that ship this pipeline require huggingface_hub >= 1.32, which transformers 4.57 cannot import with.
  • Qwen-Image (v1) pipelines call their Qwen2.5-VL encoder the same way, but they are not changed here.

…ed K/V cache

The pipeline's prompt encode runs one Qwen3-VL forward for hidden states but
leaves use_cache at the config default, so a DynamicCache of all 36 layers'
K/V (144 KiB per token) is built and never read. Only that call now passes
use_cache=False; UNSLOTH_QWEN21_TE_NO_KV=0 restores the stock call.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 8, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-08T06:12:38.356737Z e786ee6 Manual request
ℹ️ 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 self-assigned this Nov 8, 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. Breezy!

Reviewed commit: e786ee6fae

ℹ️ 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 merged commit bc8d970 into main Nov 9, 2026
@danielhanchen
danielhanchen deleted the q21-te-no-kv-cache branch November 9, 2026 01:07
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Nov 9, 2026
…tates they read (unslothai#17182)

## Problem

Both prompt encoders request `output_hidden_states=True` and keep every
decoder layer's output alive for the whole encoder call, although each
reads only a few:

- FLUX.3 (diffusers `Flux3TextEncoderStep._get_qwen3_vl_prompt_embeds`)
stacks hidden states `(4, 8, ..., 32)` of its Qwen3-VL encoder. Studio's
dead-tail truncation already drops the unread layers 33 to 36, but the
25 unread states before layer 32 stay alive: about 0.98 GiB at an
8,192-token window (bf16, width 2560).
- Qwen-Image-2.1 (`QwenImage21Pipeline._get_qwen_prompt_embeds`) reads
only `hidden_states[-1]`, but all 37 states of its 36-layer Qwen3-VL
stay alive: about 2.25 GiB at 8,192 tokens (width 4096).

## Fix

One shared helper, `core/inference/diffusion_te_select.py`:

- `run_selected(encoder, indices, call)` runs `call()` with forward
hooks that turn the encoder's `output_hidden_states=True` into `False`
for that one forward and record only the requested entries: entry `k` (1
<= k < n) is decoder layer `k - 1`'s output, read from that layer's own
output; the final entry only when the caller guarantees its stock
reading is the final norm's input (Qwen-Image-2.1's pipeline neutralizes
the norm for exactly that), recorded from the norm's input.
- The output's `hidden_states` answers exactly those indices with the
same tensors. Any other read, a recorder that did not fire, or a forward
that still built the tuple raises inside the call, and the call is
re-run stock.
- Engages only when the language stack length equals the config's
`num_hidden_layers` (passthrough tail slots from the truncation are
fine), never on a compiled encoder. Hooks are removed when the call
returns.
- FLUX.3: `Flux3Pipeline.encode_prompt` wraps its helper call.
- Qwen-Image-2.1: `select_final_hidden_state` wraps
`_get_qwen_prompt_embeds` next to the K/V-cache skip from unslothai#17118, only
when the pipeline source still has its norm-neutralizing hook.
- Kill switch: `UNSLOTH_DIFFUSION_TE_SELECT_HIDDEN=0`.

Tokenization, padding, `use_cache`, the truncation and the prompt cache
are unchanged; the embeddings are bitwise identical.

## Tests

`studio/backend/tests/test_diffusion_te_select.py` and
`test_diffusion_qwenimage21_te_no_kv.py` (CPU, random tiny Qwen3-VL), on
transformers 4.57.6 (torch 2.12) and 5.17.0 (torch 2.10, diffusers
0.42.1):

- FLUX.3 layers and the Qwen-Image-2.1 final pre-norm state are bitwise
the stock tensors, through diffusers' own FLUX.3 helper and the real
Qwen-Image-2.1 pipeline method (with the K/V skip).
- During the forward only the requested layer outputs survive (weakrefs
on every layer's output).
- An unrequested read falls back to the stock call; embeddings, final
entry without the pre-norm contract, non-encoders and the kill switch
run stock; dead-tail passthrough slots keep it exact; hooks are removed
afterwards.

## Measurements

Colab L4 (sm89, 22 GiB), torch 2.13.0+cu130, diffusers 0.42.1,
transformers 5.5.0, one VM. Base = main bdebdc8, head = base plus
unslothai#17180, unslothai#17181 and unslothai#17182 together (one patch). FLUX.3 klein, 1024x1024,
16 steps, Studio default speed; each cell is a fresh process with 3
timed renders (median), order base, head, baseline, head, base, baseline
per configuration. 6 GiB = a ballast process leaving 6 GiB free for both
stacks. The baseline runs its own INT8 / FP8 files of the same
checkpoint on the same VM.

Same L4, random Qwen3-VL text stack (36 layers, width 2560, bf16;
FLUX.3's 8 layers and Qwen-Image-2.1's final pre-norm state), peak
allocated over the encode start, stock vs selective:

| encoder read | tokens | output | extra peak MiB, stock -> selective |
encode s, stock -> selective |
|---|---|---|---|---|
| FLUX.3, 8 layers | 1,024 | bitwise equal | 267.0 -> 122.0 | 0.276 ->
0.062 (first call includes warm-up) |
| FLUX.3, 8 layers | 8,192 | bitwise equal | 2136.1 -> 976.1 | 0.414 ->
0.416 |
| Qwen-Image-2.1, final state | 1,024 | bitwise equal | 205.5 -> 35.5 |
0.059 -> 0.053 |
| Qwen-Image-2.1, final state | 8,192 | bitwise equal | 1644.2 -> 284.2
| 0.400 -> 0.410 |

(The Qwen-Image-2.1 row uses width 2560 here; its real encoder is width
4096, so its real saving is about 1.6x these numbers.)

End to end on FLUX.3 klein (same VM, base vs head with all three PRs):
the speed-off bf16 renders are pixel-identical (LPIPS 0, 3 of 3 images),
and prompt encode time is unchanged (0.12 s resident, 0.46 s at 6 GiB in
both arms). The benchmark prompts are short (an 80-token window), so the
render-level peak does not move; the saving grows with prompt length as
above.

## Not proven here

- No real Qwen-Image-2.1 render was run; the pipeline-level check is the
real pipeline method on a tiny random encoder (CPU) plus the width-2560
CUDA stack above.
- No long-prompt end-to-end render was timed; the memory saving was
measured on the encoder alone.
- Multimodal Qwen-Image-2.1 encodes (reference images through the vision
tower) were not run; the final-state read does not depend on them, but
they were not tested.
- ROCm, MPS, XPU and Windows were not run.
danielhanchen added a commit that referenced this pull request Nov 9, 2026
… a fixed sleep (#17234)

## Summary

`tests/studio/playwright_tool_activity.py` scene 3 clicks the controlled
and uncontrolled tool cards back to back, sleeps a fixed 600 ms, then
reads `aria-expanded`. On a loaded runner the second click is sometimes
lost: the first card's 200 ms Radix expansion is still moving the second
trigger, so the gate reports

```
PROBLEMS (chromium):
  - 3: uncontrolled did not open on click
```

while the controlled card opened fine. It has turned `Chat UI Tests
(extra)` red on unrelated PRs three times since yesterday:

- #17118 (staging run, Nov 8)
- #17213 (Nov 9)
- #17178 (staging run, Nov 9, a backend-only int8 change)

No frontend file changed on `main` between the last green run of that
job and those failures.

The fix opens each card in turn and waits, bounded at 5 s, until its
trigger reports `aria-expanded="true"` before clicking the next one. The
scene still reads `aria-expanded` afterwards and records the same
problem, so a card that really does not open on click still fails the
gate.

## Changes

- `tests/studio/playwright_tool_activity.py`: new `click_open(page,
name)` helper, used for the two scene 3 clicks. Every other scene is
unchanged.

## Testing

- Three local runs of the gate on Chromium: `problems == []` each time.
- Sabotage: with a capture-phase listener that swallows clicks on the
uncontrolled trigger, the gate still fails with `3: uncontrolled did not
open on click`.
- The 22 test files that read the Playwright drivers or
`_playwright_robust` pass (714 passed), and ruff and the exec-literal
lint are clean.
danielhanchen added a commit to NilayYadav/unsloth that referenced this pull request Nov 9, 2026
…the no-K/V wrapper, and key callable helpers fully (unslothai#17192)

## What happened

unslothai#17105 made the prompt cache drop denoiser-only LoRA adapters from its
key when a static check proves `encode_prompt` never runs a denoiser, so
a strength sweep on a transformer-only LoRA reuses the text embeddings
instead of re-running the text encoder.

Two gaps showed up on current main:

1. **Qwen-Image-2.1 lost the reuse.** unslothai#17118 later installed an
instance-level `_get_qwen_prompt_embeds` wrapper (it runs the text
encoder with `use_cache=False`) before `prompt_cache.install`. The check
treats any instance-level function as unprovable, so for the real
`QwenImage21Pipeline` it went from `True` to `False` once the wrapper
was installed, and every strength change re-ran the encoder again.
Embeddings stayed correct; only the saving was gone.
2. **Callable objects were not followed.** An instance attribute that is
an object with `__call__`, or an `nn.Module` that contains the denoiser,
was treated as plain data. A helper like that which reads the
transformer returned the first strength's embeddings for every later
strength (`[0.25, 0.25]` with one encode, against `[0.25, 0.75]` with
two encodes before unslothai#17105).

## Fix

- The no-K/V wrapper is marked as forwarding only to the same-named
class method. The check accepts a marked instance attribute only when
the unwrapped target is that instance's own bound class method, then
follows the class method as before. An unmarked wrapper, or a marked one
around anything else, still keeps the full key.
- A callable instance attribute now keeps the full key unless it is an
`nn.Module` that holds no denoiser (text encoders) or a tokenizer /
processor / image processor / feature extractor.

The check runs once when the cache is installed, so render-time cost is
unchanged and nothing compiled is touched.
`UNSLOTH_DIFFUSION_TE_SCOPED_LORA_KEY=0` still turns the scoped key off
entirely.

## Tests

New cases in `studio/backend/tests/test_diffusion_prompt_cache.py`: the
real no-K/V wrapper installed before the cache on a Qwen-Image-2.1
shaped pipeline and on the real `QwenImage21Pipeline` class (one encode
across a strength sweep), unmarked and mis-marked wrappers,
callable-object and denoiser-holding module helpers (two encodes, fresh
values), and a check that each run imports its own tree.

On main 5 of them fail; on this branch the file passes (55 passed, 1
CUDA-only skip, diffusers 0.42.1, CPU).
`test_diffusion_qwenimage21_te_no_kv.py` and
`test_shared_memory_offload_keeps_the_prompt_cache.py` also pass.
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