Skip to content

Studio Krea 2: denoise on the valid text rows, not 512 padded ones - #18813

Merged
danielhanchen merged 4 commits into
mainfrom
studio-krea2-text-trim
Nov 22, 2026
Merged

danielhanchen merged 4 commits into
mainfrom
studio-krea2-text-trim

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Nov 21, 2026 •

Copy link
Copy Markdown
Member

Krea 2 inference carried 512 text rows through every block, beside 4096 image rows at 1024x1024, even though a typical prompt fills a few dozen of them. Krea2Pipeline.get_text_hidden_states pads every prompt to max_sequence_length (512) in the middle of its template ([prompt | PAD | suffix]) and masks the padding.

The padded rows are never anything but masked keys:

  • The text rows all sit at the rotary origin (prepare_position_ids writes zeros for them).
  • The layerwise text-fusion blocks attend across the tapped layers of each token on its own.
  • The refiner and every main block mask the padding out as keys.
  • The text rows' own outputs are sliced away before the final layer.

Dropping the padded rows therefore leaves every kept row's math unchanged.

Change

New diffusion_krea2_text_trim.py: a forward pre-hook on the Krea 2 transformer instance.

  • What it keeps: the text columns valid for any batch row. Masked columns fill the count up to a multiple of 128, and the matching position_ids rows are kept with them.
    • Most prompts plus the template suffix fit in 128, so a step runs about 4224 tokens instead of 4608.
    • Rounding to a bucket keeps the number of input shapes small for the CUDA graphs and the compiled blocks.
    • It also gives both branches of a CFG pair the same length in the common case, so the CFG router can still batch them.
  • Cost per step: the mask is read on the host once per prompt. Every step reuses the trimmed tensors.
    • A CFG pair of one length shares one position_ids tensor, so the router batches it without a compare.
  • Left as given:
    • text rows not at the rotary origin;
    • no mask;
    • nothing to drop;
    • positional calls;
    • a capturing stream.
  • Registration: it is the krea2_text_trim load patch, on every tier except an explicit speed off. UNSLOTH_DIFFUSION_KREA2_TEXT_TRIM=0 (or UNSLOTH_DIFFUSION_PATCH_KREA2_TEXT_TRIM=0) keeps the padded rows.
  • Numerics: the output is not bit-identical to the padded call, because attention reduces over fewer keys. It is mathematically the same.

This is the inference side of the same observation as the training trim in #18788. That PR only touches the trainer, and this PR's tests use their own file name, so the two merge in either order.

Numbers

Colab L4 (22.5 GB). Krea-2-Turbo at Studio's auto INT8 (int8 text encoder, streamed denoiser, compiled, CUDA graphs), 1024x1024. Main and this branch ran in fresh processes on one VM, sharing one Studio home, with 2 warm-up cells and then 3 interleaved reps per arm. The whole batch ran twice: the pool re-ran it on a second VM after an infrastructure retry.

VM main s/step branch s/step delta
Turbo, 8 steps, no CFG (median of 9 steady renders) 1 1.927 1.687 -12.4%
2 1.859 1.620 -12.8%
guidance 3.5, CFG (2 renders) 1 3.882 3.371 -13.2%
2 3.689 3.219 -12.7%
  • Engagement: 56 trimmed forwards in the first branch cell (7 renders x 8 steps), skipping 384 text rows each (512 down to 128). On main, diffusion_krea2_text_trim does not exist.

  • Peak allocated memory: 7.63 GiB here vs 7.70 GiB on main.

  • No added compiles or graph breaks: one compiled frame per arm, and the same count of eager calls through the CUDA graph wrapper.

  • LPIPS (alex) against main, same seed: 0.150 / 0.135 mean (max 0.33) without CFG, 4 prompts; 0.339 / 0.364 with CFG, 2 prompts.

    • Every arm repeats itself bit for bit (A/A LPIPS 0.000, torch.equal on every image), so the difference is the trim.
    • The images keep the same composition. The thumbnails differ in fine detail.
  • Where that LPIPS comes from: a CPU check on a random Krea 2 transformer (512 text rows, 40 + 5 valid, 576 image rows) gives:

    • fp64: the trimmed call equals the padded call exactly (relative difference 0.0);
    • bf16: the trimmed call is 0.12% from the padded one, while each is 3.9% from fp64.

    So the trim moves a bf16 forward by a small fraction of bf16's own error, and its distance from fp64 is the same as the padded call's. The 8 distilled steps amplify that rounding-level change into the LPIPS above.

Tests

  • tests/test_diffusion_krea2_infer_text_trim.py (new, CPU, 16 cases, including a CFG pair whose branches fall in different 128-row buckets keeping one length so the CFG router can still stack them), on a tiny random Krea2Transformer2DModel fed the pipeline's own layout.
    • The trimmed call matches the padded one to 1e-5 for single and batched prompts with different valid lengths.
    • The kept rows are the valid ones in template order, padded to the bucket.
    • A prompt that fills its bucket runs unmasked.
    • The mask is read once per prompt, and steps reuse the same tensors.
    • A CFG pair of one bucket shares its position_ids.
    • Text rows off the rotary origin, no mask, a full prompt, the kill switch and an explicit off load all keep the padded call.
    • Only Krea 2 is hooked.
  • tests/test_diffusion_autoopt_parity.py: the Krea 2 cases of the parity fixture now list krea2_text_trim (engaged except on off), and the legacy sequence installs it the same way.
  • test_differential.py against the merge base: DISCRIMINATING, 0 head failures. The 14 new cases are NEW_API, because the module is new.
  • The autoopt, CFG batch, Krea 2, prompt-length and dynamic-text test files: 194 passed.

Against a bf16 reference

Krea-2-Turbo was rendered on Colab L4 with the same 4 prompts and seeds. The reference is bf16 with no speed path: speed mode off, no INT8 on the DiT or the text encoder, no compile, no CUDA graphs. Main and this branch ran at Studio defaults.

prompt main vs ref branch vs ref branch vs main
0 0.130 0.068 0.081
1 0.433 0.464 0.303
2 0.087 0.170 0.172
3 0.151 0.166 0.079
mean 0.200 0.217 0.159
  • The reference repeats itself bit for bit (LPIPS 0.000, torch.equal on all 4 images).
  • What the table shows: most of each arm's distance from the reference is INT8 quantization, about 0.2 on both arms. The branch is not clearly further from the reference than main:
    • It is closer on prompt 0 and further on prompts 1 to 3.
    • The per-prompt differences (-0.062, +0.031, +0.083, +0.014) average +0.017 with a spread of 0.06, well inside the prompt-to-prompt scatter.
    • Any change of this size moves a quantized image in a direction unrelated to the reference, which on average lengthens its distance a little even when the change is exact.
  • Decision: with the fp64 equality above, this ships on by default on every speed tier except an explicit off.

Not proven here

  • The CFG cell ran unpaired, because Studio's CFG router did not engage on this streamed load. The paired-branch path, a CFG pair of one length sharing position_ids, is covered on CPU only.
  • Krea-2-Raw (52 steps, CFG) did not run (62 GB bf16).
  • The GPU run applied this change on dbf5589013, the base of the H3 batch it shared a VM with. The branch itself sits on 32770dfd44, and the patch applied cleanly to both.
  • Only an L4 ran: no A100, G4, ROCm or Mac.

Krea2Pipeline pads every prompt to 512 text rows in the middle of its
template, and the transformer carried all of them through the text
fusion and every block beside 4096 image rows at 1024x1024. The padded
rows are only masked keys: text rows sit at the rotary origin, the
layerwise text blocks run per token, the refiner and main blocks mask
them, and their outputs are sliced away.

A forward pre-hook on the Krea 2 transformer keeps the columns valid for
any batch row, filled with masked columns up to a multiple of 128 (few
shapes for graphs and compiled blocks, one length for a CFG pair in the
common case), plus the matching position_ids rows. The mask is read once
per prompt; steps reuse the trimmed tensors, and a CFG pair of one
length shares one position_ids tensor. Text rows off the rotary origin,
no mask, or nothing to drop keep the call as given.

Registered as the krea2_text_trim load patch (every tier but an
explicit speed off). UNSLOTH_DIFFUSION_KREA2_TEXT_TRIM=0 keeps the
padded rows.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 21, 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-21T22:44:56.119400Z 5aafedf 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.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. What shall we delve into next?

Reviewed commit: 6884c432db

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

… stack; inference trim tests get their own file name

[skip ci]
@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: 20dfbab55e

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

held[rows] = pos
out = (
states.index_select(1, index),
None if all_valid else mask.index_select(1, index),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve compatible masks across CFG branches

When one CFG branch has exactly a bucket's worth of valid tokens (for example, 128 including the suffix) and the other has fewer, both branches retain 128 rows, but this expression gives one a None mask and the other a tensor mask. In diffusion_cfg_batch.py, _pad_text skips normalization when sequence lengths already match, and merge_branches then raises _NotBatchable because the mask is a tensor in only one branch. The router consequently disables batching for that request shape, regressing guided inference to two separate forwards where the padded implementation could batch them. Keep the all-valid mask when needed for CFG compatibility, or normalize the masks before merging equal-length branches.

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.

Thanks, fixed in 5aafedf: calls sharing one position_ids (the CFG branches) now keep their mask together once either branch needs one, so a branch that exactly fills its bucket no longer drops its mask while the other keeps it, and the router sees the same keys in both. Covered by test_a_cfg_pair_where_one_branch_fills_its_bucket_keeps_both_masks, which fails without the change.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 👍

Reviewed commit: 5aafedf6d1

ℹ️ 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 cbed976 into main Nov 22, 2026
@danielhanchen
danielhanchen deleted the studio-krea2-text-trim branch November 22, 2026 04:36
danielhanchen added a commit that referenced this pull request Nov 23, 2026
…nder one seed the same way (#19077)

## Summary

Krea-2 now pins Inductor's reduction-config filter
(`filter_reduction_configs = True`) and keeps `cudnn.benchmark` off for
its renders (`cudnn_benchmark = False`), as FLUX.2 Klein and FLUX.3
Klein already do. In the default speed mode one seed now renders one
image in every fresh Studio home (measured on A100 40 GB and L4). Max
speed mode is outside that claim (see below).

## What was wrong

A Krea-2 load compiles its denoiser blocks with `torch.compile`. On a
cold compile cache, Inductor benchmarks several configs for a few
reduction kernels in the loading process and keeps the fastest. Two of
those configs are nearly tied on an A100 and sum in different orders
(for one kernel, `R0_BLOCK` 2048 vs 8192). The winner is written into
the compile cache under the Studio home, so:

- two fresh Studio homes on the same machine can render the same seed
differently, and
- every later load of a home repeats whatever its first load picked.

In the #18813 accuracy recheck (A100 40 GB, Krea-2-Turbo INT8, 1024 px,
8 steps, 12 prompts) this showed up as the first INT8 load of a fresh
machine rendering differently from later loads of the same code: LPIPS
0.146 mean, 0.57 max, with identical status and identical weights. It
was not tied to the first load. It was tied to the compile cache each
home started with.

## Evidence (Colab A100 40 GB, Krea-2-Turbo INT8, 1024 px, 8 steps,
guidance 0, seeds 1000+i, every load a fresh process)

Weights: every INT8 load read the same hosted
`Krea-2-Turbo-INT8.safetensors` and
`Krea-2-Turbo-text_encoder-INT8-ConvRot.safetensors`; transformer, text
encoder and VAE weight digests were identical in every cell, so the
split is in compute, not in weights.

Same code, fresh homes, different picks (tree 9840f8f, before the
text-row trim, which has the same reduction shapes as main with
`UNSLOTH_DIFFUSION_KREA2_TEXT_TRIM=0`):

| Run | Fresh homes | Image vs fp32 reference (4 prompts, LPIPS) |
|---|---|---|
| recheck VM | `base_auto` (r0, r1) | 0.2526 |
| recheck VM | `base_int8` (r0, r1), `main_*_notrim` | 0.3499 |
| VM 2 | 4 fresh homes (auto and int8) | 0.2526 |
| VM 3 | 1 fresh home | 0.3499 |

Forcing Inductor to keep the slowest config of every autotuned reduction
(4 kernels) moves an image from one variant to the other, and the filter
removes the dependence:

| Cell (VM 3) | Reductions forced to slowest | vs fp32 | Same as default
|
|---|---|---|---|
| default | 0 | 0.3499 | |
| slowest pick | 4 | 0.2526 | no (LPIPS 0.231) |
| filter on | 0 (nothing left to benchmark) | 0.3499 | yes,
bit-identical |
| filter on + slowest pick | 0 | 0.3499 | yes, bit-identical |

With this branch (current main plus the one-line family change, same
A100 run as its main arm):

| Cell | Text-row trim | Reductions benchmarked | vs fp32 | Matches |
|---|---|---|---|---|
| main default | on | yes | 0.3433 | |
| this branch, 2 fresh homes | on | none | 0.3433 | main default,
bit-identical |
| this branch, slowest pick | on | none (0 forced) | 0.3433 | main
default, bit-identical |
| main default | off | yes | 0.3499 | |
| main, slowest pick | off | 4 forced | 0.3499 | main default |
| this branch, 2 fresh homes + slowest pick | off | none (0 forced) |
0.3499 | main default, bit-identical |

So the change keeps today's main images unchanged on this card and
removes the per-home benchmark that could move them.

On current main itself the split did not reproduce in what was tried: 9
fresh homes with the trim on (3 VMs) and 2 with it off rendered one
image per setting, and the slowest-pick override did not move pixels
there. The race is still live on main (4 reduction kernels are
benchmarked in every fresh home and their picks differ between homes),
but the picks seen so far landed on configs that sum the same way for
these shapes. Other resolutions, prompt lengths, cards and torch
versions change both the shapes and the timings.

Which variant is right: neither. Both are fp32 reductions over the same
values in a different order; an 8-step distilled sampler amplifies the
last-bit difference into a visibly different image. Against an fp32
reference (every DiT linear in fp32 on the published weights, TF32 off)
the 0.2526 variant happened to be closer on these prompts (12 prompts:
0.170 vs 0.219), but that is the luck of one reduction order on one
prompt set, not a precision gain. The fix makes the choice
deterministic; it does not pick a more accurate kernel.

Speed: per-image steady time on the A100 is unchanged within run-to-run
spread (trim on: main 3.92 s, this branch 3.92 to 3.94 s; trim off: main
4.34 s, this branch 4.34 s; 3 timed renders per cell, not an exclusive
benchmark).

## cuDNN conv picks and max speed mode (Colab L4 and A100 40 GB)

Same setup as above (INT8, 1024 px, 8 steps, guidance 0, 3 prompts,
seeds 1000+i, torch 2.14.1), every cell a fresh process with its own
fresh Studio home, Inductor cache and Triton cache, cells interleaved.
Each cell rendered 6 images (3 prompts twice); "steady" is the median of
renders 2 to 6. VAE decode is timed and hashed inside `vae.decode`
during the renders, plus a standalone decode of one fixed seeded latent
through the same `vae.decode` under the render's cuDNN scope.

cudnn.benchmark on (as before this change) vs off (this branch), default
speed mode, 3 fresh homes each:

| Card | Arm | Images across homes | In-render VAE decode across homes |
Fixed-latent VAE decode across homes | First render | Steady render (per
home) | Steady VAE decode | First VAE decode |
|---|---|---|---|---|---|---|---|---|
| L4 | on | 1 variant | 1 variant | 3 variants (3 of 3 homes differ) |
42.3 to 49.0 s | 13.44, 13.35, 13.26 s | 142 ms | 5.4 to 7.4 s |
| L4 | off | 1 variant | 1 variant | 1 variant | 44.5 to 44.7 s | 13.25,
13.29, 13.32 s | 143 ms | 3.9 s |
| A100 40 GB | on | 1 variant | 1 variant | 1 variant | 30.9 to 34.2 s |
3.400, 3.407, 3.396 s | 34.7 ms | 4.5 to 6.2 s |
| A100 40 GB | off | 1 variant | 1 variant | 1 variant | 30.0 to 30.1 s
| 3.408, 3.407, 3.416 s | 36.3 ms | 3.6 s |

So on L4 the per-process cuDNN pick decoded the same latent three
different ways in three fresh homes, and with it off all three matched.
On the A100 both settings matched. Off skips about 1 to 1.5 s of conv
benchmarking in the first render; the steady VAE decode is 1.6 ms slower
on the A100 (under 0.05% of a 3.4 s render) and unchanged on L4, and
steady render time is within the home-to-home spread on both cards. On
L4 the off setting decodes these latents slightly differently from the
on setting (a different conv algorithm), so L4 images move once versus
main; on the A100 the images are bit-identical to the on setting.

Max speed mode, main (no filter, `mode="max-autotune-no-cudagraphs"`,
coordinate descent on) vs this branch (filter on, `max_autotune` on,
coordinate descent off, which is how every family that pins the filter
already compiles in max mode):

| Card | Arm | Fresh homes | Images across homes | First render | Steady
render (per home) |
|---|---|---|---|---|---|
| L4 | main | 2 | 2 variants (the homes differ on every prompt) | 84.1,
84.8 s | 13.23, 13.23 s |
| L4 | this branch | 3 | 1 variant | 46.6 to 46.9 s | 13.25, 13.26,
13.24 s |
| A100 40 GB | main | 2 | 1 variant | 56.2, 56.7 s | 3.386, 3.390 s |
| A100 40 GB | this branch | 3 | 1 variant | 31.5 s | 3.431, 3.433,
3.440 s |

On the A100 the branch's max mode is 1.3% slower per image (0.045 s),
outside the home-to-home spread (under 0.3%); on L4 the difference is
inside the spread. Keeping coordinate descent in max mode would bring
back the per-home retiming that split main's max mode on L4 above, and
the branch's first render is 25 to 38 s faster because the cold compile
benchmarks less, so the A100 per-image cost is repaid only after about
550 images in one process. The branch keeps the existing max-mode
policy.

Max speed mode is outside the one-seed-one-image claim: `max_autotune`
still benchmarks GEMM templates in every fresh process. It rendered one
image across 3 fresh homes on each card here, but that is not
guaranteed.

Peak VRAM (one render process, after load): A100 40 GB 18.5 GiB
allocated, 20.5 to 21.3 GiB reserved, 21.9 GiB peak on the card (fully
resident); L4 7.6 GiB allocated, 10.1 to 10.8 GiB reserved, 11.1 GiB
peak on the card (Studio chose CPU offload on L4). Identical in both
cuDNN arms and both max-mode arms apart from the reserved figure.

## Changes

- `studio/backend/core/inference/diffusion_families.py`:
`filter_reduction_configs = True` and `cudnn_benchmark = False` on the
`krea-2` family.
- `tests/test_diffusion_reduction_filter_arch.py`: Krea-2 filters on
every arch, the flag reaches the compile call, and cudnn.benchmark is
off (fails on main, passes here).
- `tests/test_diffusion_speed.py`: Krea-2 joins the cudnn.benchmark
opt-out set.
- `tests/fixtures/diffusion_family_data_freeze.json`,
`tests/fixtures/diffusion_autoopt_parity.json`: the krea-2 rows only
(the compile call now carries `force_filter_reduction_configs`, and
`cudnn_benchmark` leaves the applied set).

The compile-cache key already includes the filter, so existing Krea-2
compile caches are rebuilt once on the next load.

## Tests

- New tests: 7 failed on main, 7 pass here.
- Every backend test file that mentions krea, the reduction filter or
the compile cache (95 files) run on main and here: the failing test IDs
are identical apart from the 7 new ones (46 pre-existing failures on
this host come from local package versions, for example
`huggingface_hub` lacking `get_cached_repo_tree`).

## Not tested

- Cards other than A100 40 GB and L4 (H100, B200, consumer cards): both
settings apply on every arch by design, as for the other pinned
families, but their effect there is unmeasured.
- Whether the in-render VAE decode (as opposed to the fixed-latent
decode) can split with cudnn.benchmark on: it matched across 3 homes on
both cards here.
- Which of the two max-mode differences (filter on, coordinate descent
off) accounts for the 1.3% A100 max-mode cost: they were measured
together.
- Resolutions other than 1024 px, CFG, Krea-2-Raw, LoRA, and offloaded
loads on cards other than L4.
- FLUX.2 Klein 4B and Qwen-Image-2.1 INT8 (2 prompts each, 3 loads each
across fresh and reused homes) showed no split on main; both already pin
the filter.
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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant