Repository navigation
Studio diffusion: FLUX.3 modulation heads project once per sample; offloaded Base edits reuse the conditioning streams - #17059
Conversation
…cache Every image, text and reference token of a mode shares one timestep, so the FLUX.3 modulation heads (and the output norm) now project one row per sample and the blocks broadcast it, instead of projecting an identical row per token. Applies to Base and distilled. UNSLOTH_DIFFUSION_FLUX3_COMPACT_MOD=0 restores the per-token rows. Offloaded FLUX.3 Base edits now reuse the text and reference conditioning streams across steps too: the miss is computed inside the hooked forward (so accelerate / group offload hooks have placed the weights) and later steps skip those blocks; the streamed prefetch order follows. CUDA only for now; UNSLOTH_DIFFUSION_OFFLOAD_COND_CACHE=0 keeps the stock path.
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. |
…test (CUDA / ROCm) [skip ci]
…etch chain [skip ci]
|
Codex Review: Didn't find any major issues. More of your lovely PRs please. 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". |
…p graph runs it eager and the CFG router never keeps it as a template
|
@codex review |
|
Codex Review: Didn't find any major issues. Chef's kiss. 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". |
…load cache [skip ci]
|
@codex review |
|
Codex Review: Didn't find any major issues. Another round soon, please! 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". |
…er compile The compact path bumped a module-dict int inside the forward, which Dynamo guards on: a compiled whole transformer recompiled every call (8 frames over 12 calls, then eager; fullgraph hit the recompile limit). Count only outside a trace, and let the pre-hook pass through under compile so its identity cache and counters never enter a graph. Studio's regional compile is unchanged. [skip ci]
|
@codex review |
|
Codex Review: Didn't find any major issues. Nice work! 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". |
… 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.
Two FLUX.3 denoiser changes in
studio/backend/core/inference/diffusion_cond_blocks.py, each with its own kill switch.1. One modulation row per sample (Base and distilled)
Every token of a FLUX.3 mode (image, text, reference) shares one timestep, yet the forward expands the timestep embedding to the sequence length before the modulation heads, so each head projects the same row once per token:
[B, S, 3 * 3072]per head for the image stream, the same for the text and reference streams, and[B, S, 2 * 3072]for the output norm. Studio keeps these heads dense on purpose, so INT8 / FP8 / GGUF do not remove the work.The heads now project
[B, 1, dim]and the blocks broadcast it (stride-0 views, no.contiguous()copy). The only per-token modulation left is the joint[image, reference]one, which needs both timesteps side by side; it is built once per step from the two compact rows. At 1024x1024 (S = 4096, BF16) the two image modulation outputs alone are 144 MiB per forward, 576 MiB at S = 16384, plus roughly 0.46 TFLOP of projection work per forward.scalekeep the stock diffusers forward.UNSLOTH_DIFFUSION_FLUX3_COMPACT_MOD=0(read at load) restores the per-token rows exactly.2. Offloaded Base edits reuse the conditioning streams
The per-render conditioning cache (#14367) refused the whole render when any submodule carried an accelerate or group-offload hook, because running the conditioning blocks from the forward pre-hook meets host weights and reorders the streamed prefetch. Offloaded Base edits therefore ran the 5 text-mode and 5 reference-mode blocks on every step and branch.
Now, when the denoiser is offloaded, the pre-hook only records the miss; the forward computes the conditioning itself, after the accelerate / group-offload hooks have placed the weights, caches it, and later steps skip those blocks. The event-fenced prefetcher's recorded order is pointed at the forward about to run (conditioning groups dropped on a hit, restored on the next miss), so both stay on order.
unsloth_cond, claimed only by the forward with the same source tensors and batch (a merged CFG call computes stock). Being a non-tensor, a whole-step CUDA graph runs that one call eager (so the cache fills and the hit calls stay capturable), and the CFG batch router records no second-branch template from it (the next plain step records it with the real states, instead of switching batching off for the shape).UNSLOTH_DIFFUSION_OFFLOAD_COND_CACHE=0restores the previous refusal.Evidence (CPU, tiny random
Flux3Transformer2DModel, diffusers 0.42.1)Projection input rows, merge base vs this branch:
Float64 oracle (max abs error of the denoiser output against the stock float64 forward):
Group-offloaded Base edit, 3 steps x 2 CFG branches (diffusers block-level group offload on CPU, CUDA gate opened for the proxy):
<root> is group offloadedTests:
tests/test_diffusion_cond_blocks.pygains float64 parity for compact modulation (Base and flow map, with and without references), compact-cached vs compact-uncached bitwise parity, the kill switch / grad / LoRA-scale fallbacks, the offloaded in-forward cache (one evaluation per branch per render, bitwise vs uncached), the CUDA-only gate, a stale recorded miss never reaching a declined call, and the prefetch order helper. The related suites (cfg batch, cond cache, dynamic text, FLUX.3, layer split, multi-GPU, offload prefetch): 518 passed on the merge base, 528 passed here (the 10 new tests), same 17 skipped.GPU A/B (Colab A100-SXM4-40GB, torch 2.10.0+cu130, merge base vs this branch)
1024x1024, Studio
DiffusionBackendin default speed mode (compiled blocks, CUDA graphs), 3 fresh processes per arm interleaved base/head/head/base/base/head, s/step = median of the per-step times of a full render (Base 50 steps CFG 3.5, distilled 16 steps), A/A spread in brackets. Offloaded cells load the BF16 transformer under a Studio VRAM budget (UNSLOTH_VRAM_FRACTION), which Studio serves by block streaming.The resident, distilled and 12 GiB rows were measured on d8532f6; the commits since only change the offloaded miss path and the router's template rule, and the 8 GiB rows are from the final code. First render of a process (compile included): text-only Base 27.42 s -> 26.37 s, 8 GiB 1-reference edit 102.0 s -> 95.1 s.
Offloaded cells: the merge base refuses the cache (
<root> is group offloaded); this branch records 2 misses (both computed inside the forward) and 98 hits per 50-step CFG render, and the event-fenced prefetcher issues 2810 group copies instead of 3300 (49 steps x 2 branches x 5 text-mode blocks skipped), every one prefetched on order (0 missed). Dynamo: 0 graph breaks and 0 recompiles in every measured render, both arms.Image drift (LPIPS, AlexNet, full 1024x1024 images, same seed): text-only Base 0.0004 and distilled 0.0003 head vs merge base (A/A of either arm below 0.0001 there); 1 reference 0.0008 to 0.0010 (A/A up to 0.003); 3 references 0.042 to 0.045, inside the run-to-run spread both arms already show for that cell (A/A up to 0.049 on the merge base, 0.056 on this branch).
AMD gfx1151 (ROCm, shared GPU): the new device test passes on the real card (compact modulation tracks the float64 oracle as closely as stock; a group-offloaded edit matches stock and the offload cache declines on ROCm), and the existing suites show no regression against the merge base.
Not covered here: L4 / 4090 / T4 timings (A100 only), Windows and macOS (the change is OS-neutral Python; the offload cache is gated to CUDA), XPU and MPS devices, multi-GPU layer split with offload.