Repository navigation
Studio diffusion: auto attention keeps native flash SDPA on A100 / L4 class cards - #17290
Merged
Merged
Conversation
… 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.
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. |
Member
Author
|
@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". |
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
On the compiled image tiers,
autoattention pins cuDNN fused SDPA on every NVIDIA card from sm80 up (Blackwell alreadyleaves 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
autokeep native SDPA on those two architectures when torch dispatches FLASH at every DiT head dim atthe run dtype. It follows the shape of the existing Blackwell rule:
FLASH_FASTER_CAPABILITIES = {(8, 0), (8, 9)}, each row with its measurement;_native_flash_measured_faster(pipe, target)askstorch._fused_sdp_choiceper head dim (cached per device, dtypeand head dim), so an unknown head dim, an fp32 load, a head dim FLASH does not serve, or an unaskable probe keeps
the pin;
autopick moves. An explicitcudnnrequest is still pinned, andspeed_mode=offnever reaches thecheck;
UNSLOTH_DIFFUSION_NATIVE_FLASH_ATTN=0restores 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.
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:autoattention (today: cuDNN pin, logbackend=_native_cudnn) vsattention_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.
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,
autoattention on both trees, cells interleaved (base, head, basewith explicit
native, head, base, head, base), 3 timed renders per cell.diffusion.attention: auto keeps native SDPA (flash attention measured faster than the cuDNN pin on this card; ...); the 3 base cells logdiffusion.attention: backend=_native_cudnn.autorenders are bit-identical to the merge base with an explicitattention_backend=native(LPIPS 0.0 over 3prompts), and bit-identical across head processes (LPIPS 0.0). Head vs base
auto: LPIPS 0.0313 mean / 0.0667 max.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
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.
(
test_an_imported_old_kernels_is_not_papered_over,test_two_models_under_an_unparseable_root_do_not_share_one_inductor_cache).Not covered
FailOnRecompileLimitHit: Hard failure due to fullgraph=True. That failure is on main and does not depend on thischange; it is being reported separately.