Skip to content

Studio diffusion training: Krea-2 trains on its valid caption rows instead of 512 padded ones - #18788

Merged
danielhanchen merged 2 commits into
mainfrom
nov21-train-krea2-text-trim
Nov 22, 2026
Merged

danielhanchen merged 2 commits into
mainfrom
nov21-train-krea2-text-trim

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Krea 2 LoRA training sent every caption through the transformer as 512 text rows, because encode_prompt pads to max_sequence_length=512 and masks the padding. Each row also carries the stacked text-encoder layers into the text fusion. Most captions use far fewer than 512 rows, so most of that joint sequence was masked padding.

Change

diffusion_dit_trainer.py:

  • _krea2_text_rows keeps only a prompt's valid rows. The selection follows the mask, because the pipeline's template puts padding between the prompt and its suffix, not only at the end.
  • _krea2_encode_prompts stores the trimmed form.
  • _krea2_collate trims again, for conditioning caches written by older builds. It pads a batch back to its longest prompt, or to one compile pin. A batch with no padding gets no mask at all, so attention runs unmasked.
  • The compile pin is set for compiled Krea 2 runs, as it already is for Qwen-Image: one fixed text length per run, the longest valid prompt in the dataset.

Why this is exact:

  • Every Krea 2 text token sits at the rotary origin (prepare_position_ids sets text ids to zero), and the text fusion blocks have no positions. So the order of the kept rows carries no information.
  • A padded row only ever acts as a masked key, and its own output is sliced away at hidden_states[:, text_seq_len:]. Dropping it changes nothing for the kept rows.
  • On a tiny random Krea 2 in fp64, the trimmed unmasked forward matches main's padded masked forward to within 1e-10.

Measurements

Colab L4, Krea-2-Raw with an nf4 base (the precision that fits a 22.5 GiB card), 16 tarot cards. Arms were interleaved main / this branch / this branch / main, each in a fresh process on the same VM.

px steps main s/step this branch s/step speedup pre-loop peak GiB, main / this branch loss mean, main / this branch
512 30 3.130 / 3.125 1.842 / 1.847 1.70x 10.46 / 8.13 0.10867, 0.10886 / 0.10862, 0.10878
1024 12 10.616 / 10.633 8.974 / 9.012 1.18x 14.52 / 12.20 0.09302, 0.09306 / 0.09302, 0.09305

Per-step loss, same seed:

px main vs this branch, mean abs diff main vs main (run-to-run noise) this branch vs this branch
512 0.00012 / 0.00014 0.00022 0.00020
1024 0.00003 0.00004 0.00004

The cross-arm differences sit inside the run-to-run noise. Graph breaks and recompiles were 0 on every arm. The in-loop peak is unchanged, because the checkpointing budget spends the freed room.

Tests

  • New: tests/test_diffusion_krea2_text_trim.py, which checks:
    • valid-row selection with the template's mid-sequence padding;
    • collate padding to the batch maximum and to the pin;
    • no mask when nothing is padded;
    • the fp64 forward equivalence on a tiny Krea 2.
  • Updated: tests/test_diffusion_krea2.py, where an unpadded batch now carries no mask.
  • test_differential: DISCRIMINATING, fixed=2, new_api=1, head_fail=0.
  • Trainer suites (test_diffusion_krea2*, test_diffusion_dit_trainer*, test_diffusion_gc_budget*): 386 passed here, 383 on main.

Not proven here

  • Only nf4 on L4: no bf16 or compiled run. The nf4 compile only starts at 200 or more steps, so the compile pin was not exercised on a GPU.
  • No previews: sample previews with trimmed prompts were not rendered.
  • Inference is untouched: the inference half of this item (Krea's fixed text length in inference/diffusion_dynamic_text.py and its int8-attention refusal) is not part of this change.

encode_prompt pads every Krea 2 prompt to 512 text rows and masks the padding. Text tokens all sit at the rotary
origin and the text fusion has no positions, so the padded rows are only masked keys whose outputs are sliced away:
dropping them is exact (fp64 max abs 0 on a tiny Krea 2) and shortens the joint sequence every step. Batches pad to
their longest prompt (or one compile pin over the dataset); an unpadded batch runs without a mask.
@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-21T21:26:51.232630Z f7d4d5e 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. Breezy!

Reviewed commit: 48f83f8a4c

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

…, collate trims

The persistent caption cache is shared across Studio builds. Caching the trimmed rows made an
older build's collate, which concatenates fixed 512-row entries, fail at batch 2 on this build's
cache. The cache now keeps the padded form and _krea2_collate drops the masked rows per batch;
the compile pin already reads the valid rows.

[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. Bravo.

Reviewed commit: f7d4d5e2b4

ℹ️ 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
danielhanchen merged commit 923e1a0 into main Nov 22, 2026
@danielhanchen
danielhanchen deleted the nov21-train-krea2-text-trim branch November 22, 2026 01:59
danielhanchen added a commit that referenced this pull request Nov 22, 2026
…18813)

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.
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