Repository navigation
Studio FLUX.3 / Qwen-Image-2.1: prompt encodes keep only the hidden states they read - #17182
Merged
Merged
Conversation
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
Member
Author
|
@codex review |
|
Codex Review: Didn't find any major issues. Swish! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
Both prompt encoders request
output_hidden_states=Trueand keep every decoder layer's output alive for the whole encoder call, although each reads only a few: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).QwenImage21Pipeline._get_qwen_prompt_embeds) reads onlyhidden_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)runscall()with forward hooks that turn the encoder'soutput_hidden_states=TrueintoFalsefor that one forward and record only the requested entries: entryk(1 <= k < n) is decoder layerk - 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.hidden_statesanswers 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.num_hidden_layers(passthrough tail slots from the truncation are fine), never on a compiled encoder. Hooks are removed when the call returns.Flux3Pipeline.encode_promptwraps its helper call.select_final_hidden_statewraps_get_qwen_prompt_embedsnext 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.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.pyandtest_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):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:
(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