Skip to content

Studio diffusion: fused FLUX AdaLN on by default on NVIDIA Linux (2.4% per eager step, fp32 error unchanged) - #16760

Merged
danielhanchen merged 5 commits into
mainfrom
studio-flux-fused-adaln-nvidia
Nov 5, 2026
Merged

danielhanchen merged 5 commits into
mainfrom
studio-flux-fused-adaln-nvidia

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Summary

The fused FLUX AdaLN kernel (UNSLOTH_DIFFUSION_FUSED_ADALN, one pass of LayerNorm + * (1 + scale) + shift) is now on by default on NVIDIA CUDA under Linux, the same scope the fused FLUX RoPE got in #14566.

  • It was opt-in everywhere because it gave no speed on gfx1151, and that is still true there: ROCm stays opt-in.
  • On NVIDIA it is faster (numbers below). Its output differs from stock only by rounding order: it rounds once where stock rounds three times, and its error against an fp32 reference is the same as stock's.
  • The bit-exact speed_mode=off tier keeps the stock AdaLN. The RoPE kernel is bit-identical, so it still installs there. Unset, eager, default and max get the fused AdaLN.
  • Unchanged: it never runs inside a compiled graph (torch.compiler.is_compiling() returns stock). So it only acts on eager FLUX blocks: GGUF FLUX on the default tier (dequant compiled, blocks eager), the eager tier, the first renders of an unset load, and loads that cannot compile.
  • UNSLOTH_DIFFUSION_FUSED_ADALN=0 turns it off. Windows and macOS keep stock, as with the RoPE kernel.

Evidence (A100-SXM4-40GB, Colab, torch 2.14.1, diffusers 0.42.1)

The setup is a FLUX.1-shaped FluxTransformer2DModel at real width: 24 heads x 128, joint dim 4096, 2 double + 4 single blocks, 4096 image + 512 text tokens (1024x1024), random weights. It runs eager with the fused RoPE on in both arms, which is what main does today. Each arm was timed for 5 interleaved rounds of 10 forwards, with the arm order rotated, and stock was timed twice for A/A.

dtype stock ms (min-max) fused AdaLN ms (min-max) speedup A/A spread fused AdaLN calls per forward
bf16 40.01 (39.58-40.13) 39.04 (38.78-39.15) 2.48% 0.10% 9 of 9
fp16 41.49 (41.23-41.53) 40.52 (40.33-40.73) 2.38% 0.02% 9 of 9

The fused and stock ranges do not overlap. The per-block share of AdaLN is the same in the full 19 + 38 block model, so the per-step gain on an eager FLUX.1 step should be about the same.

Accuracy, measured on the same weights and inputs against an fp32 run of the stock model (relative L2 of the transformer output):

dtype stock vs fp32 fused vs fp32 fused vs stock
bf16 0.013836 0.013845 0.0078
fp16 0.001805 0.001801 0.0011

The fused output is exactly as far from fp32 as stock is. The fused-vs-stock gap is about half of bf16's own rounding error, which is the scale of a different rounding order. The only real-weights pixel number is from FLUX.2-klein on gfx1151 (#12701): LPIPS 0.004 between the two. There it covers only the final AdaLayerNormContinuous, because FLUX.2 blocks use their own modulation.

Tests

  • New or updated in test_diffusion_rocm_fused.py:
    • auto engages RoPE and AdaLN on NVIDIA Linux (bf16, fp16).
    • adaln=False keeps the stock AdaLN but still installs RoPE.
    • The AdaLN kill switch works on NVIDIA.
    • FLUX.2 fp16 keeps its own RoPE patch.
    • The patch registry passes adaln=False only for speed_mode=off, and adaln=True for unset, eager and default.
  • Base vs head, with each arm importing its own tree, over test_diffusion_autoopt*, test_diffusion_eager*, test_diffusion_speed.py, test_diffusion_rocm* and test_diffusion_flux2*:
    • head: 327 passed, 0 failed.
    • base with the head tests: 321 passed, 6 failed.
    • The 6 base failures are exactly the new default tests.

Not covered here

  • Timing is from an A100 only. L4, H100 and Blackwell were not timed. The kernel is memory-bound, so it should gain at least as much on cards with lower bandwidth, but that is not measured.
  • No pixel LPIPS with real FLUX.1 weights in this PR (FLUX.1 is where every block uses these classes). The accuracy evidence is the fp32-reference comparison above.

… speed tiers

The one-pass LayerNorm + modulation kernel (UNSLOTH_DIFFUSION_FUSED_ADALN) was opt-in
everywhere because it gave no speed on gfx1151. On NVIDIA it is 2.4% faster per eager
FLUX.1 block stack on A100 (bf16 40.0 -> 39.0 ms, fp16 41.5 -> 40.5 ms, A/A <= 0.1%), and
its error against an fp32 reference equals stock's (it rounds once instead of three times).

auto now engages it on NVIDIA CUDA Linux like the fused RoPE, except on the bit-exact
speed=off tier, which keeps the stock AdaLN. It still never runs inside a compiled graph.
ROCm keeps it opt-in; =0 turns it off.
@danielhanchen danielhanchen self-assigned this Nov 5, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 5, 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 ✅ Completed 2026-11-05T11:26:18.167798Z a2cfbcb 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 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: 473e756e6e

ℹ️ 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 +425 to +426
exact = str(ctx.speed_mode or "").strip().lower() == "off"
return install_for_pipe(ctx.pipe, ctx.dtype, ctx.device, ctx.logger, adaln = not exact)

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 Distinguish an unset speed request from explicit off

For dense FLUX loads with speed_mode unset, load_pipeline resolves the request to SPEED_OFF and passes that effective value into STAGE_LOAD (diffusion.py:10270,10463–10469). Consequently, this check disables AdaLN for the initial eager renders and for loads that cannot compile, even though those are advertised beneficiaries of the new default. The new wiring test passes None directly to PatchContext, bypassing that production normalization. Preserve the original request separately so only an explicitly requested off disables AdaLN.

Useful? React with 👍 / 👎.

@danielhanchen danielhanchen Nov 5, 2026 •

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.

Fixed in a2cfbcb: the patch context now carries whether speed off was explicitly requested, so an unset dense load (resolved to off) gets the fused AdaLN and only an explicit off keeps stock.

…equest

load_pipeline resolves an unset dense request to off before STAGE_LOAD, so the
fused AdaLN never reached the first renders of an unset load. The patch context
now carries whether off was asked for.

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

Reviewed commit: a2cfbcb8a5

ℹ️ 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 8033ef3 into main Nov 5, 2026
@danielhanchen
danielhanchen deleted the studio-flux-fused-adaln-nvidia branch November 5, 2026 17:38
shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Nov 9, 2026
…blocks (recompile limit on first render) (unslothai#17310)

## Problem

FLUX.1 (schnell and dev) loaded in Studio on NVIDIA Linux at the default
speed tier fails its first render with

```
torch._dynamo hit config.recompile_limit (64)
   function: '_flux_single_forward' (diffusion_int8_fused.py:1120)
   last reason: 1/63: G['__import_core_dot_inference_dot_diffusion_rocm_fused'].COUNTS['adaln_stock'] == 139
     # COUNTS["adaln_stock"] += 1  # diffusion_rocm_fused.py:407 in _adaln_zero_single_forward
FailOnRecompileLimitHit: Hard failure due to fullgraph=True
```

Seen on a Colab A100 40GB with auto INT8 (the default there) at
ed3eec6, in every repeat.

## Root cause

Since unslothai#16760 the fused AdaLN forwards are installed on NVIDIA Linux off
the `off` tier, including the compiled tiers. Under `torch.compile`,
`_fused_modulate` correctly returns None so the stock math is traced.
The engagement census `COUNTS["adaln_stock"] += 1` still runs inside the
trace, though. Dynamo treats a write to a module-global dict as a side
effect: it guards on the current value (`COUNTS['adaln_stock'] == 139`)
and replays the increment after the graph. The next call therefore
always fails the guard, so every block call compiles a new graph.

FLUX.1 is the only family affected because its repeated blocks
(`FluxTransformerBlock`, `FluxSingleTransformerBlock`) call
`AdaLayerNormZero` / `AdaLayerNormZeroSingle` inside the regionally
compiled region. FLUX.2 modulates inline and only uses
`AdaLayerNormContinuous` in the eager `norm_out`. Z-Image, Qwen-Image
and FLUX.3 never install these forwards. The single block hits the limit
first (38 calls per step against 19 for the double block), under
`fullgraph=True`. That kills the CUDA graph capture and then the eager
fallback. The audit run's per-process stats show 121 unique graphs for
FLUX.1, against 2 for FLUX.2 klein and Z-Image. This is not int8
specific: a bf16 FLUX.1 at the compiled tiers hits the same guard.

The RoPE wrapper in the same file and the fp8 unit-scale path already
skip their counters while compiling. AdaLN was the one that did not.

## Fix

The AdaLN census now goes through `_count()`, which only increments
outside a trace (`torch.compiler.is_compiling()`). Eager counting is
unchanged, there are no new graph breaks, `fullgraph` is kept, and
compiled output does not change (the traced math was already the stock
branch).

## Tests

`studio/backend/tests/test_diffusion_rocm_fused.py`, CPU only:

* `test_compiled_adaln_never_recompiles_per_call` (3 classes): compiles
a call through each patched AdaLN class with `fullgraph=True,
dynamic=False` under `error_on_recompile`, checks the output against
eager and checks the census is untouched while compiled.
* `test_tiny_flux1_regional_compile_holds_its_graphs_across_steps`: a
tiny `FluxTransformer2DModel` with
`compile_repeated_blocks(fullgraph=True, dynamic=False)` (Studio's
FLUX.1 settings), three denoise steps; the graph count after step 1 must
not grow.

| | main (1b88784) | this branch |
|---|---|---|
| new tests | 4 failed (`RecompileError` x3, `recompile limit exceeded`
on the tiny FLUX.1) | 4 passed |
| whole file | 29 passed, 12 skipped (GPU) | 33 passed, 12 skipped (GPU)
|
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