Repository navigation
Studio Krea-2: probe attention with its padding mask so Auto keeps the faster cuDNN pin - #19110
Merged
Merged
Conversation
Auto attention keeps native SDPA on A100 / L4 class cards when torch's own dispatch picks FLASH, but it asked torch without a mask. Krea 2 masks every block attention call, and FLASH takes no mask, so its native calls ran mem-efficient attention. The dispatch probes now ask with a key-padding mask for DiTs that mask every call, so Krea 2 keeps the cuDNN pin there.
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". |
danielhanchen
added a commit
that referenced
this pull request
Nov 23, 2026
…ness (#19121) ## Problem Three Studio tests are red on `main` since #19040 (they fail on `Repo tests (CPU, studio)` for every PR based on it, for example #18775 and #19110): - `tests/studio/test_chat_autoload_failure_gate.py::test_a_chat_only_mac_without_mlx_skips_its_cached_mlx_repo` - `tests/studio/test_chat_autoload_failure_gate.py::test_a_chat_only_mac_auto_loads_an_omlx_folder_with_a_plain_name[false-False]` - `tests/studio/test_model_picker_contracts.py::test_cached_non_gguf_rows_get_the_chat_only_platform_gate` Bisected: all three pass on `956e62778b^` and fail on `956e62778b` (#19040). ## Cause #19040 is correct. It routes every Chat only MLX gate in `chat-adapter.ts` through the shared `isServedByMlx(isGguf, deviceType, chatOnlyReason, mlxInference)`, which answers from `mlx_inference` when the backend reports it. The tests were behind it: - The auto-load harness kept a hand-written `isServedByMlx` that took three arguments and ignored `mlx_inference`. A Chat only Mac reporting `mlx_inference: false` therefore looked like it served MLX, and the scenarios loaded an MLX repo where the shipped code does not. - The contract test pinned the old `platform.mlxInference === true` literal, which #19040 replaced with `return platformServesMlx(platform);`. ## Fix - The harness now inlines `NO_MLX_REASONS` and `isServedByMlx` from `per-model-config.ts` as shipped, the same way it already inlines `isOtherCacheSnapshot`, `llamaServerLoadFields` and the server-model wait gate. A missing definition fails with a clear message instead of a silent stub. - The contract test pins the new shape: the cached-row gate returns `platformServesMlx(platform)`, and that helper calls `isServedByMlx(...)` with `platform.mlxInference`. ## Verification - Both files: 305 passed (were 3 failed on `main`). - Sabotage 1: drop the `typeof mlxInference === "boolean"` branch from `isServedByMlx` in `per-model-config.ts`; the two harness scenarios fail again. - Sabotage 2: pass `null` instead of `platform.mlxInference` in `chat-adapter.ts`; the contract test and both scenarios fail. Tests only; no product code changes.
danielhanchen
added a commit
that referenced
this pull request
Nov 24, 2026
…8 attention can take it (#19208) ## Summary Krea 2 block attention now runs with no mask, over the valid key prefix, which lets Studio's INT8 attention kernel take it. At Studio defaults (Krea-2 Turbo, 1024 px, 8 steps), renders are **5.1% faster** than main on an L4 and **8.1% faster** on an RTX PRO 6000 (G4). The per-step error stays inside the INT8 weights' own error. ## Why The Krea 2 text trim (#18813) keeps text rows in 128-row buckets. A partly filled bucket still carries padded rows, and diffusers builds the joint sequence as `[text | image]`, so those pads sit in the middle. Every one of the 28 block attentions therefore runs with a key-padding mask. #19110 moved that masked call to cuDNN, but a masked call can never use native flash or the INT8 route. The INT8 dispatch skips any call that has a mask, and Krea 2 was left out of `AUTO_DITS` for that reason. ## What changes - `diffusion_krea2_text_trim.py`: when the prefix processors are installed, the trim lays out each row's text as `[pad | valid]` instead of `[prompt | pad | suffix]`. Every Krea 2 text row sits at the rotary origin (`prepare_position_ids`) and the refiner blocks carry no rotary, so changing the order of text rows changes no phase and no output. For each forward, the pre-hook records every row's key start, which is that row's pad count. - `diffusion_krea2_prefix_kv.py` (new): a subclass of `Krea2AttnProcessor` for the 28 main blocks. It calls an opaque custom op that does `attention(q, k[:, start:], v[:, start:])` with `attn_mask=None`. The padded query rows still run and only see valid keys, and their outputs are sliced away as before. The math matches the masked call, with fewer keys. - The start is read from a small CPU tensor that the pre-hook fills. The compiled blocks keep one graph for every prompt (no guard on the start). - A CUDA graph would freeze the start at capture time, and the start changes with the prompt, so a call with a non-zero start is never recorded: its `_unsloth_graph_key_extra` raises, which every graph layer already treats as "run eager". An earlier cut keyed graphs on the start instead; on an RTX PRO 6000 that hit the graph cap of 4 within the first prompts and paid a capture per new prompt. - When the CFG router stacks two planned branches into one batch, the op reads each row's start off the pads-first mask, with one host read per forward. - A mask that is not pads-first, or a call with no plan, keeps the masked call. - Each transformer owns its plan, and only the transformer whose own pre-hook wrote it trusts it. A deep copy (the CFG replica on a second card) reads every key start from its own current mask, and the plan is cleared after the call that wrote it, so a call that skips the hooks runs the masked attention. - Without the INT8 route, the mask-free call switches to native flash only in place of Auto's own masked-DiT cuDNN pick, only on bf16 / fp16 at A100 or L4 (`FLASH_FASTER_CAPABILITIES`), and only when the same SDPA kernel probe main runs reports flash (Windows torch builds without flash SDPA keep the pin). An explicit backend pick and `UNSLOTH_DIFFUSION_NATIVE_FLASH_ATTN=0` are respected. - A call that needs gradients runs the stock masked processor. - `diffusion_krea2.py`: installs the processors when the pipeline is assembled, before the attention backend and the INT8 route are applied. - `diffusion_int8_attention_dispatch.py`: Krea 2 joins `AUTO_DITS` and `AUTO_CUDA_ONLY`. It races its incumbent on the plain path, not the sink path. A masked call still keeps the incumbent. - Kill switch: `UNSLOTH_DIFFUSION_KREA2_PREFIX_KV=0` keeps the stock processors and the masked call. Engagement counters are in `diffusion_krea2_prefix_kv.STATS` (`prefix`, `from_mask`, `masked`), and the load logs `block attention reads the valid key prefix with no mask (28 blocks)`. ## Speed (Colab L4, torch 2.13 cu130) Krea-2 Turbo, 1024 x 1024, 8 steps, Studio defaults (INT8 weights, transformer streamed in groups). Each arm ran in 3 fresh processes with fresh Studio homes, interleaved, A/A first. Each process reports the median of 10 plain prompts, and the table shows the median of those 3 medians. | Arm | Render (s) | vs main | CFG pair renders (s) | | --- | ---: | ---: | ---: | | main (cuDNN, masked) | 11.819 (11.814 to 11.936) | | 23.47 | | prefix, bf16 native flash | 11.651 (11.648 to 11.654) | -1.4% | 23.01 (-2.0%) | | prefix + INT8 attention | 11.216 (11.156 to 11.239) | **-5.1%** | 22.21 (-5.4%) | Re-timed at the final head on a separate L4 VM (3 fresh processes per arm, interleaved; main A/A spread 0.82%): main 11.632 s, this PR 11.034 s per render (**-5.14%**), 1.458 -> 1.374 s/step; all 4032 block calls took the mask-free INT8 path. - The A/A spread of main across processes was 1.04%. - On a second VM, the head tree with no switches set (INT8 picked by the auto race) rendered in 11.03 s over 2 processes, against 11.66 s for main: -5.4%. - The load race logged INT8 at 5.12 ms per call against 7.12 ms for the incumbent at 4096 tokens. - With CUDA graphs off and the CFG router armed, the stacked CFG calls ran mask-free (588 calls planned off the mask, 0 masked). The two CFG renders took 20.20 / 20.65 s against 21.87 / 22.34 s for main (one process each). RTX PRO 6000 (Colab G4, sm120, model resident). Same setup: 3 fresh processes per arm, interleaved, main first. | Arm | Render (s) | s/step | vs main | CFG pair renders (s) | | --- | ---: | ---: | ---: | ---: | | main (Auto picked `_native_cudnn`, masked, one CUDA graph replayed) | 1.698 (1.694 to 1.706) | 0.211 | | 3.353 | | head (INT8 route, prefix calls not recorded) | 1.561 (1.559 to 1.562) | 0.195 | **-8.1%** | 3.089 (-7.9%) | On G4 the A/A spread of main was 0.75%. s/step is (8-step render minus 4-step render) / 4 on the same prompt and seed. All 4032 head block calls ran on the prefix path and INT8, with none masked. Per-call attention on the L4 (B 1, 48 heads, 4096 image rows + a 128-row text bucket with 60 valid rows): | Call | ms | | --- | ---: | | cuDNN, masked (main) | 9.10 | | prefix, native flash | 7.06 | | prefix, cuDNN | 8.17 | | prefix, INT8 | 5.07 | ## Accuracy Per-step velocity error, relative L2. There were 12 denoiser calls: 3 prompts at steps 0, 3 and 7, including both branches of a CFG pair with unequal text lengths. Every attention variant ran on the same captured inputs in one process. The bf16-weight run was a second process fed the same inputs. | Pair | mean | max | | --- | ---: | ---: | | INT8 attention vs bf16 attention (main) | 0.037 | 0.057 | | INT8 weights vs bf16 weights (shipped weight error) | 0.052 | 0.099 | | native flash vs main (same math, other kernel) | 0.042 | 0.139 | | main vs fp32 attention | 0.048 | 0.195 | | prefix flash vs fp32 attention | 0.039 | 0.076 | | prefix INT8 vs fp32 attention | 0.046 | 0.174 | The kernel's error is below the shipped INT8 weights' error in both mean and max, which is the bar the other `AUTO_DITS` families were admitted on. The card check at load passed (cosine 0.99993). Images: 12 prompts, compared against a render that uses fp32 math attention in every block. Krea-2 Turbo at 8 steps reacts strongly to any change in reduction order: main and a pure kernel swap of the same math (flash vs main) already differ by LPIPS 0.199. | Arm vs fp32-attention reference | LPIPS (mean) | rel L2 | | --- | ---: | ---: | | main | 0.189 | 0.239 | | prefix flash | 0.207 | 0.253 | | prefix INT8 | 0.208 | 0.253 | INT8 vs main is LPIPS 0.192, which is inside the 0.199 kernel-swap floor. Each arm's three fresh processes rendered bit-identical images. ## Tests `studio/backend/tests/test_diffusion_krea2_prefix_kv.py` (fails on main, since the module does not exist there): - fp32 output matches the padded masked call for single rows and batches of unequal lengths; - no main-block call carries a mask, and keys start at the first valid row. A paired test shows main masks every block call; - a CFG pair of unequal lengths shares the row count, each branch matches its padded output, and each keeps its own key start; - a stacked batch the hook did not plan reads its plan off the mask once per forward. A mid-sequence mask keeps the masked call; - a planned call is never recorded by a CUDA graph (the key hook raises); no plan or a zero start keys as before; - one compiled graph serves every key start (`error_on_recompile`); - the kill switch keeps the stock processors, and a padded call clears the plan; - the INT8 dispatch can route the block attention, and the route sees no mask; - the mask-free backend picks flash only in place of the masked-DiT pin. `test_diffusion_int8_attention_dispatch.py` and `test_diffusion_int8_attention_families.py` now pin Krea 2 in `AUTO_DITS` and `AUTO_CUDA_ONLY`, and not in `SINK_DITS`. Krea 2, INT8 attention, CFG batch and autoopt suites: 147 passed. An inductor-compiled tiny Krea 2 on CUDA bf16 matched the stock masked call with no recompiles across key starts. ## Not covered - Timing is from L4 and G4 only. A100, T4 and B200 were not measured end to end. The G4 has no fp32-attention reference arm (head vs main images: LPIPS 0.216, the same kernel-swap spread as on L4). On A100 the existing INT8 race has lost at 4096 tokens before, so it would run the bf16 prefix path on native flash, which is unmeasured end to end there. - A card where the cuDNN masked graph replay beats the unrecorded prefix step would lose time. That did not happen on G4 (-8.1%), and A100 is unmeasured. - The INT8 kernel has no sm100 config, so B200 keeps the bf16 prefix path. That path was checked for correctness only. - Layer-split / multi-GPU Krea loads were not run on hardware; the CFG replica's plan handling is covered by a CPU test using Studio's real replica copy and state mirroring. The Windows no-flash-SDPA case is covered by a mocked probe. - AMD gfx1151 (Linux ROCm and Windows): the PR's tests pass with the same pre-existing set as main, Auto keeps the native route for Krea 2 on ROCm, and the prefix call matches the masked call within one bf16 step on a random-weight Krea 2 transformer.
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 A100 and L4 class cards,
autoattention 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 totorch._fused_sdp_choice. Torch answers mem-efficient there, soautokeeps the cuDNN pin for Krea 2. Nothing else changes:autogoes back to native;speed_mode=off, andUNSLOTH_DIFFUSION_NATIVE_FLASH_ATTN=0behave 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.
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 logsbackend=_native_cudnnand all 32 processors carry_native_cudnn.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.
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
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