Repository navigation
Studio diffusion: INT8 attention folds the sink residual into the attention kernel - #18786
Conversation
…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.
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 |
|
Codex Review: Didn't find any major issues. Swish! 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". |
…n's head-dim rule [skip ci]
|
@codex review |
|
Codex Review: Didn't find any major issues. 👍 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". |
…*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.
…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.
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_i8residafter 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: withSINKSand the newRFOLD, the attention kernel adds the clipped keys back itself, before its store.unsloth_i8residused, 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.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=0keeps the separate launch.Results
The op alone, sink-path calls at head dim 128 (
attendon one quantised operand set, median of 5 x 20 calls, two interleaved passes per arm; error is the L2 error against fp32 attention):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_loadwith 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).
On a second L4 VM, the first version of the fold measured (separate homes, 3 reps each):
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.
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_streamexpects nounsloth_i8residlaunch with the fold on.tests/test_diffusion_int8_attention.pyon main and on this branch, on L4 and T4 (final code). That includestest_attention_sinks_keep_the_rest_of_v_resolvedandtest_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