Skip to content

Studio diffusion: INT8 attention folds the sink residual into the attention kernel - #18786

Merged
danielhanchen merged 2 commits into
mainfrom
studio-img-gaps-fold
Nov 21, 2026
Merged

danielhanchen merged 2 commits into
mainfrom
studio-img-gaps-fold

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

On the INT8 attention sink path (FLUX.1 / FLUX.2 / FLUX.3, Qwen-Image-2.1, Z-Image, HunyuanVideo-1.5), every call ran unsloth_i8resid after the attention kernel. That second launch re-read the int8 Q rows and read, modified and wrote back the whole output, only to add the clipped V parts of a few sink keys. On an L4 FLUX.3 klein profile it cost about 0.37 ms per call, 12 ms per denoiser forward.

Change

  • diffusion_int8_attention_cuda.py: with SINKS and the new RFOLD, the attention kernel adds the clipped keys back itself, before its store.
    • It stages the clipped keys' int8 K rows, fp32 residuals and K scales in the tile buffers, which are free after the tile loop.
    • Each key's exact P comes from the same int8 score unsloth_i8resid used, in the frame of the row maximum. It goes to shared memory, and P times the residual is added one channel block at a time.
    • The sum lands in the accumulators before the normaliser and the V gain, so the output is rounded once instead of twice.
    • The head and row base are read again after the tile loop, so no setup address stays live through it. On sm_89 at head dim 128 the folded kernel has one spill instruction inside the tile loop; the separate-launch sink kernel has six (nvdisasm of the NVRTC build).
  • diffusion_int8_attention.py: sink-path plans at head dim 128 take the folded kernel and launch nothing after it. Head dim 64 keeps the separate launch, because its NQ 2 configs spill in the tile loop once folded.
  • UNSLOTH_DIFFUSION_INT8_ATTENTION_RESID_FOLD=0 keeps the separate launch.

Results

The op alone, sink-path calls at head dim 128 (attend on one quantised operand set, median of 5 x 20 calls, two interleaved passes per arm; error is the L2 error against fp32 attention):

Card Call Separate launch (ms) Folded (ms) Change Error vs fp32, separate / folded
L4 4608 tokens, 24 heads, 4 sink keys 2.515 / 2.514 2.461 / 2.463 -2.1% 0.012153 / 0.012147
L4 4608 tokens, 24 heads, 32 sink keys 2.944 / 2.951 2.675 / 2.593 -10% 0.010591 / 0.010589
L4 4352 tokens, 32 heads, 4 sink keys 3.130 / 3.129 3.053 / 3.048 -2.5% 0.011647 / 0.011639
T4 4608 tokens, 24 heads, 4 sink keys 6.750 / 6.776 6.432 / 6.440 -4.8% 0.0115318 / 0.0115316
T4 4608 tokens, 24 heads, 32 sink keys 7.704 / 7.721 6.661 / 6.686 -13.5% 0.0105959 / 0.0105959
T4 4352 tokens, 32 heads, 4 sink keys 8.232 / 8.275 7.800 / 7.836 -5.2% 0.0116782 / 0.0116781

The folded output differs from the separate launch by at most one bf16 / fp16 unit in the last place (0.0156 / 0.00195 max abs), which is the rounding the fold removes. The error against fp32 attention is equal or lower in every case.

End to end, Colab L4, origin/main vs this branch, Studio begin_load with auto quant (hosted ConvRot INT8, INT8 attention on). 1024x1024, fresh process per cell, arms interleaved over 3 reps (ABBA), median of the new-prompt and steady renders:

Both arms share one Studio home per family. Two discarded warm-up loads ran the CUTLASS tile race first, so every timed cell reads the same GEMM plan (identical CUTLASS call counts in every cell).

Model (Colab L4) main s/step (spread) this branch s/step (spread) Change Steady s/image Sink-path plans folded
FLUX.3 klein, 16 steps, cfg 1 0.4603 (0.16%) 0.4524 (0.85%) -1.7% 7.663 -> 7.546 1 of 1
Qwen-Image-2.1-Turbo, 8 steps 0.6805 (0.16%) 0.6820 (0.60%) +0.2%, a tie 5.978 -> 5.988 4 of 4 (rep 0), 2 of 2

On a second L4 VM, the first version of the fold measured (separate homes, 3 reps each):

Model main s/step fold s/step Change
FLUX.3 klein, 16 steps 0.4859 (1.1%) 0.4768 (1.7%) -1.9%
FLUX.3 klein base, 12 steps, cfg 3.5 0.9433 (0.7%) 0.9234 (0.8%) -2.1%
Z-Image-Turbo, 8 steps (1 sink plan of 3) 0.6494 (0.8%) 0.6453 (1.1%) -0.6%, a tie

The gain follows the number of clipped keys. FLUX.3 heads clip many, so its separate residual launch was the expensive one. Qwen-Image-2.1 and Z-Image clip few.

No graph breaks and no recompiles after the first render in any cell. CUDA graphs capture and replay as on main.

Accuracy

Each arm is bit-identical to itself across processes (LPIPS 0.0 between reps), so any difference between arms comes from the change. The folded path rounds the attention output once instead of twice, and the trajectories move accordingly. As the reference I used bf16 weights on the same VM. That reference still runs main's INT8 attention, so it leans slightly toward main.

Model main vs bf16 this branch vs bf16 this branch vs main
FLUX.3 klein (LPIPS, 4 prompts) 0.0116 (max 0.018) 0.0078 (max 0.013) 0.0095
Z-Image-Turbo 0.0619 (max 0.111) 0.0577 (max 0.140) 0.0502
Qwen-Image-2.1-Turbo not run not run 0.0052
FLUX.3 klein base not run not run 0.0112

The folded path is no further from the bf16 reference than main on mean LPIPS. Z-Image moves the most between the two arms, but that is its trajectory sensitivity, not a loss: it moves as far from main as main sits from bf16, and its mean distance to bf16 drops slightly.

Tests

  • tests/test_diffusion_int8_attention_resid_fold.py (new, CPU): every card config builds the folded kernel with the three extra inputs; the staged keys fit the tile buffers; a folded sink call is one launch with the clipped keys' indices, residuals and stride appended; the kill switch keeps the residual launch; calls without sinks are unchanged.
  • test_a_call_on_another_card_uses_that_cards_stream expects no unsloth_i8resid launch with the fold on.
  • GPU: tests/test_diffusion_int8_attention.py on main and on this branch, on L4 and T4 (final code). That includes test_attention_sinks_keep_the_rest_of_v_resolved and test_more_clipped_keys_than_one_staging_pass, which check the kernel against its torch model and fp32 attention. Both trees fail the same pre-existing tests (test_a_plan_whose_sink_path_loses_its_race_runs_torch_attention, plus the two-card stream test on T4x2) and pass everything else.

Not proven here

  • sm_120 (G4) and sm_80 / sm_86 were not run on a GPU. They were checked offline only: NVRTC builds every config, and nvdisasm shows the folded kernel with no more spills in the tile loop than the separate-launch kernel (0 on sm_120 / sm_80 / sm_86 / sm_75 at head dim 128).
  • Windows and AMD were not run. ROCm runs the Triton kernel, which has no sink path, so this change does not touch it.

…e the attention kernel

The attention-sink path ran unsloth_i8resid after the attention kernel:
a second launch that re-read the int8 Q rows and read, modified and
wrote back the whole output to add the clipped V parts of a few keys
(about 0.37 ms per call on an L4 FLUX.3 klein profile).

With RFOLD the attention kernel does it before its store. It stages the
clipped keys' int8 K rows, residuals and K scales in the free tile
buffers, takes each key's exact P from the same int8 score in the frame
of the row maximum, and adds P times the residual to the accumulators
before the normaliser and the V gain, so the output is rounded once.
The head and row base are read again after the tile loop so no setup
address stays live through it: on sm_89 at head dim 128 the folded
kernel has one spill instruction in the tile loop, the separate-launch
sink kernel six. Head dim 64 keeps the separate launch (its NQ 2
configs spill in the loop once folded).

UNSLOTH_DIFFUSION_INT8_ATTENTION_RESID_FOLD=0 keeps the separate launch.
@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-21T19:31:51.904800Z dbf11ad 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. Swish!

Reviewed commit: f2f27d5a6a

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

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: dbf11adf35

ℹ️ 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 d209b3d into main Nov 21, 2026
@danielhanchen
danielhanchen deleted the studio-img-gaps-fold branch November 21, 2026 21:42
danielhanchen added a commit that referenced this pull request Nov 23, 2026
…*31 guard, CUTLASS race key covers its helpers (#18968)

## Summary

Follow-ups from a kernel-rules pass over the recent INT8 attention,
CUTLASS race cache and FLUX.2 reference preprocessing PRs (#18917,
#18797, #18786). Three commits, one per fix:

1. **FLUX.2 edits: the GPU reference preprocess probe runs at load, not
inside the first edit request (#18917).**
`install()` patches the image processor before placement, so the
per-device probe (Triton compile of the two Lanczos kernels plus two
Pillow comparison images) ran on the first edit request under the module
lock. A new `diffusion_ref_preprocess.warm(pipe)` runs the same probe
for the pipe's execution device right after placement (after the graph
arming, before the load record). It is a no-op for families without the
installed preprocess. The lazy probe stays as the fallback for a device
`warm()` never saw.
2. **FLUX.2 edits: references past 2**31 elements stay off the 32-bit
Lanczos kernels (#18917).**
The kernels index one image with int32 flat offsets. `lanczos_resize`
now refuses a resize whose source, intermediate (either pass order) or
output reaches 2**31 elements, about 715 MP. The FLUX.2 preprocess
checks before it uploads the pixels, so such an image takes the CPU
path.
3. **INT8 GEMM: CUTLASS race verdicts are keyed on the helpers the race
code calls (#18797).**
`_RACE_SOURCES` hashed the listed race functions but not the helpers
they call. An edit to `_xs_dtype` (the activation-scale dtype the race
times), `_payload`, the act quant, the row-bucket bookkeeping or the
race switches therefore kept stale verdicts.
   - Those helpers are now keyed.
- The few left out on purpose are listed in `_RACE_UNKEYED`: the key
builders, the library loader (the library is hashed by its bytes) and
the tile probe's own persistence.
- A new test walks the call closure across the three keyed modules,
including `cut.x` calls, and fails on any helper that is in neither
list.
- Performance only: tile correctness is still the per-card bit-exact
probe. Every card re-races once after this update.

## Evidence

### 1. First edit request, L4 (Colab, torch 2.14.1+cu130, Triton 3.8.0,
diffusers 0.43.0)

Each run is a fresh process with base (main) and head interleaved, 5
runs per arm. The images are 2048x1536 and then 1800x2400, resized to 1
MP and cropped. "Cold" uses an empty Triton cache per process; "warm"
uses a pre-populated one.

| Triton cache | Arm | Load step (install + warm), ms | First request,
ms | Second request, ms |
|---|---|---|---|---|
| cold | main | 0.68 [0.64, 0.70] | 2601.6 [2577.2, 2609.3] | 28.2
[27.4, 28.7] |
| cold | head | 2564.8 [2553.5, 2569.1] | 33.5 [32.9, 34.7] | 28.3
[27.9, 30.0] |
| warm | main | 0.65 [0.63, 0.68] | 1639.4 [1637.0, 1646.5] | 28.1
[27.6, 30.5] |
| warm | head | 1606.5 [1604.1, 1614.7] | 32.7 [32.3, 34.7] | 27.5
[27.2, 27.8] |

- The first request drops from 2.6 s to 34 ms with a cold Triton cache,
and from 1.6 s to 33 ms with a warm one. The base spread is 1.2%, so
this is far outside the noise.
- The same time now lands in the load step.
- The second request is a tie (A/A control).
- Output tensors hash the same on main, on head and on the stock CPU
path, for both images and all 10 runs per arm. `STATS` shows `gpu 2,
fallback 0` in every run, so the GPU path ran.

### 2. Folded sink kernel at head dim 128 on sm80 and sm120 (#18786)

The question was whether the folded sink path is right on cards where it
had only been checked offline. It is, so the code is unchanged.

- **Setup:** current main, fold on vs
`UNSLOTH_DIFFUSION_INT8_ATTENTION_RESID_FOLD=0`, each arm twice. 15
cases: Flux shape, 40 sink keys, long calls, fp16 / fp32, strided, batch
2, no-clip, hd64. Compared against fp32 reference attention.
- **A100-40GB (sm80, qreg 1):**
- Covers both hd128 configs: wpc 4 below 4608 keys and wpc 8 from 4608
on.
- The fold engaged on every clipping hd128 case: one launch instead of
two.
- Fold on vs off differs by at most 0.125 in bf16. The 40-key case
reaches 0.5, which is one bf16 step at those magnitudes.
- The folded output is nearer fp32 in every bf16 clipping case. Flux
shape rel_l2 0.0130402 -> 0.0129988; 8192 keys 0.0085737 -> 0.0085072.
  - Non-clipping and non-sink cases are bit-identical.
- **RTX PRO 6000 (sm120, qreg 0, native probability pack from #18870):**
- Same picture. Flux shape rel_l2 0.0144564 -> 0.0144301; 8192 keys
0.0160356 -> 0.0160310.
- The 40-key case is a tie: 0.0208967 vs 0.0209146, with mean abs error
lower.
- **GPU pytest subset:** 57 passed on both cards in both arms, plus one
failure that is also there with the fold off:
`test_a_plan_whose_sink_path_loses_its_race_runs_torch_attention`.
- **sm86 has no cloud tier.** Its hd128 config compiles the same defines
as the A100 long-call config: HD 128, BN 128, NQ 1, WPC 8, STAGES 2,
QREG 1. The only arch branch in the kernel source is `__CUDA_ARCH__ <
800`, so sm86 runs the same fold code path that passed on A100. It stays
enabled.

## Tests

- `tests/test_diffusion_ref_preprocess.py`:
- The probe runs in `warm()` and not on the first request (the probe is
mocked to raise).
  - An unwarmed device still probes lazily.
  - `warm()` is a no-op without the install.
  - The load calls `warm` after placement.
- The int32 size limit, including that it is checked before the pixel
upload.
- `tests/test_diffusion_int8_cutlass_race_key.py`:
- Every function the keyed race code reaches is keyed or listed as
deliberately unkeyed.
  - The unkeyed names still exist.
- Each new test fails on main.
- Targeted CPU files pass: `test_diffusion_ref_preprocess.py` 34,
`test_diffusion_ref_preprocess_gate.py` 5,
`test_diffusion_int8_cutlass_race_key.py` 29,
`test_diffusion_int8_cutlass_lib_digest.py` 5,
`test_diffusion_int8_cutlass_probe_persist.py` 8.

## Not covered

- No real FLUX.2 model load was timed end to end. The L4 numbers come
from the image processor with the real kernels, on a pipe placed on the
GPU.
- sm86 was not run on hardware. The case for it rests on the identical
compiled defines above.
- Windows was not run. Nothing here is OS specific.
danielhanchen added a commit that referenced this pull request Nov 23, 2026
…ntion plan keys, CUTLASS live race key, step-skip sample= shape (#18981)

Four small fixes from a recheck of the merged FLUX.1 ConvRot GELU
(#18766), INT8 attention sink fold (#18786), CUTLASS race key (#18797)
and SDXL static step skip (#18826) changes. Each one is its own commit
with a test that fails before it and passes after.

## Changes

1. **FLUX.1 ConvRot GELU gate traces on torch 2.10 / 2.11**
(`diffusion_convrot_quant.py`). `convrot_gelu_act_quant` chose its row
threshold with `rows[prefix is None]`. Dynamo on torch 2.10 and 2.11
cannot trace a tuple indexed by a bool. With `fullgraph=True` the
compile raises `Unsupported`; without it, every armed FF / single-block
down projection graph-breaks. torch 2.6 and 2.12+ accept it. The index
is now `1 if prefix is None else 0`, which selects the same entry.
2. **INT8 attention launch plans follow the kernel switches**
(`diffusion_int8_attention.py`). `_plan` reads
`UNSLOTH_DIFFUSION_INT8_ATTENTION_RESID_FOLD`, and `kernel_variant`
reads the sink order and native P switches, when a plan picks its
kernels. The warm lookup in `_find_plan` did not key on them. Flipping
the fold off in a running process therefore left warm shapes on the
folded kernel until `forget_plans`. The plan key now includes the three
switches as set. That costs three env reads, about 1.7 us of host time
per call, and nothing under CUDA graph replay.
3. **CUTLASS race key covers the live row race**
(`diffusion_int8_gemm.py`). `_live_row_race` decides which calls race
and applies the `force` pick. It also writes its winner into the same
disk entry that `_cutlass_plan` reads back on the next load. Neither it
nor `live_race_enabled` was in `_RACE_SOURCES`, so an edit confined to
the live race kept old verdicts. Both are keyed now. This applies
cleanly on top of the open race-key closure change, whose closure test
still passes with both applied.
4. **Step skip reads `sample=`** (`diffusion_step_skip.py`). The reuse
key took the latent from `hidden_states` or the first positional
argument. A `UNet2DConditionModel` called with `sample=` was therefore
keyed with shape `None`, and a skipped step after a latent shape change
returned the previous output at the old size. The stock SDXL pipeline
passes the latent positionally, so Studio's own renders were not
affected.

## Tests (CPU, base = parent commit, head = this branch)

| Test | Base | Head |
|---|---|---|
| `test_diffusion_convrot_gelu_route_trace.py` on torch 2.10.0 / 2.11.0
| 2 failed, 1 passed | 3 passed |
| same on torch 2.6.0 / 2.12.1 / 2.13.0 / 2.14.1 | n/a | 3 passed |
|
`test_diffusion_int8_attention_resid_fold.py::test_a_warm_plan_follows_the_kill_switch`
| failed (warm plan reused) | passed |
| `test_diffusion_int8_cutlass_race_key.py` (3 new live race cases) | 3
failed, 27 passed | 30 passed |
|
`test_diffusion_step_skip_unet.py::test_a_skipped_step_never_returns_another_latent_shape[True]`
| failed (width 8 for a width 12 latent) | passed |

The surrounding INT8 attention, CUTLASS, GEMM, step skip and FLUX.1 GELU
suites have the same results on both arms. 8 FLUX.1 GELU tests fail on
both base and head when they run in the same process after the step skip
and INT8 suites, and they pass when that file runs alone. That failure
predates this change.

## Not covered here

- No GPU run. The four changes are host-side keys and gates, and each
one is checked on CPU against the real module code.
- The `+1.7 us` host cost per INT8 attention call was measured on CPU,
not as end-to-end render time.
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