Skip to content

Studio diffusion: FLUX.1 ConvRot INT8 fuses GELU and the attention output into the rotation, and shares one Q/K/V quant - #18766

Merged
danielhanchen merged 8 commits into
mainfrom
studio-flux1-convrot-producer
Nov 22, 2026
Merged

danielhanchen merged 8 commits into
mainfrom
studio-flux1-convrot-producer

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Nov 21, 2026 •

Copy link
Copy Markdown
Member

FLUX.1-schnell on the hosted ConvRot INT8 file (#18639) was about 5% slower per image than plain INT8 on an RTX PRO 6000. Two things caused it. The FLUX.2 / FLUX.3 producer fusion (diffusion_flux_convrot_fused) did not cover FluxTransformer2DModel, so every rotated Linear rotated and quantized its own input: Q, K and V each rotated the same activation, in both the double and the single blocks. Also, the GELU(tanh) MLP output (and, in single blocks, the concat with the attention output) was written to HBM in bf16, then read back by rotq_h16.

Change

  • diffusion_flux_convrot_fused: FLUX.1 patches, scoped to the modules install marks on a FLUX.1 denoiser with ConvRot Linears.
    • transformer_flux._get_projections shares one rotation + act quant for Q / K / V and for the added context Q / K / V. This is the same wrapper FLUX.2 uses, and the diffusers body is the same.
    • FeedForward.forward (GELU tanh, Dropout, rotated down projection) and FluxSingleTransformerBlock.forward (diffusers' body, or the arch patch's addcmul body when that one is installed) give proj_out / net[2] the projection output, plus the attention output in its own layout. Neither the GELU product nor the concat is written.
    • Every gate is checked per call. Anything else (no mark, hooks, LoRA, offload, other dtypes) runs the stock forward.
  • diffusion_convrot_quant:
    • rotq_h16x gets ACT = 2: GELU(tanh) of the gate only, so the value is never loaded.
    • New op unsloth_studio::convrot_gelu_act_quant_int8(prefix?, gate, group, v2), with a fake impl.
    • The GELU helper follows ATen / Inductor op for op (one FMA for x + k x^3, pinned *_rn, plain multiplies at the end so subnormal inputs keep 0.5 * x).
    • The probe first checks every finite bf16 input bit for bit against F.gelu(approximate="tanh"), then runs codes_close on FLUX.1's shapes, including the [attention | GELU] row and GELU's non-monotonic tail.
    • Armed on sm89 and sm120 (measured). Each card keeps the stock path where the fused kernel measured slower: below 1024 rows on L4; on RTX PRO 6000 below 2048 rows with the attention prefix and always without it (the FF measured 0.94x there). The 256-row text-stream MLP is excluded everywhere.
    • The probe verdict is persisted with the other ConvRot verdicts (card fingerprint + source hash), and its kernels join the probe prewarm pool, so only a card's first load compiles them (on a thread pool). Later loads take the same time as main's.
    • ROCm gets a portable helper built on triton.language.extra.libdevice (no *_rn there).
  • diffusion_int8_gemm.gelu_linear: the producer-fed GEMM, a copy of producer_linear without the value.
  • Kill switches:
    • UNSLOTH_DIFFUSION_FLUX_CONVROT_FUSED=0 restores main exactly: no FLUX.1 patch is installed and the stock functions come back.
    • UNSLOTH_DIFFUSION_FLUX1_GELU_FUSED=0 or UNSLOTH_DIFFUSION_INT8_ROTQUANT_PRODUCER=0 turn off only the GELU producer. The shared Q / K / V quant stays; it is the same op on the same tensor, so images are bit-identical to main either way.
  • Scope: the FLUX.1 patches sit on module-wide diffusers code that other families reuse. Chroma calls transformer_flux._get_projections, and every model has FeedForward. So they act only on the attentions, FeedForwards and single blocks that install marked on a FLUX.1 denoiser. A ConvRot Chroma loaded after a ConvRot FLUX.1 in the same process keeps its stock projections. The mark is read from the instance __dict__ first, so an unmarked module pays one dict lookup per call.
  • A failed GELU probe is logged at info level with the reason; FLUX.1 then keeps the compiled GELU + concat path.

Results

RTX PRO 6000 Blackwell (sm120), Colab. FLUX.1-schnell, 1024 px, 4 steps, 8 prompts, guidance 0, Studio begin_load int8 with the ConvRot file built on the VM. Compiled + CUDA graphs, resident. Each cell is a fresh process, and the A/A repeats were interleaved.

arm steady s/image (3 reps) s/step peak_alloc GiB images vs main
main 0.6713-0.6737 0.1507-0.1510 24.42 -
shared Q / K / V only (UNSLOTH_DIFFUSION_FLUX1_GELU_FUSED=0) 0.6475 0.1443-0.1445 24.42 8/8 bit-identical
this PR 0.6243-0.6277 0.1389-0.1391 24.42 8/8 bit-identical
  • s/step is 7.9% lower than main and s/image 7.1% lower. The A/A spread is under 0.4%. These numbers are from the final head of this branch. An earlier session gave the same result: 0.1390 vs 0.1512.
  • Load time in a new process: 8.2 s for both main and this PR once the card's verdict is stored. The first load on a card takes 14.4 s, because it prewarms the probe kernels on 8 threads and stores the verdict.
  • LPIPS is 0.0 against main on every prompt. Repeats are bit-identical.
  • 0 graph breaks, 0 recompiles, and no CUDA graph fallbacks in any cell.
  • Rotation launches per render: 1676 on main, 1068 with shared Q / K / V only, 916 here. GELU producer calls: 152. The FF producer stays off on sm120 (0.94x alone), so those calls are the single-block proj_out.

Kernel alone (quant stage, do_bench_cudagraph, codes and scales torch.equal to the compiled GELU + concat + rotq_h16 on every shape, v1 and v2):

shape L4 main / fused ms RTX PRO 6000 main / fused ms
single-block proj_out, 4352 x (3072 + 12288) 2.30 / 1.54 (1.50x) 0.361 / 0.283 (1.28x)
FF, 4096 x 12288 1.46 / 1.22 (1.19x) 0.240 / 0.255 (0.94x, kept stock)
single block at 512 px, 1280 rows 0.575 / 0.472 (1.22x) 0.068 / 0.090 (0.76x, kept stock)
text FF, 256 rows 0.045 / 0.077 (0.58x, kept stock) 0.013 / 0.021 (0.63x, kept stock)

GELU helper over all 65280 finite bf16 inputs: 0 bit differences against ATen eager and against Inductor (with and without emulate_precision_casts), on L4 and RTX PRO 6000.

Tests

tests/test_diffusion_flux1_convrot_gelu.py (CPU):

  • A tiny FLUX.1 transformer with the patches forced on (int8 pieces replaced by the plain modules) matches stock bit for bit, eager and dynamo fullgraph, in fp32 and bf16, with the expected call counts.
  • The arch-patched addcmul single block is kept.
  • Unmarked FeedForwards and unrotated Linears keep the stock path.
  • Install scoping and the kill switch.
  • The patch spec covers FLUX.1.
  • Reference, fake shapes, the CPU op body equal to the stock reference, the min-rows gate, and the kernel source contract.

Also covered:

  • A tiny Chroma run after a FLUX.1 install takes the stock projections. This test fails if the mark check is removed.
  • An unmarked FeedForward is rejected without an nn.Module.__getattr__ miss.
  • What each kill switch restores.
  • A Dropout in the FF with a forward hook, a pre-hook or an instance forward keeps the stock FeedForward, so the callback still runs. This test fails without the check.
  • The info log on a failed probe.
  • tests/test_diffusion_flux1_convrot_gelu.py also covers the persisted verdict (a later load adopts it without probing) and the prewarm plumbing for FLUX.1 loads.

test_differential.py against 8b7cde7 (6 files): DISCRIMINATING, FIXED 4, HEAD_FAIL 0, 107 unchanged. The broader backend suite (315 files, about 17300 tests; the 4 test_mcp_tools_* files fail to collect on both sides and were left out) has 61 failures, the same test IDs on main (8b7cde7) and here. They come from compat_preflight, compile_cache, layer split lifecycle, memory, the QwenImage 2.1 eager and strided attention tests, the media model index, SDXL whole-pipeline GGUF, hosted video int8 offload, the prequant base id and a FLUX.2 mirror shape guard.

Not proven here

  • L4 end to end: Studio group-offloads FLUX.1 on L4, so _swapped_rec is None and none of this engages there. The L4 numbers above are the kernel alone.
  • A100 (sm80) is not armed (not measured). B200 and T4 were not run.
  • AMD: the ROCm helper is written but not run (probe ready). The FLUX.1 shared Q / K / V route also covers the RDNA native W8A8 Linears through _rdna_shared. That is bit-identical by construction but was not run on gfx1151.
  • The RTX PRO 6000 end-to-end run had the prefix-free FF still fused; it is gated off there now (about 1 ms per image). Not re-measured after that change.

…ion output straight into the down projections' rotation + act quant, and shares one Q / K / V quant
…TZ) and stays off below each card's measured row count
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 21, 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-21T20:02:00.133019Z 078330b 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.

…vRot verdicts and its kernels join the probe prewarm pool
…ately (off on RTX PRO 6000, where it measured 0.94x)

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 7928142d5f

ℹ️ 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".

Comment on lines +578 to +579
and type(net[1]) is _CLS.get("Dropout")
and (not ff.training or net[1].p == 0)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Reject hooked dropout modules before bypassing their forward

When a marked FeedForward's dropout has a forward/pre-forward hook or an instance-level forward override, this eligibility check still permits fusion. If gelu_linear succeeds, the replacement skips net[1] entirely, silently dropping the callback and any activation transformation it performs; the stock path invokes that module even in evaluation mode. Check _gemm._hooked(net[1]) alongside the dropout type check, as is already done for the activation, so these modules retain their original behavior.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, fixed in 078330b: the FF fused path now also requires the Dropout to carry no forward hook, pre-forward hook or instance-level forward, the same _hooked check the activation gets, so it falls back to the stock FeedForward and every callback fires. Covered by test_a_hooked_dropout_keeps_the_stock_ff.

…dules (Chroma keeps its projections), read the mark from the instance dict, document the kill switches and log a failed GELU probe
…rd when its Dropout has a forward hook, pre-hook or instance forward

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. What shall we delve into next?

Reviewed commit: 078330bb28

ℹ️ 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 8cc11d9 into main Nov 22, 2026
@danielhanchen
danielhanchen deleted the studio-flux1-convrot-producer branch November 22, 2026 01:57
danielhanchen added a commit that referenced this pull request Nov 23, 2026
…ntion plan keys, CUTLASS live race key, step-skip sample= shape (#18981)

Four small fixes from a recheck of the merged FLUX.1 ConvRot GELU
(#18766), INT8 attention sink fold (#18786), CUTLASS race key (#18797)
and SDXL static step skip (#18826) changes. Each one is its own commit
with a test that fails before it and passes after.

## Changes

1. **FLUX.1 ConvRot GELU gate traces on torch 2.10 / 2.11**
(`diffusion_convrot_quant.py`). `convrot_gelu_act_quant` chose its row
threshold with `rows[prefix is None]`. Dynamo on torch 2.10 and 2.11
cannot trace a tuple indexed by a bool. With `fullgraph=True` the
compile raises `Unsupported`; without it, every armed FF / single-block
down projection graph-breaks. torch 2.6 and 2.12+ accept it. The index
is now `1 if prefix is None else 0`, which selects the same entry.
2. **INT8 attention launch plans follow the kernel switches**
(`diffusion_int8_attention.py`). `_plan` reads
`UNSLOTH_DIFFUSION_INT8_ATTENTION_RESID_FOLD`, and `kernel_variant`
reads the sink order and native P switches, when a plan picks its
kernels. The warm lookup in `_find_plan` did not key on them. Flipping
the fold off in a running process therefore left warm shapes on the
folded kernel until `forget_plans`. The plan key now includes the three
switches as set. That costs three env reads, about 1.7 us of host time
per call, and nothing under CUDA graph replay.
3. **CUTLASS race key covers the live row race**
(`diffusion_int8_gemm.py`). `_live_row_race` decides which calls race
and applies the `force` pick. It also writes its winner into the same
disk entry that `_cutlass_plan` reads back on the next load. Neither it
nor `live_race_enabled` was in `_RACE_SOURCES`, so an edit confined to
the live race kept old verdicts. Both are keyed now. This applies
cleanly on top of the open race-key closure change, whose closure test
still passes with both applied.
4. **Step skip reads `sample=`** (`diffusion_step_skip.py`). The reuse
key took the latent from `hidden_states` or the first positional
argument. A `UNet2DConditionModel` called with `sample=` was therefore
keyed with shape `None`, and a skipped step after a latent shape change
returned the previous output at the old size. The stock SDXL pipeline
passes the latent positionally, so Studio's own renders were not
affected.

## Tests (CPU, base = parent commit, head = this branch)

| Test | Base | Head |
|---|---|---|
| `test_diffusion_convrot_gelu_route_trace.py` on torch 2.10.0 / 2.11.0
| 2 failed, 1 passed | 3 passed |
| same on torch 2.6.0 / 2.12.1 / 2.13.0 / 2.14.1 | n/a | 3 passed |
|
`test_diffusion_int8_attention_resid_fold.py::test_a_warm_plan_follows_the_kill_switch`
| failed (warm plan reused) | passed |
| `test_diffusion_int8_cutlass_race_key.py` (3 new live race cases) | 3
failed, 27 passed | 30 passed |
|
`test_diffusion_step_skip_unet.py::test_a_skipped_step_never_returns_another_latent_shape[True]`
| failed (width 8 for a width 12 latent) | passed |

The surrounding INT8 attention, CUTLASS, GEMM, step skip and FLUX.1 GELU
suites have the same results on both arms. 8 FLUX.1 GELU tests fail on
both base and head when they run in the same process after the step skip
and INT8 suites, and they pass when that file runs alone. That failure
predates this change.

## Not covered here

- No GPU run. The four changes are host-side keys and gates, and each
one is checked on CPU against the real module code.
- The `+1.7 us` host cost per INT8 attention call was measured on CPU,
not as end-to-end render time.
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