Skip to content

Studio diffusion: auto attention keeps native flash SDPA on A100 / L4 class cards - #17290

Merged
danielhanchen merged 2 commits into
mainfrom
studio-diffusion-ampere-native-attn
Nov 9, 2026
Merged

danielhanchen merged 2 commits into
mainfrom
studio-diffusion-ampere-native-attn

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Nov 9, 2026 •

Copy link
Copy Markdown
Member

Summary

On the compiled image tiers, auto attention pins cuDNN fused SDPA on every NVIDIA card from sm80 up (Blackwell already
leaves native when torch itself dispatches cuDNN). On A100 (sm80) and L4 (sm89) class cards, torch's native SDPA
dispatch picks FLASH, and FLASH measured faster than the cuDNN pin at every DiT and U-Net attention shape we tried, in
both bf16 and fp16. MiniMax-H3 already made the same call for its own attention (H3_FLASH_FASTER_ARCHS = {(8, 0), (8, 9)}).

This PR makes auto keep native SDPA on those two architectures when torch dispatches FLASH at every DiT head dim at
the run dtype. It follows the shape of the existing Blackwell rule:

  • new table FLASH_FASTER_CAPABILITIES = {(8, 0), (8, 9)}, each row with its measurement;
  • _native_flash_measured_faster(pipe, target) asks torch._fused_sdp_choice per head dim (cached per device, dtype
    and head dim), so an unknown head dim, an fp32 load, a head dim FLASH does not serve, or an unaskable probe keeps
    the pin;
  • only the auto pick moves. An explicit cudnn request is still pinned, and speed_mode=off never reaches the
    check;
  • kill switch UNSLOTH_DIFFUSION_NATIVE_FLASH_ATTN=0 restores the cuDNN pin.

sm86 (RTX 30xx, A10, A40), sm90 (Hopper) and every other card keep the pin: they were not measured.

Kernel measurements (Colab, torch 2.14.1+cu130)

Native SDPA vs sdpa_kernel(CUDNN_ATTENTION), one process, the two arms interleaved over 7 rounds, CUDA events,
median. x = native ms / cuDNN ms, so below 1 means cuDNN is slower. Max abs error vs an fp32 math reference is the
same for both kernels at every shape.

shape (B, H, Sq, Skv, D) A100 bf16 A100 fp16 L4 bf16 L4 fp16
SDXL level 1 self (2, 10, 4096, 4096, 64) 0.960 0.961 0.974 0.952
SDXL cross (2, 10, 4096, 77, 64) 0.591 0.561 0.932 0.952
SDXL level 2 self (2, 20, 1024, 1024, 64) 0.760 0.757 0.998 0.994
SD3.5-medium joint (2, 24, 4429, 4429, 64) 0.970 0.969 0.972 0.973
Lumina-2 joint (2, 24, 4352, 4352, 96) 0.741 0.741 0.699 0.711
FLUX joint (1, 24, 4608, 4608, 128) 0.927 0.934 0.977 0.990
FLUX joint (2, 24, 4608, 4608, 128) 0.918 0.921 0.996 0.993
HiDream joint (2, 20, 4224, 4224, 128) 0.920 0.924 0.986 0.988
SD1.5 512 self (2, 8, 4096, 4096, 40) 0.985 0.989 0.980 0.980

A/A spread: A100 0.2-3.7%; L4 1-21% (the cross-attention rows are noisier).

End to end through Studio's backend (one Colab VM per card, fresh process per cell)

Studio at merge base ed3eec632c. Arms: auto attention (today: cuDNN pin, log backend=_native_cudnn) vs
attention_backend=native (what this PR selects on these cards). 1024x1024, 3 timed renders per cell after a warm-up,
3 cells per arm in ABBA order, median of the cell medians.

card model (steps) s/image auto (cuDNN) s/image native A/A spread first compiled render auto / native peak VRAM
A100-40 FLUX.2-klein-4B (4) 0.7150 0.7045 (-1.5%) 0.1% / 0.4% 13.2-13.4 s / 12.3-12.8 s 16.79 / 16.79 GiB
A100-40 Z-Image-Turbo (8) 2.2085 2.2020 (-0.3%, inside noise) 1.7% / 0.5% 15.4-15.6 s / 13.8-14.1 s 23.98 / 23.94 GiB
L4 FLUX.2-klein-4B (4) 2.064 2.062 (inside noise) 0.4% / 0.05% 12.0-12.1 s / 11.2-11.4 s 12.27 / 12.27 GiB
L4 Lumina-Image-2.0 INT8, speed default (25) 10.991 11.002 (inside noise) 1.3% / 0.2% 31.9-32.1 s / 31.6-32.4 s 11.24 / 11.24 GiB

The first cell of each arm loads with a cold download cache, so its first render time is left out of that column.
No arm got slower in steady state on either card. Every first compiled render got faster, and peak VRAM is equal or
lower.

Accuracy: the two kernels round differently, so pixels move. Each arm is bit-identical with itself across processes
(LPIPS 0.0). Between arms, LPIPS (mean / max over 3 prompts) is 0.0084 / 0.0141 for klein on A100, 0.0332 / 0.0795 for
Z-Image-Turbo on A100, 0.031 / 0.067 for klein on L4 and 0.0037 / 0.0048 for Lumina-2 on L4. That is the size of a
change in floating point order, not a precision change: both kernels are bf16 / fp16 attention with fp32
accumulation, and their error against an fp32 reference is the same.

This branch vs the merge base on a real L4 (the path engages)

One Colab L4 VM, FLUX.2-klein-4B 1024x1024 4 steps, auto attention on both trees, cells interleaved (base, head, base
with explicit native, head, base, head, base), 3 timed renders per cell.

  • Engagement: the 3 head cells log diffusion.attention: auto keeps native SDPA (flash attention measured faster than the cuDNN pin on this card; ...); the 3 base cells log diffusion.attention: backend=_native_cudnn.
  • Head auto renders are bit-identical to the merge base with an explicit attention_backend=native (LPIPS 0.0 over 3
    prompts), and bit-identical across head processes (LPIPS 0.0). Head vs base auto: LPIPS 0.0313 mean / 0.0667 max.
  • s/image median head 2.028 vs base 2.048 (this VM drifted 1.98 -> 2.07 over the run on both trees, so steady state is
    a tie here); first compiled render head 11.16-11.46 s vs base 11.90-12.10 s (the first base cell had a cold download
    cache and is left out). Peak VRAM 12.27 GiB on both.

Tests

  • New tests/test_diffusion_attention_native_flash.py (18 cases): native on a measured card for head dims 64 / 96 /
    128 in bf16 and fp16; the pin stays for an explicit request, sm86, sm90, a head dim FLASH does not serve, fp32, the
    kill switch, an unknown head dim, no target, mixed head dims, and an unaskable probe; the probe is cached; speed off
    never reaches the check. On the merge base: 1 failed, 17 errors. On this branch: 18 passed.
  • All 25 test files that touch the attention pick: 2251 passed, 2 failed. Both failures also fail on the merge base
    (test_an_imported_old_kernels_is_not_papered_over, test_two_models_under_an_unparseable_root_do_not_share_one_inductor_cache).

Not covered

  • sm86 (RTX 30xx, A10, A40) and sm90 were not measured, so they keep the pin.
  • No Windows NVIDIA card was available. The predicate is OS neutral, so Windows sm80 / sm89 cards get the same pick.
  • FLUX.1-schnell (auto INT8) on A100-40 failed in BOTH arms on the merge base with
    FailOnRecompileLimitHit: Hard failure due to fullgraph=True. That failure is on main and does not depend on this
    change; it is being reported separately.

… class cards

Native SDPA (flash) measured faster than the cuDNN pin at every DiT and U-Net
attention shape on sm80 and sm89 (bf16 and fp16). The auto cuDNN upgrade now
leaves native there when torch dispatches FLASH at every DiT head dim, like
the Blackwell rule. Explicit cudnn requests are unchanged.
UNSLOTH_DIFFUSION_NATIVE_FLASH_ATTN=0 keeps the cuDNN pin.
@danielhanchen danielhanchen self-assigned this Nov 9, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 9, 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-09T17:55:08.549367Z df564e0 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

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Chef's kiss.

Reviewed commit: df564e0289

ℹ️ 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 a691227 into main Nov 9, 2026
@danielhanchen
danielhanchen deleted the studio-diffusion-ampere-native-attn branch November 9, 2026 18:54
dayanruben pushed a commit to dayanruben/unsloth that referenced this pull request Nov 10, 2026
unslothai#17341)

## Summary

FLUX.3 strided cuDNN attention is now verified on every card a layer
split places blocks on, not just the primary. If any secondary card
fails the probe, Studio keeps the stock processors on every FLUX.3
attention module.

## Root cause

unslothai#17180 added `diffusion_flux3_attn.install`, which swaps FLUX.3
attention processors only when a load-time probe shows the strided cuDNN
call is bitwise equal to the contiguous call. That probe runs on
`target`'s device, which is the primary GPU. It runs from
`apply_attention_backend`, and that happens before placement. The layer
split planner (`_backend_cards`) restricts secondaries to identical
cards only for flash / Sage backends, not `_native_cudnn`. So in a
mixed-card layer split, the strided processor can run on a secondary
card where it was never probed. cuDNN admission depends on the hardware
and the tensor parameters, so a pass on one card says nothing about
another. unslothai#17290 narrowed Auto's use of cuDNN, but an explicit cuDNN
selection still reaches this path.

## Fix

- `diffusion_flux3_attn.install` records the probe dtype on each swapped
processor.
- New `diffusion_flux3_attn.verify_cards(pipe, cards)` runs the existing
per-card cached probe (`strided_matches`) on every secondary card for
each swapped module's (dtype, heads, head_dim). If any card fails, it
restores the stock `Flux3AttnProcessor` and keeps the backend and
parallel config. It never raises.
- `apply_layer_split_plan` calls it with the split's non-primary cards
before `place_layer_split`, so the swap happens before the first
forward. The probes run outside any compiled forward.
- Single-card loads and splits onto cards that pass the probe are
unchanged.

## Flip test


`studio/backend/tests/test_diffusion_flux3_strided_attn.py::test_layer_split_probes_every_secondary_card[True|False]`
installs the strided processors with a mocked probe that passes on
cuda:0. It then applies a mocked two-card layer split (0, 1) and checks
two things: cuda:1 was probed, and the processors stay strided when
cuda:1 passes but revert to stock when it fails.

- origin/main: `2 failed` (`assert 1 in [0, 0, 0, 0, 0]`: only the
primary is ever probed)
- this branch: `2 passed`

## Tests run

- `tests/test_diffusion_flux3_strided_attn.py`: 11 passed (diffusers
0.42.1, CPU).
- Neighbouring files with `-o addopts= -m "not server and not
native_mxc"`: `test_diffusion_flux3_strided_attn.py`,
`test_diffusion_layer_split_plan.py`, `test_diffusion_layer_split.py`,
`test_diffusion_layer_split_order.py`,
`test_diffusion_layer_split_lifecycle.py`, `test_diffusion_flux3.py`.
Result: 230 passed, 6 failed. The same 6 failures happen on origin/main
without this change (5 in `test_diffusion_flux3.py` auto-switch / status
tests, 1 in `test_diffusion_layer_split_lifecycle.py` workflow pipeline
guard), so they are not caused by this change.
- Pre-push gate (stray files, AGPL headers, pre-commit ruff): pass.

## Not proven

- No GPU run. The probe and placement are mocked on CPU. I have not
shown that a real secondary card produces different output or fails with
the strided call.
- On a failing secondary, the processors revert on every card, including
the primary, so the primary loses the strided speedup in that case.
Per-block retention was not attempted.
danielhanchen added a commit that referenced this pull request Nov 23, 2026
…e faster cuDNN pin (#19110)

## Summary

On A100 and L4 class cards, `auto` attention keeps native SDPA when
torch's own dispatch picks FLASH (#17290). That check asked torch with
an unmasked query. Krea 2 masks every block attention call (its text
rows are padded to a 128-row bucket and masked as keys), and torch's
FLASH kernel takes no mask, so on those cards every Krea 2 block call
actually ran mem-efficient attention (`fmha_cutlassF`). On an L4 that
kernel was 34% of a Turbo render.

This PR makes the check ask the way the real call is made. For DiTs that
mask every block call (`MASKED_ATTENTION_DITS`, Krea 2 for now), both
native-dispatch probes (the A100 / L4 flash rule and the Blackwell cuDNN
rule) now pass a boolean key-padding mask to `torch._fused_sdp_choice`.
Torch answers mem-efficient there, so `auto` keeps the cuDNN pin for
Krea 2. Nothing else changes:

- unmasked DiTs are probed exactly as before and keep native flash;
- if a future torch ever runs FLASH with a mask, the probe sees it and
`auto` goes back to native;
- an explicit attention pick, `speed_mode=off`, and
`UNSLOTH_DIFFUSION_NATIVE_FLASH_ATTN=0` behave as before.

## Kernel measurements (masked calls, native dispatch vs the cuDNN pin)

Same inputs, a key-padding mask, bf16, CUDA events, median of
interleaved rounds. Error is relative L2 against an fp32 math reference
with TF32 off.

| shape (B, H, S, D) | A100 native ms | A100 cuDNN ms | L4 native ms |
L4 cuDNN ms | rel L2 native / cuDNN |
|---|---|---|---|---|---|
| Krea 2 1024 (1, 48, 4352, 128) | 5.81 | 3.33 (0.57x) | 14.77 | 8.45
(0.57x) | 0.002278 / 0.002276 |
| Krea 2 1024, CFG pair (2, 48, 4352, 128) | 11.33 | 6.32 (0.56x) |
29.83 | 16.81 (0.56x) | 0.002276 / 0.002274 |
| Krea 2 2048 (1, 48, 16640, 128) | 80.98 | 43.91 (0.54x) | 214.97 |
117.89 (0.55x) | 0.002306 / 0.002305 |

## End to end: Krea-2-Turbo, 1024 px, 8 steps, AUTO load (int8 DiT and
encoder)

Colab, one VM per card, a fresh process per arm, arms interleaved (ref,
base, head, head, base, ref). Base is the merge base `b94d31044f`; head
is this branch. Both trees carry the Krea 2 reduction-config pin from
#19077, so Inductor's per-home reduction benchmark cannot split the two
arms. 8 prompts, seeds 1000 to 1007, one warm-up render then 8 timed
renders.

Engagement: base logs `auto keeps native SDPA (flash attention measured
faster ...)` and its 32 attention processors run the native backend;
head logs `backend=_native_cudnn` and all 32 processors carry
`_native_cudnn`.

| card | base s/image (A/A) | head s/image (A/A) | change | peak
reserved base / head |
|---|---|---|---|---|
| A100 40 GB | 3.450 / 3.447 | 2.892 / 2.892 | -16.1% | 20198 / 20184
MiB |
| L4 (fresh Studio home per arm, 3 arms each) | 13.627 / 13.558 / 13.677
| 11.639 / 11.646 / 11.723 | -14.5% (medians 13.627 vs 11.646; A/A
spread 0.9% / 0.7%) | 9604 / 9590 MiB |

## Accuracy against an fp32 attention reference

The reference arm runs the same load and weights with every diffusers
attention backend replaced by fp32 math attention (q, k, v upcast, TF32
off, explicit masked softmax), so it differs from base and head only in
the DiT's attention. Distance is LPIPS (alex) and PSNR of each arm's
image to the reference image of the same prompt and seed.

| card | LPIPS to ref, base | LPIPS to ref, head | paired head minus
base (mean / median) | head closer | PSNR base / head | A/A spread |
|---|---|---|---|---|---|---|
| A100 40 GB | 0.1318 | 0.1203 | -0.0114 / -0.0155 | 6 / 8 prompts |
22.18 / 22.94 dB | base, head and ref each bit-identical across
processes |
| L4 | 0.1788 | 0.1365 | -0.0423 / -0.0289 | 6 / 8 prompts | 20.46 /
21.49 dB | base 0.00009 LPIPS, head bit-identical |

Head is no further from the reference than base on either card. On the
L4 accuracy VM the head tree also carried a memory-planner row that was
later dropped from this PR; it only changes where the DiT sits (streamed
vs uploaded per call), and on another L4 VM that placement change alone
moved no pixel beyond the 0.0001 LPIPS process-to-process variants base
shows by itself. The absolute distances are large because an 8-step
distilled sampler amplifies any last-bit attention difference into a
visibly different image; the kernel-level error above is the same for
both kernels.

## Other families that mask every block call

| family | masked block calls | this PR |
|---|---|---|
| Krea 2 | every call (text padding) | cuDNN pin on A100 / L4 |
| Chroma | every call (T5 padding as keys and queries) | unchanged:
cuDNN measured 0.62x (A100) / 0.74x (L4) per call, and 15.6% faster per
image on an A100, but its pinned renders were not repeatable across
processes (2 of 8 identical) while base was, and it moved slightly
further from the fp32 reference (LPIPS 0.0069 to 0.0110 vs 0.0064) |
| HunyuanImage-2.1 | every call | unchanged: cuDNN 0.57x per call on
both cards, not measured end to end |
| Ideogram 4 | every call | unchanged: head_dim 256 has no cuDNN kernel
on this torch, so the pin would be refused anyway |
| Qwen-Image, Z-Image, HunyuanVideo-1.5, Qwen-Image-2.1, LTX-2 | only
some calls (uneven CFG pairs, prefill text segments, a disabled trim) |
unchanged |

## Tests

`tests/test_diffusion_attention_masked_probe.py` (11 cases): a masked
DiT keeps the cuDNN pin on SM80 and SM89, an unmasked DiT still runs
native flash, a masked DiT goes native once torch would run FLASH with a
mask, a mixed pipeline asks masked, masked and unmasked answers are
cached apart, the Blackwell probe asks masked too, and the probe really
passes a boolean key-padding mask. Seven of them fail on main and all
pass here; the existing native-flash, Blackwell and cuDNN head-dim
suites pass unchanged.

## Not covered

- Blackwell: checked on SM100 (B200, torch 2.12.1, correctness only):
torch's dispatch is cuDNN for both the masked and unmasked probe at head
dim 64 and 128, so on SM100 this PR changes nothing. SM120 (RTX PRO 6000
/ RTX 50) was not checked.
- Hopper and SM86 cards already kept the cuDNN pin for Krea 2 and are
unchanged.
- Torch builds older than 2.13 were not run; the masked cuDNN path is
the one Krea 2 already used on every card outside A100 / L4.
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