Repository navigation
Studio Krea 2: attend over the valid key prefix without a mask so INT8 attention can take it - #19208
Conversation
… 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.
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. |
|
@codex review |
There was a problem hiding this comment.
💡 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".
| 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: |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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]
|
@codex review |
|
Codex Review: Didn't find any major issues. Another round soon, please! 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". |
[skip ci]
#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__`.
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 ofAUTO_DITSfor 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 ofKrea2AttnProcessorfor the 28 main blocks. It calls an opaque custom op that doesattention(q, k[:, start:], v[:, start:])withattn_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._unsloth_graph_key_extraraises, 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.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 andUNSLOTH_DIFFUSION_NATIVE_FLASH_ATTN=0are respected.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 joinsAUTO_DITSandAUTO_CUDA_ONLY. It races its incumbent on the plain path, not the sink path. A masked call still keeps the incumbent.UNSLOTH_DIFFUSION_KREA2_PREFIX_KV=0keeps the stock processors and the masked call. Engagement counters are indiffusion_krea2_prefix_kv.STATS(prefix,from_mask,masked), and the load logsblock 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.
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.
RTX PRO 6000 (Colab G4, sm120, model resident). Same setup: 3 fresh processes per arm, interleaved, main first.
_native_cudnn, masked, one CUDA graph replayed)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):
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.
The kernel's error is below the shipped INT8 weights' error in both mean and max, which is the bar the other
AUTO_DITSfamilies 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.
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):error_on_recompile);test_diffusion_int8_attention_dispatch.pyandtest_diffusion_int8_attention_families.pynow pin Krea 2 inAUTO_DITSandAUTO_CUDA_ONLY, and not inSINK_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