Skip to content

Studio Krea-2: probe attention with its padding mask so Auto keeps the faster cuDNN pin - #19110

Merged
danielhanchen merged 1 commit into
mainfrom
studio-krea2-masked-attn-resident
Nov 23, 2026
Merged

danielhanchen merged 1 commit into
mainfrom
studio-krea2-masked-attn-resident

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Nov 23, 2026 •

Copy link
Copy Markdown
Member

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.

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.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 23, 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-23T16:14:58.042777Z 24787d4 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: 24787d4c2b

ℹ️ 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 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
danielhanchen merged commit fc9d0b9 into main Nov 23, 2026
@danielhanchen
danielhanchen deleted the studio-krea2-masked-attn-resident branch November 23, 2026 18:37
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.
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