Skip to content

Studio FLUX.3 / Qwen-Image-2.1: prompt encodes keep only the hidden states they read - #17182

Merged
danielhanchen merged 3 commits into
mainfrom
perf/te-selected-hidden-states
Nov 9, 2026
Merged

danielhanchen merged 3 commits into
mainfrom
perf/te-selected-hidden-states

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Nov 9, 2026 •

Copy link
Copy Markdown
Member

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 Studio Qwen-Image-2.1: encode prompts without the text encoder's unused K/V cache #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 #17180, #17181 and #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 danielhanchen self-assigned this Nov 9, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 9, 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-09T02:05:39.642705Z fffb444 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

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Swish!

Reviewed commit: fffb444e79

ℹ️ 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 cd95bc8 into main Nov 9, 2026
@danielhanchen
danielhanchen deleted the perf/te-selected-hidden-states branch November 9, 2026 11:26
danielhanchen added a commit to Etherll/unsloth that referenced this pull request Nov 9, 2026
… the joint blocks (unslothai#17181)

## Problem

With reference images, FLUX.3's joint blocks get one modulation tensor
for the content sequence (image tokens, then reference tokens). The
image and reference spans carry different timesteps, so
`_flux3_cached_forward` expands the compact per-sample rows from unslothai#17059
back to one row per token and concatenates them:

```python
content_mod = torch.cat([_rows(image_single_mod, ...), _rows(cond_single_mod, ...)], dim = 1)
```

That is `[B, image_tokens + reference_tokens, 3 * 3072]`, alive for
every joint block of every step: 144 MiB in bf16 for a 1024x1024 image
with one 1024x1024 reference, 648 MiB with eight. Each span holds a
single repeated row.

## Fix

In `core/inference/diffusion_cond_blocks.py`:

- At load (`prepare`, before compile or offload hooks bind it)
`Flux3SingleTransformerBlock.forward` is replaced by a forward that
mirrors the stock one op for op, gated on the stock source hash
(d42ebf9c and 0.42.1). Called without the new keyword it is the stock
forward.
- With references, `_flux3_cached_forward` passes the image row as
`temb_mod` (`[B, 1, 3D]`), the reference row as `unsloth_cond_mod` (`[B,
1, 3D]`) and an empty `[reference_tokens, 0]` tensor as
`unsloth_cond_span`, which only carries the span length (no storage, so
a per-block CUDA graph can still copy every input). The block splits the
normed sequence and the residual at the span boundary, modulates and
gates each span by its own row, and concatenates. Element for element it
is what the per-token rows compute, so outputs are bitwise identical.
- Text-only renders, a kill-switched compact path and per-token rows
(`UNSLOTH_DIFFUSION_FLUX3_COMPACT_MOD=0`) are unchanged.
- Kill switch: `UNSLOTH_DIFFUSION_FLUX3_SPAN_MOD=0`.

## Tests

`studio/backend/tests/test_diffusion_cond_blocks.py`, tiny random
`Flux3Transformer2DModel` on CPU:

- Span rows vs per-token rows bitwise equal for fp32 and bf16, batch 1
and 2, 0 / 1 / 8 references with odd span lengths; every joint block
sees `[B, 1, 3D]` rows, and each of its inputs copies into a block-graph
static buffer of the same strides.
- The kill switch restores the per-token rows; the patched block without
the keyword is the stock forward.
- Per-block `torch.compile(fullgraph=True, dynamic=True)`: no graph
break, one frame per block across two reference counts (no recompile),
compiled output bitwise equal to the compiled per-token rows.
- The existing cond-block suite (cache, compact, offload,
whole-transformer compile) passes unchanged.

## 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.

CUDA check on the same L4 (tiny random FLUX.3 transformer in bf16, 1024
image tokens, 1 and 3 references of 1024 tokens plus 3): span rows vs
per-token rows are bitwise equal eager and with per-block
`torch.compile(fullgraph=True, dynamic=True)`; peak allocated 66.5 ->
63.2 MiB eager, 86.2 -> 76.0 MiB compiled. That GPU check ran the first
version of this branch (a stride-0 view for the reference row); the
current marker-tensor version is the same arithmetic and was checked on
CPU (tests above).

The full renders on that VM (text-to-image, no references, so this
change does not engage there) are in unslothai#17180.

## Not proven here

- No full render with reference images was timed or compared, on any
GPU.
- The CUDA check above predates the marker-tensor change; the current
version is CPU-verified (bitwise, eager and compiled) only.
- Offloaded and block-graph runs with references were not exercised on a
GPU; the test copies every joint-block input into a block-graph static
buffer on CPU.
danielhanchen added a commit to NilayYadav/unsloth that referenced this pull request Nov 9, 2026
…stead of contiguous copies (unslothai#17180)

## Problem

On NVIDIA cards where Studio pins cuDNN attention (Auto on sm80 to sm90,
including L4 and A100), every FLUX.3 attention call goes through
diffusers' `_native_cudnn` backend. That wrapper
(`attention_dispatch.py`, diffusers 0.42.1) does

```python
query, key, value = (x.permute(0, 2, 1, 3).contiguous() for x in (query, key, value))
```

so each call writes full contiguous `[B, H, S, D]` copies of Q, K and V,
and its `[B, H, S, D]` output then needs another copy when the processor
flattens it back to `[B, S, H * D]`. cuDNN reads the projections' own
`[B, S, H, D]` strides directly (that is its native interleaved layout),
so all four copies are avoidable. At klein's 1024x1024 shape (24 heads,
head dim 128, 4,352 joint tokens) that is 76.5 MiB of Q/K/V copies per
call, plus the output copy.

## Fix

New `core/inference/diffusion_flux3_attn.py`:

- A `Flux3AttnProcessor` subclass whose cuDNN path is the stock
processor op for op, except that SDPA gets `q.permute(0, 2, 1, 3)` views
(no `.contiguous()`), with the same `sdpa_kernel(CUDNN_ATTENTION)` pin,
no mask, no dropout, default scale. Masks, context parallelism and every
other backend call the stock `__call__`.
- `apply_attention_backend` installs it right after it engages
`_native_cudnn` on NVIDIA CUDA, before compile, only on a
`Flux3Transformer2DModel`, and only when diffusers' processor source
matches the one it mirrors (d42ebf9c and 0.42.1).
- Load-time probe: one small cuDNN call per (card, dtype, heads, head
dim), strided vs contiguous inputs. The swap happens only when the two
outputs are bitwise equal; otherwise diffusers' contiguous call stays.
- The swapped processors keep their `_attention_backend` /
`_parallel_config`; the RoPE call still goes through the module
attribute the fused RoPE install patches.
- Kill switch: `UNSLOTH_DIFFUSION_FLUX3_STRIDED_ATTN=0`.

ROCm, MPS, XPU, CPU, T4 (no cuDNN attention below sm80) and Blackwell
cards where Auto keeps native SDPA are unchanged.

## Tests

`studio/backend/tests/test_diffusion_flux3_strided_attn.py` (CPU; the
cuDNN pin is replaced by a no-op so the math runs on CPU SDPA):

- The subclass matches diffusers' `_native_cudnn` processor call bitwise
(fp32 and bf16, batch 1 and 2, odd lengths).
- Masks and other backends take the stock call; the strided path never
calls it.
- Install swaps every FLUX.3 processor, keeps the backend, is
idempotent, and declines on other backends, other transformers, non-CUDA
targets, a failed probe, a changed diffusers source and the kill switch.
- A tiny random FLUX.3 transformer is bitwise unchanged, and its
per-block `torch.compile(fullgraph=True, dynamic=True)` traces once per
block over three steps (no graph break, no recompile).

## 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.

Raw attention at klein shapes (24 heads, head dim 128, bf16, inputs as
`[B, S, 3072]` projection outputs unflattened), cuDNN pinned in both
arms, diffusers' `_native_cudnn` call vs the strided call including the
final flatten, 9 interleaved x 20 calls:

| mode | B, S | output | extra peak MiB, stock -> strided | ms per call,
stock -> strided | speedup |
|---|---|---|---|---|---|
| eager | 1, 4352 | bitwise equal | 104.0 -> 26.0 | 4.659 -> 3.951 |
1.18x |
| eager | 2, 4352 | bitwise equal | 208.0 -> 52.0 | 9.392 -> 7.825 |
1.20x |
| eager | 1, 8448 | bitwise equal | 198.0 -> 49.5 | 15.842 -> 14.464 |
1.10x |
| compiled | 1, 4352 | bitwise equal | 104.0 -> 26.0 | 4.653 -> 3.987 |
1.17x |
| compiled | 2, 4352 | bitwise equal | 208.0 -> 52.0 | 9.390 -> 7.896 |
1.19x |
| compiled | 1, 8448 | bitwise equal | 198.0 -> 49.5 | 15.785 -> 14.551
| 1.08x |

The load-time probe passed on the L4 and every head render logged `43
FLUX.3 attention calls pass cuDNN their strided views`.

Full renders:

| config | base s/img (r1, r2) | head s/img (r1, r2) | baseline s/img |
baseline / Studio, base -> head |
|---|---|---|---|---|
| INT8 resident | 8.876, 8.848 | 8.811, 8.823 | 8.594, 8.601 | 0.970 ->
0.975 |
| INT8 6 GiB | 11.685, 11.435 | 11.578, 11.735 | 9.455, 9.411 | 0.816 ->
0.809 |
| FP8 resident | 9.906, 9.919 | 9.877, 9.901 | 10.655, 10.674 | 1.076 ->
1.078 |
| FP8 6 GiB | 12.755, 12.722 | 12.674, 12.781 | 11.370, 11.394 | 0.894
-> 0.894 |

- Resident INT8: head is 0.5% faster than base (base A/A spread 0.3%).
Resident FP8: 0.2% faster, inside its spread. At 6 GiB the change is
inside the run-to-run spread (offload dominates there).
- In a whole compiled step most of the Q/K copy was already fused into
the RoPE / cast kernels by Inductor, so the render gain is much smaller
than the raw-attention gain; what is left is the V copy and the output
copy.
- Pixels: Studio's speed renders are not bit-stable across processes on
this card (base r1 vs base r2 LPIPS 0.025 INT8 resident, 0.019 FP8
resident, 0.035 INT8 6 GiB). Head vs base is inside that floor: LPIPS
0.014 / 0.022 / 0.035 / 0.011 (INT8 resident, FP8 resident, INT8 6 GiB,
FP8 6 GiB). The raw attention output is bitwise equal at every shape
above.


## Not proven here

- Only sm89 (L4) was measured. A100 / H100 / sm120 take the same path
behind the same probe but were not run; T4 (no cuDNN attention), ROCm,
MPS, XPU and CPU are untouched by construction.
- Windows was not run.
- This does not close the 6 GiB INT8 gap to the baseline (0.81x at this
budget on this VM); that cell is offload-bound.
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