Skip to content

Studio Krea 2: attend over the valid key prefix without a mask so INT8 attention can take it - #19208

Merged
danielhanchen merged 5 commits into
mainfrom
studio-krea2-prefix-kv
Nov 24, 2026
Merged

danielhanchen merged 5 commits into
mainfrom
studio-krea2-prefix-kv

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Nov 24, 2026 •

Copy link
Copy Markdown
Member

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.

… the INT8 attention route takes it

The Krea 2 text trim keeps a 128-row bucket, so a partly filled bucket carries padded
rows mid-sequence and every block attends with a key-padding mask (cuDNN, never flash
or the INT8 kernel). The trim now puts each row's pads first (text rows all sit at the
rotary origin, so their order moves no phase) and the 28 block attentions read keys
from the first valid row on with attn_mask=None, through an opaque op that reads the
per-call key start from a CPU tensor the pre-hook fills (one compiled graph for every
prompt; CUDA graphs key on it; a CFG-router stacked batch reads its plan off the mask).
Krea 2 joins the INT8 attention AUTO_DITS race.

UNSLOTH_DIFFUSION_KREA2_PREFIX_KV=0 keeps the masked call.
The key start is read at capture time and follows the prompt, so keying graphs on it
filled the graph cap within a few prompts on a resident RTX PRO 6000 (later shapes
eager, a capture paid per new start). A call with a non-zero start now makes the
graph-key hook raise, which every graph layer runs eager; calls with no plan or a
zero start record as before.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 24, 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-24T04:07:39.753434Z 6e2e213 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: da462f3589

ℹ️ 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 +162 to +166
rows = int(starts[0])
plan = starts[1 : 1 + rows].tolist() if rows == B else None
if plan is not None and mask is None and any(plan):
plan = None
if plan is None and rows and mask is not None:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Refresh the prefix plan on CFG replicas

With multi-GPU CFG enabled, the replica retains the prefix plan from when it was built. diffusion_multigpu._copy_module() deep-copies this tensor and clears the replica's root hooks, while _mirror_hook_state() synchronizes only scalar attributes, so subsequent text-trim plans never reach the replica. When another render changes the negative-prompt length or text bucket, the batch size still matches and this code trusts the stale start instead of checking the current mask. The replica then silently includes padded keys or drops valid text keys, corrupting its guidance output. Refresh the replica's plan for each call, or derive it from the current mask before discarding that mask.

Useful? React with 👍 / 👎.

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 2537ab8 and ebe7b334a4. Each transformer now owns its plan slot, and only the transformer whose own pre-hook wrote the plan trusts it. A deep copy (the CFG replica) is marked unplanned, drops the copied offset and reads every key start from its own current mask, and the plan is cleared after the call that wrote it. The memo and registry are snapshotted before pruning since the replica worker thread writes them too. test_a_cfg_replica_reads_its_own_mask_never_the_copied_plan reproduces the stale offset with the real replica copy and state mirroring, and fails on da462f3.

…icit backends, run grad calls stock

- A CFG replica (deep copy, root hooks stripped, scalar state mirrored only) kept the key start it was copied with
  and dropped its current mask when the batch size matched. Each transformer now owns a slot: only the one whose
  pre-hook plans its calls trusts the starts tensor; a copy reads every plan off its own mask and resolves its own
  processor's backend. The plan is also cleared after the call that wrote it, so a direct forward never reads it.
- The mask-free call swaps only auto's cuDNN pick for native flash, and only when the native-flash switch is on and
  the same SDPA probe Studio runs before pinning flash finds a flash kernel (PyTorch Windows 2.10-2.14 builds have
  none). An explicit cudnn request and native keep their backend.
- A call with grad enabled and a trainable input or weight runs the stock masked attention (the op has no autograd
  formula); gradients match the stock model.
…fore pruning (the replica worker thread writes them too)

[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. Another round soon, please!

Reviewed commit: 6e2e21374a

ℹ️ 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".

[skip ci]
@danielhanchen
danielhanchen merged commit 0c9bdca into main Nov 24, 2026
1 check passed
@danielhanchen
danielhanchen deleted the studio-krea2-prefix-kv branch November 24, 2026 06:08
danielhanchen added a commit that referenced this pull request Nov 24, 2026
#19230)

## Problem


`studio/backend/tests/test_diffusion_rocm_tag_detect.py::test_no_diffusion_or_video_gate_reads_version_hip_directly`
fails on main in the backend `(Python 3.13, diffusion)` shard, so open
PRs such as #19154 inherit it:

```
AssertionError: use core.inference.rocm_bf16.is_rocm_torch(torch): AMD SDK / Radeon wheels leave torch.version.hip unset. Raw reads: {'diffusion_krea2_prefix_kv.py': [170]}
```

## Cause

#19208 (Krea 2 valid key prefix without a mask) added a gate that can
swap auto's cuDNN pin for CUDA native flash on the mask-free prefix
call. It decided "not ROCm" with `getattr(torch.version, "hip", None) is
None`. AMD SDK / Radeon ROCm wheels leave `torch.version.hip` unset and
carry the tag in `torch.__version__` instead. On those builds, the gate
could treat a ROCm card as CUDA and force the CUDA flash backend.

The guard is right and this is a real bug in the new gate, not a stale
test.

## Fix

- The gate now uses `core.inference.rocm_bf16.is_rocm_torch(torch)`,
like every other diffusion and video gate.
- New test `test_a_rocm_build_keeps_the_pin` checks that a ROCm build
keeps the pin for both spellings: `torch.version.hip` set, and only a
`+rocm` tag in `torch.__version__`.

## Verification

- `test_diffusion_rocm_tag_detect.py` and
`test_diffusion_krea2_prefix_kv.py`: 32 passed.
- Main's `diffusion_krea2_prefix_kv.py` with this branch's tests fails
both the guard and
`test_a_rocm_build_keeps_the_pin[None-2.9.0+rocm7.1]`. The `version.hip`
case passes on both, because main already handled it.

I could not run this on real ROCm hardware. The check is the version-tag
detection, simulated by patching `torch.__version__`.
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