Skip to content

Studio diffusion: run FLUX.3 base conditioning blocks once per render - #14367

Merged
danielhanchen merged 4 commits into
mainfrom
studio-diffusion-cond-blocks
Oct 20, 2026
Merged

danielhanchen merged 4 commits into
mainfrom
studio-diffusion-cond-blocks

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

FLUX.3 klein base runs its reference-image and text conditioning blocks on every denoising step and every CFG branch, although their output does not change within a render. This runs them once per branch per render and feeds the cached states to the remaining steps.

What it does

  • New core/inference/diffusion_cond_blocks.py. A forward pre-hook computes the conditioning states on each CFG branch's first step and passes them into the denoiser forward. Because it runs before the forward, a CUDA graph sees the states as ordinary inputs and never replays a stale tensor.
  • The cache is cleared at the start and end of every pipeline call, and the hook is re-placed last on every render so it runs inside the dynamic text-length scope.
  • It stays off (stock path) for the distilled flow-map model, grad mode, a per-call LoRA scale, an offloaded denoiser, text-only renders, or a diffusers forward that differs from the one it mirrors (source hash check).
  • Wiring in diffusion_flux3.py: the class patch is applied at load, before graphs are built; the hook is armed per render.
  • Kill switch: UNSLOTH_DIFFUSION_COND_BLOCKS=0.

Results

FLUX.3 klein base, 1024x1024, 20 steps, guidance 4, one exclusive B200. Off and on renders alternate in the same process, 3 rounds each; the spread of the off repeats is the noise.

Mode Case s/step off s/step on Peak above start, MiB (off / on) Images
Default (compiled + CUDA graph) 1 reference image 0.1484 - 0.1491 0.1394 - 0.1395 (-6.3%) 1421 / 1624 bit-identical
Eager 1 reference image 0.289 - 0.311 0.261 - 0.278 (about -9%) 1421 / 1624 bit-identical
  • 0 graph breaks, 0 recompiles and 0 CUDA graph re-captures on prompts 2 and later (all 800 calls replayed the graph).
  • Each cached render: 38 hits, 2 misses (one per CFG branch). The extra 203 MiB is the two branches' cached states.
  • Text-only renders keep the stock path: the text blocks are about 0.6% of a step there, and the cached arm showed no reliable gain.

Checked and not worth caching (per-step conditioning work as a share of a step): Wan 2.x and LTX-2 caption projection / constant-context K/V (0.2 - 0.3%), MiniMax-H3 text token refiner (about 0.03%), Qwen-Image (its text stream is timestep-modulated in every joint block, so nothing is step-invariant).

Testing

  • tests/test_diffusion_cond_blocks.py: 12 tests, including bitwise parity against the real diffusers Flux3 forward on a tiny model, the cache lifecycle, and every decline.
  • With tests/test_diffusion_flux3.py: 114 passed, 11 skipped.

Not verified: renders under offload (the cache turns itself off there), LoRA renders, more than one reference image, and cards other than B200.

The base model's text context and reference images go through their own
per-mode blocks at timestep 0, independent of the latent, so every step
and CFG branch recomputed the same tensors. A forward pre-hook now
computes them on a branch's first step and passes them to the forward,
which skips that work. Same images bit for bit; kill switch
UNSLOTH_DIFFUSION_COND_BLOCKS=0. The distilled (flow map) model is
untouched.
The text stream alone is about 0.6% of a 1024x1024 step and measured inside
the noise on a B200 with compile and CUDA graphs, so a text-only render keeps
the stock forward. The reference stream is where the saving is.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 20, 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 ⚠️ Failed 2026-10-20T17:48:05.004821Z ad856e5 New commits
🔒 Security Review ⚠️ Failed 2026-10-20T14:56:05.607770Z c5acd70 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 danielhanchen self-assigned this Oct 20, 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: c5acd70087

ℹ️ 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 4e0fe5b into main Oct 20, 2026
@danielhanchen
danielhanchen deleted the studio-diffusion-cond-blocks branch October 20, 2026 18:21
rhsCZ pushed a commit to rhsCZ/unsloth that referenced this pull request Nov 8, 2026
…floaded Base edits reuse the conditioning streams (unslothai#17059)

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.

- Applies to the cached Base path and, through the same class forward,
to the uncached Base and distilled (flow map) forward.
- Training (grad enabled) and a per-call LoRA `scale` keep 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 (unslothai#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.

- CUDA only for now: ROCm, XPU, MPS and CPU offload keep the stock path
(reason recorded in the cache status).
- Unchanged guards: flow-map (distilled) conditioning is never cached, a
per-call LoRA scale declines, grad-enabled calls decline, CUDA-graph
capture declines, and the cache is cleared at the start and end of every
pipeline call.
- The miss travels as a small marker in `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).
- When diffusers' own stream prefetch chain drives the groups (no
event-fenced prefetcher), the cache declines: that chain is fixed after
one forward and would leave a skipped block on the device.
- `UNSLOTH_DIFFUSION_OFFLOAD_COND_CACHE=0` restores the previous
refusal.

## Evidence (CPU, tiny random `Flux3Transformer2DModel`, diffusers
0.42.1)

Projection input rows, merge base vs this branch:

| Head | Merge base | This branch |
|---|---:|---:|
| image early / joint modulation | 64 (image tokens) | 1 |
| text early / joint modulation | 9 (text tokens) | 1 |
| reference early / joint modulation (1 / 3 refs) | 48 / 144 | 1 |
| output norm | 64 | 1 |

Float64 oracle (max abs error of the denoiser output against the stock
float64 forward):

| Case | dtype | stock | this branch |
|---|---|---:|---:|
| Base, 0 / 1 / 3 refs | float64 | 0 | 5.6e-16 / 4.4e-16 / 5.3e-16 |
| Base, 0 / 1 / 3 refs | float32 | 7.4e-7 / 6.6e-7 / 5.1e-7 | 5.0e-7 /
6.6e-7 / 5.1e-7 |
| Base, 0 / 1 / 3 refs | bfloat16 | 1.15e-2 / 1.18e-2 / 1.04e-2 |
identical to stock |
| flow map, 0 / 1 refs | float64 | 0 | 8.9e-16 / 6.7e-16 |
| flow map, 0 / 1 refs | float16 | 1.36e-3 / 1.38e-3 | identical to
stock |

Group-offloaded Base edit, 3 steps x 2 CFG branches (diffusers
block-level group offload on CPU, CUDA gate opened for the proxy):

| | Merge base | This branch |
|---|---|---|
| cache status | refused, `<root> is group offloaded` | armed, 2 misses
(computed inside the forward), 4 hits |
| first text-mode / reference-mode block calls | 6 / 6 | 2 / 2 |
| image-mode / joint block calls | 6 / 6 | 6 / 6 |
| output vs the uncached forward | | bitwise equal |

Tests: `tests/test_diffusion_cond_blocks.py` gains 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 `DiffusionBackend` in 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.

| Cell | merge base s/step | this branch s/step | per image | peak
allocated / reserved MiB |
|---|---|---|---|---|
| Base, text only | 0.4132 (0.4111..0.4138) | 0.3999 (0.3998..0.4000) |
20.77 s -> 20.11 s | 16823 / 17566 -> 16823 / 17398 |
| Base, 1 reference | 0.8618 (0.8604..0.8632) | 0.8518 (0.8515..0.8518)
| 43.37 s -> 42.84 s | 17146 / 19134 -> 16925 / 18678 |
| Base, 3 references | 2.1093 (2.1086..2.1140) | 2.0960 (2.0943..2.0998)
| 106.17 s -> 105.40 s | 17869 / 21556 -> 17142 / 20388 |
| distilled, text only | 0.2066 (0.2062..0.2067) | 0.1994
(0.1990..0.1996) | 3.42 s -> 3.30 s | 16838 / 18074 -> 16838 / 17906 |
| distilled, 1 reference | 0.4618 (0.4617..0.4619) | 0.4548
(0.4547..0.4549) | 7.58 s -> 7.47 s | 16855 / 18834 -> 16855 / 18520 |
| Base, 12 GiB budget, 1 reference | 1.8604 (1.8604..1.8604) | 1.6855
(1.6853..1.6855) | 93.22 s -> 84.64 s | 4790 / 5726 -> 4504 / 5914 |
| Base, 12 GiB budget, 3 references | 3.0192 (3.0191..3.0196) | 2.6076
(2.6075..2.6077) | 151.32 s -> 131.12 s | 5820 / 7270 -> 5302 / 7240 |
| Base, 8 GiB budget, 1 reference | 1.8625 (1.8624..1.8626) | 1.6888
(1.6861..1.6888) | 93.63 s -> 85.80 s | 4790 / 5726 -> 4504 / 5408 |
| Base, 8 GiB budget, 3 references | 3.0394 (3.0392..3.0493) | 2.6307
(2.6287..2.6334) | 152.42 s -> 132.45 s | 5820 / 7270 -> 5302 / 6734 |

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